title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
Python 3 Sockets - Receiving more then 1 character
| 39,649,551 |
<p>So when I open up the CMD and create a telnet connection with:</p>
<p>telnet localhost 5555</p>
<p>It will apear a "Welcome", as you can see on the screen below.
After that every single character I type into the CMD will be printed out/send immediately.
My Question is: Is it, and if yes, how is it possible to type in messages and then send them so I receive them as 1 sentence and not char by char.
<a href="http://i.stack.imgur.com/kexib.png" rel="nofollow"><img src="http://i.stack.imgur.com/kexib.png" alt="enter image description here"></a></p>
<pre><code>import socket
import sys
from _thread import *
host = ""
port = 5555
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.bind((host,port))
except socket.error as e:
print(str(e))
s.listen(5) #Enable a server to accept connections.
print("Waiting for a connection...")
def threaded_client(conn):
conn.send(str.encode("Welcome\n"))
while True:
# for m in range (0,20): #Disconnects after x chars
data = conn.recv(2048) #Receive data from the socket.
reply = "Server output: "+ data.decode("utf-8")
print(data)
if not data:
break
conn.sendall(str.encode(reply))
conn.close()
while True:
conn, addr = s.accept()
print("connected to: "+addr[0]+":"+str(addr[1]))
start_new_thread(threaded_client,(conn,))
</code></pre>
| 0 |
2016-09-22T22:01:32Z
| 39,649,717 |
<p>It depends if you want to run on character mode or line mode.
Presently your code is fine, but your windows telnet client runs in character mode. You could use putty to give it a try in line mode, or if you really need to run in char mode, then keep reading the buffer until a newline is sent. </p>
<p>Here is what the server says when I run your code :</p>
<pre><code>Waiting for a connection...
connected to: 127.0.0.1:46738
b'Hello\r\n'
</code></pre>
<p>the telnet session beeing :</p>
<pre><code>telnet 127.0.0.1 5555
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Welcome
Hello
Server output: Hello
</code></pre>
| 0 |
2016-09-22T22:15:57Z
|
[
"python",
"sockets",
"python-3.x"
] |
Better way to convert dialog from QT Creator and incorporate it into my mainwindow
| 39,649,572 |
<p>I'm creating a simple popup box that contains settings. I want this to be a modal dialog box. I created the window from qt creator and converted the .ui to .py using pyuic. With the main window i'm able to import the .py file into my main project so that I can make changes to the gui and not have them overwritten every time that I update the GUI within QT Creator. When I try the same approach with my dialog box I was able to do so but then had no way of making the window modal. My fix was to bring the code from the file into the main py script. This has the disadvantage of me not being able to update the window from QT Creator now. Is there a better way to incorporate the new popup window that i created from QT Designer into my main GUI? When you click popup that is the window I wish to incorporate.</p>
<p>All the files:
main.py</p>
<pre><code>from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(637, 559)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
self.horizontalLayout = QtGui.QHBoxLayout(self.centralWidget)
self.horizontalLayout.setMargin(2)
self.horizontalLayout.setSpacing(1)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
spacerItem = QtGui.QSpacerItem(13, 485, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.horizontalLayout.addItem(spacerItem)
self.popup = QtGui.QPushButton(self.centralWidget)
self.popup.setObjectName(_fromUtf8("popup"))
self.horizontalLayout.addWidget(self.popup)
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setMargin(2)
self.verticalLayout.setSpacing(1)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.textBrowser = QtGui.QTextBrowser(self.centralWidget)
self.textBrowser.setObjectName(_fromUtf8("textBrowser"))
self.verticalLayout.addWidget(self.textBrowser)
self.horizontalLayout_7 = QtGui.QHBoxLayout()
self.horizontalLayout_7.setMargin(2)
self.horizontalLayout_7.setSpacing(1)
self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7"))
self.open_port = QtGui.QPushButton(self.centralWidget)
self.open_port.setObjectName(_fromUtf8("open_port"))
self.horizontalLayout_7.addWidget(self.open_port)
self.closeButton = QtGui.QPushButton(self.centralWidget)
self.closeButton.setObjectName(_fromUtf8("closeButton"))
self.horizontalLayout_7.addWidget(self.closeButton)
self.verticalLayout.addLayout(self.horizontalLayout_7)
self.horizontalLayout.addLayout(self.verticalLayout)
spacerItem1 = QtGui.QSpacerItem(13, 485, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.horizontalLayout.addItem(spacerItem1)
MainWindow.setCentralWidget(self.centralWidget)
self.statusBar = QtGui.QStatusBar(MainWindow)
self.statusBar.setObjectName(_fromUtf8("statusBar"))
MainWindow.setStatusBar(self.statusBar)
self.actionSettings = QtGui.QAction(MainWindow)
self.actionSettings.setObjectName(_fromUtf8("actionSettings"))
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.closeButton, QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.close)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.popup.setText(_translate("MainWindow", "popup", None))
self.open_port.setText(_translate("MainWindow", "Open Port", None))
self.closeButton.setText(_translate("MainWindow", "Close", None))
self.actionSettings.setText(_translate("MainWindow", "Settings", None))
</code></pre>
<p>comsettings.py what i'm hoping to turn into a dialog box</p>
<pre><code>from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_comSettings(object):
def setupUi(self, comSettings):
comSettings.setObjectName(_fromUtf8("comSettings"))
comSettings.resize(252, 209)
self.verticalLayout = QtGui.QVBoxLayout(comSettings)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.horizontalLayout_13 = QtGui.QHBoxLayout()
self.horizontalLayout_13.setObjectName(_fromUtf8("horizontalLayout_13"))
self.label_13 = QtGui.QLabel(comSettings)
self.label_13.setMinimumSize(QtCore.QSize(70, 0))
self.label_13.setObjectName(_fromUtf8("label_13"))
self.horizontalLayout_13.addWidget(self.label_13)
self.portBox_3 = QtGui.QComboBox(comSettings)
self.portBox_3.setMinimumSize(QtCore.QSize(150, 0))
self.portBox_3.setObjectName(_fromUtf8("portBox_3"))
self.horizontalLayout_13.addWidget(self.portBox_3)
spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_13.addItem(spacerItem)
self.verticalLayout.addLayout(self.horizontalLayout_13)
self.horizontalLayout_14 = QtGui.QHBoxLayout()
self.horizontalLayout_14.setObjectName(_fromUtf8("horizontalLayout_14"))
self.label_14 = QtGui.QLabel(comSettings)
self.label_14.setMinimumSize(QtCore.QSize(70, 0))
self.label_14.setObjectName(_fromUtf8("label_14"))
self.horizontalLayout_14.addWidget(self.label_14)
self.baudBox_3 = QtGui.QComboBox(comSettings)
self.baudBox_3.setMinimumSize(QtCore.QSize(150, 0))
self.baudBox_3.setObjectName(_fromUtf8("baudBox_3"))
self.baudBox_3.addItem(_fromUtf8(""))
self.baudBox_3.addItem(_fromUtf8(""))
self.baudBox_3.addItem(_fromUtf8(""))
self.baudBox_3.addItem(_fromUtf8(""))
self.baudBox_3.addItem(_fromUtf8(""))
self.baudBox_3.addItem(_fromUtf8(""))
self.baudBox_3.addItem(_fromUtf8(""))
self.baudBox_3.addItem(_fromUtf8(""))
self.baudBox_3.addItem(_fromUtf8(""))
self.baudBox_3.addItem(_fromUtf8(""))
self.baudBox_3.addItem(_fromUtf8(""))
self.baudBox_3.addItem(_fromUtf8(""))
self.baudBox_3.addItem(_fromUtf8(""))
self.baudBox_3.addItem(_fromUtf8(""))
self.baudBox_3.addItem(_fromUtf8(""))
self.horizontalLayout_14.addWidget(self.baudBox_3)
spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_14.addItem(spacerItem1)
self.verticalLayout.addLayout(self.horizontalLayout_14)
self.horizontalLayout_15 = QtGui.QHBoxLayout()
self.horizontalLayout_15.setObjectName(_fromUtf8("horizontalLayout_15"))
self.label_15 = QtGui.QLabel(comSettings)
self.label_15.setMinimumSize(QtCore.QSize(70, 0))
self.label_15.setObjectName(_fromUtf8("label_15"))
self.horizontalLayout_15.addWidget(self.label_15)
self.dataBox_3 = QtGui.QComboBox(comSettings)
self.dataBox_3.setMinimumSize(QtCore.QSize(150, 0))
self.dataBox_3.setObjectName(_fromUtf8("dataBox_3"))
self.dataBox_3.addItem(_fromUtf8(""))
self.dataBox_3.addItem(_fromUtf8(""))
self.horizontalLayout_15.addWidget(self.dataBox_3)
spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_15.addItem(spacerItem2)
self.verticalLayout.addLayout(self.horizontalLayout_15)
self.horizontalLayout_16 = QtGui.QHBoxLayout()
self.horizontalLayout_16.setObjectName(_fromUtf8("horizontalLayout_16"))
self.label_16 = QtGui.QLabel(comSettings)
self.label_16.setMinimumSize(QtCore.QSize(70, 0))
self.label_16.setObjectName(_fromUtf8("label_16"))
self.horizontalLayout_16.addWidget(self.label_16)
self.parityBox_3 = QtGui.QComboBox(comSettings)
self.parityBox_3.setMinimumSize(QtCore.QSize(150, 0))
self.parityBox_3.setObjectName(_fromUtf8("parityBox_3"))
self.parityBox_3.addItem(_fromUtf8(""))
self.parityBox_3.addItem(_fromUtf8(""))
self.parityBox_3.addItem(_fromUtf8(""))
self.parityBox_3.addItem(_fromUtf8(""))
self.parityBox_3.addItem(_fromUtf8(""))
self.horizontalLayout_16.addWidget(self.parityBox_3)
spacerItem3 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_16.addItem(spacerItem3)
self.verticalLayout.addLayout(self.horizontalLayout_16)
self.horizontalLayout_17 = QtGui.QHBoxLayout()
self.horizontalLayout_17.setObjectName(_fromUtf8("horizontalLayout_17"))
self.label_17 = QtGui.QLabel(comSettings)
self.label_17.setMinimumSize(QtCore.QSize(70, 0))
self.label_17.setObjectName(_fromUtf8("label_17"))
self.horizontalLayout_17.addWidget(self.label_17)
self.stopBox_3 = QtGui.QComboBox(comSettings)
self.stopBox_3.setMinimumSize(QtCore.QSize(150, 0))
self.stopBox_3.setObjectName(_fromUtf8("stopBox_3"))
self.stopBox_3.addItem(_fromUtf8(""))
self.stopBox_3.addItem(_fromUtf8(""))
self.stopBox_3.addItem(_fromUtf8(""))
self.horizontalLayout_17.addWidget(self.stopBox_3)
spacerItem4 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_17.addItem(spacerItem4)
self.verticalLayout.addLayout(self.horizontalLayout_17)
self.horizontalLayout_18 = QtGui.QHBoxLayout()
self.horizontalLayout_18.setObjectName(_fromUtf8("horizontalLayout_18"))
self.label_18 = QtGui.QLabel(comSettings)
self.label_18.setMinimumSize(QtCore.QSize(70, 0))
self.label_18.setObjectName(_fromUtf8("label_18"))
self.horizontalLayout_18.addWidget(self.label_18)
self.fcBox_3 = QtGui.QComboBox(comSettings)
self.fcBox_3.setMinimumSize(QtCore.QSize(150, 0))
self.fcBox_3.setObjectName(_fromUtf8("fcBox_3"))
self.fcBox_3.addItem(_fromUtf8(""))
self.fcBox_3.addItem(_fromUtf8(""))
self.fcBox_3.addItem(_fromUtf8(""))
self.horizontalLayout_18.addWidget(self.fcBox_3)
spacerItem5 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_18.addItem(spacerItem5)
self.verticalLayout.addLayout(self.horizontalLayout_18)
self.buttonBox = QtGui.QDialogButtonBox(comSettings)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
self.verticalLayout.addWidget(self.buttonBox)
self.retranslateUi(comSettings)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), comSettings.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), comSettings.reject)
QtCore.QMetaObject.connectSlotsByName(comSettings)
def retranslateUi(self, comSettings):
comSettings.setWindowTitle(_translate("comSettings", "Dialog", None))
self.label_13.setText(_translate("comSettings", "COM Port", None))
self.label_14.setText(_translate("comSettings", "Baud Rate", None))
self.baudBox_3.setItemText(0, _translate("comSettings", "110", None))
self.baudBox_3.setItemText(1, _translate("comSettings", "300", None))
self.baudBox_3.setItemText(2, _translate("comSettings", "600", None))
self.baudBox_3.setItemText(3, _translate("comSettings", "1200", None))
self.baudBox_3.setItemText(4, _translate("comSettings", "2400", None))
self.baudBox_3.setItemText(5, _translate("comSettings", "4800", None))
self.baudBox_3.setItemText(6, _translate("comSettings", "9600", None))
self.baudBox_3.setItemText(7, _translate("comSettings", "14400", None))
self.baudBox_3.setItemText(8, _translate("comSettings", "19200", None))
self.baudBox_3.setItemText(9, _translate("comSettings", "38400", None))
self.baudBox_3.setItemText(10, _translate("comSettings", "57600", None))
self.baudBox_3.setItemText(11, _translate("comSettings", "115200", None))
self.baudBox_3.setItemText(12, _translate("comSettings", "230400", None))
self.baudBox_3.setItemText(13, _translate("comSettings", "460800", None))
self.baudBox_3.setItemText(14, _translate("comSettings", "921600", None))
self.label_15.setText(_translate("comSettings", "Data", None))
self.dataBox_3.setItemText(0, _translate("comSettings", "8 bit", None))
self.dataBox_3.setItemText(1, _translate("comSettings", "7 bit", None))
self.label_16.setText(_translate("comSettings", "Parity", None))
self.parityBox_3.setItemText(0, _translate("comSettings", "None", None))
self.parityBox_3.setItemText(1, _translate("comSettings", "Odd", None))
self.parityBox_3.setItemText(2, _translate("comSettings", "Even", None))
self.parityBox_3.setItemText(3, _translate("comSettings", "Mark", None))
self.parityBox_3.setItemText(4, _translate("comSettings", "Space", None))
self.label_17.setText(_translate("comSettings", "Stop", None))
self.stopBox_3.setItemText(0, _translate("comSettings", "1 bit", None))
self.stopBox_3.setItemText(1, _translate("comSettings", "1.5 bit", None))
self.stopBox_3.setItemText(2, _translate("comSettings", "2 bit", None))
self.label_18.setText(_translate("comSettings", "Flow Control", None))
self.fcBox_3.setItemText(0, _translate("comSettings", "None", None))
self.fcBox_3.setItemText(1, _translate("comSettings", "Xon/Xoff", None))
self.fcBox_3.setItemText(2, _translate("comSettings", "hardware", None))
</code></pre>
<p>Main file that incorporates everything together:</p>
<pre><code>from PyQt4 import QtCore, QtGui
from main import Ui_MainWindow
#from comsettings import Ui_comSettings
import serial.tools.list_ports #must explicitly import tools
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class AThread(QtCore.QThread):
updated = QtCore.pyqtSignal(str)
def __init__(self):
QtCore.QThread.__init__(self)
def run(self):
while True:
if ser.in_waiting:
line=ser.readline()[:-2]#remove end of line \r\n
self.updated.emit(line.decode('utf-8'))
class SettingsDialog(QtGui.QDialog):
def __init__(self, parent=None):
super(SettingsDialog, self).__init__(parent)
self.setObjectName(_fromUtf8("settingsPopUp"))
self.resize(331, 295)
self.centralWidget = QtGui.QWidget(self)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
self.verticalLayout = QtGui.QVBoxLayout(self.centralWidget)
self.verticalLayout.setMargin(2)
self.verticalLayout.setSpacing(1)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setMargin(2)
self.horizontalLayout.setSpacing(1)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label = QtGui.QLabel(self.centralWidget)
self.label.setMinimumSize(QtCore.QSize(70, 0))
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout.addWidget(self.label)
self.portBox = QtGui.QComboBox(self.centralWidget)
self.portBox.setMinimumSize(QtCore.QSize(150, 0))
self.portBox.setObjectName(_fromUtf8("portBox"))
self.horizontalLayout.addWidget(self.portBox)
spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.verticalLayout.addLayout(self.horizontalLayout)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setMargin(2)
self.horizontalLayout_2.setSpacing(1)
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.label_2 = QtGui.QLabel(self.centralWidget)
self.label_2.setMinimumSize(QtCore.QSize(70, 0))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.horizontalLayout_2.addWidget(self.label_2)
self.baudBox = QtGui.QComboBox(self.centralWidget)
self.baudBox.setMinimumSize(QtCore.QSize(150, 0))
self.baudBox.setObjectName(_fromUtf8("baudBox"))
self.baudBox.addItem(_fromUtf8(""))
self.baudBox.addItem(_fromUtf8(""))
self.baudBox.addItem(_fromUtf8(""))
self.baudBox.addItem(_fromUtf8(""))
self.baudBox.addItem(_fromUtf8(""))
self.baudBox.addItem(_fromUtf8(""))
self.baudBox.addItem(_fromUtf8(""))
self.baudBox.addItem(_fromUtf8(""))
self.baudBox.addItem(_fromUtf8(""))
self.baudBox.addItem(_fromUtf8(""))
self.baudBox.addItem(_fromUtf8(""))
self.baudBox.addItem(_fromUtf8(""))
self.baudBox.addItem(_fromUtf8(""))
self.baudBox.addItem(_fromUtf8(""))
self.baudBox.addItem(_fromUtf8(""))
self.horizontalLayout_2.addWidget(self.baudBox)
spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem1)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.horizontalLayout_3 = QtGui.QHBoxLayout()
self.horizontalLayout_3.setMargin(2)
self.horizontalLayout_3.setSpacing(1)
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
self.label_3 = QtGui.QLabel(self.centralWidget)
self.label_3.setMinimumSize(QtCore.QSize(70, 0))
self.label_3.setObjectName(_fromUtf8("label_3"))
self.horizontalLayout_3.addWidget(self.label_3)
self.dataBox = QtGui.QComboBox(self.centralWidget)
self.dataBox.setMinimumSize(QtCore.QSize(150, 0))
self.dataBox.setObjectName(_fromUtf8("dataBox"))
self.dataBox.addItem(_fromUtf8(""))
self.dataBox.addItem(_fromUtf8(""))
self.horizontalLayout_3.addWidget(self.dataBox)
spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(spacerItem2)
self.verticalLayout.addLayout(self.horizontalLayout_3)
self.horizontalLayout_4 = QtGui.QHBoxLayout()
self.horizontalLayout_4.setMargin(2)
self.horizontalLayout_4.setSpacing(1)
self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4"))
self.label_4 = QtGui.QLabel(self.centralWidget)
self.label_4.setMinimumSize(QtCore.QSize(70, 0))
self.label_4.setObjectName(_fromUtf8("label_4"))
self.horizontalLayout_4.addWidget(self.label_4)
self.parityBox = QtGui.QComboBox(self.centralWidget)
self.parityBox.setMinimumSize(QtCore.QSize(150, 0))
self.parityBox.setObjectName(_fromUtf8("parityBox"))
self.parityBox.addItem(_fromUtf8(""))
self.parityBox.addItem(_fromUtf8(""))
self.parityBox.addItem(_fromUtf8(""))
self.parityBox.addItem(_fromUtf8(""))
self.parityBox.addItem(_fromUtf8(""))
self.horizontalLayout_4.addWidget(self.parityBox)
spacerItem3 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem3)
self.verticalLayout.addLayout(self.horizontalLayout_4)
self.horizontalLayout_5 = QtGui.QHBoxLayout()
self.horizontalLayout_5.setMargin(2)
self.horizontalLayout_5.setSpacing(1)
self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
self.label_5 = QtGui.QLabel(self.centralWidget)
self.label_5.setMinimumSize(QtCore.QSize(70, 0))
self.label_5.setObjectName(_fromUtf8("label_5"))
self.horizontalLayout_5.addWidget(self.label_5)
self.stopBox = QtGui.QComboBox(self.centralWidget)
self.stopBox.setMinimumSize(QtCore.QSize(150, 0))
self.stopBox.setObjectName(_fromUtf8("stopBox"))
self.stopBox.addItem(_fromUtf8(""))
self.stopBox.addItem(_fromUtf8(""))
self.stopBox.addItem(_fromUtf8(""))
self.horizontalLayout_5.addWidget(self.stopBox)
spacerItem4 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_5.addItem(spacerItem4)
self.verticalLayout.addLayout(self.horizontalLayout_5)
self.horizontalLayout_6 = QtGui.QHBoxLayout()
self.horizontalLayout_6.setMargin(2)
self.horizontalLayout_6.setSpacing(1)
self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6"))
self.label_6 = QtGui.QLabel(self.centralWidget)
self.label_6.setMinimumSize(QtCore.QSize(70, 0))
self.label_6.setObjectName(_fromUtf8("label_6"))
self.horizontalLayout_6.addWidget(self.label_6)
self.fcBox = QtGui.QComboBox(self.centralWidget)
self.fcBox.setMinimumSize(QtCore.QSize(150, 0))
self.fcBox.setObjectName(_fromUtf8("fcBox"))
self.fcBox.addItem(_fromUtf8("1"))
self.fcBox.addItem(_fromUtf8("2"))
self.fcBox.addItem(_fromUtf8("3"))
self.horizontalLayout_6.addWidget(self.fcBox)
spacerItem5 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem5)
self.verticalLayout.addLayout(self.horizontalLayout_6)
self.buttonBox = QtGui.QDialogButtonBox(self)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
self.verticalLayout.addWidget(self.buttonBox)
self.setLayout(self.verticalLayout)
self.retranslateUi(self)
def retranslateUi(self, settingsPopUp):
settingsPopUp.setWindowTitle(_translate("settingsPopUp", "settingsPopUp", None))
self.label.setText(_translate("settingsPopUp", "COM Port", None))
self.label_2.setText(_translate("settingsPopUp", "Baud Rate", None))
self.baudBox.setItemText(0, _translate("settingsPopUp", "110", None))
self.baudBox.setItemText(1, _translate("settingsPopUp", "300", None))
self.baudBox.setItemText(2, _translate("settingsPopUp", "600", None))
self.baudBox.setItemText(3, _translate("settingsPopUp", "1200", None))
self.baudBox.setItemText(4, _translate("settingsPopUp", "2400", None))
self.baudBox.setItemText(5, _translate("settingsPopUp", "4800", None))
self.baudBox.setItemText(6, _translate("settingsPopUp", "9600", None))
self.baudBox.setItemText(7, _translate("settingsPopUp", "14400", None))
self.baudBox.setItemText(8, _translate("settingsPopUp", "19200", None))
self.baudBox.setItemText(9, _translate("settingsPopUp", "38400", None))
self.baudBox.setItemText(10, _translate("settingsPopUp", "57600", None))
self.baudBox.setItemText(11, _translate("settingsPopUp", "115200", None))
self.baudBox.setItemText(12, _translate("settingsPopUp", "230400", None))
self.baudBox.setItemText(13, _translate("settingsPopUp", "460800", None))
self.baudBox.setItemText(14, _translate("settingsPopUp", "921600", None))
self.label_3.setText(_translate("settingsPopUp", "Data", None))
self.dataBox.setItemText(0, _translate("settingsPopUp", "8 bit", None))
self.dataBox.setItemText(1, _translate("settingsPopUp", "7 bit", None))
self.label_4.setText(_translate("settingsPopUp", "Parity", None))
self.parityBox.setItemText(0, _translate("settingsPopUp", "None", None))
self.parityBox.setItemText(1, _translate("settingsPopUp", "Odd", None))
self.parityBox.setItemText(2, _translate("settingsPopUp", "Even", None))
self.parityBox.setItemText(3, _translate("settingsPopUp", "Mark", None))
self.parityBox.setItemText(4, _translate("settingsPopUp", "Space", None))
self.label_5.setText(_translate("settingsPopUp", "Stop", None))
self.stopBox.setItemText(0, _translate("settingsPopUp", "1 bit", None))
self.stopBox.setItemText(1, _translate("settingsPopUp", "1.5 bit", None))
self.stopBox.setItemText(2, _translate("settingsPopUp", "2 bit", None))
self.label_6.setText(_translate("settingsPopUp", "Flow Control", None))
self.fcBox.setItemText(0, _translate("settingsPopUp", "None", None))
self.fcBox.setItemText(1, _translate("settingsPopUp", "Xon/Xoff", None))
self.fcBox.setItemText(2, _translate("settingsPopUp", "hardware", None))
#self.closeButton.setText(_translate("settingsPopUp", "Close", None))
class New_Ui_MainWindow(Ui_MainWindow):
def setupUi(self, MainWindow):
Ui_MainWindow.setupUi(self,MainWindow)
self.open_port.clicked.connect(self.start_serial)
self.popup.clicked.connect(self.popupSettings)
self.textBrowser.document().setMaximumBlockCount(5000)#number of lines before deleting.
self.thread= AThread()
self.thread.updated.connect(self.updateText)
#self.comboadd=serial.tools.list_ports.comports()
#for port in self.comboadd:
# self.portBox.addItem(str(port))
def updateText (self, text ):
self.textBrowser.append(text)
def start_serial(self):
ser.baudrate = 115200
ser.port = self.portBox.currentText()[:4]
ser.timeout=.1
ser.open()
self.thread.start();
def popupSettings(self):
self.settings = SettingsDialog()
self.settings.exec_()
if __name__ == "__main__":
import sys
import serial
ser = serial.Serial()
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = New_Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
</code></pre>
| 1 |
2016-09-22T22:03:45Z
| 39,651,176 |
<p>Generally, you would override the Qt Widget (i.e. <code>QMainWindow</code>) and not the class that Qt creator generates, but you can still do it the way you're doing if you want. You just need to pass the parent <code>QMainWindow</code> to the Dialog. Currently, you're not storing a reference to it.</p>
<pre><code>class New_Ui_MainWindow(Ui_MainWindow):
def setupUi(self, MainWindow):
self.MainWindow = MainWindow
...
def popupSettings(self):
self.settings = SettingsDialog(self.MainWindow)
self.settings.exec_()
</code></pre>
<p>If you wanted to just use the generated dialog code. You could do this. You</p>
<pre><code>from dialog import Ui_comSettings
class New_Ui_MainWindow(Ui_MainWindow):
def setupUi(self, MainWindow):
self.MainWindow = MainWindow
...
def popupSettings(self):
self.settings = QDialog(self.MainWindow)
self.settings.ui = Ui_comSettings()
self.settings.ui.setupUi(self.settings)
self.settings.exec_()
</code></pre>
| 1 |
2016-09-23T01:26:36Z
|
[
"python",
"pyqt",
"pyqt4",
"qt-creator"
] |
Index values of specific rows in python
| 39,649,649 |
<p>I am trying to find out Index of such rows before "None" occurs.</p>
<pre><code>pId=["a","b","c","None","d","e","None"]
df = pd.DataFrame(pId,columns=['pId'])
pId
0 a
1 b
2 c
3 None
4 d
5 e
6 None
df.index[df.pId.eq('None') & df.pId.ne(df.pId.shift(-1))]
</code></pre>
<p>I am expecting the output of the above code should be</p>
<pre><code>Index([2,5])
</code></pre>
<p>It gives me </p>
<pre><code>Index([3,6])
</code></pre>
<p>Please correct me</p>
| 0 |
2016-09-22T22:10:34Z
| 39,649,809 |
<p>I am not sure for the specific example you showed. Anyway, you could do it in a more simple way:</p>
<pre><code>indexes = [i-1 for i,x in enumerate(pId) if x == 'None']
</code></pre>
| 1 |
2016-09-22T22:24:52Z
|
[
"python",
"pandas",
"indexing",
"shift"
] |
Index values of specific rows in python
| 39,649,649 |
<p>I am trying to find out Index of such rows before "None" occurs.</p>
<pre><code>pId=["a","b","c","None","d","e","None"]
df = pd.DataFrame(pId,columns=['pId'])
pId
0 a
1 b
2 c
3 None
4 d
5 e
6 None
df.index[df.pId.eq('None') & df.pId.ne(df.pId.shift(-1))]
</code></pre>
<p>I am expecting the output of the above code should be</p>
<pre><code>Index([2,5])
</code></pre>
<p>It gives me </p>
<pre><code>Index([3,6])
</code></pre>
<p>Please correct me</p>
| 0 |
2016-09-22T22:10:34Z
| 39,649,838 |
<p>The problem is that you're returning the index of the "None". You <em>compare</em> it against the previous item, but you're still reporting the index of the "None". Note that your accepted answer doesn't make this check.</p>
<p>In short, you still need to plaster a "-1" onto the result of your checking.</p>
| 0 |
2016-09-22T22:27:06Z
|
[
"python",
"pandas",
"indexing",
"shift"
] |
Index values of specific rows in python
| 39,649,649 |
<p>I am trying to find out Index of such rows before "None" occurs.</p>
<pre><code>pId=["a","b","c","None","d","e","None"]
df = pd.DataFrame(pId,columns=['pId'])
pId
0 a
1 b
2 c
3 None
4 d
5 e
6 None
df.index[df.pId.eq('None') & df.pId.ne(df.pId.shift(-1))]
</code></pre>
<p>I am expecting the output of the above code should be</p>
<pre><code>Index([2,5])
</code></pre>
<p>It gives me </p>
<pre><code>Index([3,6])
</code></pre>
<p>Please correct me</p>
| 0 |
2016-09-22T22:10:34Z
| 39,649,927 |
<p>Just <code>-1</code> from <code>df[df["pId"] == "None"].index</code>:</p>
<pre><code>import pandas as pd
pId=["a","b","c","None","d","e","None"]
df = pd.DataFrame(pId,columns=['pId'])
print(df[df["pId"] == "None"].index - 1)
</code></pre>
<p>Which gives you:</p>
<pre><code>Int64Index([2, 5], dtype='int64')
</code></pre>
<p>Or if you just want a list of values:</p>
<pre><code>(df[df["pId"] == "None"].index - 1).tolist()
</code></pre>
<p>You should be aware that for a list like:</p>
<pre><code>pId=["None","None","b","c","None","d","e","None"]
</code></pre>
<p>You get a df like:</p>
<pre><code> pId
0 None
1 None
2 b
3 c
4 None
5 d
6 e
7 None
</code></pre>
<p>And output like:</p>
<pre><code>[-1, 0, 3, 6]
</code></pre>
<p>Which does not make a great deal of sense.</p>
| 0 |
2016-09-22T22:37:15Z
|
[
"python",
"pandas",
"indexing",
"shift"
] |
In python How can I extract data from webservices response using suds
| 39,649,665 |
<p>I am using python 2.71. I got this response from webservices call using python and suds library. I would like to extract the value of tag problemName. How can I do that ?</p>
<p>(200, (TESTResult){
ProblemList =
(ArrayList){
Items =
(ArrayOfAnyType){
Item[] =
(Problem){</p>
<pre><code> comment = None
name = None
problemName = "Sad"
relation = "Mother"
source = "Provider"
},
(Problem){
comment = None
name = None
problemName = "Stress"
relation = "Father"
source = "Provider"
}
}
}
</code></pre>
<p>})</p>
| 0 |
2016-09-22T22:11:36Z
| 39,652,022 |
<p>I was able to remove (200, (TESTResult) by calling webservice without faults=False parameter for example :</p>
<pre><code>#client = Client(url, transport=t, faults=False)
client = Client(url, transport=t)
resp = client.service.getProblemHistory(ProblemRequest)
probs = resp.ProblemList.Items.Item
for prob in probs
print "problem : " , prob.problemName
</code></pre>
| 0 |
2016-09-23T03:18:16Z
|
[
"python",
"suds"
] |
Add escape characters to a variable in Python
| 39,649,709 |
<p>I need to add an escape character to a variable which I'm appending to another string and have it apply its effects. This is what I have:</p>
<pre><code>h1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
h2 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
h3 = list(itertools.product(h1, h2))
h4 = []
for item in h3:
h4.append(''.join(item))
temp = r'\x' + str(h4[0]) + '\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'
</code></pre>
<p>So if i have \xh I need the character with hex value hh but I can't seem to find anything in python that does this besides \x which I can't seem to use on variables.</p>
<p>Any suggestions?</p>
| 2 |
2016-09-22T22:15:25Z
| 39,649,787 |
<p>Use <code>int()</code> to convert your hex value to an integer and then <code>chr()</code> to convert that number to a character:</p>
<pre><code>import itertools
hexdigits = "123456789abcdef"
for dig1, dig2 in itertools.product(hexdigits, hexdigits):
char = chr(int(dig1 + dig2, 16))
temp = char + '\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'
</code></pre>
| 0 |
2016-09-22T22:23:36Z
|
[
"python"
] |
Add escape characters to a variable in Python
| 39,649,709 |
<p>I need to add an escape character to a variable which I'm appending to another string and have it apply its effects. This is what I have:</p>
<pre><code>h1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
h2 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
h3 = list(itertools.product(h1, h2))
h4 = []
for item in h3:
h4.append(''.join(item))
temp = r'\x' + str(h4[0]) + '\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'
</code></pre>
<p>So if i have \xh I need the character with hex value hh but I can't seem to find anything in python that does this besides \x which I can't seem to use on variables.</p>
<p>Any suggestions?</p>
| 2 |
2016-09-22T22:15:25Z
| 39,649,879 |
<p>A somewhat faster solution that repeated <code>int</code>/<code>chr</code> calls (assuming you're using more than just the first byte produced) is to create a complete hex string and parse it all at once:</p>
<pre><code>import itertools
import binascii
hexdigits = "123456789abcdef"
completehex = ''.join(map(''.join, itertools.product(hexdigits, repeat=2)))
completebytes = binascii.unhexlify(completehex)
</code></pre>
<p>This will bulk decode all the hexpairs into the raw byte values (the "escapes" you want), so <code>completebytes</code> would be <code>'\x00\x01\x02\x03...\xfd\xfe\xff'</code>.</p>
<p>Of course, for this specific case (if your real problem isn't just generating all possible bytes values in order), you could simplify it even further, because what you're doing is just generating all possible byte values:</p>
<pre><code># Py3
completebytes = bytes(range(256))
# On Py2, bytes is alias for str, so must use bytearray first to accept iterable of int
completebytes = bytes(bytearray(range(256)))
</code></pre>
<p>Or, just for fun, the fastest possible way abusing <code>maketrans</code>:</p>
<pre><code># Py3:
completebytes = bytes.maketrans(b'', b'') # Add .decode('latin-1') if you really want str
# Py2:
import string
completebytes = string.maketrans('', '')
</code></pre>
| 1 |
2016-09-22T22:32:52Z
|
[
"python"
] |
Add escape characters to a variable in Python
| 39,649,709 |
<p>I need to add an escape character to a variable which I'm appending to another string and have it apply its effects. This is what I have:</p>
<pre><code>h1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
h2 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
h3 = list(itertools.product(h1, h2))
h4 = []
for item in h3:
h4.append(''.join(item))
temp = r'\x' + str(h4[0]) + '\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'
</code></pre>
<p>So if i have \xh I need the character with hex value hh but I can't seem to find anything in python that does this besides \x which I can't seem to use on variables.</p>
<p>Any suggestions?</p>
| 2 |
2016-09-22T22:15:25Z
| 39,650,183 |
<p>To answer the OP question, here is a way to convert, <strong>using the escape notation</strong>, a string containing two hexadecimal digits to a character</p>
<pre><code>h = '11'
temp = eval( r"'\x" + h + "'" )
</code></pre>
<p>It is not, however, the best way to do the conversion (see other answers). I would suggest <code>chr(int(h,16))</code>. Another way would be to use integers instead of strings <code>h=0x11</code> and <code>temp = chr(h)</code>.</p>
| 0 |
2016-09-22T23:08:42Z
|
[
"python"
] |
Python loop not cooperating
| 39,649,737 |
<p>I'm trying to create a loop for the given problem. I need help; it's not printing the way it should.</p>
<blockquote>
<p>Given positive integer num_insects, write a while loop that prints
that number doubled without exceeding 100. Follow each number with a
space. </p>
<p>Ex: If num_insects = 8, print:</p>
<pre><code>8 16 32 64
</code></pre>
</blockquote>
<p>Here's what I have</p>
<pre><code>num_insects = 8 # Must be >= 1
print(num_insects, '', end='')
while num_insects <= 100 :
num_insects = num_insects * 2
print(num_insects,'', end="")
</code></pre>
<p>This code prints the number 128 even thought the loop is set to end after 100? Why is that?</p>
| -2 |
2016-09-22T22:18:28Z
| 39,649,770 |
<p>the <code>print</code> function implicitly adds a newline:
<a href="https://docs.python.org/2/library/functions.html#print" rel="nofollow">https://docs.python.org/2/library/functions.html#print</a></p>
<p>You can pass an alternative ending with the <code>end =</code> argument; try passing <code>None</code> or <code>' '</code> and see if that gets you a result that you like better.</p>
| 2 |
2016-09-22T22:21:50Z
|
[
"python"
] |
Python loop not cooperating
| 39,649,737 |
<p>I'm trying to create a loop for the given problem. I need help; it's not printing the way it should.</p>
<blockquote>
<p>Given positive integer num_insects, write a while loop that prints
that number doubled without exceeding 100. Follow each number with a
space. </p>
<p>Ex: If num_insects = 8, print:</p>
<pre><code>8 16 32 64
</code></pre>
</blockquote>
<p>Here's what I have</p>
<pre><code>num_insects = 8 # Must be >= 1
print(num_insects, '', end='')
while num_insects <= 100 :
num_insects = num_insects * 2
print(num_insects,'', end="")
</code></pre>
<p>This code prints the number 128 even thought the loop is set to end after 100? Why is that?</p>
| -2 |
2016-09-22T22:18:28Z
| 39,649,843 |
<p>You want to multiply <code>num_insects</code> after you print out the result. You can pass in an empty string to the end parameter as stated in matt's answer:</p>
<pre><code>num_insects = 8
while num_insects <= 100:
print(num_insects,'', end="")
num_insects = num_insects * 2
print("") # newline
</code></pre>
<p>Output:</p>
<pre><code>8 16 32 64
</code></pre>
| 3 |
2016-09-22T22:27:48Z
|
[
"python"
] |
divide a disk image into smaller parts using Python
| 39,649,744 |
<p>I would like to write a program that takes a .dmg file that is 1.6 GB and split it into 100 MB chunks.</p>
<p>I would like to also write another program that later can put everything back together so that it can be mounted and used.</p>
<p>I am very new to Python (and any type of programming language in general) and cannot find anything on here about this specific thing. Let me know if I am using incorrect terminology too so that I can learn how to search more effectively. </p>
<p>Thanks!</p>
| 0 |
2016-09-22T22:19:05Z
| 39,650,248 |
<p>Try this example:</p>
<p><strong>split.py</strong></p>
<pre><code>import sys, os
kilobytes = 1024
megabytes = kilobytes * 1000
chunksize = int(1.4 * megabytes)
def split(fromfile, todir, chunksize=chunksize):
if not os.path.exists(todir):
os.mkdir(todir)
else:
for fname in os.listdir(todir):
os.remove(os.path.join(todir, fname))
partnum = 0
input = open(fromfile, 'rb')
while 1:
chunk = input.read(chunksize)
if not chunk: break
partnum = partnum+1
filename = os.path.join(todir, ('part%04d' % partnum))
fileobj = open(filename, 'wb')
fileobj.write(chunk)
fileobj.close()
input.close( )
assert partnum <= 9999
return partnum
if __name__ == '__main__':
try:
parts = split('/Users/example/Desktop/SO/st/example.mp4', '/Users/example/Desktop/SO/st/new', 2000000) # 100000000 == 100 mb
except:
print('Error during split')
</code></pre>
<p>for join:</p>
<p><strong>join.py</strong></p>
<pre><code>import os, sys
readsize = 1024
def join(fromdir, tofile):
output = open(tofile, 'wb')
parts = os.listdir(fromdir)
parts.sort( )
for filename in parts:
filepath = os.path.join(fromdir, filename)
fileobj = open(filepath, 'rb')
while 1:
filebytes = fileobj.read(readsize)
if not filebytes: break
output.write(filebytes)
fileobj.close( )
output.close( )
if __name__ == '__main__':
try:
join('/Users/example/Desktop/SO/st/new', 'example_join.mp4')
except:
print('Error joining files:')
else:
print('Join complete!')
</code></pre>
| 0 |
2016-09-22T23:16:21Z
|
[
"python",
"python-3.x",
"dmg"
] |
how to deform an image deforming the coordinates
| 39,649,761 |
<p>I would like to see how an image get deformed if I know how its coordinates are deformed.</p>
<p>for example: here I draw a circle</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from math import *
plane_side = 500.0 #arcsec
y_l, x_l, = np.mgrid[-plane_side:plane_side:1000j, -plane_side:plane_side:1000j]
r = np.sqrt(y_l**2 + x_l**2)
indexes1 = np.where(r<150.0)
indexes2 = np.where(r>160.0)
image = r.copy()
image[:,:] = 1.0
image[indexes1] = 0.0
image[indexes2] = 0.0
imgplot = plt.imshow(image,cmap="rainbow")
plt.colorbar()
plt.show()
</code></pre>
<p>If I want to deform the coordinates like this:</p>
<pre><code>y_c = y_lense**3
x_c = x_lense**2
</code></pre>
<p>and plot the image distorted, what should I do?</p>
| 1 |
2016-09-22T22:20:31Z
| 39,650,032 |
<p>You can use <code>plt.pcolormesh()</code>:</p>
<pre><code>y_c = (y_l/plane_side)**3
x_c = (x_l/plane_side)**2
ax = plt.gca()
ax.set_aspect("equal")
plt.pcolormesh(x_c, y_c, image, cmap="rainbow")
ax.set_xlim(0, 0.2)
ax.set_ylim(-0.1, 0.1);
</code></pre>
<p>the result:</p>
<p><a href="http://i.stack.imgur.com/7NpJw.png" rel="nofollow"><img src="http://i.stack.imgur.com/7NpJw.png" alt="enter image description here"></a></p>
| 2 |
2016-09-22T22:50:11Z
|
[
"python",
"python-2.7",
"numpy",
"matplotlib"
] |
how to deform an image deforming the coordinates
| 39,649,761 |
<p>I would like to see how an image get deformed if I know how its coordinates are deformed.</p>
<p>for example: here I draw a circle</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from math import *
plane_side = 500.0 #arcsec
y_l, x_l, = np.mgrid[-plane_side:plane_side:1000j, -plane_side:plane_side:1000j]
r = np.sqrt(y_l**2 + x_l**2)
indexes1 = np.where(r<150.0)
indexes2 = np.where(r>160.0)
image = r.copy()
image[:,:] = 1.0
image[indexes1] = 0.0
image[indexes2] = 0.0
imgplot = plt.imshow(image,cmap="rainbow")
plt.colorbar()
plt.show()
</code></pre>
<p>If I want to deform the coordinates like this:</p>
<pre><code>y_c = y_lense**3
x_c = x_lense**2
</code></pre>
<p>and plot the image distorted, what should I do?</p>
| 1 |
2016-09-22T22:20:31Z
| 39,650,341 |
<p>In general (without using a dedicated library), you should apply an inverse transformation to the coordinates of the new image. Than, you interpolate values from the original image at the calculated coordinates.</p>
<p>For example, if you want to apply the following transformation:</p>
<pre><code>x_new = x**2
y_new = y**2
</code></pre>
<p>you would do something like that:</p>
<pre><code>import numpy as np
# some random image
image = np.random.rand(10,10)
# new interpolated image - actually not interpolated yet :p
# TODO: in some cases, this image should be bigger than the original image. You can calculate optimal size from the original image considering the transformation used.
image_new = np.zeros(image.shape)
# get the coordinates
x_new, y_new = np.meshgrid( range(0,image_new.shape[1]), range(0,image_new.shape[0]) )
x_new = np.reshape(x_new, x_new.size)
y_new = np.reshape(y_new, y_new.size)
# do the inverse transformation
x = np.sqrt(x_new)
y = np.sqrt(y_new)
# TODO: here you should check that all x, y coordinates fall inside the image borders
# do the interpolation. The simplest one is nearest neighbour interpolation. For better image quality, bilinear interpolation should be used.
image_new[y_new,x_new] = image[np.round(y).astype(np.int) , np.round(x).astype(np.int)]
</code></pre>
| 1 |
2016-09-22T23:27:33Z
|
[
"python",
"python-2.7",
"numpy",
"matplotlib"
] |
python pandas 'AttributeError: Can only use .dt accessor with datetimelike values' decimal to hours
| 39,649,902 |
<p>I have a column in a df that looks like </p>
<pre><code>hour
1.0
2.0
3.0
6.0
Nan
</code></pre>
<p>I want to convert this into a time format so like below</p>
<pre><code>hour
1:00
2:00
3:00
6:00
</code></pre>
<p>However I cannot get the formatting correct. I have tried to coerce the format like below. I would also like the logic to leave the Nan values.</p>
<pre><code>pd.to_datetime(df['hour'], format='%H', coerce=True)
</code></pre>
<p>But this only returns NaT values.</p>
| 1 |
2016-09-22T22:35:01Z
| 39,653,829 |
<p>Here:</p>
<pre><code>pd.to_datetime(df['hour'], unit='h')
</code></pre>
<p>Change the <code>format</code> to <code>unit</code>. If you are using numeric data (like you are), then you <strong>cannot</strong> use <code>format</code>. <code>format</code> works only on strings.</p>
<p><code>%H</code>, for example is string interpolation, and since your data is numeric (float), string interpolation will fail.</p>
<hr>
<p>Note that the printed output will not resemble the output in the question. Because, pandas will convert it to datetime type. It will look like <code>'1970-01-01 00:00:00'</code> when printed. If you want the desired format, you can run either:</p>
<pre><code>pd.to_datetime(df['hour'], unit='h').apply(lambda h: '{}:00'.format(h.hour))
</code></pre>
<p>Or:</p>
<pre><code>df['hour'].apply(lambda h: '{}:00'.format(h))
</code></pre>
| 0 |
2016-09-23T06:18:07Z
|
[
"python",
"pandas"
] |
self.request.GET[] with href HTML
| 39,649,904 |
<p>I need to have self.request.GET[] have the correct code for when the user clicks, based on what they click in the HTML.</p>
<p>Below is Main.py:</p>
<pre><code>import webapp2
from data import Fighter
from data import Data
from pages import Page
from pages import ContentPage
class MainHandler(webapp2.RequestHandler):
def get(self):
f = Fighter()
d = Data()
p = Page()
c = ContentPage()
if self.request.GET[1]:
self.response.write(c.results(d.fighter_data[0].name, d.fighter_data[0].rank, d.fighter_data[0].age, d.fighter_data[0].hometown, d.fighter_data[0].fights_out_of, d.fighter_data[0].height, d.fighter_data[0].weight, d.fighter_data[0].reach, d.fighter_data[0].wins, d.fighter_data[0].loses, d.fighter_data[0].bio))
else:
self.response.write(p.page)
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
</code></pre>
<p>Where if self.request.GET[1]: needs to work if ?fighter=1 is clicked</p>
<p>Pages.py below:</p>
<pre><code>class Page(object):
def __init__(self):
self.page = '''
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<a href="?fighter=1">Flweight</a>
<a href="?fighter=2">Bantamweight</a>
<a href="?fighter=3">Featherweight</a>
<a href="?fighter=4">Lightweight</a>
<a href="?fighter=5">Welterweight</a>
</body>
</html>'''
def content(self):
content_page = self.page # set content page equal to page
content_page = content_page.format(**locals()) # get locals
return content_page # return content_page
class ContentPage(object):
def __init__(self):
self.data_page = '''
{name} {age} {rank} {hometown} {fights_out_of} {height} {weight} {reach} {wins} {loses} {bio}'''
def results(self, name, age, rank, hometown, fights_out_of, height, weight, reach, wins, loses, bio): # get stuff from page
results_page = self.data_page # set results page equal to data page
results_page = results_page.format(**locals()) # get locals
return results_page # returns results_page
</code></pre>
<p>I appreciate any help. Thanks.</p>
| 0 |
2016-09-22T22:35:07Z
| 39,651,343 |
<p>I have solved my own question. It's:</p>
<pre><code> if self.request.GET:
if self.request.GET['fighter']:
self.response.write(c.results(d.fighter_data[0].name, d.fighter_data[0].rank, d.fighter_data[0].age, d.fighter_data[0].hometown, d.fighter_data[0].fights_out_of, d.fighter_data[0].height, d.fighter_data[0].weight, d.fighter_data[0].reach, d.fighter_data[0].wins, d.fighter_data[0].loses, d.fighter_data[0].bio))
elif self.request.GET['fighter'] == 2:
self.response.write(c.results(d.fighter_data[1].name, d.fighter_data[1].rank, d.fighter_data[1].age, d.fighter_data[1].hometown, d.fighter_data[1].fights_out_of, d.fighter_data[1].height, d.fighter_data[1].weight, d.fighter_data[1].reach, d.fighter_data[1].wins, d.fighter_data[1].loses, d.fighter_data[1].bio))
elif self.request.GET['fighter'] == 3:
self.response.write(c.results(f.name, f.age, f.rank, f.hometown, f.fights_out_of, f.height, f.weight, f.reach, f.wins, f.loses, f.bio))
elif self.request.GET['fighter'] == 4:
self.response.write(c.results(f.name, f.age, f.rank, f.hometown, f.fights_out_of, f.height, f.weight, f.reach, f.wins, f.loses, f.bio))
elif self.request.GET['fighter'] == 5:
self.response.write(c.results(f.name, f.age, f.rank, f.hometown, f.fights_out_of, f.height, f.weight, f.reach, f.wins, f.loses, f.bio))
else:
self.response.write(p.page)
</code></pre>
| 0 |
2016-09-23T01:48:28Z
|
[
"python"
] |
How to output a variable inside a Listbox in Tkinter
| 39,650,018 |
<p>I've looked up on the net different guides on how to do what I want to, but i didn't find any solution that I could understand.
What I want to do is to display the content stored in any variable in a Listbox in Tkinter.</p>
<pre><code>#! /usr/bin/env python
from tkinter import *
window = Tk()
test = Listbox(window, width=28, heigh=10, font=("Helvetica", 14), state="disabled")
test.grid(row=0, column=0)
for x in range(30):
test.insert(END, x)
window.mainloop()
</code></pre>
<p>If you think the best solution to my problem would be reached with something different from a Listbox it's fine anyway.
Thank you in advance</p>
| -1 |
2016-09-22T22:48:40Z
| 39,661,275 |
<p>Your listbox is disabled, which means you can't insert or delete items. Set the state to <code>"normal"</code> before inserting.</p>
| 0 |
2016-09-23T12:52:19Z
|
[
"python",
"tkinter"
] |
Import different files based on where script is being called from
| 39,650,075 |
<p>I have a file <code>global_params.py</code> which defines some global parameters that are used by a script <code>client_script.py</code>.</p>
<p>Now <code>client_script.py</code> can be called from the terminal, or it can be called from another python script <code>caller.py</code>. When it's called from the terminal I want the global parameters to be loaded from <code>global_params.py</code> I can do that with:</p>
<pre><code>if __name__ == '__main__':
from global_params import *
</code></pre>
<p>When <code>client_script.py</code> is called by <code>caller.py</code> how do I make it load global parameters from another file, say <code>global_params_2.py</code></p>
| 0 |
2016-09-22T22:54:09Z
| 39,650,762 |
<p><code>__name__</code> has the name of the caller, it is <code>__main__</code> if you call <code>client_script.py</code> from the terminal, and the name of the calling script if it is called from another script. If <code>client_script.py</code> is called from within <code>caller.py</code> then <code>__name__</code> is <code>caller</code></p>
<p>So in your case this should do what you want:</p>
<pre><code>if __name__ == 'caller':
from global_params_2 import *
</code></pre>
| 0 |
2016-09-23T00:23:01Z
|
[
"python",
"python-2.7",
"import"
] |
I cant align FloatLayout in center in Kivy
| 39,650,082 |
<p>Iam tried align floatlayout in center, help-me?
Uploaded image for understanding...
My idea is recreate layout Windows 8 retro in Kivy, after add icons windows 8 retro in button.</p>
<p><a href="http://i.stack.imgur.com/XrLFb.png" rel="nofollow"><img src="http://i.stack.imgur.com/XrLFb.png" alt="enter image description here"></a></p>
<p>My kv file:</p>
<pre><code><SMAgro>:
AnchorLayout:
anchor_x: 'center'
anchor_y: 'center'
FloatLayout:
canvas:
Color:
rgb: [1,1,1,1]
Rectangle:
pos: self.pos
size: self.size
Button:
background_color: [.4,1,.1,1]
pos_hint: {'x': 0.26, 'y': 0.328571}
size_hint: 0.45, 0.3
text: "Equipamentos"
# StackLayout:
# pos: self.parent.pos
# size: self.parent.size
# orientation: 'lr-tb'
# Image:
# source: 'kivy.png'
# size_hint_x: None
# width: 74
# Label:
# size_hint_x: None
# width: 100
# text: "Equipamentos"
Button:
background_color: [.4,1,.1,1]
pos_hint: {'x': 0.26, 'y': 0.15}
size_hint: 0.225, 0.18
text: 'Configuracoes'
Button:
background_color: [.4,1,.1,1]
pos_hint: {'x': 0.486, 'y': 0.15}
size_hint: 0.225, 0.18
text: 'Sobre'
</code></pre>
| 0 |
2016-09-22T22:54:43Z
| 39,650,403 |
<p>You can set FloatLayout size and add <code>pos_hint: {'center_y': 0.5, 'center_x': 0.5}</code>, so for example: your widest button has size_hint_x = 0.45 and buttons have size_hint_y = 0.18 + 0.3.</p>
<p>Size of container: <code>size_hint: 0.45, 0.48</code></p>
<p>Now, if button has <code>size_hint: 1, 1</code>, it's 100% width and height of parent container(FloatLayout) and it's equal to 45% width and 48% height of window.</p>
<p>This code shows centered FloatLayout</p>
<pre><code>FloatLayout:
pos_hint: {'center_y': 0.5, 'center_x': 0.5}
size_hint: 0.45, 0.48
canvas:
Color:
rgb: [1,1,1,1]
Rectangle:
pos: self.pos
size: self.size
Button:
background_color: [.4,1,.1,1]
pos_hint: {'x': 0, 'y': 0.375}
size_hint: 1, 0.625
text: "Equipamentos"
Button:
background_color: [.4,1,.1,1]
pos_hint: {'x': 0, 'y': 0}
size_hint: .5, 0.375
text: 'Configuracoes'
Button:
background_color: [.4,1,.1,1]
pos_hint: {'x': .5, 'y': 0}
size_hint: .5, 0.375
text: 'Sobre'
</code></pre>
<p><a href="http://i.stack.imgur.com/jN6Am.png" rel="nofollow">centered FloatLayout</a></p>
| 0 |
2016-09-22T23:35:51Z
|
[
"python",
"kivy"
] |
Group list of tuples by item
| 39,650,110 |
<p>I have this list as example:</p>
<pre><code>[(148, Decimal('3.0')), (325, Decimal('3.0')), (148, Decimal('2.0')), (183, Decimal('1.0')), (308, Decimal('1.0')), (530, Decimal('1.0')), (594, Decimal('1.0')), (686, Decimal('1.0')), (756, Decimal('1.0')), (806, Decimal('1.0'))]
</code></pre>
<p>Now i want to group by the id, so I will use <code>itemgetter(0)</code>:</p>
<pre><code>import operator, itertools
from decimal import *
test=[(148, Decimal('3.0')), (325, Decimal('3.0')), (148, Decimal('2.0')), (183, Decimal('1.0')), (308, Decimal('1.0')), (530, Decimal('1.0')), (594, Decimal('1.0')), (686, Decimal('1.0')), (756, Decimal('1.0')), (806, Decimal('1.0'))]
for _k, data in itertools.groupby(test, operator.itemgetter(0)):
print list(data)
</code></pre>
<p>I don't know why but I am getting this wrong output:</p>
<pre><code>[(148, Decimal('3.0'))]
[(325, Decimal('3.0'))]
[(148, Decimal('2.0'))]
[(183, Decimal('1.0'))]
[(308, Decimal('1.0'))]
[(530, Decimal('1.0'))]
[(594, Decimal('1.0'))]
[(686, Decimal('1.0'))]
[(756, Decimal('1.0'))]
[(806, Decimal('1.0'))]
</code></pre>
<p>As you can see the output is not grouped by id. However the code above works fine if I use <code>itemgetter(1)</code>. The output is grouped by decimal val.</p>
<pre><code>[(148, Decimal('3.0')), (325, Decimal('3.0'))]
[(148, Decimal('2.0'))]
[(183, Decimal('1.0')), (308, Decimal('1.0')), (530, Decimal('1.0')), (594, Decimal('1.0')), (686, Decimal('1.0')), (756, Decimal('1.0')), (806, Decimal('1.0'))]
</code></pre>
<p>What I am missing here?</p>
| 2 |
2016-09-22T22:58:05Z
| 39,650,142 |
<p><code>itertools.groupby()</code> requires the data to be consistent or sorted.</p>
<p><code>[(148, Decimal('3.0')), (148, Decimal('2.0')), (325, Decimal('3.0'))]</code> will work but <code>[(148, Decimal('3.0')), (325, Decimal('3.0')), (148, Decimal('2.0'))]</code> will not as the id is <code>148, 325, 148</code> instead of <code>148, 148, 325</code>.</p>
| 2 |
2016-09-22T23:01:26Z
|
[
"python",
"python-2.7",
"itertools"
] |
Group list of tuples by item
| 39,650,110 |
<p>I have this list as example:</p>
<pre><code>[(148, Decimal('3.0')), (325, Decimal('3.0')), (148, Decimal('2.0')), (183, Decimal('1.0')), (308, Decimal('1.0')), (530, Decimal('1.0')), (594, Decimal('1.0')), (686, Decimal('1.0')), (756, Decimal('1.0')), (806, Decimal('1.0'))]
</code></pre>
<p>Now i want to group by the id, so I will use <code>itemgetter(0)</code>:</p>
<pre><code>import operator, itertools
from decimal import *
test=[(148, Decimal('3.0')), (325, Decimal('3.0')), (148, Decimal('2.0')), (183, Decimal('1.0')), (308, Decimal('1.0')), (530, Decimal('1.0')), (594, Decimal('1.0')), (686, Decimal('1.0')), (756, Decimal('1.0')), (806, Decimal('1.0'))]
for _k, data in itertools.groupby(test, operator.itemgetter(0)):
print list(data)
</code></pre>
<p>I don't know why but I am getting this wrong output:</p>
<pre><code>[(148, Decimal('3.0'))]
[(325, Decimal('3.0'))]
[(148, Decimal('2.0'))]
[(183, Decimal('1.0'))]
[(308, Decimal('1.0'))]
[(530, Decimal('1.0'))]
[(594, Decimal('1.0'))]
[(686, Decimal('1.0'))]
[(756, Decimal('1.0'))]
[(806, Decimal('1.0'))]
</code></pre>
<p>As you can see the output is not grouped by id. However the code above works fine if I use <code>itemgetter(1)</code>. The output is grouped by decimal val.</p>
<pre><code>[(148, Decimal('3.0')), (325, Decimal('3.0'))]
[(148, Decimal('2.0'))]
[(183, Decimal('1.0')), (308, Decimal('1.0')), (530, Decimal('1.0')), (594, Decimal('1.0')), (686, Decimal('1.0')), (756, Decimal('1.0')), (806, Decimal('1.0'))]
</code></pre>
<p>What I am missing here?</p>
| 2 |
2016-09-22T22:58:05Z
| 39,650,170 |
<p>You would first need to <em>sort</em> the data for the <em>groupby</em> to work, it groups <em>consecutive elements</em> based on the key you provide:</p>
<pre><code>import operator, itertools
from decimal import *
test=[(148, Decimal('3.0')), (325, Decimal('3.0')), (148, Decimal('2.0')), (183, Decimal('1.0')), (308, Decimal('1.0')), (530, Decimal('1.0')), (594, Decimal('1.0')), (686, Decimal('1.0')), (756, Decimal('1.0')), (806, Decimal('1.0'))]
for _k, data in itertools.groupby(sorted(test), operator.itemgetter(0)):
print list(data)
</code></pre>
<p>But you would be better using a dict to group to avoid an unnecessary O(n log n) sort:</p>
<pre><code>from collections import defaultdict
d = defaultdict(list)
for t in test:
d[t[0]].append(t)
for v in d.values():
print(v)
</code></pre>
<p>Both would give you the same groupings, just not necessarily in the same order.</p>
| 4 |
2016-09-22T23:07:04Z
|
[
"python",
"python-2.7",
"itertools"
] |
How to calculate data transfer ifconfig per second in python?
| 39,650,173 |
<p>I have script like this</p>
<pre><code>import os
import time
os.chdir('/sys/class/net/wlan1/statistics')
while True:
up = open('tx_bytes').read()
time.sleep(1)
print 'UP:',up
</code></pre>
<p>And the value is</p>
<pre><code>UP: 2177453
UP: 2177539
UP: 2177789
UP: 2177990
</code></pre>
<p>How to find diferent value TX bytes after delay time.sleep and Befor delay time.sleep to get bandwidth Byte persecond?
Byte persecond = TXbytes_after_time_sleep - TXbytes_before_time_sleep
and the value can loopen no endless with while true.</p>
| 0 |
2016-09-22T23:07:22Z
| 39,650,242 |
<p>Just like you did I guess.</p>
<p>It's quite rough and not very accurate but the same time spent reading the before is taken into account in reading the after so I guess it's fine.</p>
<pre><code>with open('/sys/class/net/wlan1/statistics/tx_bytes') as myfile:
before = myfile.read()
time.sleep(3) # The longer this is the more accurate it will be on average.
with open('/sys/class/net/wlan1/statistics/tx_bytes') as myfile:
after = myfile.read()
print((int(after)-int(before))/3)
</code></pre>
| 0 |
2016-09-22T23:15:51Z
|
[
"python",
"time",
"ifconfig"
] |
How to calculate data transfer ifconfig per second in python?
| 39,650,173 |
<p>I have script like this</p>
<pre><code>import os
import time
os.chdir('/sys/class/net/wlan1/statistics')
while True:
up = open('tx_bytes').read()
time.sleep(1)
print 'UP:',up
</code></pre>
<p>And the value is</p>
<pre><code>UP: 2177453
UP: 2177539
UP: 2177789
UP: 2177990
</code></pre>
<p>How to find diferent value TX bytes after delay time.sleep and Befor delay time.sleep to get bandwidth Byte persecond?
Byte persecond = TXbytes_after_time_sleep - TXbytes_before_time_sleep
and the value can loopen no endless with while true.</p>
| 0 |
2016-09-22T23:07:22Z
| 39,650,274 |
<p>What is your worry so far? YOu have a certain amount of innate overhead, since you have to return to the start of the file. We can reduce it somewhat by getting rid of the superfluous <strong>open</strong> commands:</p>
<pre><code>import time
old = 0
with open('/sys/class/net/wlan1/statistics/tx_bytes') as vol:
while True:
vol.seek(0)
new = vol.read()
time.sleep(1)
print "UP:", new-old
old = new
</code></pre>
<p>The <strong>seek</strong> command resets the file's "bookmark"" to byte 0, the start of the file. It's faster than reopening the file, since it's merely an integer assignment to an object attribute.</p>
<p>Is this granularity good enough for your purposes?</p>
| 1 |
2016-09-22T23:19:40Z
|
[
"python",
"time",
"ifconfig"
] |
UTF-16 Code Units In Python Polyglot
| 39,650,198 |
<p>I need to extract the number of UTF-16 code units from the start of the string at which a location name starts from a Python sting. I am using Polyglot NER to tag a location in a Python string. For example, "Obama was born in the United States. But I was born in Alabama", would mark "United States" and "Alabama". The Python Polyglot extractor simply returns to the locations tagged, and the how many words from the front they start. How do I figure out the number of UTF-16 code units from the start of the string the word occurs? </p>
<p>Java interface that requires the information <a href="https://github.com/Berico-Technologies/CLAVIN/blob/master/src/main/java/com/bericotech/clavin/extractor/LocationOccurrence.java" rel="nofollow">https://github.com/Berico-Technologies/CLAVIN/blob/master/src/main/java/com/bericotech/clavin/extractor/LocationOccurrence.java</a></p>
| 0 |
2016-09-22T23:10:21Z
| 39,650,900 |
<p>Just to clarify some of @Ignacio Vazquez-Abrams' comments.
When processing or analyzing text you don't want to have to worry about how many bytes a given character takes up. That's why you take the 'encoding' out of the equation by first 'decoding' the encoded text to a separate text/str representation.</p>
<pre><code>>>> encoded_text = 'hello world'.encode('utf16')
>>> encoded_text
b'\xff\xfeh\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00'
>>> type(encoded_text)
<class 'bytes'>
>>> len(encoded_text)
24
>>> decoded_text = encoded_text.decode('utf16')
>>> decoded_text
'hello world'
>>> type(decoded_text)
<class 'str'>
>>>
>>> len(decoded_text)
11
</code></pre>
<p>I did see the <code>UTF-16 code units</code> in the java code you posted... </p>
<p>You could do something like this to get the number of bytes from the start:</p>
<pre><code>sentence = "Obama was born in the United States. But I was born in Alabama".encode('UTF-16LE')
word = 'United States'.encode('UTF-16LE')
bytes_from_start = None
for start_byte_position in range(len(sentence)):
candidate = sentence[start_byte_position: start_byte_position + len(word)]
if word == candidate:
bytes_from_start = len(sentence[:start_byte_position])
print('bytes from start: ', bytes_from_start)
print('len(sentence[:start_byte_position]): ', len(sentence[:start_byte_position]))
print('Preceding text: "{}"'.format(sentence[:start_byte_position].decode('UTF-16LE')))
break
</code></pre>
<p>But it's still not clear if <em>UTF-16 code units</em> == <em>bytes</em>. I have a feeling it really just wants the number of characters from the start. And if that's all you need you can use the str object's .index() method:</p>
<pre><code>sentence = "Obama was born in the United States. But I was born in Alabama"
word = 'United States'
characters_from_start = sentence.index(word)
</code></pre>
| 0 |
2016-09-23T00:42:57Z
|
[
"python",
"utf-8",
"utf",
"polyglot"
] |
Convert a numpy array into an array of signs with 0 as positive
| 39,650,312 |
<p>I have a large numpy array with positive data, negative data and 0s. I want to convert it to an array with the signs of the current values such that 0 is considered positive. If I use <code>numpy.sign</code> it returns 0 if the current value is 0 but I want something that returns 1 instead. Is there an easy way to do this?</p>
| 0 |
2016-09-22T23:24:16Z
| 39,650,350 |
<p>If <code>x</code> is the array, you could use <code>2*(x >= 0) - 1</code>.</p>
<p><code>x >= 0</code> will be an array of boolean values (i.e. <code>False</code> and <code>True</code>), but when you do arithmetic with it, it is effectively cast to an array of 0s and 1s.</p>
<p>You could also do <code>np.sign(x) + (x == 0)</code>. (Note that <code>np.sign(x)</code> returns floating point values, even when <code>x</code> is an integer array.)</p>
| 1 |
2016-09-22T23:28:59Z
|
[
"python",
"numpy"
] |
Creating a Number Pyramid
| 39,650,318 |
<p>I first off would like to say this may be classified as a duplicate post, based on my current research:</p>
<p><a href="http://stackoverflow.com/questions/38537364/how-to-do-print-formatting-in-python-with-chunks-of-strings?noredirect=1&lq=1">How to do print formatting in Python with chunks of strings?</a>
and
<a href="http://stackoverflow.com/questions/19129279/number-pyramid-nested-for-loop">Number Pyramid Nested for Loop</a>
and
<a href="http://stackoverflow.com/questions/13077491/pyramid-of-numbers-in-python">pyramid of numbers in python</a></p>
<p>[Edit: The reason I cannot use the conclusions to these previous questions very similar to mine is that I cannot use anything except what we have covered in my class so far. I am not allowed to use solutions such as: len, map, join, etc. I am limited to basic formats and string conversion.]</p>
<p>I'm in the process of working on an assignment for my Python class (using 3.0+) and I've reached a point where I'm stuck. This program is meant to allow the user to input a number from 1 to 15 as a line count and output a number pyramid based on their choice, such as the following example where the user would input 5:</p>
<pre><code> 1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
</code></pre>
<p>So far I've gotten to the point where I can successfully print inputs 1 through 9, but have run into 2 issues.</p>
<ul>
<li>Inputs from 10 to 15 the numbers become misaligned (which users in the above posts seemed to have as well).</li>
<li>I can't seem to correctly format the printed numbers to have spaces in between them like my example above</li>
</ul>
<p>My current code for the program is:</p>
<pre><code>print("This program creates a number pyramid with 1 to 15 lines")
lines = eval(input("Enter an integer from 1 to 15: "))
if lines < 16:
for i in range(1, lines + 1):
#Print leading space
for j in range(lines - i, 0, -1):
print(" ", end = '')
#Print left decreasing numbers
for j in range(i, 0, -1):
print(j, end = '')
#Print right increasing numbers
for j in range(2, i + 1):
print(j, end = '')
print("")
else:
print("The number you have entered is greater than 15.")
</code></pre>
<p>And my current output is:</p>
<pre><code>Enter an integer from 1 to 15: 15
1
212
32123
4321234
543212345
65432123456
7654321234567
876543212345678
98765432123456789
109876543212345678910
1110987654321234567891011
12111098765432123456789101112
131211109876543212345678910111213
1413121110987654321234567891011121314
15141312111098765432123456789101112131415
</code></pre>
<p>I am asking you guys out of a desire to learn, not for anyone to code for me. I want to understand what I'm doing wrong so I can fix it. Thank you all in advance!</p>
| 0 |
2016-09-22T23:25:09Z
| 39,650,568 |
<ol>
<li>You need to print one space more for the numbers from 10 to 15 because there is an extra character you have to take into consideration. If you change your max number to 100, you will need another space(total of 3), and so on. This means that instead if <code>print(" ")</code> you have to use <code>print(" " * len(str(j)))</code>, where <code>*</code> duplicates the space <code>len(str(j))</code> times and <code>len(str(j))</code> counts the number of digits from j. Also, if you want the pyramid properly aligned, you have to print another space, the one between numbers. </li>
<li>To add a space between numbers, you have to print the space<br>
<code>print(j, end=' ')</code></li>
</ol>
| 0 |
2016-09-22T23:56:02Z
|
[
"python",
"python-3.x",
"numbers",
"alignment",
"shapes"
] |
accessing elements of a counter containing ngrams
| 39,650,355 |
<p>I am taking a string, tokenizing it, and want to look at the most common bigrams, here is what I have got:</p>
<pre><code>import nltk
import collections
from nltk import ngrams
someString="this is some text. this is some more test. this is even more text."
tokens=nltk.word_tokenize(someString)
tokens=[token.lower() for token in tokens if len()>1]
bigram=ngrams(tokens,2)
aCounter=collections.Counter(bigram)
</code></pre>
<p>If I:</p>
<pre><code>print(aCounter)
</code></pre>
<p>Then it will output the bigrams in sorted order. </p>
<pre><code>for element in aCounter:
print(element)
</code></pre>
<p>Will print the elements, but not with a count, and not in order of the count. I want to do a for loop, where I print out the X most common bigrams in a text.</p>
<p>I am essentially trying to learn both Python and nltk at the same time, so this could be why I am struggling here (I assume this is a trivial thing).</p>
| 0 |
2016-09-22T23:30:11Z
| 39,650,392 |
<p>You're probably looking for something that already exists, namely, the <a href="https://docs.python.org/3/library/collections.html#collections.Counter.most_common" rel="nofollow"><code>most_common</code></a> method on counters. From the docs: </p>
<blockquote>
<p>Return a list of the <code>n</code> most common elements and their counts from the most common to the least. If <code>n</code> is omitted or <code>None</code>, <code>most_common()</code> returns all elements in the counter. Elements with equal counts are ordered arbitrarily:</p>
</blockquote>
<p>You can call it and supply a value <code>n</code> in order to get the <code>n</code> most common value-count pairs. For example:</p>
<pre><code>from collections import Counter
# initialize with silly value.
c = Counter('aabbbccccdddeeeeefffffffghhhhiiiiiii')
# Print 4 most common values and their respective count.
for val, count in c.most_common(4):
print("Value {0} -> Count {1}".format(val, count))
</code></pre>
<p>Which prints out:</p>
<pre><code>Value f -> Count 7
Value i -> Count 7
Value e -> Count 5
Value h -> Count 4
</code></pre>
| 2 |
2016-09-22T23:34:18Z
|
[
"python",
"python-3.x",
"nltk",
"n-gram"
] |
How to add checking for more than 1dp
| 39,650,356 |
<p>Id like to stop a decimal input from being more than 00.0 (1dp).
So they input a number but i want it to 1dp as its percentage (such as 44.7% or 7.5%)
Here is the code:</p>
<pre><code>while nameSave <=0 or nameSave >99:
while True:
try:
nameSave = float(input("Enter % Savings (Between 1-99%): "))
break
except:
print("Needs to be a number ")
</code></pre>
| 0 |
2016-09-22T23:30:18Z
| 39,650,386 |
<pre><code>while nameSave <=0 or nameSave >99:
while True:
try:
nameSave = float(input("Enter % Savings (Between 1-99%): "))
check = str(nameSave)
if (check[1] == '.' and len(check) > 3) or len(check) > 4:
print("Needs to be precise to 1 decimal point")
break
except:
print("Needs to be a number ")
</code></pre>
| 0 |
2016-09-22T23:33:31Z
|
[
"python",
"python-3.4"
] |
Is there a faster way to make GET requests in Go?
| 39,650,397 |
<p>Consider this program:</p>
<pre><code>package main
import (
"net/http"
"os"
)
var url = "https://upload.wikimedia.org/wikipedia/commons/f/fe/FlumeRide%2C_Liseberg_-_last_steep_POV.ogv"
func main() {
response, _ := http.Get(url)
defer response.Body.Close()
f, _ := os.Create("output.ogv")
defer f.Close()
_, err = io.Copy(f, response.Body)
}
</code></pre>
<p>It has the same functionality as <code>wget $url</code> and takes ~<strong>7.3 seconds</strong> to run (for me). <code>wget</code> takes only ~<strong>4.6 seconds</strong>. Why the huge discrepancy? This trivial Python program, which loads the entire video into memory before writing it to disk, takes around <strong>5.2 seconds</strong>:</p>
<pre><code>import requests
url = "https://upload.wikimedia.org/wikipedia/commons/f/fe/FlumeRide%2C_Liseberg_-_last_steep_POV.ogv"
def main():
r = requests.get(url)
with open('output.ogv','wb') as output:
output.write(r.content)
if __name__ == "__main__":
main()
</code></pre>
<h1>Profiling</h1>
<p>I've investigated this quite a bit. Here are some approaches I've taken:</p>
<ol>
<li>Use different buffer sizes in <code>io.Copy</code></li>
<li>Use other Readers/Writers</li>
<li>Concurrency / parallelism</li>
<li>Downloading larger files</li>
</ol>
<h3>Different buffer sizes</h3>
<p>I tried many different buffer sizes using <code>io.CopyBuffer</code>, and I found that the default buffer size of 32KB leaves me with the best speeds (which are still 1.6 to 1.8 times slower than <code>wget</code> and Python's <code>reqeusts</code>).</p>
<h3>Other Readers/Writers</h3>
<p>All of the other readers and writers were negligibly slower than using <code>io.Copy</code>. I tried using <code>(f *File) Write</code> and some other buffered readers/writers.</p>
<h3>Concurrency / Parallelism</h3>
<p>I even wrote a fairly long program that uses <code>range</code> in headers to download this file in parallel, but as expected I didn't seem any remarkable improvements in speed.</p>
<h3>Larger files</h3>
<p>I downloaded a file more than three times as large as this one, and my Go implementation is still 1.5 to 2 times slower than wget and requests.</p>
<h1>Other Things of Note</h1>
<ol>
<li>I'm building a binary before timing anything.</li>
<li>The vast majority of the time is spent on actually writing/copying <code>response.Body</code>. The part seems to account for all but ~0.3 seconds of elapsed time, regardless of how large the file I'm downloading is.</li>
</ol>
<hr>
<p>So what am I doing wrong? Should I just expect GET requests to take this much longer in Go?</p>
| 3 |
2016-09-22T23:35:31Z
| 39,652,442 |
<p>I'm not sure what to tell you. I just tried to duplicate your findings, but for me, all 3 versions take roughly the same amount of time</p>
<pre><code>wget 8.035s
go 8.174s
python 8.242s
</code></pre>
<p>Maybe try the same experiment inside a clean VM or docker container?</p>
| 3 |
2016-09-23T04:05:24Z
|
[
"python",
"http",
"go",
"wget"
] |
Pandas.read_csv() with special characters (accents) in column names �
| 39,650,407 |
<p>I have a <code>csv</code> file that contains some data with columns names:</p>
<ul>
<li><em>"PERIODE"</em></li>
<li><em>"IAS_brut"</em></li>
<li><em>"IAS_lissé"</em></li>
<li><em>"Incidence_Sentinelles"</em></li>
</ul>
<p>I have a problem with the third one <strong><em>"IAS_lissé"</em></strong> which is misinterpreted by <code>pd.read_csv()</code> method and returned as �.</p>
<p>What is that character?</p>
<p>Because it's generating a bug in my flask application, is there a way to read that column in an other way <strong>without modifying the file?</strong></p>
<pre class="lang-py prettyprint-override"><code>In [1]: import pandas as pd
In [2]: pd.read_csv("Openhealth_S-Grippal.csv",delimiter=";").columns
Out[2]: Index([u'PERIODE', u'IAS_brut', u'IAS_liss�', u'Incidence_Sentinelles'], dtype='object')
</code></pre>
| 1 |
2016-09-22T23:36:12Z
| 39,650,730 |
<p>You can change the <code>encoding</code> parameter for read_csv, see the pandas doc <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#dealing-with-unicode-data" rel="nofollow">here</a>. Also the python standard encodings are <a href="https://docs.python.org/3/library/codecs.html#standard-encodings" rel="nofollow">here</a>. </p>
<p>I believe for your example you can use the <code>utf-8</code> encoding (assuming that your language is French). </p>
<pre><code>df = pd.read_csv("Openhealth_S-Grippal.csv", delimiter=";", encoding='utf-8')
</code></pre>
<hr>
<p>Here's an example showing some sample output. All I did was make a csv file with one column, using the problem characters.</p>
<pre><code>df = pd.read_csv('sample.csv', encoding='utf-8')
</code></pre>
<p>Output:</p>
<pre><code> IAS_lissé
0 1
1 2
2 3
</code></pre>
| 0 |
2016-09-23T00:17:57Z
|
[
"python",
"pandas",
"unicode",
"utf-8",
"special-characters"
] |
'self' parameter in Python non-class functions
| 39,650,515 |
<p>I'm currently teaching some basic Python to an eager primary school student, and I'm having a bit of trouble wrapping my head around a strange little anomaly in this code for an etch-a-sketch.</p>
<pre><code># myEtchASketch application
from tkinter import *
#####Set variables
canvas_height = 400
canvas_width=600
canvas_colour="black"
p1_x=canvas_width/2
p1_y=canvas_height
p1_colour="blue"
line_width=6
line_length=9
####New window
window=Tk()
window.title("MyEtchASketch")
canvas=Canvas(bg=canvas_colour, height=canvas_height, width=canvas_width,highlightthickness=0)
canvas.pack()
##### Functions:
#player controls
def p1_move_N(self):
global p1_y
canvas.create_line(p1_x, p1_y, p1_x, (p1_y-line_length), width=line_width, fill=p1_colour)
p1_y = p1_y - line_length
def p1_move_S(self):
global p1_y
canvas.create_line(p1_x, p1_y, p1_x, (p1_y+line_length), width=line_width, fill=p1_colour)
p1_y=p1_y+line_length
def p1_move_W(self):
global p1_x
canvas.create_line(p1_x, p1_y, (p1_x-line_length), p1_y, width=line_width, fill=p1_colour)
p1_x=p1_x-line_length
def p1_move_E(self):
global p1_x
canvas.create_line(p1_x, p1_y, (p1_x+line_length), p1_y, width=line_width, fill=p1_colour)
p1_x=p1_x+line_length
def erase_all(self):
canvas.delete(ALL)
#bind movement to key presses
window.bind("<Up>", p1_move_N)
window.bind("<Down>",p1_move_S)
window.bind("<Left>", p1_move_W)
window.bind("<Right>", p1_move_E)
window.bind("<u>", erase_all)
window.mainloop()
</code></pre>
<p>The player controls are what's bugging me. The code doesn't work if I don't have <code>self</code> added. I get:</p>
<pre><code>Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\ThisIsNotMyRealUserFolder\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
TypeError: p1_move_N() takes 0 positional arguments but 1 was given
</code></pre>
<p>I've done a bit of research and found that <code>self</code> is used for class methods. As you can see, none of the functions are class methods. The only thing I can think of is that <code>bind()</code> treats all functions passed to it as class methods, meaning they require <code>self</code> to function correctly.</p>
<p>Any and all help is appreciated.</p>
| -2 |
2016-09-22T23:48:00Z
| 39,650,572 |
<p>The callable passed to <code>bind</code> takes one argument: event. So, the correct way to define the function is e.g.:</p>
<pre><code>def p1_move_W(event):
global p1_x
canvas.create_line(p1_x, p1_y, (p1_x-line_length), p1_y, width=line_width, fill=p1_colour)
p1_x=p1_x-line_length
</code></pre>
<p><code>Tk</code> is going to pass one positional argument, so you are free to call the argument anything you want (<code>self</code> works, yes, and <code>banana</code> would work as well).</p>
<p>See also <a href="https://docs.python.org/2/library/tkinter.html#bindings-and-events" rel="nofollow">the documentation for Tk event binding</a>.</p>
| 0 |
2016-09-22T23:56:50Z
|
[
"python",
"class",
"tkinter",
"key-bindings"
] |
making change counter, cant divide coins
| 39,650,539 |
<p>I have to design a program that when an amount of an item is entered, asks the user for the amount paid,and then provides change in 20's 10's 5's 1s quarters, dimes, nickels, and pennies. I've spent hours trying to find the flaws in my code but I can't get it right. If someone could help me out that would be greatly appreciated!</p>
<p>I realize that my code is not very polished, but I just started and haven't learned too many techniques so far.
I have it all working until it hits dimes, then things go bad.</p>
<p>Here is my code at this point:</p>
<pre><code>#assign variables#
import math
cost=float(input("Enter the price of the item: $"))
paid=float(input("Enter the amount paid: $"))
#calculations#
difference=round(paid,2)-round(cost,2)
change= round(difference,2)
#twentys#
remain20=float(change%20)
twent=float(change-remain20)
twent1=abs(float(twent)//20)
twent2=float(twent1*20)
sub1=float(change-float(twent2))
print(sub1,"sub1")
#tens
remain10=change%10
ten=sub1-remain10
ten1=ten//10
ten2=ten1*10
sub2=sub1-ten2
print(sub2,"sub2")
#fives
remain5=float(abs(change%5))
five=abs(float(sub2)-float(abs(remain5)))
five1=float(round(abs(five)//5))
five2=float(round(five*5))
sub3=abs(float(sub2)-abs(float(five2)))
print(sub3,"sub3")
#ones
remain1=change%1
one=abs(round(sub3)-abs(remain1))
one1=abs(round(one//1))
one2=abs(round(one*1))
sub4=abs(float(sub3))-abs(float(one2))
print(sub4,"sub4")
#quarters
remainq=change%(0.25)
remainq1=round(remainq,2)
q=abs(sub4)-(remainq1)
q1=abs(q//float(0.25))
q2=abs(q*0.25)
sub5=abs(float(sub4))-(float(q2))
print(sub5,"sub5")
#dimes
remaind=change%(0.10)
remaind1=round(remaind,2)
d=abs(round(sub5,2)-remaind1)
d1=abs(d//float(0.10))
d2=abs(d1*0.10)
sub6=abs(float(sub5))-abs(float(d2))
print(sub6,"sub6")
#nickles
remainn=change%(0.05)
remainn1=round(remainn,2)
n=abs(round(sub6,2)-abs(remainn1))
n1=abs(d//float(0.05))
n2=abs(d1*0.05)
sub7=float(abs(sub6)-float(n2))
print(sub7,"sub7")
#pennies
remainp=change%(0.01)
remainp1=round(remainp,2)
p=abs(round(sub7,2)-abs(remainp1))
p1=abs(d//float(0.01))
p2=abs(d1*0.01)
#outputs
print(round(twent1),str("Twenty dollar bills"))
print(round(ten1),str("Ten dollar bills"))
print(round(five1),str("Five dollar bills"))
print(round(one1),str("One dollar bills"))
print(round(q1),str("Quarters"))
print(int(d1),str("dimes"))
print(int(n1),str("nickles"))
print(int(p1),str("Pennies"))
</code></pre>
| 1 |
2016-09-22T23:51:22Z
| 39,650,672 |
<pre><code>import math
def to_pennies(amt):
return int(math.floor(amt * 100))
def make_change(amt):
pennies = to_pennies(amt)
twenties = pennies % 2000
pennies -= twenties * 2000
fives = pennies % 500
pennies -= fives * 500
... # Fill in the rest
nickels = pennies % 5
pennies -= nickels * 5
return dict(
twenties=twenties,
fives=fives,
... # fill in the rest
nickels=nickels,
pennies=pennies)
</code></pre>
| -1 |
2016-09-23T00:10:50Z
|
[
"python"
] |
making change counter, cant divide coins
| 39,650,539 |
<p>I have to design a program that when an amount of an item is entered, asks the user for the amount paid,and then provides change in 20's 10's 5's 1s quarters, dimes, nickels, and pennies. I've spent hours trying to find the flaws in my code but I can't get it right. If someone could help me out that would be greatly appreciated!</p>
<p>I realize that my code is not very polished, but I just started and haven't learned too many techniques so far.
I have it all working until it hits dimes, then things go bad.</p>
<p>Here is my code at this point:</p>
<pre><code>#assign variables#
import math
cost=float(input("Enter the price of the item: $"))
paid=float(input("Enter the amount paid: $"))
#calculations#
difference=round(paid,2)-round(cost,2)
change= round(difference,2)
#twentys#
remain20=float(change%20)
twent=float(change-remain20)
twent1=abs(float(twent)//20)
twent2=float(twent1*20)
sub1=float(change-float(twent2))
print(sub1,"sub1")
#tens
remain10=change%10
ten=sub1-remain10
ten1=ten//10
ten2=ten1*10
sub2=sub1-ten2
print(sub2,"sub2")
#fives
remain5=float(abs(change%5))
five=abs(float(sub2)-float(abs(remain5)))
five1=float(round(abs(five)//5))
five2=float(round(five*5))
sub3=abs(float(sub2)-abs(float(five2)))
print(sub3,"sub3")
#ones
remain1=change%1
one=abs(round(sub3)-abs(remain1))
one1=abs(round(one//1))
one2=abs(round(one*1))
sub4=abs(float(sub3))-abs(float(one2))
print(sub4,"sub4")
#quarters
remainq=change%(0.25)
remainq1=round(remainq,2)
q=abs(sub4)-(remainq1)
q1=abs(q//float(0.25))
q2=abs(q*0.25)
sub5=abs(float(sub4))-(float(q2))
print(sub5,"sub5")
#dimes
remaind=change%(0.10)
remaind1=round(remaind,2)
d=abs(round(sub5,2)-remaind1)
d1=abs(d//float(0.10))
d2=abs(d1*0.10)
sub6=abs(float(sub5))-abs(float(d2))
print(sub6,"sub6")
#nickles
remainn=change%(0.05)
remainn1=round(remainn,2)
n=abs(round(sub6,2)-abs(remainn1))
n1=abs(d//float(0.05))
n2=abs(d1*0.05)
sub7=float(abs(sub6)-float(n2))
print(sub7,"sub7")
#pennies
remainp=change%(0.01)
remainp1=round(remainp,2)
p=abs(round(sub7,2)-abs(remainp1))
p1=abs(d//float(0.01))
p2=abs(d1*0.01)
#outputs
print(round(twent1),str("Twenty dollar bills"))
print(round(ten1),str("Ten dollar bills"))
print(round(five1),str("Five dollar bills"))
print(round(one1),str("One dollar bills"))
print(round(q1),str("Quarters"))
print(int(d1),str("dimes"))
print(int(n1),str("nickles"))
print(int(p1),str("Pennies"))
</code></pre>
| 1 |
2016-09-22T23:51:22Z
| 39,650,778 |
<p>I'd recommend you to avoid using floating point numbers if the problem can be solved with integers. Think about it, in this particular problem you can convert all ammounts into pennies (multiplied by 100). That way the solution becomes straightforward, for instance:</p>
<pre><code>def distribute(value):
result = {
2000: [0, "Twenty dollar"],
1000: [0, "Ten dollar"],
500: [0, "Five dollar"],
100: [0, "One dollar"],
25: [0, "Quarters"],
10: [0, "dimes"],
5: [0, "nickles"],
1: [0, "Pennies"]
}
if value < 0:
print("Not enough money... you need {0}$ more".format(abs(value)))
elif value == 0:
print("Thanks for buying in the shop!")
else:
pennies = value * 100
for k in reversed(sorted(result.keys())):
if k < pennies:
result[k][0] = num_coins = int(pennies / k)
print("{0} {1}{2}".format(
num_coins, result[k][1], " bills" if k >= 100 else ""))
pennies -= num_coins * k
return result
if __name__ == "__main__":
try:
print("---------------------------")
print(" Welcome to shopping 0.0.1 ")
print("---------------------------")
cost = int(input("Enter the price of the item: $"))
paid = int(input("Enter the amount paid: $"))
summary = distribute(paid - cost)
except Exception as e:
print("Something unexpected happened! {0}".format(e))
</code></pre>
| 1 |
2016-09-23T00:24:17Z
|
[
"python"
] |
making change counter, cant divide coins
| 39,650,539 |
<p>I have to design a program that when an amount of an item is entered, asks the user for the amount paid,and then provides change in 20's 10's 5's 1s quarters, dimes, nickels, and pennies. I've spent hours trying to find the flaws in my code but I can't get it right. If someone could help me out that would be greatly appreciated!</p>
<p>I realize that my code is not very polished, but I just started and haven't learned too many techniques so far.
I have it all working until it hits dimes, then things go bad.</p>
<p>Here is my code at this point:</p>
<pre><code>#assign variables#
import math
cost=float(input("Enter the price of the item: $"))
paid=float(input("Enter the amount paid: $"))
#calculations#
difference=round(paid,2)-round(cost,2)
change= round(difference,2)
#twentys#
remain20=float(change%20)
twent=float(change-remain20)
twent1=abs(float(twent)//20)
twent2=float(twent1*20)
sub1=float(change-float(twent2))
print(sub1,"sub1")
#tens
remain10=change%10
ten=sub1-remain10
ten1=ten//10
ten2=ten1*10
sub2=sub1-ten2
print(sub2,"sub2")
#fives
remain5=float(abs(change%5))
five=abs(float(sub2)-float(abs(remain5)))
five1=float(round(abs(five)//5))
five2=float(round(five*5))
sub3=abs(float(sub2)-abs(float(five2)))
print(sub3,"sub3")
#ones
remain1=change%1
one=abs(round(sub3)-abs(remain1))
one1=abs(round(one//1))
one2=abs(round(one*1))
sub4=abs(float(sub3))-abs(float(one2))
print(sub4,"sub4")
#quarters
remainq=change%(0.25)
remainq1=round(remainq,2)
q=abs(sub4)-(remainq1)
q1=abs(q//float(0.25))
q2=abs(q*0.25)
sub5=abs(float(sub4))-(float(q2))
print(sub5,"sub5")
#dimes
remaind=change%(0.10)
remaind1=round(remaind,2)
d=abs(round(sub5,2)-remaind1)
d1=abs(d//float(0.10))
d2=abs(d1*0.10)
sub6=abs(float(sub5))-abs(float(d2))
print(sub6,"sub6")
#nickles
remainn=change%(0.05)
remainn1=round(remainn,2)
n=abs(round(sub6,2)-abs(remainn1))
n1=abs(d//float(0.05))
n2=abs(d1*0.05)
sub7=float(abs(sub6)-float(n2))
print(sub7,"sub7")
#pennies
remainp=change%(0.01)
remainp1=round(remainp,2)
p=abs(round(sub7,2)-abs(remainp1))
p1=abs(d//float(0.01))
p2=abs(d1*0.01)
#outputs
print(round(twent1),str("Twenty dollar bills"))
print(round(ten1),str("Ten dollar bills"))
print(round(five1),str("Five dollar bills"))
print(round(one1),str("One dollar bills"))
print(round(q1),str("Quarters"))
print(int(d1),str("dimes"))
print(int(n1),str("nickles"))
print(int(p1),str("Pennies"))
</code></pre>
| 1 |
2016-09-22T23:51:22Z
| 39,650,893 |
<p>Your primary problem is that monetary calculations (and remainder operations) don't work so well with <code>float</code>. Convert to an <code>int</code> number of pennies up front, and most sources of error disappear (as long as you round properly).</p>
<p>You can also simplify the code a lot. Right now, every denomination is its own special case, even though the work is fundamentally the same for all of them aside from the string name and the unit. Generalize the code, and you can simplify it all down to a simple loop with a couple (constant, top-level) <code>tuple</code>s defining the parts that actually change:</p>
<pre><code># These are the only thing that differ as you go, so just list them explicitly
denominations = ('Twenty dollar bills', 'Ten dollar bills', 'Five dollar bills', 'One dollar bills', 'quarters', 'dimes', 'nickels', 'pennies')
divisors = (2000, 1000, 500, 100, 25, 10, 5, 1)
def make_change(paid, cost):
'''paid and cost should be floats with up to two decimal places of precision'''
# Calculate the difference in price, then convert to an int penny count
# so we can use accurate math
change = round((paid - cost) * 100) # Wrap round in int constructor on Py2
# Not necessary if inputs are trusted, but good form
if change < 0: raise ValueError("Underpaid!")
# Each loop replaces a special case from your code by swapping in the
# string and divisor for that round
for denom, div in zip(denominations, divisors):
numdenom, change = divmod(change, div)
# Conditional print; weird to say "0 fives", "0 ones" over and over
# You can print unconditionally if you prefer
if numdenom:
print(numdenom, denom)
</code></pre>
<p>That's it. The whole of the calculation is (ignoring comments and blank lines) two constant definitions and seven lines of actual code.</p>
| 0 |
2016-09-23T00:42:10Z
|
[
"python"
] |
Convert a simple command into an AST in python
| 39,650,579 |
<p>I would like a function in Python that converts a string command into an AST (Abstract Syntax Tree).</p>
<p>The syntax for the command is as follows:</p>
<pre><code>commandName(3, "hello", 5.0, x::int)
</code></pre>
<p>A command can accept any number of comma separated values that can be either</p>
<ol>
<li>Integers</li>
<li>Strings</li>
<li>Floats</li>
<li>Types</li>
</ol>
<p>Suppose the function is called <code>convert_to_ast</code>, then</p>
<pre><code>convert_to_ast('commandName(3, "hello", 5.0, x::int)')
</code></pre>
<p>Should yield the following AST:</p>
<pre><code>{
'type': 'command',
'name': 'commandName',
'args': [{
'type': 'int',
'value': 3
}, {
'type': 'str',
'value': 'Hello'
}, {
'type': 'float',
'value': 5.0
}, {
'type': 'var',
'kind': 'int',
'name': 'x
}]
</code></pre>
| 0 |
2016-09-22T23:57:20Z
| 39,650,641 |
<p>Seems like you could just evaluate the string and then pick off the types from there:</p>
<pre><code>>>> items = ast.literal_eval('(404.5, "Hello", 5)')
>>> [{'type': type(item).__name__, 'value': item} for item in items]
[{'type': 'float', 'value': 404.5}, {'type': 'str', 'value': 'Hello'}, {'type': 'int', 'value': 5}]
</code></pre>
<p>Of course, if you want to do more interesting things, you can access the AST directly:</p>
<pre><code>>>> ast.dump(ast.parse('(404.5, "Hello", 5)'))
"Module(body=[Expr(value=Tuple(elts=[Num(n=404.5), Str(s='Hello'), Num(n=5)], ctx=Load()))])"
>>> ast.parse('(404.5, "Hello", 5)').body[0].value.elts
[<_ast.Num object at 0x107fa1250>, <_ast.Str object at 0x107fa1290>, <_ast.Num object at 0x107fa12d0>]
</code></pre>
<p>For a more general thing than parsing a tuple (as you've added to the question), we still can use python's AST to parse this (as long as your syntax <em>is</em> valid python). In this case, we'll create an <code>ast.NodeVisitor</code> which will pull out the information that we as it visits each node of the python AST that we care about. In this case, we care about <code>Call</code>, <code>Num</code>, <code>Str</code> and <code>Name</code> nodes:</p>
<pre><code>import ast
class Parser(ast.NodeVisitor):
def __init__(self):
self.calls = []
self.current_command = None
def visit_Call(self, node):
name = node.func.id
self.current_command = {
'type': 'command',
'name': name,
'args': []
}
self.calls.append(self.current_command)
for arg in node.args:
self.visit(arg)
self.current_command = None
def visit_Num(self, node):
if not self.current_command:
return
args = self.current_command['args']
arg = {
'type': type(node.n).__name__,
'value': node.n
}
args.append(arg)
def visit_Str(self, node):
if not self.current_command:
return
args = self.current_command['args']
arg = {
'type': 'str',
'value': node.s
}
args.append(arg)
def visit_Name(self, node):
if not self.current_command:
return
args = self.current_command['args']
arg = {
'type': 'type',
'kind': node.id
}
args.append(arg)
S = 'commandName(3, "hello", 5.0, int)'
tree = ast.parse(S)
p = Parser()
p.visit(tree)
print p.calls
</code></pre>
| 5 |
2016-09-23T00:05:03Z
|
[
"python",
"parsing",
"abstract-syntax-tree",
"pyparsing"
] |
sentry-youtrack plugin: PicklingError: Can't pickle <type 'generator'>: attribute lookup __builtin__.generator failed
| 39,650,623 |
<ul>
<li>sentry: 8.4.0</li>
<li>sentry-youtrack plugin: 0.3.1</li>
<li>youtrack-6.5.17105</li>
<li>python-memcached: 1.53</li>
</ul>
<p>I'm trying to integrate <a href="https://www.jetbrains.com/youtrack/" rel="nofollow">youtrack</a> into <a href="https://github.com/getsentry/sentry" rel="nofollow">sentry</a> using <a href="https://github.com/bogdal/sentry-youtrack" rel="nofollow">this</a> plugin.</p>
<p>The problem is the page seems to hang when we click More --> Create YouTrack Issue. Looking at the syslog, I saw this:</p>
<pre><code>Traceback (most recent call last):
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../django/core/handlers/base.py", line 112, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../django/utils/decorators.py", line 29, in _wrapper
return bound_func(*args, **kwargs)
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../django/utils/decorators.py", line 99, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../django/utils/decorators.py", line 25, in bound_func
return func(self, *args2, **kwargs2)
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/web/frontend/base.py", line 172, in dispatch
return self.handle(request, *args, **kwargs)
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/web/frontend/group_plugin_action.py", line 25, in handle
response = plugin.get_view_response(request, group)
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../sentry_youtrack/plugin.py", line 113, in get_view_response
return super(YouTrackPlugin, self).get_view_response(request, group)
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/plugins/base/v1.py", line 296, in get_view_response
response = self.view(request, group)
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../sentry_youtrack/plugin.py", line 131, in view
return view(request, group, **kwargs)
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/plugins/bases/issue.py", line 169, in view
form = self.get_new_issue_form(request, group, event)
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../sentry_youtrack/plugin.py", line 77, in get_new_issue_form
project_fields=self.get_project_fields(group.project),
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../sentry_youtrack/plugin.py", line 57, in get_project_fields
return cached_fields(self.get_option('ignore_fields', project))
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../sentry_youtrack/utils.py", line 16, in wrapper
cache.set(key, result, timeout)
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../django/core/cache/backends/memcached.py", line 82, in set
self._cache.set(key, value, self._get_memcache_timeout(timeout))
File "/usr/local/sentry/local/lib/python2.7/site-packages/memcache.py", line 740, in set
return self._set("set", key, val, time, min_compress_len, noreply)
File "/usr/local/sentry/local/lib/python2.7/site-packages/memcache.py", line 1060, in _set
return _unsafe_set()
File "/usr/local/sentry/local/lib/python2.7/site-packages/memcache.py", line 1034, in _unsafe_set
store_info = self._val_to_store_info(val, min_compress_len)
File "/usr/local/sentry/local/lib/python2.7/site-packages/memcache.py", line 998, in _val_to_store_info
pickler.dump(val)
PicklingError: Can't pickle <type 'generator'>: attribute lookup __builtin__.generator failed
</code></pre>
<p>Follow the traceback (<a href="https://github.com/bogdal/sentry-youtrack/blob/master/sentry_youtrack/utils.py#L6" rel="nofollow">https://github.com/bogdal/sentry-youtrack/blob/master/sentry_youtrack/utils.py#L6</a>):</p>
<pre><code>def cache_this(timeout=60):
def decorator(func):
def wrapper(*args, **kwargs):
def get_cache_key(*args, **kwargs):
params = list(args) + kwargs.values()
return md5("".join(map(str, params))).hexdigest()
key = get_cache_key(func.__name__, *args, **kwargs)
result = cache.get(key)
if not result:
result = func(*args, **kwargs)
cache.set(key, result, timeout)
return result
return wrapper
return decorator
</code></pre>
<p>I understand that we got this error because <code>result</code> is a generator.</p>
<p><a href="https://github.com/bogdal/sentry-youtrack/blob/master/sentry_youtrack/plugin.py#L51" rel="nofollow">https://github.com/bogdal/sentry-youtrack/blob/master/sentry_youtrack/plugin.py#L51</a>:</p>
<pre><code>def get_project_fields(self, project):
@cache_this(600)
def cached_fields(ignore_fields):
yt_client = self.get_youtrack_client(project)
return yt_client.get_project_fields(
self.get_option('project', project), ignore_fields)
return cached_fields(self.get_option('ignore_fields', project))
</code></pre>
<p><a href="https://github.com/bogdal/sentry-youtrack/blob/master/sentry_youtrack/youtrack.py#L198" rel="nofollow">https://github.com/bogdal/sentry-youtrack/blob/master/sentry_youtrack/youtrack.py#L198</a>:</p>
<pre><code>def get_project_fields(self, project_id, ignore_fields=None):
ignore_fields = ignore_fields or []
for field in self.get_project_fields_list(project_id):
if not field['name'] in ignore_fields:
yield self._get_custom_project_field_details(field)
</code></pre>
<p>So, I'm trying to convert it into a list:</p>
<pre><code> if not result:
result = func(*args, **kwargs)
cache.set(key, [f for f in result], timeout)
return result
</code></pre>
<p>but still got the same error:</p>
<pre><code> File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../sentry_youtrack/utils.py", line 16, in wrapper
cache.set(key, [f for f in result], timeout)
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../django/core/cache/backends/memcached.py", line 82, in set
self._cache.set(key, value, self._get_memcache_timeout(timeout))
File "/usr/local/sentry/local/lib/python2.7/site-packages/memcache.py", line 740, in set
return self._set("set", key, val, time, min_compress_len, noreply)
File "/usr/local/sentry/local/lib/python2.7/site-packages/memcache.py", line 1060, in _set
return _unsafe_set()
File "/usr/local/sentry/local/lib/python2.7/site-packages/memcache.py", line 1034, in _unsafe_set
store_info = self._val_to_store_info(val, min_compress_len)
File "/usr/local/sentry/local/lib/python2.7/site-packages/memcache.py", line 998, in _val_to_store_info
pickler.dump(val)
PicklingError: Can't pickle <type 'generator'>: attribute lookup __builtin__.generator failed
</code></pre>
<p>Then I tried to log the value of <code>val</code> into a file:</p>
<pre><code> try:
pickler.dump(val)
except Exception:
with open('/tmp/quanta.log', 'a+') as f:
f.write(str(val))
</code></pre>
<p>but that file is not created. And the strange thing is the traceback said that the error happened at the same line as before:</p>
<pre><code> File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../sentry_youtrack/utils.py", line 16, in wrapper
cache.set(key, [f for f in result], timeout)
File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../django/core/cache/backends/memcached.py", line 82, in set
self._cache.set(key, value, self._get_memcache_timeout(timeout))
File "/usr/local/sentry/local/lib/python2.7/site-packages/memcache.py", line 740, in set
return self._set("set", key, val, time, min_compress_len, noreply)
File "/usr/local/sentry/local/lib/python2.7/site-packages/memcache.py", line 1060, in _set
msg = msg[1]
File "/usr/local/sentry/local/lib/python2.7/site-packages/memcache.py", line 1034, in _unsafe_set
File "/usr/local/sentry/local/lib/python2.7/site-packages/memcache.py", line 998, in _val_to_store_info
try:
PicklingError: Can't pickle <type 'generator'>: attribute lookup __builtin__.generator failed
</code></pre>
<p>So, I have two questions:</p>
<ol>
<li>Why the error still said that <code>Can't pickle <type 'generator'>...</code> while it had been converted to a list?</li>
<li>How can I debug this situation to know the value of <code>val</code> before calling <code>pickler.dump(val)</code>?</li>
</ol>
| 1 |
2016-09-23T00:02:55Z
| 39,663,322 |
<p>This is a bug for sentry-youtrack, it should not cache a generator object. python-memcached might have a pyc file, that's why it did not dump the value like you modified. And you added (i for i in list) which also is a generator.</p>
<p>You should use getsentry/sentry-youtrack since it has the <a href="https://github.com/getsentry/sentry-youtrack/commit/7989f3db695e2a7b3bf0eff18b6e4140d27e8d0f" rel="nofollow">correct fix</a> for caching generator. </p>
| 2 |
2016-09-23T14:30:07Z
|
[
"python",
"django",
"generator",
"sentry",
"youtrack"
] |
How to convert a string list to integer in python?
| 39,650,735 |
<p>I have the following list of values:</p>
<pre><code>DATA = [['5', '1'], ['5', '5'], ['3', '1'], ['6', '1'], ['4', '3']]
</code></pre>
<p>How can I convert it to :</p>
<pre><code>DATA = [[5, 1], [5, 5], [3, 1], [6, 1], [4, 3]]
</code></pre>
<p>Note : I have already tried the following but all are not working in <strong>Python 3</strong> :</p>
<pre><code> 1. DATA = [int(i) for i in DATA]
2. DATA = list(list(int(a) for a in b) for b in DA if a.isdigit())
3. DATA = [map(int,x) for x in DATA]
</code></pre>
<p>Please help me with this. Thanks!!</p>
| 3 |
2016-09-23T00:18:39Z
| 39,650,771 |
<p>Your third one is actually correct. In Python 3 <a href="https://docs.python.org/3/library/functions.html#map">map</a> returns a map object, so you just have to call <code>list</code> on it to get a <em>list</em>. </p>
<pre><code>DATA = [['5', '1'], ['5', '5'], ['3', '1'], ['6', '1'], ['4', '3']]
d = [list(map(int, x)) for x in DATA]
# Output:
# [[5, 1], [5, 5], [3, 1], [6, 1], [4, 3]]
# type of one of the items in the sublist
# print(type(d[0][0])
# <class 'int'>
</code></pre>
| 5 |
2016-09-23T00:23:36Z
|
[
"python",
"python-3.x"
] |
Group by sparse matrix in scipy and return a matrix
| 39,650,749 |
<p>There are a few questions on SO dealing with using <code>groupby</code> with sparse matrices. However the output seem to be lists, <a href="http://stackoverflow.com/questions/35410839/group-by-on-scipy-sparse-matrix">dictionaries</a>, <a href="http://stackoverflow.duapp.com/questions/30295570/groupby-sum-sparse-matrix-in-pandas-or-scipy-looking-for-performance?rq=1" rel="nofollow">dataframes</a> and other objects. </p>
<p>I'm working on an NLP problem and would like to keep all the data in sparse scipy matrices during processing to prevent memory errors.</p>
<p>Here's the context:</p>
<p>I have vectorized some documents (<a href="http://andrewbrown.ca/data/groupbysparsematrix%20.csv" rel="nofollow">sample data here</a>): </p>
<pre><code>import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
df = pd.read_csv('groupbysparsematrix.csv')
docs = df['Text'].tolist()
vectorizer = CountVectorizer()
train_X = vectorizer.fit_transform(docs)
print("Dimensions of training set: {0}".format(train_X.shape))
print type(train_X)
Dimensions of training set: (8, 180)
<class 'scipy.sparse.csr.csr_matrix'>
</code></pre>
<p>From the original dataframe I use the date, in a day of the year format, to create the groups I would like to sum over:</p>
<pre><code>from scipy import sparse, hstack
df['Date'] = pd.to_datetime(df['Date'])
groups = df['Date'].apply(lambda x: x.strftime('%j'))
groups_X = sparse.csr_matrix(groups.astype(float)).T
train_X_all = sparse.hstack((train_X, groups_X))
print("Dimensions of concatenated set: {0}".format(train_X_all.shape))
Dimensions of concatenated set: (8, 181)
</code></pre>
<p>Now I'd like to apply <code>groupby</code> (or a similar function) to find the sum of each token per day. I would like the output to be another sparse scipy matrix. </p>
<p>The output matrix would be 3 x 181 and look something like this:</p>
<pre><code> 1, 1, 1, ..., 2, 1, 3
2, 1, 3, ..., 1, 1, 4
0, 0, 0, ..., 1, 2, 5
</code></pre>
<p>Where the columns 1 to 180 represent the tokens and column 181 represents the day of the year.</p>
| 1 |
2016-09-23T00:20:38Z
| 39,651,444 |
<p>The best way of calculating the sum of selected columns (or rows) of a <code>csr</code> sparse matrix is a matrix product with another sparse matrix that has 1's where you want to sum. In fact <code>csr</code> sum (for a whole row or column) works by matrix product, and index rows (or columns) is also done with a product (<a href="http://stackoverflow.com/a/39500986/901925">http://stackoverflow.com/a/39500986/901925</a>)</p>
<p>So I'd group the dates array, and use that information to construct the summing 'mask'.</p>
<p>For sake of discussion, consider this dense array:</p>
<pre><code>In [117]: A
Out[117]:
array([[0, 2, 7, 5, 0, 7, 0, 8, 0, 7],
[0, 0, 3, 0, 0, 1, 2, 6, 0, 0],
[0, 0, 0, 0, 2, 0, 5, 0, 0, 0],
[4, 0, 6, 0, 0, 5, 0, 0, 1, 4],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 7, 0, 8, 1, 0, 9, 0, 2, 4],
[9, 0, 8, 4, 0, 0, 0, 0, 9, 7],
[0, 0, 0, 1, 2, 0, 2, 0, 4, 7],
[3, 0, 1, 0, 0, 0, 0, 0, 0, 2],
[0, 0, 1, 8, 5, 0, 0, 0, 8, 0]])
</code></pre>
<p>Make a sparse copy:</p>
<pre><code>In [118]: M=sparse.csr_matrix(A)
</code></pre>
<p>generate some groups, based on the last column; <code>collections.defaultdict</code> is a convenient tool to do this:</p>
<pre><code>In [119]: grps=defaultdict(list)
In [120]: for i,v in enumerate(A[:,-1]):
...: grps[v].append(i)
In [121]: grps
Out[121]: defaultdict(list, {0: [1, 2, 4, 9], 2: [8], 4: [3, 5], 7: [0, 6, 7]})
</code></pre>
<p>I can iterate on those groups, collect rows of <code>M</code>, sum across those rows and produce:</p>
<pre><code>In [122]: {k:M[v,:].sum(axis=0) for k, v in grps.items()}
Out[122]:
{0: matrix([[0, 0, 4, 8, 7, 2, 7, 6, 8, 0]], dtype=int32),
2: matrix([[3, 0, 1, 0, 0, 0, 0, 0, 0, 2]], dtype=int32),
4: matrix([[4, 7, 6, 8, 1, 5, 9, 0, 3, 8]], dtype=int32),
7: matrix([[ 9, 2, 15, 10, 2, 7, 2, 8, 13, 21]], dtype=int32)}
</code></pre>
<p>In the last column, values include 2*4, and 3*7</p>
<p>So there are 2 tasks - collecting the groups, whether with this defaultdict, or <code>itertools.groupby</code> (which in this case would require sorting), or <code>pandas</code> groupby. And secondly this collection of rows and summing. This dictionary iteration is conceptually simple. </p>
<p>A masking matrix might work like this:</p>
<pre><code>In [141]: mask=np.zeros((10,10),int)
In [142]: for i,v in enumerate(A[:,-1]): # same sort of iteration
...: mask[v,i]=1
...:
In [143]: Mask=sparse.csr_matrix(mask)
...
In [145]: Mask.A
Out[145]:
array([[0, 1, 1, 0, 1, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
....
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int32)
In [146]: (Mask*M).A
Out[146]:
array([[ 0, 0, 4, 8, 7, 2, 7, 6, 8, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 3, 0, 1, 0, 0, 0, 0, 0, 0, 2],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 4, 7, 6, 8, 1, 5, 9, 0, 3, 8],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 9, 2, 15, 10, 2, 7, 2, 8, 13, 21],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int32)
</code></pre>
<p>This <code>Mask*M</code> has the same values as the dictionary row, but with the extra 0s. I can isolate the nonzero values with the <code>lil</code> format:</p>
<pre><code>In [147]: (Mask*M).tolil().data
Out[147]:
array([[4, 8, 7, 2, 7, 6, 8], [], [3, 1, 2], [],
[4, 7, 6, 8, 1, 5, 9, 3, 8], [], [],
[9, 2, 15, 10, 2, 7, 2, 8, 13, 21], [], []], dtype=object)
</code></pre>
<p>I can construct the <code>Mask</code> matrix directly using the <code>coo</code> sparse style of input:</p>
<pre><code>Mask = sparse.csr_matrix((np.ones(A.shape[0],int),
(A[:,-1], np.arange(A.shape[0]))), shape=(A.shape))
</code></pre>
<p>That should be faster and avoid the memory error (no loop or large dense array).</p>
| 1 |
2016-09-23T02:02:45Z
|
[
"python",
"matrix",
"scipy",
"nlp"
] |
How can I "jump" into stackframe from exception?
| 39,650,793 |
<p>Having a raised <code>exception</code> I would like to jump into that frame. To explain better what I mean I wrote this mwe:</p>
<p>Assuming I have the following code:</p>
<pre><code>from multiprocessing import Pool
import sys
# Setup debugger
def raiseDebugger(*args):
""" http://code.activestate.com/recipes/65287-automatically-start-the-
debugger-on-an-exception/ """
import traceback, pdb
traceback.print_exception(*args)
pdb.pm()
sys.excepthook = raiseDebugger
# Now start with the question
def faulty(i):
return 1 / i
with Pool() as pool:
pool.map(faulty, range(6))
</code></pre>
<p>which unsurprisingly leads to:</p>
<pre><code>multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
File "/home/bin/conda/lib/python3.5/multiprocessing/pool.py", line 119, in worker
result = (True, func(*args, **kwds))
File "/home/bin/conda/lib/python3.5/multiprocessing/pool.py", line 44, in mapstar
return list(map(*args))
File "test2.py", line 19, in faulty
return 1 / i
ZeroDivisionError: division by zero
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "test2.py", line 23, in <module>
pool.map(faulty, range(6))
File "/home/bin/conda/lib/python3.5/multiprocessing/pool.py", line 260, in map
return self._map_async(func, iterable, mapstar, chunksize).get()
File "/home/bin/conda/lib/python3.5/multiprocessing/pool.py", line 608, in get
raise self._value
ZeroDivisionError: division by zero
> /home/bin/conda/lib/python3.5/multiprocessing/pool.py(608)get()
-> raise self._value
(Pdb)
</code></pre>
<p>Now to debug the problem I would like to "jump" into the frame which originally raised the <code>exception</code> (<code>ZeroDivisionError</code>). </p>
<p>The original exception is still available under <code>self._value</code> complete with <code>self._value.__traceback__</code>.</p>
| 1 |
2016-09-23T00:26:12Z
| 39,651,127 |
<p>The call that <code>pm</code> (or <code>post_mortem</code>) calls is from the value field of <a href="https://docs.python.org/3/library/sys.html#sys.exc_info" rel="nofollow"><code>sys.exc_info</code></a>, and the default invocation of <code>post_mortem</code> is done on the <code>__traceback__</code> of that value. However if you want to get to the underlying object, you want to access its <code>__context__</code> instead. Given this code example:</p>
<pre><code>import pdb
import sys
import traceback
def top():
value = 1
raise Exception('this always fails')
def bottom():
try:
top()
except Exception as bot_ex:
x = {}
return x['nothing']
try:
bottom()
except Exception as main_ex:
pdb.post_mortem()
</code></pre>
<p>Running the code. The <code>main_ex</code> would be analogous to your <code>self._value</code>.</p>
<pre><code>> /tmp/foo.py(14)bottom()
-> return x['nothing']
(Pdb) main_ex
KeyError('nothing',)
(Pdb) pdb.post_mortem(main_ex.__traceback__)
> /tmp/foo.py(14)bottom()
-> return x['nothing']
</code></pre>
<p>Note we have a new pdb prompt at the same location, which is where the exception was originally raised. Let's try it with <code>__context__</code> if we need to go further up:</p>
<pre><code>(Pdb) c
(Pdb) pdb.post_mortem(main_ex.__context__.__traceback__)
> /tmp/foo.py(7)top()
-> raise Exception('this always fails')
</code></pre>
<p>If needed, keep repeating until you get to the target context/traceback desired.</p>
<hr>
<p>Now for the multiprocessing case, which I wasn't aware would have made this much difference, as the question implies something general (How can I âjumpâ into stackframe from exception?), but it turns out the specifics in <code>multiprocessing</code> made all the difference.</p>
<p>In Python 3.4 a workaround was done to just show that traceback as a string; due to how much stuff a traceback actually has, communicating all that proved to be difficult as discussed in the <a href="http://bugs.python.org/issue13831Ups" rel="nofollow">issue 13831</a> on the Python tracker, so instead a hack was done to bring a <code>__cause__</code> attribute into the current exception, but it is no full <code>__traceback__</code> as it just has the string representation of that, as I had suspected.</p>
<p>Anyway this is what would have happened:</p>
<pre><code>(Pdb) !import pdb
(Pdb) !self._value.__cause__
RemoteTraceback('\n"""\nTraceback (most recent call last):...',)
(Pdb) !type(self._value.__cause__)
<class 'multiprocessing.pool.RemoteTraceback'>
(Pdb) !self._value.__cause__.__traceback__
(Pdb) !self._value.__cause__.__context__
</code></pre>
<p>So this isn't actually possible until they figure out how to bring all those states across process boundaries.</p>
| 1 |
2016-09-23T01:18:27Z
|
[
"python",
"python-3.x",
"debugging",
"exception"
] |
Python: multiplying 'for i in range(..) iteration'
| 39,650,852 |
<p>So I have an assignment where I am required to return <code>inf</code> by multiplying <code>x</code> by 10 multiple times using a:</p>
<pre><code>for i in range(...)
</code></pre>
<p>so the main part of my code is:</p>
<pre><code> def g(x):
x = 10.*x
for i in range(308):
return x
</code></pre>
<p>and if I enter </p>
<pre><code> >>> g(3.)
>>> 30.0
</code></pre>
<p>I expected it to iterate it 308 times to the point where I get <code>inf</code>. Is there a line I can use that uses the number in the <code>for i in range(..)</code> to iterate the equation that many times? For example:</p>
<pre><code> def g(x):
x = 2.*x
for i in range(3):
# the mystery line I need for it to work
return x
>>> g(4.)
>>> 16.0
</code></pre>
<p>but it doesn't give me that. Rather it returns <code>8.0</code></p>
<p>Another way I did it that actually made it work was using print. But I don't think it's valid using a print statement in an assignment asking to <code>return inf</code>. </p>
| -2 |
2016-09-23T00:35:42Z
| 39,650,979 |
<p>The reason it isn't iterating like you expect is because of the <code>return</code> statement. <code>return</code> exits from whatever procedure/function that you are running immediately and returns the value given to it. Here is a walk through of your first function, assuming it was called with the value of <code>4</code> as in <code>g(4.)</code>. </p>
<pre><code># the start of the function
# x = 10
# this line sets x = 100. I think you can see why.
x = 10. * x
# this sets i = 0 and begins to loop
for i in range(308):
# this IMMEDIATELY returns from the function with the value
# of x. At this point, x = 100. It does not continue looping!
# Without this line, i would be set to 1, 2, 3, ..., 307 as
# you loop through the range. This is why it worked with print.
return x
</code></pre>
<p>What you want instead of this is something that will accumulate the value of the repeated multiplications. You don't want to return anything at all within the loop, assuming you want every iteration to run. I will not give you the exact answer because this is homework but I will give a hint. You probably do not want <code>return</code> to be indented, as it is in the second bit of code you provided. You probably want something more like this:</p>
<pre><code>def g(x):
x = 2 * x
for i in range(3):
# { your code here }
# You want to accumulate the value!
return x
</code></pre>
| 0 |
2016-09-23T00:54:35Z
|
[
"python",
"python-3.x"
] |
Python: multiplying 'for i in range(..) iteration'
| 39,650,852 |
<p>So I have an assignment where I am required to return <code>inf</code> by multiplying <code>x</code> by 10 multiple times using a:</p>
<pre><code>for i in range(...)
</code></pre>
<p>so the main part of my code is:</p>
<pre><code> def g(x):
x = 10.*x
for i in range(308):
return x
</code></pre>
<p>and if I enter </p>
<pre><code> >>> g(3.)
>>> 30.0
</code></pre>
<p>I expected it to iterate it 308 times to the point where I get <code>inf</code>. Is there a line I can use that uses the number in the <code>for i in range(..)</code> to iterate the equation that many times? For example:</p>
<pre><code> def g(x):
x = 2.*x
for i in range(3):
# the mystery line I need for it to work
return x
>>> g(4.)
>>> 16.0
</code></pre>
<p>but it doesn't give me that. Rather it returns <code>8.0</code></p>
<p>Another way I did it that actually made it work was using print. But I don't think it's valid using a print statement in an assignment asking to <code>return inf</code>. </p>
| -2 |
2016-09-23T00:35:42Z
| 39,651,079 |
<p>I think you have the right parts, just not arranged correctly. Try something like this:</p>
<pre><code>def g(x):
for i in range(308):
x = 10.*x # because we've moved this line into the loop, it gets run 308 times
return x # since we've unindented this line, it runs only once (after the loop ends)
</code></pre>
<p>The part you want to be repeated needs to be indented after the line with the <code>for</code> statement. Stuff you don't want repeated (like the <code>return</code>, which can only happen once), should not be in the loop.</p>
| 0 |
2016-09-23T01:09:57Z
|
[
"python",
"python-3.x"
] |
tkinter window/frame blinks on button click
| 39,650,869 |
<p>This is a tkinter program with a start/stop button to enter and exit an infinite loop that logs to a text logger widget. I cannot for the life of me figure out why, but only when the start <em>button</em> is pressed, the frame blinks/flashes, but the function runs fine. When I select start from the file menu, there is no flash... any ideas as to why this may be? Is it a bug in my code? </p>
<pre><code>import tkinter as tk
import tkinter.scrolledtext as tkst
from tkinter import ttk
import logging
def popupmsg(msg):
popup = tk.Tk()
popup.wm_title("!")
label = ttk.Label(popup, text=msg)
label.pack(side="top", fill="x", pady=10)
b1 = ttk.Button(popup, text="Okay", command=popup.destroy)
b1.pack()
popup.mainloop()
class TextHandler(logging.Handler):
def __init__(self, text):
# run the regular Handler __init__
logging.Handler.__init__(self)
# Store a reference to the Text it will log to
self.text = text
def emit(self, record):
msg = self.format(record)
def append():
self.text.configure(state='normal')
self.text.insert(tk.END, msg + '\n')
self.text.configure(state='disabled')
# Autoscroll to the bottom
self.text.yview(tk.END)
# This is necessary because we can't modify the Text from other threads
self.text.after(0, append)
def create(self, num):
# Create textLogger
topframe = tk.Frame(root)
topframe.pack(side=tk.TOP)
if num == 0:
st = tkst.ScrolledText(topframe, state='disabled')
st.configure(font='TkFixedFont')
st.pack()
self.text_handler = TextHandler(st)
# Add the handler to logger
self.logger = logging.getLogger()
self.logger.addHandler(self.text_handler)
print(num)
else:
# Add the handler to logger
self.logger = logging.getLogger()
print(num)
def stop():
root.flag = False
def loop():
th = TextHandler("none")
th.create(1)
def start():
if root.flag:
th.logger.error("error")
root.after(1000, start)
else:
th.logger.error("Loop stopped")
root.flag = True
return
start()
class HomePage(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
#logger and main loop
th = TextHandler("none")
th.create(0)
root.flag = True
bottomframe = tk.Frame(root)
bottomframe.pack(side=tk.BOTTOM)
topframe = tk.Frame(root)
topframe.pack(side=tk.TOP)
topframe = tk.Frame(root)
topframe.pack(side=tk.TOP)
# Create taskbar/menu
taskbar = tk.Menu(self.master)
self.master.config(menu=taskbar)
file = tk.Menu(taskbar)
file.add_command(label="Run", command=loop)
file.add_command(label="Stop", command=stop)
file.add_separator()
file.add_command(label="Settings", command=lambda: popupmsg("Coming \"soon\"..."))
file.add_separator()
file.add_command(label="Quit", command=quit)
taskbar.add_cascade(label="File", menu=file)
startButton = tk.Button(bottomframe, text="Start", command=loop)
startButton.pack()
stopButton = tk.Button(bottomframe, text="Stop", command=stop)
stopButton.pack()
exitButton = tk.Button(bottomframe, text="Exit", command=quit)
exitButton.pack()
if __name__ == "__main__":
root = tk.Tk()
app = HomePage(root)
root.wm_title("Scraper")
root.mainloop()
</code></pre>
| 0 |
2016-09-23T00:37:58Z
| 39,659,394 |
<p>I'm not totally sure why, but adjusting my code like so has fixed this screen blink.</p>
<p>I moved the <code>stop</code> and <code>loop</code> functions into the <code>TextHandler</code> class as methods. This allowed me to remove the second call to <code>TextHandler</code> and the <code>create</code> method that was in the <code>loop</code> function. I also now have no need for a second argument in the <code>create</code> method (was using it as a sort of flag), so that was removed.</p>
<p>I'm guessing the flash was this second call whenever the start button was being clicked.</p>
<pre><code>import tkinter as tk
import tkinter.scrolledtext as tkst
from tkinter import ttk
import logging
def popupmsg(msg):
popup = tk.Tk()
popup.wm_title("!")
label = ttk.Label(popup, text=msg)
label.pack(side="top", fill="x", pady=10)
b1 = ttk.Button(popup, text="Okay", command=popup.destroy)
b1.pack()
popup.mainloop()
class TextHandler(logging.Handler):
def __init__(self, text):
# run the regular Handler __init__
logging.Handler.__init__(self)
# Store a reference to the Text it will log to
self.text = text
def emit(self, record):
msg = self.format(record)
def append():
self.text.configure(state='normal')
self.text.insert(tk.END, msg + '\n')
self.text.configure(state='disabled')
# Autoscroll to the bottom
self.text.yview(tk.END)
# This is necessary because we can't modify the Text from other threads
self.text.after(0, append)
def create(self):
# Create textLogger
topframe = tk.Frame(root)
topframe.pack(side=tk.TOP)
st = tkst.ScrolledText(topframe, state='disabled')
st.configure(font='TkFixedFont')
st.pack()
self.text_handler = TextHandler(st)
# Add the handler to logger
self.logger = logging.getLogger()
self.logger.addHandler(self.text_handler)
def stop(self):
root.flag = False
def loop(self):
def start():
if root.flag:
self.logger.error("error")
root.after(1000, start)
else:
self.logger.error("Loop stopped")
root.flag = True
return
start()
class HomePage(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
#logger and main loop
th = TextHandler("none")
th.create()
root.flag = True
bottomframe = tk.Frame(root)
bottomframe.pack(side=tk.BOTTOM)
topframe = tk.Frame(root)
topframe.pack(side=tk.TOP)
topframe = tk.Frame(root)
topframe.pack(side=tk.TOP)
# Create taskbar/menu
taskbar = tk.Menu(self.master)
self.master.config(menu=taskbar)
file = tk.Menu(taskbar)
file.add_command(label="Run", command=lambda: th.loop())
file.add_command(label="Stop", command=lambda: th.loop())
file.add_separator()
file.add_command(label="Settings", command=lambda: popupmsg("Coming \"soon\"..."))
file.add_separator()
file.add_command(label="Quit", command=quit)
taskbar.add_cascade(label="File", menu=file)
startButton = tk.Button(text="Start", command=lambda: th.loop())
startButton.pack()
stopButton = tk.Button(text="Stop", command=lambda: th.stop())
stopButton.pack()
exitButton = tk.Button(text="Exit", command=quit)
exitButton.pack()
if __name__ == "__main__":
root = tk.Tk()
app = HomePage(root)
root.wm_title("Scraper")
root.mainloop()
</code></pre>
<p>¯\_(ã)_/¯ </p>
| 1 |
2016-09-23T11:14:05Z
|
[
"python",
"tkinter"
] |
Python: TypeError: 'int' object is not subscriptable and IndexError: string index out of range
| 39,650,883 |
<p>What's the way to tokenize/separate the input passed in the function?
For example, if <code>12356</code> is passed as an input, and I want to access, let's say 3rd symbol, which is <code>3</code>, what will I do?
I have tried the below code in my function, but it's giving error:</p>
<pre><code>print(s[2]) IndexError: 'int' object is not subscriptable
</code></pre>
<p>Code:</p>
<pre><code>def s_test(input):
s=input
print(s)
print(s[2])
s_test(12356)
</code></pre>
<p>In one other program, when I am doing the same, I am getting an error: </p>
<pre><code>"IndexError: string index out of range" for the instruction print(s[2])
</code></pre>
<p>Thanks</p>
| 1 |
2016-09-23T00:40:01Z
| 39,651,335 |
<p>The main problems are into the following <code>function</code>. </p>
<pre><code>def TestComponents(months, days, years, seps):
print("\nTest Months FSA")
# print(months.m[0][1])
for input in ["", "0", "1", "9", "10", "11", "12", "13"]:
print("'%s'\t%s" % (input, NDRecognize(input, months)))
print("\nTest Days FSA")
for input in ["", "0", "1", "9", "10", "11", "21", "31", "32"]:
print("'%s'\t%s" % (input, NDRecognize(input, days)))
print("\nTest Years FSA")
for input in ["", "1899", "1900", "1901", "1999", "2000", "2001", "2099", "2100"]:
print("'%s'\t%s" % (input, NDRecognize(input, years)))
print("\nTest Separators FSA")
for input in ["", ",", " ", "-", "/", "//", ":"]:
print("'%s'\t%s" % (input, NDRecognize(input, seps)))
def TestDates(dates):
print("\nTest Date Expressions FSA")
for input in ["", "12 31 2000", "12/31/2000", "12-31-2000", "12:31:2000",
"1 2 2000", "1/2/2000", "1-2-2000", "1:2:2000",
"00-31-2000", "12-00-2000", "12-31-0000",
"12-32-1987", "13-31-1987", "12-31-2150"]:
print("'%s'\t%s" % (input, NDRecognize(input, dates)))
</code></pre>
<p>You are executing a <code>for</code> loop over this type of list <code>["", "0", "1", "9", "10", "11", "12", "13"]</code> which contain <code>1</code> empty string in the <code>first</code> element. So in the first iteration an empty value is passed to the <code>NDRecognize(input, dates))</code> function into every <code>for</code> loop. That's why an error occurred into the <code>NDRecognize(input, dates))</code> function.</p>
<p>I hope you understand what I'm telling. Thank you.</p>
| 0 |
2016-09-23T01:47:17Z
|
[
"python"
] |
How can I make the FigureCanvas fill the entire Figure in a matplotlib widget embedded in a pyqt GUI?
| 39,650,940 |
<p>I have attempted to make a GUI with embedded matplotlib widget in it. I just need the figure to be completely filled by the FigureCanvas, I have tried about 100 different things and nothing has changed the size of the canvas one bit. I left a few of my attempts in the code denoted by "#useless" to let you know that I tried it and it had no impact. Please help.</p>
<pre><code>import sys
from PyQt4 import QtGui
from matplotlib import pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
class Terminal(QtGui.QDialog):
def __init__(self, parent=None):
try:
super(Terminal, self).__init__(parent)
self.resize(1000,800)
self.figure = plt.figure(facecolor='black')
self.canvas = FigureCanvas(self.figure)
self.canvas.autoFillBackground()#useless
self.myComboBox = QtGui.QComboBox()
self.plotButton = QtGui.QPushButton('Plot')
self.xMplWidget = MatplotlibWidget(self.canvas)
self.plotButton.clicked.connect(self.plotCircles)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.canvas)
layout.addWidget(self.myComboBox)
layout.addWidget(self.plotButton)
policy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)#useless
self.canvas.setSizePolicy = policy#useless
layout.setStretchFactor(self.canvas, 1)#useless
self.setLayout(layout)
self.canvas.autoFillBackground()#useless
except Exception as err:
print("Error in Terminal.init: Other - ", err)
def createDashboard(self,oDashboard):
print("DoStuff")
def plotCircles(self):
print("DoStuff")
class MatplotlibWidget(FigureCanvas):
def __init__(self, parent=None, title='Title', xlabel='x label', ylabel='y label', dpi=100, hold=False):
super(MatplotlibWidget, self).__init__(Figure())
self.setParent(parent)
self.figure = Figure(dpi=dpi)
self.canvas = FigureCanvas(self.figure)
self.theplot = self.figure.add_subplot(111)
self.theplot.set_title(title)
self.theplot.set_xlabel(xlabel)
self.theplot.set_ylabel(ylabel)
def plotChart(self,oOxyName):
print("DoStuff")
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Terminal()
main.show()
app.exec_()
</code></pre>
<p><a href="http://i.stack.imgur.com/MAE37.png" rel="nofollow"><img src="http://i.stack.imgur.com/MAE37.png" alt="enter image description here"></a></p>
| 0 |
2016-09-23T00:49:56Z
| 39,663,721 |
<p>I figured it out after continued studying. I had made a mess early on in the project and had failed to carefully reread my code when changing the initial design. The issue was that I was creating a canvas widget and passing that widget to the MplWidget. The MplWidget correctly had its own canvas, and therefor did not need an additional one passed to it. Essentially I was making the MplWidget within the canvas widget, rather than the MplWidget within the main form. </p>
<p>Here is the corrected code with notes on the corrections.</p>
<pre><code>import sys
from PyQt4 import QtGui
from PyQt4.QtCore import Qt
from matplotlib import pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import (
FigureCanvasQTAgg as FigureCanvas)
class Terminal(QtGui.QDialog):
def __init__(self, parent=None):
try:
super(Terminal, self).__init__(parent)
self.resize(1000,800)
self.figure = plt.figure(facecolor='black')
#This was creating a canvas which I was adding my widget to (bad idea)
# self.canvas = FigureCanvas(self.figure)
self.myComboBox = QtGui.QComboBox()
self.plotButton = QtGui.QPushButton('Plot')
self.xMplWidget = MatplotlibWidget()
self.plotButton.clicked.connect(self.plotCircles)
layout = QtGui.QVBoxLayout()
#Needed to add my MatplotlibWidget, not a canvas widget, because the MPLWidget has its own canvas
#layout.addWidget(self.canvas)
layout.addWidget(self.xMplWidget) #This was added
layout.addWidget(self.myComboBox)
layout.addWidget(self.plotButton)
self.setLayout(layout)
except Exception as err:
print("Error in Terminal.init: Other - ", err)
def createDashboard(self,oDashboard):
print("DoStuff")
def plotCircles(self):
print("DoStuff")
class MatplotlibWidget(FigureCanvas):
def __init__(self, parent=None, title='Title', xlabel='x label', ylabel='y label', dpi=100, hold=False):
super(MatplotlibWidget, self).__init__(Figure())
self.setParent(parent)
self.figure = Figure(dpi=dpi)
self.canvas = FigureCanvas(self.figure)
self.theplot = self.figure.add_subplot(111)
self.theplot.set_title(title)
self.theplot.set_xlabel(xlabel)
self.theplot.set_ylabel(ylabel)
def plotChart(self,oOxyName):
print("DoStuff")
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Terminal()
main.show()
app.exec_()
</code></pre>
| 0 |
2016-09-23T14:50:12Z
|
[
"python",
"matplotlib",
"pyqt4"
] |
Login using Python 3.5 to SobrusPharma
| 39,650,967 |
<p>I'm trying to crawl my erp (SobrusPharma), I tried a whole lot of modules for python 3.5 and nothing works, if only someone can give me the solution for the login part, as for the crawling part it's done.
The login url is : </p>
<p><a href="https://sobruspharma.com/auth/login" rel="nofollow">https://sobruspharma.com/auth/login</a></p>
<p>And the pages to crawl have the following structure:</p>
<p><a href="https://sobruspharma.com/product/63301/table" rel="nofollow">https://sobruspharma.com/product/63301/table</a> (the number changes, that's the dynamic part.</p>
<p>Thank you in advance, I've tried the following modules:</p>
<pre><code>import requests
import urllib.request
import mechanicalSoup
</code></pre>
<p>In need of help here,
Thanks a lot!</p>
| 0 |
2016-09-23T00:53:32Z
| 39,658,918 |
<p>It is pretty straightforward, all you need to parse is the <em>hash</em> from the form:</p>
<pre><code>id="connex_form"
class=" login_form">
<input type="hidden" name="hash" value="e60f5fef37fe07b0b516d71666071316" id="hash">
</code></pre>
<p>which you can find with <em>bs4</em> and post the remaining data:</p>
<pre><code>post = "https://sobruspharma.com/auth/login"
form_data = {"hash": "",
"email": "foo@bar.com",
"password": "foo",
"remember_me": "0",
"submit": "To log in"}
from bs4 import BeautifulSoup
from requests import Session
with Session() as s:
soup = BeautifulSoup(s.get("https://sobruspharma.com/auth/login").content)
hash_ = soup.select_one("#hash")["value"]
form_data["hash"] = hash_
login = s.post(post, data=form_data)
</code></pre>
| 0 |
2016-09-23T10:48:41Z
|
[
"python",
"python-requests",
"python-3.5"
] |
Nginx Not Serving Static Files (Django + Gunicorn) Permission denied
| 39,650,974 |
<p>nginx.conf</p>
<pre><code>server {
listen 80;
server_name serveraddress.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/ec2-user/projectname;
}
location / {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://unix:/home/ec2-user/projectname/projectname.sock;
}
}
</code></pre>
<p>settings.py</p>
<pre><code>STATIC_URL = '/static/'
STATICFILES_DIR = '/home/ec2-user/projectname/static/'
STATIC_ROOT = '/home/ec2-user/projectname/static/'
</code></pre>
<p>If I run the server using the Django development server with manage.py runserver or with gunicorn, all the static files work perfectly, but using nginx on port 80, none of the static files work; which leads me to believe that it's an issue involving nginx. And yes, I've ran python manage.py collectstatic and 'django.contrib.staticfiles' is installed. I'm using RHEL 7 (Centos 7).</p>
<p>Nginx error.log</p>
<pre><code>2016/09/22 20:44:33 [error] 322#0: *371 open() "/home/ec2-user/projectname/static/css/home.css" failed (13: Permission denied), client :##.###.##.##, server: ##.###.###.###, request: "GET /static/css/home.css HTTP/1.1", host: "##.###.###.###", referrer: "http://##.###.###.###/"
</code></pre>
| 0 |
2016-09-23T00:54:27Z
| 39,651,048 |
<p>You have a permission denied issue it seems. <code>(13: Permission denied)</code></p>
<p>nginx often runs under it's own <code>nginx</code> user, and this user probably does not have the permissions to access the location/files and can't serve them.</p>
| 0 |
2016-09-23T01:05:13Z
|
[
"python",
"django",
"nginx",
"static",
"gunicorn"
] |
Nginx Not Serving Static Files (Django + Gunicorn) Permission denied
| 39,650,974 |
<p>nginx.conf</p>
<pre><code>server {
listen 80;
server_name serveraddress.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/ec2-user/projectname;
}
location / {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://unix:/home/ec2-user/projectname/projectname.sock;
}
}
</code></pre>
<p>settings.py</p>
<pre><code>STATIC_URL = '/static/'
STATICFILES_DIR = '/home/ec2-user/projectname/static/'
STATIC_ROOT = '/home/ec2-user/projectname/static/'
</code></pre>
<p>If I run the server using the Django development server with manage.py runserver or with gunicorn, all the static files work perfectly, but using nginx on port 80, none of the static files work; which leads me to believe that it's an issue involving nginx. And yes, I've ran python manage.py collectstatic and 'django.contrib.staticfiles' is installed. I'm using RHEL 7 (Centos 7).</p>
<p>Nginx error.log</p>
<pre><code>2016/09/22 20:44:33 [error] 322#0: *371 open() "/home/ec2-user/projectname/static/css/home.css" failed (13: Permission denied), client :##.###.##.##, server: ##.###.###.###, request: "GET /static/css/home.css HTTP/1.1", host: "##.###.###.###", referrer: "http://##.###.###.###/"
</code></pre>
| 0 |
2016-09-23T00:54:27Z
| 39,651,067 |
<p>I just fixed it by disabling SELinux, which caused me another problem a few days ago with nginx.</p>
| -1 |
2016-09-23T01:08:19Z
|
[
"python",
"django",
"nginx",
"static",
"gunicorn"
] |
Sqlite3 Insertion does not retain records with Python
| 39,651,106 |
<p>I am trying to insert multiple records to sqlite database. This is my test script. </p>
<pre><code>import sqlite3
from datetime import datetime
company = 'fghjk'
keyword = 'awesome'
filename = 'test.txt'
date_found = datetime.now()
conn = sqlite3.connect('C:\\sqlite\\test.db')
c = conn.cursor()
for i in range(0,4):
insert_query = "INSERT into records (company,keyword,filename,date_found) values (?,?,?,?)"
c.execute(insert_query, [company,keyword,filename,date_found])
select_query = "SELECT * FROM records"
c.execute(select_query)
res = c.fetchall()
print res
for i in res:
for b in i:
print b
</code></pre>
<p>When I execute the script above <strong>twice</strong>, I am expecting to have 8 records, but it's always giving back 4 rows. Can someone enlighten me? </p>
<p>Output: </p>
<pre><code>1
fghjk
awesome
test.txt
2016-09-23 09:11:19.585000
2
fghjk
awesome
test.txt
2016-09-23 09:11:19.585000
3
fghjk
awesome
test.txt
2016-09-23 09:11:19.585000
4
fghjk
awesome
test.txt
2016-09-23 09:11:19.585000
</code></pre>
<p>This is my table's create statement. </p>
<pre><code>conn.execute('''CREATE TABLE records
# (ID INTEGER PRIMARY KEY AUTOINCREMENT,
# company TEXT NOT NULL,
# keyword INT NOT NULL,
# filename CHAR(50),
# date_found DATETIME);''')
</code></pre>
| 0 |
2016-09-23T01:15:33Z
| 39,651,242 |
<p>The problem looks to be that you're not committing the data to the database.</p>
<p>Each time you open the database, you put in 4 rows, then print them, then let the cursor and connection be destroyed without committing your changes.</p>
<p>Calling <code>conn.commit()</code> after all of your inserts are done will fix this. IIRC, the table creation is automatically committed immediately after it runs, which is why it is saved in the database.</p>
| 2 |
2016-09-23T01:34:13Z
|
[
"python",
"python-2.7",
"sqlite"
] |
Sqlite3 Insertion does not retain records with Python
| 39,651,106 |
<p>I am trying to insert multiple records to sqlite database. This is my test script. </p>
<pre><code>import sqlite3
from datetime import datetime
company = 'fghjk'
keyword = 'awesome'
filename = 'test.txt'
date_found = datetime.now()
conn = sqlite3.connect('C:\\sqlite\\test.db')
c = conn.cursor()
for i in range(0,4):
insert_query = "INSERT into records (company,keyword,filename,date_found) values (?,?,?,?)"
c.execute(insert_query, [company,keyword,filename,date_found])
select_query = "SELECT * FROM records"
c.execute(select_query)
res = c.fetchall()
print res
for i in res:
for b in i:
print b
</code></pre>
<p>When I execute the script above <strong>twice</strong>, I am expecting to have 8 records, but it's always giving back 4 rows. Can someone enlighten me? </p>
<p>Output: </p>
<pre><code>1
fghjk
awesome
test.txt
2016-09-23 09:11:19.585000
2
fghjk
awesome
test.txt
2016-09-23 09:11:19.585000
3
fghjk
awesome
test.txt
2016-09-23 09:11:19.585000
4
fghjk
awesome
test.txt
2016-09-23 09:11:19.585000
</code></pre>
<p>This is my table's create statement. </p>
<pre><code>conn.execute('''CREATE TABLE records
# (ID INTEGER PRIMARY KEY AUTOINCREMENT,
# company TEXT NOT NULL,
# keyword INT NOT NULL,
# filename CHAR(50),
# date_found DATETIME);''')
</code></pre>
| 0 |
2016-09-23T01:15:33Z
| 39,651,263 |
<p>You can use the connection as a context manager. This will properly terminate the connection, including a commit.</p>
<pre><code>import sqlite3
from datetime import datetime
company = 'fghjk'
keyword = 'awesome'
filename = 'test.txt'
date_found = datetime.now()
conn = sqlite3.connect('test.db')
first = False
# use context manager here!!
with conn:
c = conn.cursor()
if first:
conn.execute('''CREATE TABLE records
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
company TEXT NOT NULL,
keyword INT NOT NULL,
filename CHAR(50),
date_found DATETIME);''')
for i in range(0,4):
insert_query = "INSERT into records (company,keyword,filename,date_found) values (?,?,?,?)"
c.execute(insert_query, [company,keyword,filename,date_found])
select_query = "SELECT * FROM records"
c.execute(select_query)
res = c.fetchall()
print res
for i in res:
for b in i:
print b
</code></pre>
| 3 |
2016-09-23T01:37:06Z
|
[
"python",
"python-2.7",
"sqlite"
] |
Storing location of characters in string
| 39,651,141 |
<p>I am writing a Hangman program during my free time at school, as an entry level project for Python, and I have finally run into an obstacle. </p>
<h1>What I want to do:</h1>
<p>So far I have printed a board to the size of the word inputted, and I can decide if the guesses are correct or not, with a working score. Now I need to take a correct guess, and change the correct underscores in str(board) into their actual letter. To do this I wanted to grab the locations of the character guessed (if correct) in the FULL CORRECT WORD and then simply change that position in board into the correct letter. Sorry for the wordyness! Here is my code.</p>
<pre><code>print("Welcome to Tyler's Hangman game!!!! Player one, input a word for player two to guess, lowercase!\n")
playAgain = True
guessing = True
#assure game starts in the True state
while playAgain == True:
word = str(raw_input())
wordLength = int(len(word))
board = "_ " * wordLength
lives = 9
#initialize/reset variables on a new play
while guessing == True:
print("\n" * 15)
print("Now its player two's turn to make a guess! You have 9 lives! Only one letter at a time, lowercase!\n")
print(board + "Lives: " + str(lives) + "\n")
#print board + lives
guess = str(raw_input())
if guess in word:
print("Correct!")
word.index(guess)
else:
print("Wrong.")
score -= 1
#check guess and change board
</code></pre>
<p>The statement starting with if guess in word: is where things start to get confusing for me. Thanks!!</p>
<p>Snippet I'm confused with</p>
<pre><code> if guess in word:
print("Correct!")
word.index(guess)
</code></pre>
| 0 |
2016-09-23T01:21:08Z
| 39,651,251 |
<p>I'm going to propose an alternative solution to your real problem. Mutating strings is not very idiomatic in Python and is prone to errors. My approach instead will be to keep track of which letters have been guessed and then compute the board state from that and the actual answer.</p>
<pre><code>answer = 'hello world'
guessed = ['a', 'e', 'm', 'r']
def compute_board(answer, guessed):
return ''.join(c if c == ' ' or c in guessed else '_' for c in answer)
compute_board(answer, guessed) # gives _e___ __r__
</code></pre>
<p>Now you can easily get the number of guesses from the length of the <code>guessed</code> list, you can check for repeated guesses easily by checking if their guess is already in the list, and you can add guesses easily by just adding them to the end of the list.</p>
| 1 |
2016-09-23T01:35:32Z
|
[
"python"
] |
How to check and get the newest file(.xlsx) in a tempfolder?
| 39,651,164 |
<p>Here is a complicated problem...<br>
When I run Python, I want to determine the newest Excel file in temporary folder (<code>%USERPROFILE%\\AppData\\Local\\Temp\\</code>) and copy it to the <code>D</code> drive on Windows.</p>
<p>I searched for examples but there weren't any...</p>
<p>How can I solve this problem?</p>
<p>This is the code below...</p>
<pre><code>import os
import win32com.client as win32
import time
import subprocess
import tempfile
dated_files = [(os.path.getmtime(fn), os.path.basename(fn)) for fn in os.listdir(os.getenv('TEMP')) if fn.lower().endswith('.xlsx')]
dated_files.sort()
dated_files.reverse()
newest = dated_files[0][1]
print(newest)
</code></pre>
<p>=============================================================</p>
<pre><code>Traceback (most recent call last):
File "D:/1002.py", line 11, in <module>
for fn in os.listdir(os.getenv('TEMP')) if fn.lower().endswith('.xlsx')]
File "D:/M1002.py", line 11, in <listcomp>
for fn in os.listdir(os.getenv('TEMP')) if fn.lower().endswith('.xlsx')]
File "C:\Python35\lib\genericpath.py", line 55, in getmtime
return os.stat(filename).st_mtime
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'SampleCheck.xlsx'
Process finished with exit code 1
</code></pre>
| -1 |
2016-09-23T01:24:36Z
| 39,690,739 |
<p>Obviously you missed <code>os.chdir(os.getenv('TEMP'))</code> before the list comprehension. Or you should do <code>os.path.join(os.getenv('TEMP'), fn)</code> to pass it into <code>os.path.getmtime</code>.</p>
<p>In more details:</p>
<p><code>getmtime</code> cannot find the file <code>fn</code> in the current working directory. So you have to change the working dir (with <code>os.chdir</code>) or to use the full path (constructed by <code>os.path.join</code> for example).</p>
| 1 |
2016-09-25T19:09:11Z
|
[
"python",
"excel",
"python-3.x"
] |
Raspberry Pi Python Code Won't Move Servo
| 39,651,222 |
<p>So I am doing a little project with a Raspberry Pi that involves moving a servo motor. In the following code in <strong>Python 3</strong>, I begin by starting the servo at approximately 45 degrees. Later in the code, a different angle is determined based on the previous angle, and the the Duty Cycle is changed.</p>
<pre><code>def main():
#Import functions
import measure, move
import time
import RPi.GPIO as GPIO
#Declare Variables
Servo_pin = 35
angle = 45
freq = 50
#Setup board
GPIO.setmode(GPIO.BOARD)
GPIO.setup(Servo_pin, GPIO.OUT)
servo = GPIO.PWM(Servo_pin,freq)
#Determine Duty Cycle
dc = 1/18 * (angle) + 2
print("Starting Duty Cycle: ",dc)
#Start servo
servo.start(dc)
i = 1
#Determine angle based on previous angle
while True:
if (i == 0):
angle = 45
elif (i == 1):
angle = 90
elif (i == 2):
angle = 180
elif (i > 2):
angle = 45
i = 0
i = i+1
#Change servo's position
#Convert angle to Duty Cycle
dc = 1/18 * (angle) + 2
print("Setting Duty Cycle: ",dc)
#Change position
servo.ChangeDutyCycle(dc)
#Give servo time to finish moving
time.sleep(0.3)
main()
</code></pre>
<p>I have the servo connected to a battery pack (4 AA batteries), yet the servo won't move with this code. Now, I'll admit that I'm a beginner, and it's probably something really easy and I apologize in advance if it that is the case.</p>
<p>Any help is appreciated!</p>
| 0 |
2016-09-23T01:31:59Z
| 39,651,434 |
<p>According to the docs on <a href="https://sourceforge.net/p/raspberry-gpio-python/wiki/PWM/" rel="nofollow">https://sourceforge.net/p/raspberry-gpio-python/wiki/PWM/</a><a href="https://sourceforge.net/p/raspberry-gpio-python/wiki/PWM/" rel="nofollow">sourceforge</a>, the PWM will stop when the the instance variable representing the PWM goes out of scope. Both of your functions contain this line: <code>servo = GPIO.PWM(pin,freq)</code>, creating a local variable <code>servo</code> that will go out of scope as soon as the end of the function is reached. One fix is to move these lines:</p>
<pre><code>import time
import RPi.GPIO as GPIO
# HERE you need to define which pin you are using
# I can't tell you how to do that
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pin, GPIO.OUT)
freq = 10.0 # or some other value to get started
servo = GPIO.PWM(pin,freq)
</code></pre>
<p>to the top of the script, and then remove those lines from the individual functions. Now <code>servo</code> will be a global variable that will not go out of scope at any point during the program.</p>
<p>There may also be other problems. Do you have a voltmeter or an oscilloscope to verify that the pin is doing what you intend? I deal with this kind of application all the time, and it helps a lot to know if the small pieces of the puzzle are actually working before you connect all the hardware. Nothing ever works right the first time :-).</p>
| 0 |
2016-09-23T02:01:48Z
|
[
"python",
"python-3.x",
"raspberry-pi",
"servo"
] |
Raspberry Pi Python Code Won't Move Servo
| 39,651,222 |
<p>So I am doing a little project with a Raspberry Pi that involves moving a servo motor. In the following code in <strong>Python 3</strong>, I begin by starting the servo at approximately 45 degrees. Later in the code, a different angle is determined based on the previous angle, and the the Duty Cycle is changed.</p>
<pre><code>def main():
#Import functions
import measure, move
import time
import RPi.GPIO as GPIO
#Declare Variables
Servo_pin = 35
angle = 45
freq = 50
#Setup board
GPIO.setmode(GPIO.BOARD)
GPIO.setup(Servo_pin, GPIO.OUT)
servo = GPIO.PWM(Servo_pin,freq)
#Determine Duty Cycle
dc = 1/18 * (angle) + 2
print("Starting Duty Cycle: ",dc)
#Start servo
servo.start(dc)
i = 1
#Determine angle based on previous angle
while True:
if (i == 0):
angle = 45
elif (i == 1):
angle = 90
elif (i == 2):
angle = 180
elif (i > 2):
angle = 45
i = 0
i = i+1
#Change servo's position
#Convert angle to Duty Cycle
dc = 1/18 * (angle) + 2
print("Setting Duty Cycle: ",dc)
#Change position
servo.ChangeDutyCycle(dc)
#Give servo time to finish moving
time.sleep(0.3)
main()
</code></pre>
<p>I have the servo connected to a battery pack (4 AA batteries), yet the servo won't move with this code. Now, I'll admit that I'm a beginner, and it's probably something really easy and I apologize in advance if it that is the case.</p>
<p>Any help is appreciated!</p>
| 0 |
2016-09-23T01:31:59Z
| 39,693,140 |
<p>There needed to be a common ground. I was using two separate breadboards, and did not connect a common ground. As soon as I connected a common ground, the servo began to operate as I wanted. </p>
<p>Thank you for the coding help!</p>
| 0 |
2016-09-26T00:24:45Z
|
[
"python",
"python-3.x",
"raspberry-pi",
"servo"
] |
Download a gzipped file, md5 checksum it, and then save extracted data if matches
| 39,651,277 |
<p>I'm currently attempting to download two files using Python, one a gzipped file, and the other, its checksum.</p>
<p>I would like to verify that the gzipped file's contents match the md5 checksum, and then I would like to save the contents to a target directory.</p>
<p>I found out how to download the files <a href="http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python">here</a>, and I learned how to calculate the checksum <a href="http://stackoverflow.com/questions/16874598/how-do-i-calculate-the-md5-checksum-of-a-file-in-python">here</a>. I load the URLs from a JSON config file, and I learned how to parse JSON file values <a href="http://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file-in-python">here</a>.</p>
<p>I put it all together into the following script, but I'm stuck attempting to store the verified contents of the gzipped file.</p>
<pre class="lang-python prettyprint-override"><code>import json
import gzip
import urllib
import hashlib
# Function for creating an md5 checksum of a file
def md5Gzip(fname):
hash_md5 = hashlib.md5()
with gzip.open(fname, 'rb') as f:
# Make an iterable of the file and divide into 4096 byte chunks
# The iteration ends when we hit an empty byte string (b"")
for chunk in iter(lambda: f.read(4096), b""):
# Update the MD5 hash with the chunk
hash_md5.update(chunk)
return hash_md5.hexdigest()
# Open the configuration file in the current directory
with open('./config.json') as configFile:
data = json.load(configFile)
# Open the downloaded checksum file
with open(urllib.urlretrieve(data['checksumUrl'])[0]) as checksumFile:
md5Checksum = checksumFile.read()
# Open the downloaded db file and get it's md5 checksum via gzip.open
fileMd5 = md5Gzip(urllib.urlretrieve(data['fileUrl'])[0])
if (fileMd5 == md5Checksum):
print 'Downloaded Correct File'
# save correct file
else:
print 'Downloaded Incorrect File'
# do some error handling
</code></pre>
| 0 |
2016-09-23T01:39:16Z
| 39,652,515 |
<p>In your <code>md5Gzip</code>, return a <code>tuple</code> instead of just the hash.</p>
<pre><code>def md5Gzip(fname):
hash_md5 = hashlib.md5()
file_content = None
with gzip.open(fname, 'rb') as f:
# Make an iterable of the file and divide into 4096 byte chunks
# The iteration ends when we hit an empty byte string (b"")
for chunk in iter(lambda: f.read(4096), b""):
# Update the MD5 hash with the chunk
hash_md5.update(chunk)
# get file content
f.seek(0)
file_content = f.read()
return hash_md5.hexdigest(), file_content
</code></pre>
<p>Then, in your code:</p>
<pre><code>fileMd5, file_content = md5Gzip(urllib.urlretrieve(data['fileUrl'])[0])
</code></pre>
| 1 |
2016-09-23T04:13:13Z
|
[
"python",
"io",
"gzip",
"md5",
"downloading"
] |
int() not working for floats?
| 39,651,352 |
<p>I recently ran into this in Python 3.5:</p>
<pre><code>>>> flt = '3.14'
>>> integer = '5'
>>> float(integer)
5.0
>>> float(flt)
3.14
>>> int(integer)
5
>>> int(flt)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
int(flt)
ValueError: invalid literal for int() with base 10: '3.14'
</code></pre>
<p>Why is this? It seems like it should return <code>3</code>. Am I doing something wrong, or does this happen for a good reason?</p>
| 1 |
2016-09-23T01:50:00Z
| 39,651,371 |
<p>It does not work because <code>flt</code> is not a string representation of an integer. You would need to convert it to <code>float</code> first then an <code>int</code>.</p>
<p>e.g.</p>
<pre><code>flt = '3.14'
f = int(float(flt))
</code></pre>
<p>output is</p>
<pre><code>3
</code></pre>
| 3 |
2016-09-23T01:53:30Z
|
[
"python",
"python-3.x",
"floating-point",
"int"
] |
int() not working for floats?
| 39,651,352 |
<p>I recently ran into this in Python 3.5:</p>
<pre><code>>>> flt = '3.14'
>>> integer = '5'
>>> float(integer)
5.0
>>> float(flt)
3.14
>>> int(integer)
5
>>> int(flt)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
int(flt)
ValueError: invalid literal for int() with base 10: '3.14'
</code></pre>
<p>Why is this? It seems like it should return <code>3</code>. Am I doing something wrong, or does this happen for a good reason?</p>
| 1 |
2016-09-23T01:50:00Z
| 39,651,391 |
<p><code>int()</code> expects an number or string that contains an integer literal. Per the <a href="https://docs.python.org/3/library/functions.html#int" rel="nofollow">Python 3.5.2</a> documentation:</p>
<blockquote>
<p>If <em>x</em> is not a number or if <em>base</em> is given, then <strong><em>x</em> must be a string, <code>bytes</code>, or <code>bytearray</code> instance representing an integer literal</strong> in <em>radix base</em>. (Emphasis added)</p>
</blockquote>
<p>Meaning <code>int()</code> can only convert strings that contain integers. You can easily do this:</p>
<pre><code>>>> flt = '3.14'
>>> int(float(flt))
3
</code></pre>
<p>This will convert <code>flt</code> into a float, which is then valid for <code>int()</code> because it is a number. Then it will convert to integer by removing fractional parts.</p>
| 5 |
2016-09-23T01:55:34Z
|
[
"python",
"python-3.x",
"floating-point",
"int"
] |
int() not working for floats?
| 39,651,352 |
<p>I recently ran into this in Python 3.5:</p>
<pre><code>>>> flt = '3.14'
>>> integer = '5'
>>> float(integer)
5.0
>>> float(flt)
3.14
>>> int(integer)
5
>>> int(flt)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
int(flt)
ValueError: invalid literal for int() with base 10: '3.14'
</code></pre>
<p>Why is this? It seems like it should return <code>3</code>. Am I doing something wrong, or does this happen for a good reason?</p>
| 1 |
2016-09-23T01:50:00Z
| 39,651,548 |
<p>The other answers already give you a good explanation about your issue, another way to understand what's going would be doing something like this:</p>
<pre><code>import sys
for c in ['3.14', '5']:
try:
sys.stdout.write(
"Casting {0} {1} to float({0})...".format(c, c.__class__))
value = float(c)
sys.stdout.write("OK -> {0}\n".format(value))
print('-' * 80)
except:
sys.stdout.write("FAIL\n")
try:
sys.stdout.write(
"Casting {0} {1} to int({0})...".format(c, c.__class__))
value = int(c)
sys.stdout.write("OK -> {0}\n".format(value))
except:
sys.stdout.write("FAIL\n")
sys.stdout.write("Casting again using int(float({0}))...".format(value))
value = int(float(c))
sys.stdout.write("OK -> {0}\n".format(value))
print('-' * 80)
</code></pre>
<p>Which outputs:</p>
<pre><code>Casting 3.14 <class 'str'> to float(3.14)...OK -> 3.14
--------------------------------------------------------------------------------
Casting 3.14 <class 'str'> to int(3.14)...FAIL
Casting again using int(float(3.14))...OK -> 3
--------------------------------------------------------------------------------
Casting 5 <class 'str'> to float(5)...OK -> 5.0
--------------------------------------------------------------------------------
Casting 5 <class 'str'> to int(5)...OK -> 5
</code></pre>
| 0 |
2016-09-23T02:15:24Z
|
[
"python",
"python-3.x",
"floating-point",
"int"
] |
Error : The program 'django-admin' is currently not installed
| 39,651,380 |
<p>But it is installed, coz when I run </p>
<p><code>python -m django --version</code></p>
<p>it shows </p>
<p><code>1.10.1</code>.</p>
<p>But when I try to start some project <code>django-admin startproject mysite</code> or check the version with <code>django-admin --version</code> , it shows</p>
<pre><code>The program 'django-admin' is currently not installed. You can install it by typing:
sudo apt-get install python-django`
</code></pre>
<p>I'm using ubuntu 14.04. I'm new to django, I was just trying to follow some tutorial to learn it and faced this issue.</p>
| 0 |
2016-09-23T01:54:35Z
| 39,652,745 |
<p>Reinstall django:</p>
<pre><code>sudo apt-get purge python-django
sudo pip uninstall django
sudo apt-get install python-django
sudo pip install django --upgrade
</code></pre>
<p>Also you can use <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a> and <a href="https://virtualenvwrapper.readthedocs.io/en/latest/" rel="nofollow">virtualenvwrapper</a> to have a better package isolation for multiple projects.</p>
| 1 |
2016-09-23T04:40:16Z
|
[
"python",
"django"
] |
Tally votes from an input file?
| 39,651,527 |
<p>I'm trying to use python to create a program that can tally votes using an input file.</p>
<p>Say the input file contains:</p>
<pre class="lang-none prettyprint-override"><code>Abby 10 Bob 3
Abby 5 Cathy 7
Cathy 2
Bob 1
Abby 22
</code></pre>
<p>I would want the program to be able to tally the numbers linked to their key (the name of the candidate) and then output from highest voted for to least voted for.</p>
<p>So an example output of:</p>
<pre class="lang-none prettyprint-override"><code>Abby 37
Cathy 9
Bob 4
</code></pre>
<p>I was told I could use a looping mechanism but I am unsure how to do this in python.</p>
<p>My attempt is here:</p>
<p><a href="http://i.stack.imgur.com/1bn30.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/1bn30.jpg" alt="screenshot of my code"></a></p>
| 0 |
2016-09-23T02:12:38Z
| 39,651,737 |
<p>It looks like you're using <code>+</code> where you want <code>+=</code>:</p>
<pre><code>if voteinfo[i] in candidates:
candidates[voteinfo[i]] + int(voteinfo[i+1])
</code></pre>
<p>Should be:</p>
<pre><code>if voteinfo[i] in candidates:
candidates[voteinfo[i]] += int(voteinfo[i+1])
</code></pre>
| 0 |
2016-09-23T02:39:59Z
|
[
"python",
"loops",
"dictionary",
"file-io"
] |
First Unique Character in a String
| 39,651,540 |
<p>Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.</p>
<pre><code>first_unique('leetcode') # 0
first_unique('loveleetcode') # 2
</code></pre>
<p>I came up with the following solution. How can I make it more efficient for very long input strings?</p>
<pre><code>def first_unique(self, s):
if s == '':
return -1
for item in s:
if s.count(item) == 1:
return s.index(item)
break
return -1
</code></pre>
| 2 |
2016-09-23T02:14:11Z
| 39,651,600 |
<p>My solution uses <code>Counter</code> form the <code>collections</code> module.</p>
<pre><code>from collections import Counter
def first_unique(s):
c = Counter(s)
for i in range(len(s)):
if c[s[i]] == 1:
return i
return -1
</code></pre>
| 4 |
2016-09-23T02:23:59Z
|
[
"python"
] |
First Unique Character in a String
| 39,651,540 |
<p>Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.</p>
<pre><code>first_unique('leetcode') # 0
first_unique('loveleetcode') # 2
</code></pre>
<p>I came up with the following solution. How can I make it more efficient for very long input strings?</p>
<pre><code>def first_unique(self, s):
if s == '':
return -1
for item in s:
if s.count(item) == 1:
return s.index(item)
break
return -1
</code></pre>
| 2 |
2016-09-23T02:14:11Z
| 39,651,637 |
<p>Suave version:</p>
<pre><code>from collections import Counter, OrderedDict
class OrderedCounter(Counter, OrderedDict):
pass
def first_unique(s):
counter = OrderedCounter(s)
try:
return counter.values().index(1)
except ValueError:
return -1
</code></pre>
<hr>
<p>Weird version:</p>
<pre><code>from collections import OrderedDict
def first_unique(s):
nah = {0}-{0} # funny pair of eyes
yeah = OrderedDict()
for i,c in enumerate(s):
if c not in nah:
try:
del yeah[c]
except KeyError:
yeah[c] = i
else:
nah.add(c)
return next(yeah.itervalues(), -1)
</code></pre>
| 4 |
2016-09-23T02:27:47Z
|
[
"python"
] |
First Unique Character in a String
| 39,651,540 |
<p>Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.</p>
<pre><code>first_unique('leetcode') # 0
first_unique('loveleetcode') # 2
</code></pre>
<p>I came up with the following solution. How can I make it more efficient for very long input strings?</p>
<pre><code>def first_unique(self, s):
if s == '':
return -1
for item in s:
if s.count(item) == 1:
return s.index(item)
break
return -1
</code></pre>
| 2 |
2016-09-23T02:14:11Z
| 39,651,698 |
<p>Your version isn't bad for few cases with "nice" strings... but using count is quite expensive for long "bad" strings, I'd suggest you cache items, for instance:</p>
<pre><code>def f1(s):
if s == '':
return -1
for item in s:
if s.count(item) == 1:
return s.index(item)
break
return -1
def f2(s):
cache = set()
if s == '':
return -1
for item in s:
if item not in cache:
if s.count(item) == 1:
return s.index(item)
else:
cache.add(item)
return -1
import timeit
import random
import string
random.seed(1)
K, N = 500, 100000
data = ''.join(random.choice(string.ascii_uppercase + string.digits)
for _ in range(K))
print(
timeit.timeit('f1(data)', setup='from __main__ import f1, data', number=N))
print(
timeit.timeit('f2(data)', setup='from __main__ import f2, data', number=N))
</code></pre>
<p>The results on my laptop are:</p>
<pre><code>32.05926330029437
4.267771588590406
</code></pre>
<p>The version using cache gives you 8x speed up factor vs yours wich is using count function all the time. So, my general advice would be... cache as much as possible whether it's possible</p>
<p>EDIT:</p>
<p>I've added Patrick Haugh version to the benchmark and it gave <code>10.92784585620725</code></p>
<p>EDIT2:</p>
<p>I've added Mehmet Furkan Demirel version to the benchmark and it gave <code>10.325440507549331</code></p>
<p>EDIT3:</p>
<p>I've added wim version to the benchmark and it gave <code>12.47985351744839</code></p>
<p>CONCLUSION:</p>
<p>I'd use the version i've proposed initially using a simple cache without relying on Python counter modules, it's not necessary (in terms of performance)</p>
| 1 |
2016-09-23T02:35:22Z
|
[
"python"
] |
First Unique Character in a String
| 39,651,540 |
<p>Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.</p>
<pre><code>first_unique('leetcode') # 0
first_unique('loveleetcode') # 2
</code></pre>
<p>I came up with the following solution. How can I make it more efficient for very long input strings?</p>
<pre><code>def first_unique(self, s):
if s == '':
return -1
for item in s:
if s.count(item) == 1:
return s.index(item)
break
return -1
</code></pre>
| 2 |
2016-09-23T02:14:11Z
| 39,651,714 |
<p>I would use a for loop to iterate the <code>String</code> from the beginning and at each index, I would check if the rest of the <code>String</code> has the character at the current index by using Substring.</p>
<p>Try this:</p>
<pre><code>def firstUniqChar(word):
for i in range(0,len(word)): ## iterate through the string
if not word[i] in word[i+1:len(word)]: ## check if the rest contains that char
index=i
break
return index
</code></pre>
<p>Hope it helps!</p>
| 0 |
2016-09-23T02:37:06Z
|
[
"python"
] |
First Unique Character in a String
| 39,651,540 |
<p>Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.</p>
<pre><code>first_unique('leetcode') # 0
first_unique('loveleetcode') # 2
</code></pre>
<p>I came up with the following solution. How can I make it more efficient for very long input strings?</p>
<pre><code>def first_unique(self, s):
if s == '':
return -1
for item in s:
if s.count(item) == 1:
return s.index(item)
break
return -1
</code></pre>
| 2 |
2016-09-23T02:14:11Z
| 39,652,337 |
<p>The idea in this solution is to use a pair of defaultdicts. The first one contains an integer count of each character and the second contains the index location of the latest character read.</p>
<p>After reading all of the characters, a list comprehension is used to find all of those that only occurred once (<code>result</code>). The minimum index locations of these characters (found in our other defaultdict <code>order</code>) will give us the first index location of non-repeating characters.</p>
<pre><code>from collections import defaultdict
# To Create random string:
from string import ascii_lowercase
from random import choice, randint, seed
# Create a random sentence of 1000 words (1-8 characters each).
seed(0)
gibberish = ' '.join(''.join(choice(ascii_lowercase)
for _ in range(randint(1, 8)))
for _ in range(1000))
print(len(gibberish))
# Output: 5614
# Solution.
def first_unique(s):
dd = defaultdict(int)
order = defaultdict(int)
for n, c in enumerate(s):
dd[c] += 1
order[c] = n
result = [order[c] for c in dd if dd[c] == 1]
return min(result) if result else -1
</code></pre>
<h1>Timings</h1>
<pre><code>%timeit first_unique(gibberish)
100 loops, best of 3: 2.13 ms per loop
@wim solution:
%timeit first_unique(gibberish)
100 loops, best of 3: 5.06 ms per loop
@PatrickHaugh solution (which is much easier to understand than mine):
%timeit first_unique(gibberish)
100 loops, best of 3: 4.2 ms per loop
@BPL solution:
%timeit f1(gibberish)
10 loops, best of 3: 39.2 ms per loop
%timeit f2(gibberish)
1000 loops, best of 3: 890 µs per loop
</code></pre>
<p>Using a much shorter sentence of twenty words (133 characters):</p>
<pre><code>%timeit first_unique(gibberish)
10000 loops, best of 3: 62.8 µs per loop
@wim solution:
%timeit first_unique(gibberish)
10000 loops, best of 3: 169 µs per loop
@PatrickHaugh solution:
%timeit first_unique(gibberish)
10000 loops, best of 3: 101 µs per loop
@BPL solution:
%timeit f1(gibberish)
10000 loops, best of 3: 55.1 µs per loop
%timeit f2(gibberish)
10000 loops, best of 3: 31 µs per loop
</code></pre>
<h1>Test cases.</h1>
<pre><code>s1 = 'leetcode'
s2 = 'loveleetcode'
>>> first_unique(s1)
0
>>> first_unique(s2)
2
</code></pre>
| 0 |
2016-09-23T03:56:06Z
|
[
"python"
] |
Override the class patch with method patch (decorator)
| 39,651,686 |
<p>I have several test methods in a class that use one type of patching for a object, so I have patched with class decorator. For a single another method i want to patch the same object differently. I tried the following approach, but the patch made as class decorator is in effect despite the method itself being decorated with different patch. I expected method patch to override class patch. Why is this not the case?</p>
<p>In this particular case I can remove class patch and patch individual methods, but that would be repetitive. How can I implement such overriding (method overrides class patch) mechanism? </p>
<pre><code>from unittest TestCase
from unittest import mock
@mock.patch('my_module.cls.method', mock.Mock(side_effect=RuntimeError('testing'))
class SwitchViewTest(TestCase):
def test_use_class_patching(self):
# several other methods like this
# test code ..
@mock.patch('my_module.cls.method', mock.Mock(side_effect=RuntimeError('custom'))
def test_override_class_patching(self):
# test code ...
</code></pre>
| 0 |
2016-09-23T02:32:50Z
| 39,651,756 |
<p>This can only work if the class decorator is written to account for the use of method decorators. Although the class decorator appears first, it can only run after the class object has been created, which happens after all of the methods have been defined (and decorated).</p>
<p>Class decorators run <em>after</em> method decorators, not before.</p>
| 0 |
2016-09-23T02:42:15Z
|
[
"python",
"unit-testing",
"tdd",
"python-unittest",
"python-unittest.mock"
] |
Override the class patch with method patch (decorator)
| 39,651,686 |
<p>I have several test methods in a class that use one type of patching for a object, so I have patched with class decorator. For a single another method i want to patch the same object differently. I tried the following approach, but the patch made as class decorator is in effect despite the method itself being decorated with different patch. I expected method patch to override class patch. Why is this not the case?</p>
<p>In this particular case I can remove class patch and patch individual methods, but that would be repetitive. How can I implement such overriding (method overrides class patch) mechanism? </p>
<pre><code>from unittest TestCase
from unittest import mock
@mock.patch('my_module.cls.method', mock.Mock(side_effect=RuntimeError('testing'))
class SwitchViewTest(TestCase):
def test_use_class_patching(self):
# several other methods like this
# test code ..
@mock.patch('my_module.cls.method', mock.Mock(side_effect=RuntimeError('custom'))
def test_override_class_patching(self):
# test code ...
</code></pre>
| 0 |
2016-09-23T02:32:50Z
| 39,665,324 |
<p>I would take an entirely different approach.</p>
<pre><code>class SwitchViewTest(TestCase):
class SwitchViewStub(SwitchView):
""" Stub out class under test """
def __init__(self):
""" Bypass Constructor """
self.args = None
... # Fill in the rest
def setUp():
self.helper = self.SwitchViewStub()
self.helper.method_to_mock = MagicMock(...)
...
def test_override_class_patching(self):
with mock.patch.object(self.helper, 'method_to_mock', ...):
...
</code></pre>
| 0 |
2016-09-23T16:16:42Z
|
[
"python",
"unit-testing",
"tdd",
"python-unittest",
"python-unittest.mock"
] |
Does import call __new__ static method?
| 39,651,989 |
<p>I know that <code>__new__</code> method is called when attempt to create an instance of a class before <code>__init__</code> is called.</p>
<p>But i happened to find that, import a module withou create instance will also call <code>__new__</code></p>
<p>suppose i have this:</p>
<p>a.py:</p>
<pre><code>import abc
class A(abc.ABCMeta):
def __new__(cls, name, bases, namespace):
print("ttt:", cls, name, bases, namespace)
retval = abc.ABCMeta.__new__(cls, name, bases, namespace)
return retval
class B(object):
__metaclass__ = A
</code></pre>
<p>and</p>
<p>b.py</p>
<pre><code>import a
class C(B):
def a():
pass
</code></pre>
<p>Then i execute <code>python b.py</code>, i can see two <code>ttt</code> print by <code>__new__</code>.
So, when does the <strong>new</strong> exactly called, in this case, i never create any instance of the three classes i defined</p>
| 1 |
2016-09-23T03:14:11Z
| 39,652,110 |
<p>When you use a metaclass to define a class, the metaclass is "called" implicitly (which invokes <code>__new__</code> since the metaclass here is an actual class), see <a href="https://www.python.org/dev/peps/pep-3115/" rel="nofollow">Invoking the metaclass</a>. I can't say why you see three prints here (you only have two classes that uses <code>A</code> as a metaclass, directly or indirectly through inheritance), but that explains two of the <code>print</code>s.</p>
| 2 |
2016-09-23T03:29:36Z
|
[
"python",
"class",
"metaclass"
] |
"'module' object has no attribute 'SSLContext'" error when using flocker-api
| 39,651,998 |
<p>This is the flocker api url </p>
<p><a href="https://docs.clusterhq.com/en/latest/reference/api.html" rel="nofollow">https://docs.clusterhq.com/en/latest/reference/api.html</a></p>
<p>I try to use httplib to make https connection,but I can not get through the ssl verification [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:765)</p>
<p>by the way: it shows an error :</p>
<blockquote>
<p>AttributeError: 'module' object has no attribute 'SSLContext' </p>
</blockquote>
<p>My python version is 2.7.6, <strong>BUT</strong> if I use python 2.7.5 it pass through.</p>
| 0 |
2016-09-23T03:15:22Z
| 39,652,872 |
<p>i solved my problem myself,this is my code
import httplib
import ssl
import json
import socket</p>
<pre><code>httpsConn = None
# KEY_FILE = "/etc/flocker/scio01.key"
# CERT_FILE = "/etc/flocker/scio01.crt"
# CA_FILE = "/etc/flocker/cluster.crt"
KEY_FILE = "/root/lichao_test/scio01.key"
CERT_FILE = "/root/lichao_test/scio01.crt"
CA_FILE = "/root/lichao_test/cluster.crt"
HOST = "192.168.9.14"
PORT = 4523
body = {
"dataset_id": "a1234567-3fb9-4c1a-81ce-efeeb9f2c788",
"primary": "c1234567-17b2-4812-beca-1434997d6c3f",
"metadata": {
"name": "demo",
"owner": "lichao"
},
"maximum_size": 67108864
}
try:
httpsConn = httplib.HTTPSConnection(HOST, PORT)
sock = socket.create_connection((HOST, PORT))
try:
httpsConn.sock = ssl.wrap_socket(sock, ca_certs=CA_FILE, keyfile=KEY_FILE, certfile=CERT_FILE,
cert_reqs=ssl.CERT_REQUIRED, ssl_version=ssl.PROTOCOL_SSLv3)
json_body = json.dumps(body)
# httpsConn.request(method="POST", url="https://192.168.9.14:4523/v1/configuration/datasets",
# headers={"Content-type": "application/json", 'Connection': 'keep-alive'}, body=json_body)
httpsConn.request(method="GET",url="/v1/configuration/datasets",headers={"Content-type": "application/json", 'Connection': 'keep-alive'})
res = httpsConn.getresponse()
body = res.read()
status = res.status
print "-" * 70
print status, body
except ssl.SSLError, e:
print "Trying SSLv23.",e
except Exception, e:
import traceback
print traceback.format_exc()
</code></pre>
| 0 |
2016-09-23T04:54:55Z
|
[
"python",
"ssl"
] |
What is wrong with my histogram?
| 39,652,026 |
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import xlrd
import xlwt
wb = xlrd.open_workbook('Scatter plot.xlsx')
sh1 = wb.sheet_by_name('T180')
sh2=wb.sheet_by_name("T181")
sh3=wb.sheet_by_name("Sheet1")
x= np.array([sh1.col_values(7, start_rowx=50, end_rowx=315)])
x1= np.array([sh2.col_values(1, start_rowx=48, end_rowx=299)])
y=np.array([sh1.col_values(2, start_rowx=50, end_rowx=299)])
y1= np.array([sh2.col_values(2, start_rowx=48, end_rowx=299)])
print x
plt.hist(x,bins=50)
plt.xlabel("dx (micron)")
plt.ylabel("dy (micron)")
plt.show()
</code></pre>
<p>As you can see the figure from link is obtained by this code. Why this histogram is like this?</p>
<p><a href="http://i.stack.imgur.com/EmvTR.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/EmvTR.jpg" alt="enter image description here"></a></p>
<p>How can I solve it? Thanks in advance for your kind help.</p>
| 0 |
2016-09-23T03:18:45Z
| 39,674,127 |
<p>The shape of <code>x</code> is <code>(1, 265)</code>, it's a 2-dim array, you need to convert it to 1-dim array first:</p>
<pre><code>plt.hist(x.ravel(), bins=50)
</code></pre>
| 1 |
2016-09-24T08:15:34Z
|
[
"python",
"arrays",
"numpy",
"histogram"
] |
Django - Filtering inside of get_context_data
| 39,652,109 |
<p>Using class-based views in Django, I'm having a problem filering inside of a DetailView.</p>
<p>What i would like to get is a list of all movies in a specific genre ie: <code>Movie.objects.all().filter(genre=genre_id)</code>.</p>
<pre><code>class GenreView(generic.DetailView):
model = Genre
template_name = 'movies/genre.html'
context_object_name = 'this_genre'
def get_context_data(self, **kwargs):
context = super(GenreView, self).get_context_data(**kwargs)
context.update({
'all_movies': Movie.objects.all().filter(genre=pk),
'all_genres': Genre.objects.all()
})
return context
</code></pre>
<p>I get this error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handler
s\base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handler
s\base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\views\generi
c\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\views\generi
c\base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\views\generi
c\detail.py", line 118, in get
context = self.get_context_data(object=self.object)
File "C:\Users\admin\trailers\movies\views.py", line 43, in get_context_data
'all_movies': Movie.objects.all().filter(genre=pk),
NameError: name 'pk' is not defined
</code></pre>
<p>When I tried replacing <code>Movie.objects.all().filter(genre=pk)</code> with <code>Movie.objects.all().filter(genre=kwargs['pk'])</code> I got:</p>
<pre><code>Traceback (most recent call last):
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handler
s\base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handler
s\base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\views\generi
c\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\views\generi
c\base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\views\generi
c\detail.py", line 118, in get
context = self.get_context_data(object=self.object)
File "C:\Users\admin\trailers\movies\views.py", line 43, in get_context_data
'all_movies': Movie.objects.all().filter(genre=kwargs['pk']),
KeyError: 'pk'
</code></pre>
<p>I can't seem to figure out what's wrong, any help would be appreciated!</p>
| 1 |
2016-09-23T03:29:32Z
| 39,652,198 |
<pre><code> 'all_movies': Movie.objects.all().filter(genre=pk)
</code></pre>
<p>you literally haven't defined pk. You need to assign the pk to the pk variable first.</p>
<p>Also you don't need to include all:</p>
<pre><code>Movie.objects.filter(genre=pk)
</code></pre>
| 0 |
2016-09-23T03:39:41Z
|
[
"python",
"django"
] |
Django - Filtering inside of get_context_data
| 39,652,109 |
<p>Using class-based views in Django, I'm having a problem filering inside of a DetailView.</p>
<p>What i would like to get is a list of all movies in a specific genre ie: <code>Movie.objects.all().filter(genre=genre_id)</code>.</p>
<pre><code>class GenreView(generic.DetailView):
model = Genre
template_name = 'movies/genre.html'
context_object_name = 'this_genre'
def get_context_data(self, **kwargs):
context = super(GenreView, self).get_context_data(**kwargs)
context.update({
'all_movies': Movie.objects.all().filter(genre=pk),
'all_genres': Genre.objects.all()
})
return context
</code></pre>
<p>I get this error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handler
s\base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handler
s\base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\views\generi
c\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\views\generi
c\base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\views\generi
c\detail.py", line 118, in get
context = self.get_context_data(object=self.object)
File "C:\Users\admin\trailers\movies\views.py", line 43, in get_context_data
'all_movies': Movie.objects.all().filter(genre=pk),
NameError: name 'pk' is not defined
</code></pre>
<p>When I tried replacing <code>Movie.objects.all().filter(genre=pk)</code> with <code>Movie.objects.all().filter(genre=kwargs['pk'])</code> I got:</p>
<pre><code>Traceback (most recent call last):
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handler
s\base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handler
s\base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\views\generi
c\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\views\generi
c\base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\views\generi
c\detail.py", line 118, in get
context = self.get_context_data(object=self.object)
File "C:\Users\admin\trailers\movies\views.py", line 43, in get_context_data
'all_movies': Movie.objects.all().filter(genre=kwargs['pk']),
KeyError: 'pk'
</code></pre>
<p>I can't seem to figure out what's wrong, any help would be appreciated!</p>
| 1 |
2016-09-23T03:29:32Z
| 39,652,206 |
<p>The <code>kwargs</code> parameter passed to <code>get_context_data</code> doesn't contain the primary key value of the object. You can get it from <code>self.kwargs</code> though:</p>
<pre><code>Movie.objects.all().filter(genre=self.kwargs['pk'])
</code></pre>
<p>Furthermore, you will see <code>self.object</code> <em>(which is the the <code>Genre</code> instance fetched)</em> is present and accessible when you are inside <code>get_context_data</code>, so you can use that in order to do the following as well:</p>
<pre><code>Movie.objects.all().filter(genre=self.object)
</code></pre>
| 2 |
2016-09-23T03:40:27Z
|
[
"python",
"django"
] |
How can I improve the speed of this shortest path/shortcut(array graph DS) solution?
| 39,652,116 |
<p>Given a maze as an array of arrays where 1 is a wall and 0 is a passable area:
</p>
<pre><code>Must include start node in distance, if you BFS this it will give you 21.
[0][0] is the start point.
|
[ V
[0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0]<-- [-1][-1] is the end point.
]
</code></pre>
<p>We must find the shortest path possible, we can remove one '1' to help create a shortcut.</p>
<p>The shortcut that creates the shortest path is changing [1][0] to 0, opening a path that makes the distance 11.</p>
<pre><code>[
[0, 0, 0, 0, 0, 0],
-->[0, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0]
]
return 11
</code></pre>
<p>My original thought process was run through every element and check if it's == 1, then do a bfs compare the distance with the min.</p>
<p>But ofcourse that was too slow. So I thought running through every element and check if it's 1, then see if it has exactly two neighbors that are passable because that seems to the only possible case where a shortcut is meaningful.</p>
<p>Here is my code:</p>
<pre><code>import copy
def bfs(maze):
visited = set()
queue = []
mazeHeight = len(maze)
mazeWidth = len(maze[0])
queue.append(((0,0),1))
while queue:
yx,distance = queue.pop(0)
y,x = yx
visited.add(yx)
if yx == (mazeHeight-1,mazeWidth-1):
return distance
if y+1 < mazeHeight:
if not maze[y+1][x] and (y+1,x) not in visited:
queue.append(((y+1,x),distance+1))
if y-1 >= 0:
if not maze[y-1][x] and (y-1,x) not in visited:
queue.append(((y-1,x),distance+1))
if x+1 < mazeWidth:
if not maze[y][x+1] and (y,x+1) not in visited:
queue.append(((y,x+1),distance+1))
if x-1 >= 0:
if not maze[y][x-1] and (y,x-1) not in visited:
queue.append(((y,x-1),distance+1))
return False
def answer(maze):
min = bfs(maze)
mazeHeight = len(maze)
mazeWidth = len(maze[0])
for y in range(mazeHeight):
for x in range(mazeWidth):
if maze[y][x]:
oneNeighbors = 0
if y+1 < mazeHeight:
if not maze[y+1][x]:
oneNeighbors += 1
if y-1 >= 0:
if not maze[y-1][x]:
oneNeighbors += 1
if x+1 < mazeWidth:
if not maze[y][x+1]:
oneNeighbors += 1
if x-1 >= 0:
if not maze[y][x-1]:
oneNeighbors += 1
if oneNeighbors == 2:
tmpMaze = copy.deepcopy(maze)
tmpMaze[y][x] = 0
tmpMin = bfs(tmpMaze)
if tmpMin < min:
min = tmpMin
return min
print(answer([[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]]))
</code></pre>
<p>Any suggestions to improve the speed?</p>
| 1 |
2016-09-23T03:30:14Z
| 39,652,368 |
<p>You seem to be on the right track. The following approach can be considered:</p>
<ol>
<li><p>Form a graph of <code>n x m</code> nodes where <code>n</code> and <code>m</code> are the dimensions of the maze matrix.</p></li>
<li><p>There is an edge of cost <strong>zero</strong> between two nodes if they are adjacent <code>0</code>s. There is an edge of cost <strong>one</strong> between two nodes if they are both <code>0</code>s separated by a <code>1</code>.</p></li>
</ol>
<p>(Note that there shall be two costs that you shall need to maintain for each path, one is the above <code>zero-one</code> cost and the other is the number of nodes in the path to keep track of the minimum).</p>
<ol start="3">
<li><p>Then perform BFS and consider only paths that have a <code>zero-one cost <= 1</code>.</p></li>
<li><p>This shall give you a linear time algorithm (linear in number of nodes).</p></li>
</ol>
<p>Following code may contain bugs but it should get you started.</p>
<pre><code>def bfs(maze):
visited = set()
queue = []
mazeHeight = len(maze)
mazeWidth = len(maze[0])
queue.append(((0,0),1,0))
while queue:
yx,distance, cost = queue.pop(0)
y,x = yx
visited.add(yx)
if yx == (mazeHeight-1,mazeWidth-1):
return distance
if y+1 < mazeHeight:
if not maze[y+1][x] and (y+1,x) not in visited:
queue.append(((y+1,x),distance+1, cost))
if y-1 >= 0:
if not maze[y-1][x] and (y-1,x) not in visited:
queue.append(((y-1,x),distance+1, cost))
if x+1 < mazeWidth:
if not maze[y][x+1] and (y,x+1) not in visited:
queue.append(((y,x+1),distance+1, cost))
if x-1 >= 0:
if not maze[y][x-1] and (y,x-1) not in visited:
queue.append(((y,x-1),distance+1, cost))
if cost == 0:
if y+2 < mazeHeight:
if not maze[y+2][x] and (y+2,x) not in visited and maze[y+1][x] == 1:
queue.append(((y+2,x),distance+2, cost+1))
if y-1 >= 0:
if not maze[y-2][x] and (y-2,x) not in visited and maze[y-1][x] == 1:
queue.append(((y-2,x),distance+2, cost+1))
if x+1 < mazeWidth:
if not maze[y][x+2] and (y,x+2) not in visited and maze[y][x+1] == 1:
queue.append(((y,x+2),distance+2, cost+1))
if x-1 >= 0:
if not maze[y][x-2] and (y,x-2) not in visited and maze[y][x-1] == 1:
queue.append(((y,x-2),distance+2, cost+1))
return False
</code></pre>
| 1 |
2016-09-23T03:58:37Z
|
[
"python",
"algorithm",
"data-structures",
"array-algorithms"
] |
Error when trying to write a matplotlib plot from Pandas DataFrame to pdf
| 39,652,147 |
<p>I'm trying to write a plot from matplotlib to a pdf file but getting an error. </p>
<p>I'm creating a plot using matplotlib from a Pandas DataFrame like this:</p>
<pre><code>bplot = dfbuild.plot(x='Build',kind='barh',stacked='True')
</code></pre>
<p>From the documentation: <a href="http://matplotlib.org/faq/howto_faq.html#save-multiple-plots-to-one-pdf-file" rel="nofollow">http://matplotlib.org/faq/howto_faq.html#save-multiple-plots-to-one-pdf-file</a></p>
<p>It seems like I should be doing it this way:</p>
<pre><code>from matplotlib.backends.backend_pdf import PdfPages
pp = PdfPages(r'c:\temp\page.pdf')
figure = bplot.fig
pp.savefig(figure)
pp.close()
</code></pre>
<p>I get this error: </p>
<pre><code>AttributeError: 'AxesSubplot' object has no attribute 'fig'
</code></pre>
| 0 |
2016-09-23T03:34:03Z
| 39,652,874 |
<p>I works when I do it this way.</p>
<pre><code>pp = PdfPages(r'c:\temp\page.pdf')
dfbuild.plot(x=['Build','Opperator'],kind='barh',stacked='True')
pp.savefig()
pp.close()
</code></pre>
<p>From <a href="http://stackoverflow.com/questions/21364405/saving-plots-to-pdf-files-using-matplotlib">Saving plots to pdf files using matplotlib</a></p>
| 0 |
2016-09-23T04:54:59Z
|
[
"python",
"pandas",
"matplotlib",
"plot",
"pdfpages"
] |
Error when trying to write a matplotlib plot from Pandas DataFrame to pdf
| 39,652,147 |
<p>I'm trying to write a plot from matplotlib to a pdf file but getting an error. </p>
<p>I'm creating a plot using matplotlib from a Pandas DataFrame like this:</p>
<pre><code>bplot = dfbuild.plot(x='Build',kind='barh',stacked='True')
</code></pre>
<p>From the documentation: <a href="http://matplotlib.org/faq/howto_faq.html#save-multiple-plots-to-one-pdf-file" rel="nofollow">http://matplotlib.org/faq/howto_faq.html#save-multiple-plots-to-one-pdf-file</a></p>
<p>It seems like I should be doing it this way:</p>
<pre><code>from matplotlib.backends.backend_pdf import PdfPages
pp = PdfPages(r'c:\temp\page.pdf')
figure = bplot.fig
pp.savefig(figure)
pp.close()
</code></pre>
<p>I get this error: </p>
<pre><code>AttributeError: 'AxesSubplot' object has no attribute 'fig'
</code></pre>
| 0 |
2016-09-23T03:34:03Z
| 39,656,357 |
<p>The problem is that <code>dfbuild.plot</code> returns an <code>AxesSubplot</code> and not a <code>Figure</code> instance, which is required by the <code>savefig</code> function.</p>
<p>This solves the issue:</p>
<pre><code>pp.savefig(bplot.figure)
</code></pre>
| 1 |
2016-09-23T08:37:56Z
|
[
"python",
"pandas",
"matplotlib",
"plot",
"pdfpages"
] |
Django Integration tests for urls
| 39,652,204 |
<p>I have a django app I wanted to write tests for. For now Im writing integration tests for the urls. </p>
<p>For my <code>signin</code> test , my url looks like:
<code>url(r'^signin/$', login_forbidden(signin), name='signin')</code></p>
<p>and my test looks like:</p>
<pre><code>from django.test import TestCase
class SigninTest(TestCase):
def test_signin(self):
resp = self.client.get('/signin/')
self.assertEqual(resp.status_code, 200)
</code></pre>
<p>However I have no idea to test a a longer url, for instance I have one entry in urls like:</p>
<pre><code>url(
r'^ad_accounts/(?P<ad_account_id>[^/]+)/$',
AdAccountDetailView.as_view(),
name='campaigns'
),
</code></pre>
<p>If I repeat the above test I have for the signin page (replacing <code>resp = self.client.get('/ad_accounts/')</code>) returns a failure</p>
<pre><code>======================================================================
FAIL: test_signin (engineoftravel.tests.SigninTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "path/to/project/tests.py", line 7, in test_signin
self.assertEqual(resp.status_code, 200)
AssertionError: 302 != 200
----------------------------------------------------------------------
Ran 1 test in 0.103s
FAILED (failures=1)
</code></pre>
| 0 |
2016-09-23T03:40:23Z
| 39,652,238 |
<p>why not use reverse: <a href="https://docs.djangoproject.com/en/1.10/ref/urlresolvers/#reverse" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/urlresolvers/#reverse</a></p>
<pre><code>from django.core.urlresolvers import reverse
....
resp = self.client.get(reverse('campaigns', args=[1]))
</code></pre>
<p>where args is the id you need to pass in.</p>
<p>EDIT: since django 1.10 reverse imports from django.urls</p>
| 1 |
2016-09-23T03:44:40Z
|
[
"python",
"django",
"integration-testing"
] |
Django Integration tests for urls
| 39,652,204 |
<p>I have a django app I wanted to write tests for. For now Im writing integration tests for the urls. </p>
<p>For my <code>signin</code> test , my url looks like:
<code>url(r'^signin/$', login_forbidden(signin), name='signin')</code></p>
<p>and my test looks like:</p>
<pre><code>from django.test import TestCase
class SigninTest(TestCase):
def test_signin(self):
resp = self.client.get('/signin/')
self.assertEqual(resp.status_code, 200)
</code></pre>
<p>However I have no idea to test a a longer url, for instance I have one entry in urls like:</p>
<pre><code>url(
r'^ad_accounts/(?P<ad_account_id>[^/]+)/$',
AdAccountDetailView.as_view(),
name='campaigns'
),
</code></pre>
<p>If I repeat the above test I have for the signin page (replacing <code>resp = self.client.get('/ad_accounts/')</code>) returns a failure</p>
<pre><code>======================================================================
FAIL: test_signin (engineoftravel.tests.SigninTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "path/to/project/tests.py", line 7, in test_signin
self.assertEqual(resp.status_code, 200)
AssertionError: 302 != 200
----------------------------------------------------------------------
Ran 1 test in 0.103s
FAILED (failures=1)
</code></pre>
| 0 |
2016-09-23T03:40:23Z
| 39,652,433 |
<pre><code>from django.test import TestCase
from django.test import Client
from django.core.urlresolvers import reverse
client = Client()
class MainTest(TestCase):
##user login in django
def user_login(self, username, password):
response = self.client.login(username=username, password=username)
return self.assertEqual(resp.status_code, 200)
## first case
def detail(self):
response = self.client.get('/ad_accounts/<test_num>/') ## url regex
self.assertEquals(response.status_code, 200)
def detail2(self):
response = self.client.get(reverse('campaigns'))
self.assertEqual(response.status_code, 200)
</code></pre>
| 0 |
2016-09-23T04:04:56Z
|
[
"python",
"django",
"integration-testing"
] |
Django Integration tests for urls
| 39,652,204 |
<p>I have a django app I wanted to write tests for. For now Im writing integration tests for the urls. </p>
<p>For my <code>signin</code> test , my url looks like:
<code>url(r'^signin/$', login_forbidden(signin), name='signin')</code></p>
<p>and my test looks like:</p>
<pre><code>from django.test import TestCase
class SigninTest(TestCase):
def test_signin(self):
resp = self.client.get('/signin/')
self.assertEqual(resp.status_code, 200)
</code></pre>
<p>However I have no idea to test a a longer url, for instance I have one entry in urls like:</p>
<pre><code>url(
r'^ad_accounts/(?P<ad_account_id>[^/]+)/$',
AdAccountDetailView.as_view(),
name='campaigns'
),
</code></pre>
<p>If I repeat the above test I have for the signin page (replacing <code>resp = self.client.get('/ad_accounts/')</code>) returns a failure</p>
<pre><code>======================================================================
FAIL: test_signin (engineoftravel.tests.SigninTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "path/to/project/tests.py", line 7, in test_signin
self.assertEqual(resp.status_code, 200)
AssertionError: 302 != 200
----------------------------------------------------------------------
Ran 1 test in 0.103s
FAILED (failures=1)
</code></pre>
| 0 |
2016-09-23T03:40:23Z
| 39,652,671 |
<p>For the test failure, you should first <a href="https://docs.djangoproject.com/en/1.10/topics/testing/tools/#django.test.Client.login" rel="nofollow">login</a> with some test user then make a request, otherwise the page will be redirected to the login page and thus you will get a 302 status code.</p>
<p>Also you can test the status code of the redirected page with <code>client.get('/foo', follow=True)</code> which returns the status code of the sign in page. (In your example)</p>
| 0 |
2016-09-23T04:32:04Z
|
[
"python",
"django",
"integration-testing"
] |
Python multiprocessing lock strange behavior
| 39,652,270 |
<p>I notice a behaviour in my code that I cannot explain. This is the code:</p>
<pre><code>import multiprocessing
from collections import deque
LOCK = multiprocessing.Lock()
data = deque(['apple', 'orange', 'melon'])
def f(*args):
with LOCK:
data.rotate()
print data[0]
pool = multiprocessing.Pool()
pool.map(f, range(4))
</code></pre>
<p>I expect that the output would be </p>
<pre><code>melon
orange
apple
melon
</code></pre>
<p>but instead I get</p>
<pre><code>melon
melon
melon
</code></pre>
<p>Any ideas would be greatly appreciated.</p>
| 0 |
2016-09-23T03:48:46Z
| 39,652,421 |
<p>As Tim Peters commented, the problem is not the <code>Lock</code> but that the <code>deque</code> is not shared across the processes but every process will have their own copy.</p>
<p>There are some data structures provided by the <code>multiprocessing</code> module which will be shared across processes, e.g. <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Queue" rel="nofollow"><code>multiprocessing.Queue</code></a>. Use that instead.</p>
| 1 |
2016-09-23T04:04:19Z
|
[
"python",
"multiprocessing",
"python-multiprocessing"
] |
or statement invalid syntax
| 39,652,319 |
<p>So, a friend of mine told me about or statements but when I use it, it says invalid syntax... but won't tell me where </p>
<pre><code>#Fun Game
print("Enter name")
firstname = input()
print ("Thousands of years further from our time, the continents collided, creating mass devastation and heat.You,"+firstname+" lived in a peacful village until")
print (" your village was raided by four men, everyone else died other than you, who was trained as an assasin and killed them all")
age1 = input ("you,"+firstname+" as a 16 year old killed them all and escaped into a cave. Now that cave is what you call home.Enter your character's current age(max 25 min 20) ")
if age1 == "20":
print("")
or age1 == "21":
print("")
or age1 == "22":
print ("")
or age1 == "23":
print ("")
or age1 == "24":
print ("")
or age1 == "25":
print("")
else:
print ("Choose an age in the list")
cave1 = input ("You can do 2 things:")
print ("1.Go to your friend's village(700 people,military grade)and trade,look for bountys and find news")
</code></pre>
| 0 |
2016-09-23T03:54:25Z
| 39,652,375 |
<pre><code>print("Enter name")
firstname = input()
print ("Thousands of years further from our time, the continents collided, creating mass devastation and heat.You,"+firstname+" lived in a peacful village until")
print (" your village was raided by four men, everyone else died other than you, who was trained as an assasin and killed them all")
age1 = input ("you,"+firstname+" as a 16 year old killed them all and escaped into a cave. Now that cave is what you call home.Enter your character's current age(max 25 min 20) ")
if age1 == "20": print("")
elif age1 == "21": print("")
elif age1 == "22": print ("")
elif age1 == "23": print ("")
elif age1 == "24": print ("")
elif age1 == "25": print("")
else: print ("Choose an age in the list")
cave1 = input ("You can do 2 things:")
print ("1.Go to your friend's village(700 people,military grade)and trade,look for bountys and find news")
</code></pre>
| 0 |
2016-09-23T03:59:09Z
|
[
"python",
"python-3.x"
] |
or statement invalid syntax
| 39,652,319 |
<p>So, a friend of mine told me about or statements but when I use it, it says invalid syntax... but won't tell me where </p>
<pre><code>#Fun Game
print("Enter name")
firstname = input()
print ("Thousands of years further from our time, the continents collided, creating mass devastation and heat.You,"+firstname+" lived in a peacful village until")
print (" your village was raided by four men, everyone else died other than you, who was trained as an assasin and killed them all")
age1 = input ("you,"+firstname+" as a 16 year old killed them all and escaped into a cave. Now that cave is what you call home.Enter your character's current age(max 25 min 20) ")
if age1 == "20":
print("")
or age1 == "21":
print("")
or age1 == "22":
print ("")
or age1 == "23":
print ("")
or age1 == "24":
print ("")
or age1 == "25":
print("")
else:
print ("Choose an age in the list")
cave1 = input ("You can do 2 things:")
print ("1.Go to your friend's village(700 people,military grade)and trade,look for bountys and find news")
</code></pre>
| 0 |
2016-09-23T03:54:25Z
| 39,652,438 |
<p>When you use the 'or' operator, you use it as part of the condition.
For example:</p>
<pre><code>if x == 1 or x == 5:
print(x)
</code></pre>
<p>So your code would be one long line, without all of the print statements:</p>
<pre><code>if age1 == "20" or age1 == "21" or age1 == "22" or age1 == "23" or age1 == "24" or age1 == "25":
print("")
</code></pre>
<p>From your code I think what you want is an elif statement:</p>
<pre><code>if age1 == "20":
##Do something based on input of 20
elif age1 == "21":
##Do something else if input is 21
elif age1 == "22":
##Something else again if input is 22
else:
##Do something if the age is not captured above.
</code></pre>
<p>You only need to use the "or" operator if you need one of two or more conditions to be true. But if you just want to check if the input age is within the range try this:</p>
<pre><code>if inval >= 20 and inval <= 25:
print("Correct Value")
else:
print("Incorrect value")
</code></pre>
<p>Or, using range:</p>
<pre><code>if inval in range(20, 26):
print("Correct Value")
else:
print("Incorrect value")
</code></pre>
| 0 |
2016-09-23T04:05:09Z
|
[
"python",
"python-3.x"
] |
or statement invalid syntax
| 39,652,319 |
<p>So, a friend of mine told me about or statements but when I use it, it says invalid syntax... but won't tell me where </p>
<pre><code>#Fun Game
print("Enter name")
firstname = input()
print ("Thousands of years further from our time, the continents collided, creating mass devastation and heat.You,"+firstname+" lived in a peacful village until")
print (" your village was raided by four men, everyone else died other than you, who was trained as an assasin and killed them all")
age1 = input ("you,"+firstname+" as a 16 year old killed them all and escaped into a cave. Now that cave is what you call home.Enter your character's current age(max 25 min 20) ")
if age1 == "20":
print("")
or age1 == "21":
print("")
or age1 == "22":
print ("")
or age1 == "23":
print ("")
or age1 == "24":
print ("")
or age1 == "25":
print("")
else:
print ("Choose an age in the list")
cave1 = input ("You can do 2 things:")
print ("1.Go to your friend's village(700 people,military grade)and trade,look for bountys and find news")
</code></pre>
| 0 |
2016-09-23T03:54:25Z
| 39,652,451 |
<p>Poonam's answer looks fine, but you probably also don't want that many if statements:</p>
<pre><code>print("Enter name")
firstname = input()
print ("Thousands of years further from our time, the continents collided, creating mass devastation and heat.You,"+firstname+" lived in a peacful village until")
print (" your village was raided by four men, everyone else died other than you, who was trained as an assasin and killed them all")
age1 = input ("you,"+firstname+" as a 16 year old killed them all and escaped into a cave. Now that cave is what you call home.Enter your character's current age(max 25 min 20) ")
if age1 in ["20","21","22","23","24","25"]:
print("")
else:
print ("Choose an age in the list")
cave1 = input ("You can do 2 things:")
print ("1.Go to your friend's village(700 people,military grade)and trade,look for bountys and find news")
</code></pre>
| 0 |
2016-09-23T04:06:25Z
|
[
"python",
"python-3.x"
] |
regex - merge repeated consecutive words preserving last space
| 39,652,420 |
<p>I have a string like this</p>
<p><code>{{TAG}} {{TAG}}{{TAG}} {{TAG}} some other text. {{TAG}} {{TAG}}</code></p>
<p>and I am trying to merge multiple consecutive occurrences of <code>{{TAG}}</code> into one. So I have this regex <code>re.sub(r'(({{TAG}})\s*)+', "{{TAG}}", text)</code> which works fine to remove multiple occurrences and gives me this </p>
<p><code>{{TAG}}some other text. {{TAG}}</code>.</p>
<p>But its taking one extra space at the end, which I am trying to avoid. So that I get </p>
<p><code>{{TAG}} some other text. {{TAG}}</code></p>
<p>Found a similar question <a href="http://stackoverflow.com/questions/14930320/regular-expression-matching-a-sequence-of-consecutive-words-with-spaces-except-f">here</a>, but that didn't solve my problem. Any suggestions to improve my regex or any other alternative in python?</p>
| 0 |
2016-09-23T04:04:17Z
| 39,652,519 |
<p>One simple way is that instead of <code>+</code> you can split the regex into two as</p>
<pre><code>>>> re.sub(r'(?:{{TAG}}\s*)*{{TAG}}', r'{{TAG}}', string)
'{{TAG}} some other text. {{TAG}}'
</code></pre>
<ul>
<li><p><code>(?:{{TAG}}\s*)*</code> Matches zero or more <code>{{TAG}}</code> with space at the end.</p></li>
<li><p><code>{{TAG}}</code> Match the last <code>{{TAG}}</code> without any space.</p></li>
</ul>
<hr>
<p>You can also solve this using a positive look ahead </p>
<pre><code>>>> re.sub(r'{{TAG}}\s*(?={{TAG}})', r'', string)
'{{TAG}} some other text. {{TAG}}'
</code></pre>
<ul>
<li><p><code>{{TAG}}\s*</code> Matches one <code>{{TAG}}</code> followed by space.</p></li>
<li><p><code>(?={{TAG}}</code> Positive look ahead. Checks if the <code>{{TAG}}</code> matched in the above point is followed by another <code>{{TAG}}</code></p></li>
</ul>
| 3 |
2016-09-23T04:13:20Z
|
[
"python",
"regex"
] |
regex - merge repeated consecutive words preserving last space
| 39,652,420 |
<p>I have a string like this</p>
<p><code>{{TAG}} {{TAG}}{{TAG}} {{TAG}} some other text. {{TAG}} {{TAG}}</code></p>
<p>and I am trying to merge multiple consecutive occurrences of <code>{{TAG}}</code> into one. So I have this regex <code>re.sub(r'(({{TAG}})\s*)+', "{{TAG}}", text)</code> which works fine to remove multiple occurrences and gives me this </p>
<p><code>{{TAG}}some other text. {{TAG}}</code>.</p>
<p>But its taking one extra space at the end, which I am trying to avoid. So that I get </p>
<p><code>{{TAG}} some other text. {{TAG}}</code></p>
<p>Found a similar question <a href="http://stackoverflow.com/questions/14930320/regular-expression-matching-a-sequence-of-consecutive-words-with-spaces-except-f">here</a>, but that didn't solve my problem. Any suggestions to improve my regex or any other alternative in python?</p>
| 0 |
2016-09-23T04:04:17Z
| 39,652,581 |
<p>You're matching <code>{{TAG}}\s*</code> once or more, but you want to match <code>{{TAG}}</code> once, followed by zero or more instances of <code>\s*{{TAG}}</code>.</p>
<pre><code>re.sub('({{TAG}}(?:\s*{{TAG}})*)', '{{TAG}}', text)
</code></pre>
| 1 |
2016-09-23T04:20:08Z
|
[
"python",
"regex"
] |
Confusion matrix raws are mismatched
| 39,652,447 |
<p>I've created a confusion matrix that works all right but its raws don't seem to be connected with the labels as should be.</p>
<p>I have some list of strings which is splitted into train and test sections:</p>
<pre><code> train + test:
positive: 16 + 4 = 20
negprivate: 53 + 14 = 67
negstratified: 893 + 224 = 1117
</code></pre>
<p>The Confusion matrix is built on the test data:</p>
<pre><code> [[ 0 14 0]
[ 3 220 1]
[ 0 4 0]]
</code></pre>
<p>Here is the code:</p>
<pre><code>my_tags = ['negprivate', 'negstratified', 'positive']
def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues):
logging.info('plot_confusion_matrix')
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(my_tags))
target_names = my_tags
plt.xticks(tick_marks, target_names, rotation=45)
plt.yticks(tick_marks, target_names)
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
def evaluate_prediction(target, predictions, taglist, title="Confusion matrix"):
logging.info('Evaluate prediction')
print('accuracy %s' % accuracy_score(target, predictions))
cm = confusion_matrix(target, predictions)
print('confusion matrix\n %s' % cm)
print('(row=expected, col=predicted)')
print 'rows: \n %s \n %s \n %s ' % (taglist[0], taglist[1], taglist[2])
cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
plot_confusion_matrix(cm_normalized, title + ' Normalized')
</code></pre>
<p>...</p>
<pre><code>test_targets, test_regressors = zip(
*[(doc.tags[0], doc2vec_model.infer_vector(doc.words, steps=20)) for doc in alltest])
logreg = linear_model.LogisticRegression(n_jobs=1, C=1e5)
logreg = logreg.fit(train_regressors, train_targets)
evaluate_prediction(test_targets, logreg.predict(test_regressors), my_tags, title=str(doc2vec_model))
</code></pre>
<p>But the point is that I actually have to look at the numbers in the resulting matrix and to change the order of my_tags so that they could be in accordance with each other. And as far as I understand this should be made in some automatic way.
In which, I wonder?</p>
| 0 |
2016-09-23T04:06:11Z
| 39,653,103 |
<p>I think it is just sort-order of your labels, i.e. the output of <code>np.unique(target)</code>.</p>
| 0 |
2016-09-23T05:20:06Z
|
[
"python",
"scikit-learn",
"confusion-matrix"
] |
Confusion matrix raws are mismatched
| 39,652,447 |
<p>I've created a confusion matrix that works all right but its raws don't seem to be connected with the labels as should be.</p>
<p>I have some list of strings which is splitted into train and test sections:</p>
<pre><code> train + test:
positive: 16 + 4 = 20
negprivate: 53 + 14 = 67
negstratified: 893 + 224 = 1117
</code></pre>
<p>The Confusion matrix is built on the test data:</p>
<pre><code> [[ 0 14 0]
[ 3 220 1]
[ 0 4 0]]
</code></pre>
<p>Here is the code:</p>
<pre><code>my_tags = ['negprivate', 'negstratified', 'positive']
def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues):
logging.info('plot_confusion_matrix')
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(my_tags))
target_names = my_tags
plt.xticks(tick_marks, target_names, rotation=45)
plt.yticks(tick_marks, target_names)
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
def evaluate_prediction(target, predictions, taglist, title="Confusion matrix"):
logging.info('Evaluate prediction')
print('accuracy %s' % accuracy_score(target, predictions))
cm = confusion_matrix(target, predictions)
print('confusion matrix\n %s' % cm)
print('(row=expected, col=predicted)')
print 'rows: \n %s \n %s \n %s ' % (taglist[0], taglist[1], taglist[2])
cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
plot_confusion_matrix(cm_normalized, title + ' Normalized')
</code></pre>
<p>...</p>
<pre><code>test_targets, test_regressors = zip(
*[(doc.tags[0], doc2vec_model.infer_vector(doc.words, steps=20)) for doc in alltest])
logreg = linear_model.LogisticRegression(n_jobs=1, C=1e5)
logreg = logreg.fit(train_regressors, train_targets)
evaluate_prediction(test_targets, logreg.predict(test_regressors), my_tags, title=str(doc2vec_model))
</code></pre>
<p>But the point is that I actually have to look at the numbers in the resulting matrix and to change the order of my_tags so that they could be in accordance with each other. And as far as I understand this should be made in some automatic way.
In which, I wonder?</p>
| 0 |
2016-09-23T04:06:11Z
| 39,659,665 |
<p>It's always best to have integer class labels, everything seems to run a bit smoother. You can get these using <code>LabelEncoder</code>, i.e.</p>
<pre><code>from sklearn import preprocessing
my_tags = ['negprivate', 'negstratified', 'positive']
le = preprocessing.LabelEncoder()
new_tags = le.fit_transform(my_tags)
</code></pre>
<p>So now you will have <code>[0 1 2]</code> as your new tags. When you do your plotting, you want your labels to be intuitive, so you can use <code>inverse_transform</code> to get your labels, i.e.</p>
<pre><code>le.inverse_transform(0)
</code></pre>
<p>Outputs:</p>
<pre><code>'negprivate'
</code></pre>
| 0 |
2016-09-23T11:27:49Z
|
[
"python",
"scikit-learn",
"confusion-matrix"
] |
Can't kick out of while loop
| 39,652,449 |
<pre><code>#Fiery Elsa
#ID:899525
#Homework 2, Program 2
#Initialization
count=0
name=input("Enter stock name OR -999 to Quit:")
#Input
while name!=-999:
count=count+1
name=input("Enter stock name OR -999 to Quit:")
shares=int(input("Enter number of shares:"))
pp=float(input("Enter purchase price:"))
sp=float(input("Enter selling price:"))
commission=float(input("Enter commission:"))
#Calculations
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
#Output
print("Stock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))
</code></pre>
<p>Program loops, but doesn't kick out to print output when you press -999. What am I doing wrong?</p>
<p>Ideally, the program should allow the user to input as many times as he/she wants until the user is done. For example: 3 sets of inputs resulting in 3 sets of outputs. </p>
| 0 |
2016-09-23T04:06:18Z
| 39,652,568 |
<p>Your problem seems to be that <code>name</code> is type <code>string</code>, but you're comparing it to <code>-999</code> which has type <code>int</code>.</p>
<p>If you change your loop to read <code>name != "-999"</code> then the comparison works. You'll need to refactor your code some more to make it behave the way you're wanting, but this should be a good start :)</p>
| 0 |
2016-09-23T04:18:31Z
|
[
"python",
"python-3.x",
"while-loop"
] |
Can't kick out of while loop
| 39,652,449 |
<pre><code>#Fiery Elsa
#ID:899525
#Homework 2, Program 2
#Initialization
count=0
name=input("Enter stock name OR -999 to Quit:")
#Input
while name!=-999:
count=count+1
name=input("Enter stock name OR -999 to Quit:")
shares=int(input("Enter number of shares:"))
pp=float(input("Enter purchase price:"))
sp=float(input("Enter selling price:"))
commission=float(input("Enter commission:"))
#Calculations
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
#Output
print("Stock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))
</code></pre>
<p>Program loops, but doesn't kick out to print output when you press -999. What am I doing wrong?</p>
<p>Ideally, the program should allow the user to input as many times as he/she wants until the user is done. For example: 3 sets of inputs resulting in 3 sets of outputs. </p>
| 0 |
2016-09-23T04:06:18Z
| 39,667,764 |
<p>You need to evaluate the value of name after each input.</p>
<pre><code>stock_name = [] # make a list for stock name
shares = [] # change also all other input variables into list type
while True: # this will allow you to loop the input part
name = input()
if name != '-999': # this will evaluate the value of name
stock_name.append(name) # this will add your latest name input to the list
# Do the same to your other inputs
else:
break # exit your while loop
# you need another loop here to do calculations and output
# I think this is where your count variable should go to index your lists
</code></pre>
| 0 |
2016-09-23T18:56:55Z
|
[
"python",
"python-3.x",
"while-loop"
] |
Can't kick out of while loop
| 39,652,449 |
<pre><code>#Fiery Elsa
#ID:899525
#Homework 2, Program 2
#Initialization
count=0
name=input("Enter stock name OR -999 to Quit:")
#Input
while name!=-999:
count=count+1
name=input("Enter stock name OR -999 to Quit:")
shares=int(input("Enter number of shares:"))
pp=float(input("Enter purchase price:"))
sp=float(input("Enter selling price:"))
commission=float(input("Enter commission:"))
#Calculations
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
#Output
print("Stock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))
</code></pre>
<p>Program loops, but doesn't kick out to print output when you press -999. What am I doing wrong?</p>
<p>Ideally, the program should allow the user to input as many times as he/she wants until the user is done. For example: 3 sets of inputs resulting in 3 sets of outputs. </p>
| 0 |
2016-09-23T04:06:18Z
| 39,673,570 |
<pre><code>while name!="-999": #try this one
count=count+1
name=input("Enter stock name OR -999 to Quit:")
shares=int(input("Enter number of shares:"))
pp=float(input("Enter purchase price:"))
sp=float(input("Enter selling price:"))
commission=float(input("Enter commission:"))
</code></pre>
| 0 |
2016-09-24T07:05:26Z
|
[
"python",
"python-3.x",
"while-loop"
] |
How do I not declare a variable in a loop in Python when I have an except argument
| 39,652,464 |
<p>I am trying to iterate through all of the rows on the xml list and write those to csv I need each element value, if it exists, to be written, pipe delimited into the row, or else display a null value. I am able to create the header row and write in the first row of data by using variables, (which is obviously incorrect, but I am very new to python!) Any assistance is appreciated! By the way, please feel free to add anything specific which I could be doing more efficiently or pythonic.</p>
<pre><code>import xml.etree.ElementTree as ET
import sys
import requests
from requests_ntlm import HttpNtlmAuth
import csv
csv.register_dialect(
'mydialect',
delimiter = '|',
quotechar = '"',
doublequote = True,
skipinitialspace = True,
lineterminator = '\n',
quoting = csv.QUOTE_MINIMAL)
url="http://sharepoint/projects/urp/_vti_bin/owssvr.dll?Cmd=Display&List={8e2de4cf-79a0-4267-8b84-889a5b890b28}&XMLDATA=TRUE"
#url="http://sharepoint/projects/urp/Lists/HITS%20Estimation%20LOE/AllItems.aspx"
password = "#######"
Username = "YYYY\\XXXXX"
server_url="http://sharepoint/"
r=requests.get(url, auth=HttpNtlmAuth(Username,password))
data=r.content
tree = ET.fromstring(data) # load the string into a native XML structure
namespaces = {'s': 'uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882','dt': 'uuid:C2F41010-65B3-11d1-A29F-00AA00C14882', 'rs': 'urn:schemas-microsoft-com:rowset', 'z': '#RowsetSchema'}
header_results = tree.findall('./s:Schema/s:ElementType/s:AttributeType', namespaces)
row_results = tree.findall('./rs:data/z:row', namespaces)
with open('c:\output.csv','w') as f:
writer = csv.writer(f, dialect='mydialect')
#This causes the column name to be pipe delimited across the top row of the csv
Header_Row=""
for header in header_results:
try:
Header_Row += header.attrib['name']+"|"
except KeyError:
Header_Row += "NULL|"
writer.writerow([Header_Row])
#This part needs help - I need each element value, if it exists, to be written, pipe delimited into the row, or else display a null value
#Currently this only returns one row of data because I am declaring the variable in the loop... how do I accomplish this otherwise?
for result in row_results:
try:
urpid = result.attrib['ows_CnELookup_x003a_URPID']
except KeyError:
urpid = "NULL"
try:
Attachments = result.attrib['ows_Attachments']
except KeyError:
Attachments = "NULL"
try:
Title = result.attrib['ows_LinkTitle']
except KeyError:
Title = "NULL"
try:
Area = result.attrib['ows_Area_x0020_Name']
except KeyError:
Area = "NULL"
try:
Group = result.attrib['ows_Group']
except KeyError:
Group = "NULL"
try:
HITS_Hours = result.attrib['ows_HITS_x0020_Hours']
except KeyError:
HITS_Hours = "NULL"
try:
Consult_Hours = result.attrib['ows_Consultant_x0020_Hours']
except KeyError:
Consult_Hours = "NULL"
try:
Complete = result.attrib['ows_C_x0026_E_x0020_Completed']
except KeyError:
Complete = "NULL"
try:
Area_Order = result.attrib['ows_Area_x0020_Order']
except KeyError:
Area_Order = "NULL"
SP_Row = urpid, Attachments, Title, Area, Group, HITS_Hours, Consult_Hours, Complete, Area_Order
writer.writerow(SP_Row)
</code></pre>
| 0 |
2016-09-23T04:07:51Z
| 39,653,079 |
<p>Actually, if you indent the last two lines one level, I think you'd have what you're looking for. Your comment in the code mentions "declaring the variable in the loop", but Python variables aren't declared - the only rule is that they must be defined before they are used, which is what you are doing.</p>
<p>As far as a more pythonic way of doing things, the <code>try: ... except KeyError:</code> blocks aren't really the way things are usually done - if you need to get either a stored or default value from a dictionary (named <code>d</code>, for example), use <code>value = d.get(name, default)</code> instead.</p>
<p>Additionally, it looks to me like your header will have an extra <code>|</code> at the end - I'd use this instead:</p>
<pre><code> Header_Row = [ header.attrib.get('name', 'NULL') for header in header_results ]
writer.writerow(Header_Row)
</code></pre>
<p>In place of your loop over the result rows, I'd use the following code:</p>
<pre><code> for results in row_results:
SP_ROW = [ result.attrib.get(key, 'NULL')
for key in [ 'ows_CnELookup_x003a_URPID', 'ows_Attachments',
'ows_LinkTitle', 'ows_Area_x0020_Name', 'ows_Group',
'ows_HITS_x0020_Hours', 'ows_Consultant_x0020_Hours',
'ows_C_x0026_E_x0020_Completed', 'ows_Area_x0020_Order' ] ]
writer.writerow(SP_ROW)
</code></pre>
<p>Your context manager will make sure the output file is closed, so that should be all you need.</p>
| 0 |
2016-09-23T05:17:50Z
|
[
"python",
"xml",
"list",
"loops",
"csv"
] |
pillow image TypeError: an integer is required (got type tuple)
| 39,652,480 |
<p>I am a bit lost as to why this is happening any help would be greatly appreciated. So I am trying to take the median value of images and create a new image from them, but when trying to make newpix take in the values of my red green and blue median pixel the error: </p>
<p>TypeError: an integer is required (got type tuple) </p>
<p>happens</p>
<pre><code>from PIL import Image, ImageChops,ImageDraw,ImageFilter
import math
import glob
import os.path
from os import listdir;
import numpy
image_list = []
redPixels = []
greenPixels = []
bluePixels = []
for filename in glob.glob(r"C:\Users\Elias\Desktop\Proj1\images\*.png"):
im = Image.open(filename)
image_list.append(im)
im = Image.open(open(r"C:\Users\Elias\Desktop\Proj1\images\1.png",'rb'))
width, height = im.size
print(height)
print (width)
result = Image.new('RGB', (width,height))
newpix = result.load()
for x in range (width):
for y in range (height):
for z in (image_list):
red = z.getpixel((x,y))
blue = z.getpixel((x,y))
green = z.getpixel((x,y))
redPixels.append(red)
greenPixels.append(green)
bluePixels.append(blue)
red = sorted(redPixels)
blue = sorted(bluePixels)
green = sorted(greenPixels)
mid = int( (len(image_list)+1)/2)-1
newRed = redPixels[mid]
newBlue = bluePixels[mid]
newGreen = greenPixels[mid]
newpix[x,y] = (newRed,newGreen,newBlue)
result.save("Stacked.png")
</code></pre>
| 1 |
2016-09-23T04:09:42Z
| 39,672,503 |
<p>Problem is at the lines</p>
<pre><code> red = z.getpixel((x,y))
blue = z.getpixel((x,y))
green = z.getpixel((x,y))
redPixels.append(red)
greenPixels.append(green)
bluePixels.append(blue)
</code></pre>
<p><code>red = z.getpixel((x,y))</code> will get all R,G,B data at x,y position, so it will be tuple like (255,255,255). Hence making changes to your code like below made it work:</p>
<pre><code>from PIL import Image, ImageChops,ImageDraw,ImageFilter
import math
import glob
import os.path
from os import listdir;
import numpy
image_list = []
redPixels = []
greenPixels = []
bluePixels = []
for filename in glob.glob(r"C:\Users\Elias\Desktop\Proj1\images\*.png"):
im = Image.open(filename)
image_list.append(im)
im = Image.open(open(r"C:\Users\Elias\Desktop\Proj1\images\1.png",'rb'))
width, height = im.size
print(height)
print (width)
result = Image.new('RGB', (width,height))
newpix = result.load()
for x in range (width):
for y in range (height):
for z in (image_list):
rgb = z.getpixel((x,y))
redPixels.append(rgb[0])
greenPixels.append(rgb[1])
bluePixels.append(rgb[2])
red = sorted(redPixels)
blue = sorted(bluePixels)
green = sorted(greenPixels)
mid = int( (len(image_list)+1)/2)-1
newRed = redPixels[mid]
newBlue = bluePixels[mid]
newGreen = greenPixels[mid]
newpix[x,y] = (newRed,newGreen,newBlue)
result.save("Stacked.png")
</code></pre>
| 2 |
2016-09-24T04:28:20Z
|
[
"python",
"image",
"python-3.x",
"python-imaging-library",
"pillow"
] |
unable to write to CSV after replace
| 39,652,537 |
<p>I have an input file, in which I am making an string replace operation.</p>
<p>I read the file cell by cell, replace the string and then write it back to a new CSV file.</p>
<pre><code>input_file = open('/Users/tcssig/Desktop/unstacked2.csv', 'r', encoding='utf-8')
output_file = open('/Users/tcssig/Desktop/unstacked3.csv', 'w', encoding='utf-8')
writer = csv.writer(output_file , delimiter=' ')
reader = csv.reader(input_file)
for row in reader:
for string in row:
data = [string.replace('read','write')]
print(data)
writer.writerow(data)
</code></pre>
<p>Above code runs well, but I get an empty output file.</p>
<pre><code>Example of data :
reading reading reading reading
interval 0 1 2 3
who axis
Mikael X 0 10 20 30
Mikael Y 50 40 30 20
Mikael Z 100 90 80 70
Mike X 0 0.1 0.2 0.3
Mike Y 0.5 0.4 0.3 0.2
</code></pre>
<p>Mike Z 1 0.9 0.8 0.7</p>
<p>What am i missing?</p>
| 1 |
2016-09-23T04:14:56Z
| 39,652,627 |
<p>Close your files: </p>
<pre><code>output_file.close()
input_file.close()
</code></pre>
<p>Also see this answer regarding use of context managers
<a href="http://stackoverflow.com/a/441446/4663466">http://stackoverflow.com/a/441446/4663466</a></p>
| 2 |
2016-09-23T04:26:23Z
|
[
"python",
"csv"
] |
unable to write to CSV after replace
| 39,652,537 |
<p>I have an input file, in which I am making an string replace operation.</p>
<p>I read the file cell by cell, replace the string and then write it back to a new CSV file.</p>
<pre><code>input_file = open('/Users/tcssig/Desktop/unstacked2.csv', 'r', encoding='utf-8')
output_file = open('/Users/tcssig/Desktop/unstacked3.csv', 'w', encoding='utf-8')
writer = csv.writer(output_file , delimiter=' ')
reader = csv.reader(input_file)
for row in reader:
for string in row:
data = [string.replace('read','write')]
print(data)
writer.writerow(data)
</code></pre>
<p>Above code runs well, but I get an empty output file.</p>
<pre><code>Example of data :
reading reading reading reading
interval 0 1 2 3
who axis
Mikael X 0 10 20 30
Mikael Y 50 40 30 20
Mikael Z 100 90 80 70
Mike X 0 0.1 0.2 0.3
Mike Y 0.5 0.4 0.3 0.2
</code></pre>
<p>Mike Z 1 0.9 0.8 0.7</p>
<p>What am i missing?</p>
| 1 |
2016-09-23T04:14:56Z
| 39,653,046 |
<p>Content of input file:</p>
<pre><code>"Roll No" English read Science
"Roll No" English Write Science
</code></pre>
<p><strong>Problem with your code:</strong></p>
<ol>
<li>As mentioned by <strong>@Scott</strong>, files are not closed.</li>
<li><p>Your are reading cell by <code>for string in row:</code> and replacing string there. But after replacement you are writing that cell as row in your file. For example, output file with your code looks file :</p>
<p>Roll No</p>
<p>English</p>
<p>read</p>
<p>Science</p></li>
</ol>
<p>This is due to above mentioned reason i.e. you are writing each cell.</p>
<p><strong>How to make it working?</strong></p>
<p><em>Comments inline with code</em></p>
<pre><code>import csv
input_file = open('mark.csv', 'r', encoding='utf-8')
output_file = open('result.csv', 'w')
writer = csv.writer(output_file , delimiter=' ', encoding='utf-8')
reader = csv.reader(input_file)
for row in reader:
#Initailize empty list for each row
data = []
for string in row:
#Replace and add to data list
data.append(string.replace('read','write'))
#Now write complete
writer.writerow(data)
input_file.close()
output_file.close()
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>"Roll No" English write Science
"Roll No" English Write Science
</code></pre>
<p>You can achieve same thing without <code>csv</code> module.</p>
<pre><code>with open("mark.csv") as input_file:
with open("result.csv",'w') as output_file:
for line in input_file:
new_line = (line.replace("read","write")).replace(","," ")
output_file.write(new_line)
</code></pre>
| 1 |
2016-09-23T05:15:04Z
|
[
"python",
"csv"
] |
How to know which .whl module is suitable for my system with so many?
| 39,652,553 |
<p>We have so may versions of wheel.
How could we know which version should be installed into my system?
I remember there is a certain command which could check my system environment.
Or is there any other ways?</p>
<p>---------------------Example Below this line -----------</p>
<p>scikit_learn-0.17.1-cp27-cp27m-win32.whl
scikit_learn-0.17.1-cp27-cp27m-win_amd64.whl
scikit_learn-0.17.1-cp34-cp34m-win32.whl
scikit_learn-0.17.1-cp34-cp34m-win_amd64.whl
scikit_learn-0.17.1-cp35-cp35m-win32.whl
scikit_learn-0.17.1-cp35-cp35m-win_amd64.whl
scikit_learn-0.18rc2-cp27-cp27m-win32.whl
scikit_learn-0.18rc2-cp27-cp27m-win_amd64.whl
scikit_learn-0.18rc2-cp34-cp34m-win32.whl
scikit_learn-0.18rc2-cp34-cp34m-win_amd64.whl
scikit_learn-0.18rc2-cp35-cp35m-win32.whl
scikit_learn-0.18rc2-cp35-cp35m-win_amd64.whl</p>
| 0 |
2016-09-23T04:16:44Z
| 39,652,742 |
<p>You don't have to know. Use <code>pip</code> - it will select the most specific wheel available.</p>
| 0 |
2016-09-23T04:40:01Z
|
[
"python",
"python-wheel",
"python-install"
] |
Creating EC2 instances with key pairs in Boto2
| 39,652,655 |
<p>I have the following code using boto.ec2 to connect to Amazon EC2 from python, but I'm struggling to deal with the .pem files. If I pass None to the run_instances call as the key name, I can create instances without any problem. However, if I pass any key name (whether or not I create it using the console, or manually as below), I systematically get the following error when I try to run an instance </p>
<pre><code>EC2ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>InvalidKeyPair.NotFound</Code><Message>The key pair 'newkey.pem' does not exist</Message></Error></Errors><RequestID>e4da5b1e-a8ec-42fb-b3ce-20aa883a0615</RequestID></Response>
</code></pre>
<p>When I check on the console for the appropriate region, the key is indeed created (it is also created in my home directory, but I still get the key does not exist error)</p>
<p>Any ideas?</p>
<p>Below is my current Python test code</p>
<pre><code> try:
key_res = conn.get_all_key_pairs(keynames=[key])[0]
print key_res
print "Key pair found"
except boto.exception.EC2ResponseError, e:
print e
if e.code == 'InvalidKeyPair.NotFound':
print 'Creating keypair: %s' % key
# Create an SSH key to use when logging into instances.
key_aws = conn.create_key_pair(key)
# AWS will store the public key but the private key is
# generated and returned and needs to be stored locally.
# The save method will also chmod the file to protect
# your private key.
key_aws.save(".")
else:
raise
print "Creating instances"
try:
conn.run_instances(ami[c.region.name], key_name=key,instance_type=instance,security_groups=[security_group])
except Exception as e:
print e
print "Failed to create instance in " + c.region.name
</code></pre>
| 0 |
2016-09-23T04:29:58Z
| 39,669,962 |
<p>This code (derived from yours) worked for me:</p>
<pre><code>>>> import boto.ec2
>>> conn = boto.ec2.connect_to_region('ap-southeast-2')
>>> key_res = conn.get_all_key_pairs(keynames=['class'])[0]
>>> key_res
KeyPair:class
>>> key_res.name
u'class'
>>> conn.run_instances('ami-ced887ad', key_name=key_res.name, instance_type='t1.micro', security_group_ids=['sg-94cb39f6'])
Reservation:r-0755a9700e3886841
</code></pre>
<p>I then tried your key-creating code:</p>
<pre><code>>>> key_aws = conn.create_key_pair('newkey')
>>> key_aws.save(".")
True
>>> conn.run_instances('ami-ced887ad', key_name=key_aws.name,instance_type='t1.micro',security_group_ids=['sg-93cb39f6'])
Reservation:r-07f831452bf869a14
>>> conn.run_instances('ami-ced887ad', key_name='newkey',instance_type='t1.micro',security_group_ids=['sg-93cb39f6'])
Reservation:r-0476ef041ed26a52f
</code></pre>
<p>It seems to work fine!</p>
| 1 |
2016-09-23T21:41:50Z
|
[
"python",
"amazon-web-services",
"amazon-ec2",
"boto"
] |
Dask Bag read_text() line order
| 39,652,733 |
<p>Does dask.bag.read_text() preserve the line order? Is it still preserved when reading from multiple files?</p>
<pre><code>bag = db.read_text('program.log')
bag = db.read_text(['program.log', 'program.log.1'])
</code></pre>
| 0 |
2016-09-23T04:39:03Z
| 39,653,040 |
<p>Informally, yes, most Dask.bag operations do preserve order. </p>
<p>This behavior is not strictly guaranteed, however I don't see any reason to anticipate a change in the near future.</p>
| 1 |
2016-09-23T05:14:41Z
|
[
"python",
"data-science",
"dask",
"bag"
] |
How to refactor polymorphic method to keep code DRY
| 39,652,788 |
<p>Here is an example of the code I am working with while learning polymorphic behaviour in python.
My question is: Why do I have to declare the very similar function of show_affection twice? Why not check if the caller (the instance calling the method) and if it is Dog, do one thing, if it is a cat do another.</p>
<p>As you can see in the example code below, show_affection is defined in both Cat and Dog classes which inherit from Animal.</p>
<p>Why not declare show_affection in the Animal Class but I am not sure how to check for the caller. like</p>
<pre><code>def show_affection(self):
If caller is the Dog instance:
print("{0}.barks".format(self.name))
else:
print("{0}.wags tail".format(self.name))
</code></pre>
<p>Here is the what I have</p>
<pre><code>class Animal(object):
def __init__(self, name):
self.name = name
def eat(self, food):
print("{0} eats {1}".format(self.name, food))
class Dog(Animal):
def fetch(self, thing):
print("{0} goes after the {1}".format(self.name, thing))
def show_affection(self):
print("{0} wags tail".format(self.name))
class Cat(Animal):
def swatstring(self):
print("{0} shreds the string".format(self.name))
def show_affection(self):
print("{0} purrs".format(self.name))
for a in (Dog('rover'), Cat('fluffy'), Cat('precious'), Dog('Scout')):
a.show_affection()
a.eat('bananas')
</code></pre>
| 0 |
2016-09-23T04:45:28Z
| 39,653,050 |
<p>This is not an example of "repeating yourself", because <code>Cat.show_affection()</code> does something different from <code>Dog.show_affection()</code>. If the two methods were the same, then you could avoid repetition by defining the implementation once in <code>Animal</code>. But since you want to have different behaviors for <code>Cat</code> and <code>Dog</code>, the correct way to do it is to implement the method in each class.</p>
<p>In general:</p>
<ul>
<li>Cat-specific behaviors should be defined in <code>Cat</code>.</li>
<li>Dog-specific behaviors should be defined in <code>Dog</code>.</li>
<li>Behaviors that apply to all animals should be defined in <code>Animal</code>.</li>
</ul>
| 1 |
2016-09-23T05:15:24Z
|
[
"python",
"polymorphism"
] |
Regex Match Whole Multiline Comment Cointaining Special Word
| 39,652,922 |
<p>I've been trying to design this regex but for the life of me I could not get it to not match if */ was hit before the special word.</p>
<p>I'm trying to match a whole multi line comment only if it contains a special word. I tried negative lookaheads/behinds but I could not figure out how to do it properly.</p>
<p>This is what I have so far:
<code>(?s)(/\*.+?special.+?\*/)</code></p>
<p>Am I close or horribly off base? I tried including <code>(?!\*/)</code> unsuccessfully.</p>
<p><a href="https://regex101.com/r/mD1nJ2/3" rel="nofollow">https://regex101.com/r/mD1nJ2/3</a></p>
<p>Edit: I had some redundant parts to the regex I removed.</p>
| 2 |
2016-09-23T05:01:13Z
| 39,652,970 |
<p>You were not totally off base:</p>
<pre><code>/\* # match /*
(?:(?!\*/)[\s\S])+? # match anything lazily, do not overrun */
special # match special
[\s\S]+? # match anything lazily afterwards
\*/ # match the closing */
</code></pre>
<p>The technique is called a tempered greedy token, see <a href="https://regex101.com/r/mD1nJ2/4" rel="nofollow"><strong>a demo on regex101.com</strong></a> (mind the modifiers, e.g. <code>x</code> for verbose mode !).<br>
<hr>
You might want to try another approach tough: analyze your document, grep the comments (using eg <code>BeautifulSoup</code>) and run string functions over them (<code>if "special" in comment...</code>). </p>
| 2 |
2016-09-23T05:06:06Z
|
[
"python",
"regex"
] |
Repeated "Kernel died, restarting" forever
| 39,652,946 |
<p>When I attempt to run</p>
<pre><code>$ jupyter qtconsole
</code></pre>
<p>The console shows up, with the message</p>
<pre><code>Kernel died, restarting
________________________
Kernel died, restarting
________________________
Kernel died, restarting
________________________
Kernel died, restarting
________________________
Kernel died, restarting
________________________
</code></pre>
<p>Which continues.</p>
<p>Trying <code>$ jupyter qtconsole --debug</code> didn't print anything else, and neither has adding</p>
<pre><code>c.Application.log_level = 0
c.Session.debug = True
</code></pre>
<p>into <code>$USERHOME/.jupyter/jupyter_qtconsole_config.py</code></p>
<p>Also, I found nothing in <code>$USERHOME/.ipython/profile_default/log/</code> and the other directories around there.</p>
<p>Nothing has changed in my configuration since last time I started up <code>jupyter-qtconsole</code>.</p>
<p>How can I at least find out what's going wrong with the kernel? Surely there is some option in Jupyter to get the kernel's STDERR output to see what exception had upset it?</p>
| 0 |
2016-09-23T05:04:00Z
| 39,652,947 |
<p>Given that the kernel is another process, I was able to catch the command line it was started with, using Process Explorer. The command line was</p>
<pre><code>$ pythonw -m ipykernel -f "$USERHOME/AppData/Roaming/jupyter/runtime/kernel-2744.json"
</code></pre>
<p>Then, I just launched <code>python</code> and tried importing <code>ipykernel</code>, and got this:</p>
<pre><code>$ python
Python 2.7.12 [...] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ipykernel
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Programs\Python2712\lib\site-packages\ipykernel\__init__.py", line 2,
in <module>
from .connect import *
File "C:\Programs\Python2712\lib\site-packages\ipykernel\connect.py", line 13,
in <module>
from IPython.core.profiledir import ProfileDir
File "C:\Programs\Python2712\lib\site-packages\IPython\__init__.py", line 48,
in <module>
from .core.application import Application
File "C:\Programs\Python2712\lib\site-packages\IPython\core\application.py", l
ine 25, in <module>
from IPython.core import release, crashhandler
File "C:\Programs\Python2712\lib\site-packages\IPython\core\crashhandler.py",
line 28, in <module>
from IPython.core import ultratb
File "C:\Programs\Python2712\lib\site-packages\IPython\core\ultratb.py", line
119, in <module>
from IPython.core import debugger
File "C:\Programs\Python2712\lib\site-packages\IPython\core\debugger.py", line
36, in <module>
from IPython.utils import PyColorize, ulinecache
File "C:\Programs\Python2712\lib\site-packages\IPython\utils\PyColorize.py", l
ine 55, in <module>
from IPython.utils.py3compat import PY3
File "C:\Programs\Python2712\lib\site-packages\IPython\utils\py3compat.py", li
ne 296, in <module>
PYPY = platform.python_implementation() == "PyPy"
AttributeError: 'module' object has no attribute 'python_implementation'
>>> exit()
</code></pre>
<p>And this quickly led to the problem, as described in <a href="http://stackoverflow.com/a/27391094/1143274">this answer</a>, being that the directory I was trying to start <code>jupyter qtconsole</code> in had a subdirectory called <code>platform</code>, which conflicted with the name of a module.</p>
<p>While this fixes this specific instance of "Kernel died, restarting", the general question still stands: how to make sure that the stacktrace, like the one above, is reported to the user of Jupyter console, instead of the kernel dying silently?</p>
| 0 |
2016-09-23T05:04:00Z
|
[
"python",
"jupyter",
"qtconsole",
"jupyter-console"
] |
Django How PermissionRequireMixin class works in code level?(I am even looking into mixins.py in auth folder)
| 39,652,954 |
<p>I would like to know how PermissionRequireMixin works in Django. (I couldn't find any question explaining how PermissionRequireMixin works in very detail. I am looking into code 'mixins.py' in path of 'django.contrib.auth'.)</p>
<p>For example, if write codes like below, it will check if login-user has permission named 'test_permission'. if the login-user has this permission, it moves to a template which is written in template_name attribute. if not, it moves to login page(or another page depend on what you set up). so PermissionRequiredMixin check permission to move on in a class type view.</p>
<pre><code>from django.contrib.auth.mixins import PermissionRequiredMixin
from django.views.generic import ListView
class ViewTest(PermissionRequiredMixin, ListView):
permission_required = ('pertest.test_permission',)
model = Test
template_name = 'pertest/pertest_check_list.html'
</code></pre>
<p>what I want to know is...</p>
<p>I looked into 'django.contrib.auth.mixin.py code to understand how PermissionRequiredMixin class works. I can see it is subclass of AccessMixin and understand what kind of methods it has. but I can't understand how it proceed to check login's permission. I would like to understand flow in code base. where should i check to understand process for checking permission fully?</p>
<p>I even want to know this.</p>
<p>Let's say a login-user 'A' has permission named 'test_permission' and the 'A' user is in a group which has permission named 'group_test_permission'.</p>
<pre><code>case A : permission_required = ('pertest.test_permission',)
case B : permission_required = ('pertest.group_test_permission',)
</code></pre>
<p>in case A, a user A can move on because it has 'test_permission'.
in case B, a user A can move on because it is in a group which has 'group_test_permission'.</p>
<p>does it check a login user has the permission in auth_user_user_permission table and then check in auth_user_group table and auth_group_permissions? or in opposite direction? I am confused because group, user, permission are in individual tables and are connected to each other by ForiegnKey(ManyToMany or ForiegnKey).</p>
<p>In a nutshell, I would like to know process of how PermissionRequiredMixin class checks permissions and which part(what codes) I should check to understand this process.</p>
<p>Thank you in advance. Let me know if my question is not clear.</p>
| 0 |
2016-09-23T05:04:21Z
| 39,653,258 |
<p>In the end the authentication backends are responsible to grant or deny access.</p>
<p>As you might have noticed, the <code>PermissionRequiredMixin</code> in the end calls <code>has_perm</code> on the user object with the defined permissions. This method just wraps an internal method called <a href="https://github.com/django/django/blob/master/django/contrib/auth/models.py#L180" rel="nofollow">_user_has_perm</a> in auth models.py.</p>
<p>Finally you'll might want to read the <a href="https://github.com/django/django/blob/master/django/contrib/auth/backends.py" rel="nofollow">backends.py</a> shipped by <code>django.contrib.auth</code> to see how access is granted by default.</p>
<p>As far as i can see, by default it just checks if you have either a grant through your user, or through your group and let you in or not.</p>
<p>HTH</p>
| 0 |
2016-09-23T05:33:53Z
|
[
"python",
"django"
] |
How to parse dates for incomplete dates in Python
| 39,653,042 |
<p>I am using dateutil.parser to parse dates and I want to throw an exception if the date is incomplete i.e January 1 (missing year) or January 2016 (missing day). So far I have the following </p>
<pre><code>try:
parse(date)
return parse(date).isoformat()
except ValueError:
return 'invalid'
</code></pre>
| 0 |
2016-09-23T05:14:47Z
| 39,655,096 |
<p>You can use private method <code>_parse</code> of class <code>dateutil.parser.parser</code> to determine if day, month and year have been supplied. Since the method is private its behaviour may change and it is generally not advisable to use private methods of other classes in production code, but in this particular case using it is the most easy and robust method, so its probably OK.</p>
<p>Modified code looks like:</p>
<pre><code>from dateutil.parser import parser, parse
# Check if passed date is complete and valid
def is_date_complete (date, must_have_attr=("year","month","day")):
parse_res, _ = parser()._parse(date)
# If date is invalid `_parse` returns (None,None)
if parse_res is None:
return False
# For a valid date `_result` object is returned. E.g. _parse("Sep 23") returns (_result(month=9, day=23), None)
for attr in must_have_attr:
if getattr(parse_res,attr) is None:
return False
return True
## your code section
if not is_date_complete(date):
return 'invalid'
else:
return parse(date).isoformat()
</code></pre>
<p>Here we utilized result of <code>_parse</code> to determine if the date has missing year, month or day. </p>
| 0 |
2016-09-23T07:29:51Z
|
[
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.