AttributeError: 'QSlider' object has no attribute 'subtractStep' - python-2.7

I am getting an error when I try to run this code:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'scaler_gui_3.ui'
#
# Created: Thu May 14 13:05:28 2015
# by: PyQt4 UI code generator 4.11.3
#
# WARNING! All changes made in this file will be lost!
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_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(270, 219)
self.gridLayout_2 = QtGui.QGridLayout(Form)
self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
self.horizontalSliderFrames = QtGui.QSlider(Form)
self.horizontalSliderFrames.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSliderFrames.setObjectName(_fromUtf8("horizontalSliderFrames"))
self.gridLayout_2.addWidget(self.horizontalSliderFrames, 1, 0, 1, 1)
self.gridLayout = QtGui.QGridLayout()
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.verticalScrollBarIW = QtGui.QScrollBar(Form)
self.verticalScrollBarIW.setOrientation(QtCore.Qt.Vertical)
self.verticalScrollBarIW.setObjectName(_fromUtf8("verticalScrollBarIW"))
self.gridLayout.addWidget(self.verticalScrollBarIW, 0, 2, 1, 1)
self.verticalLayout_2 = QtGui.QVBoxLayout()
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.labelMain = QtGui.QLabel(Form)
self.labelMain.setObjectName(_fromUtf8("labelMain"))
self.verticalLayout_2.addWidget(self.labelMain)
self.horizontalScrollBarIW = QtGui.QScrollBar(Form)
self.horizontalScrollBarIW.setOrientation(QtCore.Qt.Horizontal)
self.horizontalScrollBarIW.setObjectName(_fromUtf8("horizontalScrollBarIW"))
self.verticalLayout_2.addWidget(self.horizontalScrollBarIW)
self.gridLayout.addLayout(self.verticalLayout_2, 0, 0, 1, 1)
spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.gridLayout.addItem(spacerItem, 0, 1, 1, 1)
self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.gridLayout_2.addLayout(self.horizontalLayout_2, 6, 1, 1, 1)
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.horizontalLayout_3 = QtGui.QHBoxLayout()
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
self.labelSmallIW = QtGui.QLabel(Form)
self.labelSmallIW.setObjectName(_fromUtf8("labelSmallIW"))
self.horizontalLayout_3.addWidget(self.labelSmallIW)
self.labelBigIW = QtGui.QLabel(Form)
self.labelBigIW.setObjectName(_fromUtf8("labelBigIW"))
self.horizontalLayout_3.addWidget(self.labelBigIW)
self.pushButton = QtGui.QPushButton(Form)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.horizontalLayout_3.addWidget(self.pushButton)
self.verticalLayout.addLayout(self.horizontalLayout_3)
self.gridLayout_2.addLayout(self.verticalLayout, 4, 0, 1, 1)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.toolButtonLoad = QtGui.QToolButton(Form)
self.toolButtonLoad.setObjectName(_fromUtf8("toolButtonLoad"))
self.horizontalLayout.addWidget(self.toolButtonLoad)
self.prevButton = QtGui.QPushButton(Form)
self.prevButton.setObjectName(_fromUtf8("prevButton"))
self.horizontalLayout.addWidget(self.prevButton)
self.nextButton = QtGui.QPushButton(Form)
self.nextButton.setObjectName(_fromUtf8("nextButton"))
self.horizontalLayout.addWidget(self.nextButton)
self.gridLayout_2.addLayout(self.horizontalLayout, 2, 0, 1, 1)
self.checkBox = QtGui.QCheckBox(Form)
self.checkBox.setObjectName(_fromUtf8("checkBox"))
self.gridLayout_2.addWidget(self.checkBox, 5, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QObject.connect(self.prevButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.horizontalSliderFrames.subtractStep)
QtCore.QObject.connect(self.nextButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.horizontalSliderFrames.addStep)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
self.labelMain.setText(_translate("Form", "TextLabel", None))
self.labelSmallIW.setText(_translate("Form", "TextLabel", None))
self.labelBigIW.setText(_translate("Form", "TextLabel", None))
self.pushButton.setText(_translate("Form", "PushButton", None))
self.toolButtonLoad.setText(_translate("Form", "...", None))
self.prevButton.setText(_translate("Form", "<", None))
self.nextButton.setText(_translate("Form", ">", None))
self.checkBox.setText(_translate("Form", "CheckBox", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setStyle('cleanlooks')
Form = QtGui.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
It seems like similar error happen to other people due to some "class related problems" which I have no idea about. I do not understand why it seems to work fine when I "run" in from Geany text editor, but not when I run it from terminal using python my_gui.py I get this error :
Traceback (most recent call last):
File "gui_template.ui.py", line 136, in <module>
ui = Ui_Form()
File "gui_template.ui.py", line 39, in __init__
self.setupUi(self)
File "gui_template.ui.py", line 89, in setupUi
QtCore.QObject.connect(self.prevButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.horizontalSliderFrames.subtractStep)
AttributeError: 'QSlider' object has no attribute 'subtractStep'
I also tried creating a seperate .py file in a similar fashion to how this person does it:
https://youtu.be/FcX2FsPlVeI?t=10m25s
However, I still get the same error... Any ideas?

The addStep and subtractStep slots are deprecated members of QSlider. They are only there to provide backwards compatibility with Qt3.
It seems you must be trying to run the example script using builds of Qt4/PyQt4 that do not include such deprecated APIs.
The documentation suggests using the setValue slot instead. But that requires passing an appropriate increment/decrement value, so it's not really a drop-in replacement (especially if you're connecting the signals via Qt Designer).
If you wanted to fix the example, you'd have to replace the two signal/slot connections with something like:
def setSlider(delta):
self.horizontalSliderFrames.setValue(
self.horizontalSliderFrames.value() +
delta * self.horizontalSliderFrames.singleStep())
self.prevButton.clicked.connect(lambda: setSlider(-1))
self.nextButton.clicked.connect(lambda: setSlider(+1))

Related

Unhandled exception in thread started by <function wrapper at 0x7f2f82ee3aa0> on Django

Unhandled exception occurs while passing function inside models.py in Django (installing by pip install numpy django requests)
I am trying to manipulate face detection api on web using OpenCV, Numpy and Redis.
But i got an exception on passing the fuctions inside the models.py
I am just a newbee on Django framework and Python languages.
Here is my error while running my Django server !
Unhandled exception in thread started by
Traceback (most recent call last):
File "/home/xyz/.xyz/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/home/xyz/.xyz/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception()
File "/home/xyz/.xyz/lib/python2.7/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception
six.reraise(*_exception)
File "/home/xyz/.xyz/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/home/xyz/.xyz/lib/python2.7/site-packages/django/init.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/xyz/.xyz/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models()
File "/home/xyz/.xyz/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name)
File "/home/xyz/PycharmProjects/xyz_project/OpencvWeb/opencv_api/Face_detection/models.py", line 28, in
class LFace:
File "/home/xyz/PycharmProjects/xyz_project/OpencvWeb/opencv_api/Face_detection/models.py", line 29, in LFace
def init(self, faceRect = LRect(), eyes=[], id = 0, mt = 0, vel = LVector(0,0)):
NameError: name 'LRect' is not defined
And Here is my code in models.py
This is the class for LFace
class LFace:
def __init__(self, faceRect = LRect(), eyes=[], id = 0, mt = 0, vel = LVector(0,0)):
self.face = faceRect.clone()
self.eyes = [e.clone() for e in eyes]
self.id = id
self.name = ''
self.missingTicks = mt
self.velocity = vel
def clone(self):
return LFace(self.face, self.eyes, self.id)
def setAs(self, f2):
self.face = f2.face.clone()
self.eyes = [e.clone() for e in f2.eyes]
self.id = f2.id
self.missintTicks = f2.missingTicks
self.velocity = f2.velocity.clone()
def dist(self, f2, scalar1 = 1.0, scalar2 = 0.2):
#distance is defined as: center differences * scalar1 + size differences * scalar2
d1 = self.face.center().dist(f2.face.center())
d2 = self.face.wh().dist(f2.face.wh())
return d1 * scalar1 + d2 * scalar2
def interpolateTo(self, f2, t):
self.face.interpolateTo(f2.face, t)
self.eyes = f2.clone().eyes if t > 0.5 else []
def getPredicted(self):
rv = self.clone()
p = rv.face.center()
oldP = p.clone()
p += self.velocity
rv.velocity = LVector(0,0)
rv.face.setFromCenter(p)
return rv
This is the class for LRect
class LRect:
def __init__(self, x=0, y=0, w=0, h=0):
self.x = x
self.y = y
self.w = w
self.h = h
def pos(self):
return LVector(self.x, self.y)
def wh(self):
return LVector(self.w, self.h)
def hwh(self):
return LVector(self.w, self.h) * 0.5
def center(self):
return (self.pos() + self.hwh())
def toString(self):
return '[x={0},y={1},width={2},height={3}]'.format(*self.toList())
def __str__(self):
return self.toString()
def toList(self):
return [self.x, self.y, self.w, self.h]
def clone(self):
return LRect(self.x, self.y, self.w, self.h)
def setFromCenter(self, centerPoint):
hp = self.hwh()
self.x = centerPoint[0] - hp[0]
self.y = centerPoint[1] - hp[1]
def scaleWH(self, scalar):
# scalar can be either an LVector or a number
c = self.center()
hwh = self.wh() * scalar
self.w, self.h = hwh[0], hwh[1]
self.setFromCenter(c)
def interpolateTo(self, r2, t):
c = self.center()
wh = self.wh()
c.interpolateTo(r2.center(), t)
wh.interpolateTo(r2.wh(), t)
self.w, self.h = wh[0], wh[1]
self.setFromCenter(c)
Please Help !!

debug:decoding Unicode is not supported

My code can run,but when I debug,it can enter the Subroutine.And the error is:"decoding Unicode is not supported".
I use anaconda.When I open the untitled0.py,the encoding is UTF-8 at the bottom of the screen,but when I open the fhmm_exact.py,the encoding is UTF-8-GUESSED.
Traceback (most recent call last):
File "<ipython-input-1-f6910c2dfa77>", line 1, in <module>
debugfile('/home/wenwu/untitled0.py', wdir='/home/wenwu')
File "/home/wenwu/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 702, in debugfile
debugger.run("runfile(%r, args=%r, wdir=%r)" % (filename, args, wdir))
File "/home/wenwu/anaconda/lib/python2.7/bdb.py", line 400, in run
exec cmd in globals, locals
File "<string>", line 1, in <module>
File "/home/wenwu/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 682, in runfile
execfile(filename, namespace)
File "/home/wenwu/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 78, in execfile
builtins.execfile(filename, *where)
File "/home/wenwu/untitled0.py", line 37, in <module>
fhmm.disaggregate(test_elec.mains(),output,sample_period = 60)
File "/home/wenwu/nilmtk/nilmtk/disaggregate/fhmm_exact.py", line 287, in disaggregate
mains_data_location = '{}/elec/meter1'.format(building_path)
File "/home/wenwu/nilmtk/nilmtk/disaggregate/fhmm_exact.py", line 287, in disaggregate
mains_data_location = '{}/elec/meter1'.format(building_path)
File "/home/wenwu/anaconda/lib/python2.7/bdb.py", line 49, in trace_dispatch
return self.dispatch_line(frame)
File "/home/wenwu/anaconda/lib/python2.7/bdb.py", line 67, in dispatch_line
self.user_line(frame)
File "/home/wenwu/anaconda/lib/python2.7/pdb.py", line 158, in user_line
self.interaction(frame, None)
File "/home/wenwu/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 488, in interaction
self.notify_spyder(frame) #-----Spyder-specific-------------------------
File "/home/wenwu/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 432, in notify_spyder
fname = unicode(fname, "utf-8")
TypeError: decoding Unicode is not supported
The following is code.
untitled0.py*
from matplotlib import rcParams
import matplotlib.pyplot as plt
rcParams['figure.figsize'] = (13,6)
plt.style.use('ggplot')
from nilmtk import DataSet,TimeFrame,MeterGroup,HDFDataStore
train = DataSet('/home/wenwu/redd.h5')
test = DataSet('/home/wenwu/redd.h5')
building = 1
train.set_window(end = '30-4-2011')
test.set_window(start = '30-4-2011')
train_elec = train.buildings[1].elec
test_elec = test.buildings[1].elec
fridge_meter = train_elec['fridge']
fridge_df = fridge_meter.load().next()
fridge_df.head()
mains = train_elec.mains()
mains_df = mains.load().next()
top_5_train_elec = train_elec.submeters().select_top_k(k = 5)
from nilmtk.disaggregate import fhmm_exact
from nilmtk.metrics import f1_score
fhmm = fhmm_exact.FHMM()
fhmm.train(top_5_train_elec,sample_period = 60)
disag_filename = '/home/wenwu/redd-disag-fhmm.h5'
output = HDFDataStore(disag_filename,'w')
fhmm.disaggregate(test_elec.mains(),output,sample_period = 60)
output.close()
disag_fhmm = DataSet(disag_filename)
disag_fhmm_elec = disag_fhmm.buildings[building].elec
f1_fhmm = f1_score(disag_fhmm_elec,test_elec)
f1_fhmm.plot(kind = 'barh')
disaggreate part of fhmm_exact.py
def disaggregate(self, mains, output_datastore, **load_kwargs):
'''Disaggregate mains according to the model learnt previously.
Parameters
----------
mains : nilmtk.ElecMeter or nilmtk.MeterGroup
output_datastore : instance of nilmtk.DataStore subclass
For storing power predictions from disaggregation algorithm.
output_name : string, optional
The `name` to use in the metadata for the `output_datastore`.
e.g. some sort of name for this experiment. Defaults to
"NILMTK_FHMM_<date>"
resample_seconds : number, optional
The desired sample period in seconds.
**load_kwargs : key word arguments
Passed to `mains.power_series(**kwargs)`
'''
import warnings
warnings.filterwarnings("ignore", category=Warning)
MIN_CHUNK_LENGTH = 100
if not self.model:
raise RuntimeError(
"The model needs to be instantiated before"
" calling `disaggregate`. For example, the"
" model can be instantiated by running `train`.")
# Extract optional parameters from load_kwargs
date_now = datetime.now().isoformat().split('.')[0]
output_name = load_kwargs.pop('output_name', 'NILMTK_FHMM_' + date_now)
resample_seconds = load_kwargs.pop('resample_seconds', 60)
resample_rule = '{:d}S'.format(resample_seconds)
timeframes = []
building_path = '/building{}'.format(mains.building())
mains_data_location = '{}/elec/meter1'.format(building_path)
data_is_available = False
for chunk in mains.power_series(**load_kwargs):
# Check that chunk is sensible size before resampling
if len(chunk) < MIN_CHUNK_LENGTH:
continue
# Record metadata
timeframes.append(chunk.timeframe)
measurement = chunk.name
chunk = chunk.resample(rule=resample_rule)
# Check chunk size *again* after resampling
if len(chunk) < MIN_CHUNK_LENGTH:
continue
# Start disaggregation
predictions = self.disaggregate_chunk(chunk)
for meter in predictions.columns:
data_is_available = True
meter_instance = meter.instance()
cols = pd.MultiIndex.from_tuples([chunk.name])
predicted_power = predictions[[meter]]
output_df = pd.DataFrame(predicted_power)
output_df.columns = pd.MultiIndex.from_tuples([chunk.name])
output_datastore.append('{}/elec/meter{}'
.format(building_path, meter_instance),
output_df)
# Copy mains data to disag output
output_datastore.append(key=mains_data_location,
value=pd.DataFrame(chunk, columns=cols))
if not data_is_available:
return
##################################
# Add metadata to output_datastore
# TODO: `preprocessing_applied` for all meters
# TODO: split this metadata code into a separate function
# TODO: submeter measurement should probably be the mains
# measurement we used to train on, not the mains measurement.
# DataSet and MeterDevice metadata:
meter_devices = {
'FHMM': {
'model': 'FHMM',
'sample_period': resample_seconds,
'max_sample_period': resample_seconds,
'measurements': [{
'physical_quantity': measurement[0],
'type': measurement[1]
}]
},
'mains': {
'model': 'mains',
'sample_period': resample_seconds,
'max_sample_period': resample_seconds,
'measurements': [{
'physical_quantity': measurement[0],
'type': measurement[1]
}]
}
}
merged_timeframes = merge_timeframes(timeframes, gap=resample_seconds)
total_timeframe = TimeFrame(merged_timeframes[0].start,
merged_timeframes[-1].end)
dataset_metadata = {'name': output_name, 'date': date_now,
'meter_devices': meter_devices,
'timeframe': total_timeframe.to_dict()}
output_datastore.save_metadata('/', dataset_metadata)
# Building metadata
# Mains meter:
elec_meters = {
1: {
'device_model': 'mains',
'site_meter': True,
'data_location': mains_data_location,
'preprocessing_applied': {}, # TODO
'statistics': {
'timeframe': total_timeframe.to_dict()
}
}
}
# TODO: FIX THIS! Ugly hack for now
# Appliances and submeters:
appliances = []
for i, meter in enumerate(self.meters):
meter_instance = meter.instance()
for app in meter.appliances:
appliance = {
'meters': [meter_instance],
'type': app.identifier.type,
'instance': app.identifier.instance
# TODO this `instance` will only be correct when the
# model is trained on the same house as it is tested on.
# https://github.com/nilmtk/nilmtk/issues/194
}
appliances.append(appliance)
elec_meters.update({
meter_instance: {
'device_model': 'FHMM',
'submeter_of': 1,
'data_location': ('{}/elec/meter{}'
.format(building_path, meter_instance)),
'preprocessing_applied': {}, # TODO
'statistics': {
'timeframe': total_timeframe.to_dict()
}
}
})
# Setting the name if it exists
if meter.name:
if len(meter.name) > 0:
elec_meters[meter_instance]['name'] = meter.name
building_metadata = {
'instance': mains.building(),
'elec_meters': elec_meters,
'appliances': appliances
}
output_datastore.save_metadata(building_path, building_metadata)

wxPython: My toolbar does't show buttons in Windows

I did a small application and it works nice in linux. But, I get some problems with the toolbar in Windows 7.
The toolbar has some buttons which Windows doesn't show (But, there are in Linux). I am using Python 2.7 and wxPython 2.8.
I don't know what I am missing.
Regards,
Cristian.
import wx
from wx.lib.pubsub import Publisher
from excel import excelmaker
from model import Model
from ObjectListView import ColumnDefn, ObjectListView
import utils
import threading
wildcard = "Excel (*.xlsx)|*.xlsx|" \
"All files (*.*)|*.*"
class ApplicationGui(wx.App):
def __init__(self, redirect=False, filename=None):
wx.App.__init__(self, redirect, filename)
def OnInit(self):
# create frame here
frame = MainFrame()
frame.Show()
return True
class MainPanel(wx.Panel):
def __init__(self,parent):
self.exportText=''
wx.Panel.__init__(self,parent=parent, id=wx.ID_ANY)
self.objectListView = ObjectListView(self, wx.ID_ANY,style=wx.LC_REPORT|wx.SUNKEN_BORDER)
self.objectListView.cellEditMode = ObjectListView.CELLEDIT_SINGLECLICK
self.objectListView.SetObjects([Model()])
mainSizer = wx.BoxSizer(wx.VERTICAL)
self.create_toolbar(mainSizer)
mainSizer.Add(self.progress, 0, wx.EXPAND)
mainSizer.Add(self.objectListView, 1, wx.ALL|wx.EXPAND, 5)
self.SetSizer(mainSizer)
def create_toolbar(self,sizer):
toolbar = wx.ToolBar(self)
loadBtn = toolbar.AddLabelTool(wx.ID_ANY, 'Cargar Excel', wx.Bitmap('resources/open.png'), shortHelp='Cargar Excel')
pasteBtn = toolbar.AddLabelTool(wx.ID_ANY, 'Pegar', wx.Bitmap('resources/paste.png'), shortHelp='Pegar Columnas')
cleanBtn = toolbar.AddLabelTool(wx.ID_ANY, 'Borrar', wx.Bitmap('resources/clean.png'), shortHelp='Borrar tabla')
toolbar.AddSeparator()
addBtn = toolbar.AddLabelTool(wx.ID_ANY, 'Agregar', wx.Bitmap('resources/add.png'), shortHelp='Agregar fila')
toolbar.AddSeparator()
self.exportText = wx.TextCtrl(toolbar, -1, size=(140,-1))
self.exportText.SetValue('output.xlsx')
toolbar.AddControl(self.exportText)
exportBtn = toolbar.AddLabelTool(wx.ID_ANY, 'Exportar', wx.Bitmap('resources/export.png'), shortHelp='Generar Excel')
toolbar.AddSeparator()
about = toolbar.AddLabelTool(wx.ID_ANY, 'Acerca', wx.Bitmap('resources/about.png'), shortHelp='Ayuda')
randomId = wx.NewId()
self.Bind(wx.EVT_MENU, self.onPaste, id=randomId)
accel_tbl = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('V'), randomId )])
self.SetAcceleratorTable(accel_tbl)
sizer.Add(toolbar, 0, wx.EXPAND)
self.Bind(wx.EVT_TOOL, self.onOpenFile, loadBtn)
self.Bind(wx.EVT_TOOL, self.onPaste, pasteBtn)
self.Bind(wx.EVT_TOOL, self.onClean, cleanBtn)
self.Bind(wx.EVT_TOOL, self.onExport, exportBtn)
self.Bind(wx.EVT_TOOL, self.onAddRow, addBtn)
self.Bind(wx.EVT_TOOL, self.onAbout, about)
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent=None, id=wx.ID_ANY,
title="Exceltronic", size=(800,600))
panel = MainPanel(self)
You are missing the call
toolbar.Realize()
http://wxpython.org/Phoenix/docs/html/ToolBar.html?highlight=toolbar#ToolBar.Realize

Attribute error while executing a python code

I am a student and working on GNU Radio.
I have a python code which i want to run in GNU radio companion but i am unable to search for the right block to execute that code...can anyone help me with that??When I execute the same python code(not in GNU), I get the following error:
AttributeError: 'top_block_sptr' object has no attribute 'wxgui_'
the code is as shown:
#!/usr/bin/env python
from gnuradio import blocks
from gnuradio import eng_notation
from gnuradio import gr
from gnuradio import uhd
#from gnuradio import window
from gnuradio.eng_option import eng_option
#from gnuradio.gr import firdes
from gnuradio.wxgui import forms
from gnuradio.wxgui import waterfallsink2
from grc_gnuradio import wxgui as grc_wxgui
from optparse import OptionParser
import wx
class top_block(grc_wxgui.top_block_gui):
def __init__(self):
grc_wxgui.top_block_gui.__init__(self, title="Top Block")
_icon_path = "/usr/share/icons/hicolor/32x32/apps/gnuradio-grc.png"
self.SetIcon(wx.Icon(_icon_path, wx.BITMAP_TYPE_ANY))
##################################################
# Variables
###
###############################################
self.variable_slider_1 = variable_slider_1 = 32
self.variable_slider_0 = variable_slider_0 = 0
self.samp_rate = samp_rate = 21e6
self.gain = gain = variable_slider_1
self.delay_length = delay_length= variable_slider_0
##################################################
# Blocks
##################################################
self.wxgui_waterfallsink2_0_0 = waterfallsink2.waterfall_sink_c(
self.GetWin(),
baseband_freq=0,
dynamic_range=100,
ref_level=0,
ref_scale=2.0,
sample_rate=samp_rate,
fft_size=512,
fft_rate=15,
average=False,
avg_alpha=None,
title="Output Waterfall Plot",
)
self.GridAdd(self.wxgui_waterfallsink2_0_0.win, 0, 10, 10, 10)
self.wxgui_
waterfallsink2_0 = waterfallsink2.waterfall_sink_c(
self.GetWin(),
baseband_freq=0,
dynamic_range=100,
ref_level=0,
ref_scale=2.0,
sample_rate=samp_rate,
fft_size=512,
fft_rate=15,
average=False,
avg_alpha=None,
title="Input Waterfall Plot",
)
self.GridAdd(self.wxgui_waterfallsink2_0.win, 0, 0, 10, 10)
_variable_slider_1_sizer = wx.BoxSizer(wx.VERTICAL)
self._variable_slider_1_text_box = forms.text_box(
parent=self.GetWin(),
sizer=_variable_slider_1_sizer,
value=self.variable_slider_1,
callback=self.set_variable_slider_1,
label="Output Gain",
converter=forms.float_converter(),
proportion=0,
)
self._variable_slider_1_slider = forms.slider(
parent=self.GetWin(),
sizer=_variable_slider_1_sizer,
value=self.variable_slider_1,
callback=self.set_variable_slider_1,
minimum=0,
maximum=32,
num_steps=31,
style=wx.SL_HORIZONTAL,
cast=float,
proportion=1,
)
self.GridAdd(_variable_slider_1_sizer, 12, 10, 1, 9)
_variable_sl
ider_0_sizer = wx.BoxSizer(wx.VERTICAL)
self._variable_slider_0_text_box = forms.text_box(
parent=self.GetWin(),
sizer=_variable_slider_0_sizer,
value=self.variable_slider_0,
callback=self.set_variable_slider_0,
label="Delay Length",
converter=forms.int_converter(),
proportion=0,
)
self._variable_slider_0_slider = forms.slider(
parent=self.GetWin(),
sizer=_variable_slider_0_sizer,
value=self.variable_slider_0,
callback=self.set_variable_slider_0,
minimum=0,
maximum=710000,
num_steps=1000,
style=wx.SL_HORIZONTAL,
cast=int,
proportion=1,
)
self.GridAdd(_variable_slider_0_sizer, 10, 10, 1, 9)
self.uhd_usrp_source_0 = uhd.usrp_source(
device_addr="",
stream_args=uhd.stream_args(
cpu_format="fc32",
channels=range(1),
),
)
self.uhd_usrp_source_0.set_samp_rate(samp_rate)
self.uhd_usrp_source_0.set_center_freq(2.28e9, 0)
self.uhd_usrp_source_0.set_gain(0, 0)
self.uhd_usrp_sink_0 = uhd.usrp_sink(
device_addr="",
stream_args
=uhd.stream_args(
cpu_format="fc32",
channels=range(1),
),
)
self.uhd_usrp_sink_0.set_samp_rate(samp_rate)
self.uhd_usrp_sink_0.set_center_freq(2.28e9, 0)
self.uhd_usrp_sink_0.set_gain(gain, 0)
self.gr_file_source_0_0 = gr.file_source(
gr.sizeof_gr_complex*1,
"/home/ubuntu/radar-rx3.capture", True)
self.gr_file_source_0 = gr.file_source(gr.sizeof_gr_complex*1,
"/home/ubuntu/radar-rx3.capture", True)
self.gr_delay_0_0 = gr.delay(gr.sizeof_gr_complex*1, delay_length)
self.blocks_mult
iply_xx_0 = blocks.multiply_vcc(1)
##################################################
# Connections
##################################################
self.connect((self.uhd_usrp_source_0, 0), (self.wxgui_waterfallsink2_0, 0))
self.connect((self.gr_file_source_0_0, 0), (self.gr_delay_0_0, 0))
self.connect((self.gr_file_source_0, 0), (self.blocks_multiply_xx_0, 0))
self.connect((self.gr_delay_0_0, 0), (self.blocks_multiply_xx_0, 1))
self.connect((self.blocks_multiply_xx_0, 0), (self.uhd_usrp_sink_0, 0))
self.connect((self.blocks_multiply_xx_0, 0), (self.wxgui_waterfallsink2_0_0, 0))
def get_variable_slider_1(self):
return self.variable_slider_1
def set_variable_slider_1(self, variable_slider_1):
self.variable_slider_1 = variable_slider_1
self.set_gain(self.variable_slider_1)
self._variable_slider_1_slider.set_value(self.variable_slider_1)
self._variable_slider_1_text_box.set_value(self.variable_slider_1)
def get_variable_slider_0(self):
return self.variable_slider_0
def set_variable_slider_0(self, variable_slider_0):
self.variable_slider_0 = variable_slider_0
self.set_delay_length(self.variable_slider_0)
self._variable_slider_0_slider.set_value(self.variable_slider_0)
self._variable_slider_0_text_box.set_value(self.variable_slider_0)
def get_samp_rate(self):
return self.samp_rate
def set_samp_rate(self, samp_rate):
self.samp_rate = samp_rate
self.wxgui_waterfallsink2_0.set_sample_rate(self.samp_rate)
self.wxgui_waterfallsink2_0_0.set_sample_rate(self.samp_rate)
self.uhd_usrp_sink_0.set_samp_rate(self.samp_rate)
self.uhd_usrp_source_0.set_samp_rate(self.samp_rate)
def get_gain(self):
return self.gain
def set_gain(self, gain):
self.gain = gain
self.uhd_usrp_sink_0.set_gain(self.gain, 0)
def get_delay_length(self):
return self.delay_length
def set_delay_length(self, delay_length):
self.delay_length = delay_length
self.gr_delay_0_0.set_delay(self.delay_length)
if __name__ == '__main__':
parser = OptionParser(option_class=eng_option,usage="%prog: [options]")
(options, args) = parser.parse_args()
tb = top_block()
tb.Run(True)
There's an erroneous line break in
self.wxgui_
waterfallsink2_0 = waterfallsink2.waterfall_sink_c(...
remove the wrong line breaks, and it should work. If in doubt, re-generate the python file using the GNU Radio Companion. Make sure your editor doesn't add line breaks where he should not.

loading a pickle file

I'm trying to get a "getting started with pickles" script working. I managed to save a pickle file from a file, and load it. But when I save a pickle file in one file (the main.py in this case) and load it from another, I get an error. I probably missed something small, but can't figure out what.
main.py
import pickle
class Node:
"""This class represents a node"""
def __init__(self, value = None):
self.val = value
def toString(self):
return self.val
class Link:
"""This class represents a link between 2 nodes"""
def __init__(self, sourceNode, targetNode, LinkWigth):
self.source = sourceNode
self.target = targetNode
self.wight = LinkWigth
def setWeight(self, newWeight):
self.wight = newWeight
def toString(self):
return self.wight
class Graph:
"""This class represents a graph"""
def __init__(self):
self.nodes = []
self.links = []
def addNode(self, node):
self.nodes.append(node)
def addLink(self, link):
self.links.append(link)
def getInDegree(self, node):
counter = 0
for link in self.links:
if link.target == node:
counter +=1
else:
print "target is: %s" % link.target.toString()
print "source is: %s" % link.source.toString()
return counter
def toString(self):
for link in self.links:
print link.toString()
for node in self.nodes:
print node.toString()
if __name__ == "__main__":
n1 = Node(4)
l1 = Link(n1, n1, 1)
g = Graph()
g.addNode(n1)
g.addLink(l1)
pickle.dump(g, open('haha', 'wb') )
pickleLoader.py
import pickle
import main
n = main.Node(44)
print n.toString()
g = pickle.load( open('haha', 'rb') )
print "ha"
The error
C:\Users\R\Desktop\pickle test>main.py
C:\Users\R\Desktop\pickle test>pickleLoader.py
44
Traceback (most recent call last):
File "C:\Users\R\Desktop\pickle test\pickleLoader.py", line 7, in <module>
g = pickle.load( open('haha', 'rb') )
File "C:\Program Files\Python27\lib\pickle.py", line 1378, in load
return Unpickler(file).load()
File "C:\Program Files\Python27\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Program Files\Python27\lib\pickle.py", line 1069, in load_inst
klass = self.find_class(module, name)
File "C:\Program Files\Python27\lib\pickle.py", line 1126, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'Graph'
C:\Users\R\Desktop\pickle test>
I guess that the problem is something with the namespace because main.py has been imported, but I have no idea how to get it working.
This does appear to be related to how the classes are defined in relation to the module. A quick way to allow this to work is to import the components of the main module directly into pickleLoader:
from main import Graph, Node, Link
A better solution might be to move the common components (Graph, Node, Link) into their own module, and then import that module into both main and pickleLoader.