Why does my while code cause my simulator to crash? - while-loop

Whenever I add the while code to my game, the simulator stops responding. I know its the while code that causes this problem because if I take the while code out, the game works like its supposed to. Whats wrong with my while code, and how do i fix it? Let me know if you need any more information to solve the problem. Here is the code:
function scene:createScene ( event )
local group = self.view
local tap = display.newText("Tap:", 0, 0, "Helvetica", 36)
tap.x = 100
tap.y = screenTop + 20
group:insert(tap)
local imageFiles = {"redbox.png", "bluebox.png"}
local imageFile = imageFiles[math.random(2)]
local randomImage = display.newImage(imageFile, centerX, screenTop + 20)
local button1 = display.newImage("redbox.png")
button1.x = centerX
button1.y = centerY
group:insert(button1)
local button2 = display.newImage("bluebox.png")
button2.x = centerX
button2.y = centerY - 100
group:insert(button2)
local function endGame(event)
if imageFile == "redbox.png" then
button1.x = math.random( 55, 300)
button1.y = math.random( 55, 300)
button2.x = math.random( 55, 300)
button2.y = math.random( 55, 300)
local imageFile = imageFiles[math.random(2)]
local randomImage = display.newImage(imageFile, centerX, screenTop + 20)
while imageFile == "redbox.png" do
if imageFile ~= "redbox.png" then
storyboard.gotoScene( "restartEasy" )
end
end
end
end
local function endGame2(event)
if imageFile == "bluebox.png" then
button1.x = math.random( 55, 300)
button1.y = math.random( 55, 300)
button2.x = math.random( 55, 300)
button2.y = math.random( 55, 300)
local imageFile = imageFiles[math.random(2)]
local randomImage = display.newImage(imageFile, centerX, screenTop + 20)
while imageFile == "bluebox.png" do
if imageFile ~= "bluebox.png" then
storyboard.gotoScene("restartEasy")
end
end
end
end
button1:addEventListener("tap", endGame)
button2:addEventListener("tap", endGame2)
end

I dont know why you are using while and the if statement unnecessarily, try this it should work.
local function endGame(event)
if imageFile == "redbox.png" then
button1.x = math.random( 55, 300)
button1.y = math.random( 55, 300)
button2.x = math.random( 55, 300)
button2.y = math.random( 55, 300)
local imageFile = imageFiles[math.random(2)]
local randomImage = display.newImage(imageFile, centerX, screenTop + 20)
else
storyboard.gotoScene( "restartEasy" )
end
end

Related

how to pass continuous video stream to pyqt5 using Qthread correctly for face recognition?

I want to pass continuous video stream to pyqt5 qlabel named label_cam to show up in ui using QThread but it keep failed showing the video stream on the qlabel. The video stream is later aimed to recognize people out.
I have been trying to connect the signal "change_Pixmap" from the VideoThread class to the "set_image" function in the "label_cam" object but i guess the flow of code or variable assign is wrong. Below is my code.
class FaceRecogScreen(QDialog):
def init(self):
super(FaceRecogScreen, self).init()
uic.loadUi("face_recog.ui", self)
self.update_date_time()
self.pushButton_back.clicked.connect(self.back_to_main3)
self.load_model()
def load_model(self):
self.prototxt = "deploy.prototxt.txt"
self.model = "res10_300x300_ssd_iter_140000.caffemodel"
print("[INFORMATION] Loading model....")
self.net = cv2.dnn.readNetFromCaffe(self.prototxt, self.model)
weight = "facenet_keras_weights.h5"
self.model2 = load_model('FaceNetModel.h5')
self.model2.load_weights(weight)
self.collected_encodings = pickle.loads(open('face_encoding.pickle', "rb").read())
infile = open('face_encoding', 'rb')
data = pickle.load(infile)
self.knownEncodings, self.knownNames = data['encodings'], data['names']
self.knownEncodings = np.array(self.knownEncodings)
self.knownNames = np.array(self.knownNames)
self.clf = svm.SVC(gamma="scale", probability=True, tol=0.01)
self.clf.fit(self.knownEncodings, self.knownNames)
# self.label_cam= VideoLabel()
self.thread = VideoThread(self)
self.thread.change_Pixmap.connect(self.set_image)
# call the run() function in VideoThread class
self.thread.start()
# self.thread.change_Pixmap.connect(self.label_cam.set_image)
# # call the run() function in VideoThread class
# self.thread.start()
# layout = self.layout()
# layout.addWidget(self.label_cam)
# self.thread.run.start()
def update_date_time(self):
# Get the current date and time
date_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.label_datetime.setText(date_time)
# Update the date and time in the table
def back_to_main3(self):
pushButton_back = WelcomeScreen()
widget.addWidget(pushButton_back)
widget.setCurrentIndex(widget.currentIndex()+1)
def set_image(self, frame):
self.setPixmap(QPixmap.fromImage(frame))
class VideoThread(QtCore.QThread):
change_Pixmap = QtCore.pyqtSignal(QtGui.QImage)
def run(self):
cap = cv2.VideoCapture(1)
while True:
ret, frame = cap.read()
if ret:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
h, w, ch = frame.shape
bytesPerLine = ch * w
convertToQtFormat = QtGui.QImage(frame.data, w, h, bytesPerLine, QtGui.QImage.Format_RGB888)
p = convertToQtFormat.scaled(640, 480, QtCore.Qt.KeepAspectRatio)
self.change_Pixmap.emit(p)
(h, w) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(
frame, (160, 160)), 1.0, (300, 300), (104, 177, 123))
self.net.setInput(blob)
detections = self.net.forward()
self.frame = frame
# self.frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
cv2.normalize(frame, None, 0, 1.0, cv2.NORM_MINMAX, dtype=cv2.CV_32F)
pixels = np.expand_dims(frame, axis=0)
encode = self.model2.predict(pixels)
face_name = []
for encoding in encode:
name = self.clf.predict([encoding])
face_name.extend(name)
for i in range(0, detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence < 0.5:
continue
box = detections[0, 0, i, 3:7]*np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
text = "{:.2f}%".format(confidence*100)
y = startY - 10 if startY - 10 > 10 else startY*10
if name == 'unknown':
cv2.rectangle(frame, (startX, y), (endX, endY), (0, 0, 255), 2)
cv2.putText(frame, name, (startX, startY),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
else:
cv2.rectangle(frame, (startX, y), (endX, endY), (0, 255, 0), 2)
cv2.putText(frame, name[0], (startX, startY),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)

My code cant find a function in my module script Roblox

I'm writing a 2D game engine in Roblox for fun, but I have run into an issue.
It seems my code cant find the function I'm referencing.
My output says:
Players.SpookyDervish.PlayerGui.SpookyEngine.SpookyEngine:31: attempt to call a nil value
I have 3 module scripts and a main script.
Here is my explorer window:
The main script:
local gui = script.Parent
local spookyEngine = require(gui:WaitForChild("SpookyEngine"))
spookyEngine.Init()
spookyEngine:CreateObject("TestObject", Vector2.new(0, 0), Vector2.new(50, 50), "rbxassetid://183598555", Color3.fromRGB(85, 170, 255))
wait(2)
spookyEngine:Transform("test", Vector2.new(50, 50), Vector2.new(50, 50), 0)
My SpookyEngine module:
local object = require(script:WaitForChild("Object"))
local input = require(script:WaitForChild("Input"))
local gui = script.Parent
local spookyEngine = {}
function spookyEngine.Init()
spookyEngine.screen = Instance.new("Frame", gui)
spookyEngine.screen.Name = "Screen"
spookyEngine.screen.Position = UDim2.new(0.5, 0, 0.5, 0)
spookyEngine.screen.Size = UDim2.new(1.25, 0, 1.25, 0)
spookyEngine.screen.AnchorPoint = Vector2.new(0.5, 0.5)
spookyEngine.screen.BackgroundColor3 = Color3.fromRGB(0, 0, 0)
spookyEngine.screen.BorderSizePixel = 0
spookyEngine.screen.BorderColor3 = Color3.fromRGB(0, 0, 0)
object.Init()
spookyEngine.objects = object.objects
game.StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.All, false)
print("INFO: Initialized SpookyEngine!")
end
function spookyEngine:CreateObject(name, pos, size, sprite, colour)
object.New(name, pos, size, sprite, colour)
end
function spookyEngine:Transform(object, pos, size, rotation)
object:Transform(nil, nil, nil, nil)
end
return spookyEngine
My object module:
local spookyEngine = script.Parent
local gui = spookyEngine.Parent
local Object = {}
Object.__index = Object
function Object.Init()
local Objects = Instance.new("Folder", gui.Screen)
Objects.Name = "Objects"
Object.objects = Objects
end
function Object.New(name, pos, size, sprite, colour)
local newObject = {}
setmetatable(newObject, Object)
local position = UDim2.new(0.5, pos.X, 0.5, pos.Y)
local objectSize = UDim2.new(0, size.X, 0, size.Y)
local newObjectInstance = Instance.new("Frame", Object.objects)
newObjectInstance.Name = name
newObjectInstance.Position = position
newObjectInstance.Size = objectSize
newObjectInstance.BackgroundColor3 = colour
newObjectInstance.AnchorPoint = Vector2.new(0.5, 0.5)
newObjectInstance.BorderSizePixel = 0
if sprite ~= nil then
local objectSprite = Instance.new("ImageLabel", newObjectInstance)
objectSprite.Size = UDim2.new(1, 0, 1, 0)
objectSprite.Name = "Sprite"
objectSprite.Image = sprite
objectSprite.BackgroundTransparency = 1
objectSprite.BackgroundColor3 = colour
newObjectInstance.BackgroundTransparency = 1
end
newObject.Name = name
newObject.Position = position
newObject.Size = objectSize
newObject.Sprite = sprite
newObject.Colour = colour
newObject.Instance = newObjectInstance
return newObject
end
function Object:Transform(object, pos, size, rotation)
object = tostring(object)
if Object.objects:FindFirstChild(object) then
else
warn("ERROR: Cant find object with name: '"..object.."'")
end
end
return Object
Any help would be appreciated!
Your error is pointing at this line :
function spookyEngine:Transform(object, pos, size, rotation)
object:Transform(nil, nil, nil, nil)
end
which is called by...
spookyEngine:Transform("test", Vector2.new(50, 50), Vector2.new(50, 50), 0)
Because you have a function argument named object, it shadows the object local variable that you used to define your module. So the string that you pass in is what gets used. So you are effectively trying to execute
string.Transform("test", nil, nil, nil, nil)
The lua string library does not have a function called Transform, so when you try to index the function, it comes back as nil. That is why you get the error attempt to call a nil value.
Since you intended to use the Object:Transform function from your module, the easy fix is to rename the function argument to avoid the name collision. Try something like :
function spookyEngine:Transform(obj, pos, size, rotation)
object:Transform(obj, pos, size, rotation)
end

How do I set legend element titles?

I am using code from this biostars post to get myself more acquainted with creating plots in ggplot. I am a bit stuck on setting the legend variables though
Is there a way to set the colour and control the number of breaks/dots in the legend (under numDEInCat)
term <-c("snoRNA binding", "preprophase band", "kinesin complex", "microtubule motor activity", "DNA replication")
fc <-runif(5, 1.00, 5.00)
padj_BH <-runif(5, 0.001, 0.05)
numDEInCat <-runif(5, 30, 300)
ggdata <- data.frame(term,fc,padj_BH, numDEInCat)
gg1 <- ggplot(ggdata,
aes(x = term, y = fc, size = numDEInCat, color = padj_BH)) +
expand_limits(y = 1) +
geom_point(shape = 16,inherit.aes = T) +
scale_size(range = c(2.5,12.5)) +
scale_color_gradient(low= "#ff0303",
high="#1e00b3")+ #colour for p value
xlab('') + ylab('Fold Enrichment') + #lavel fold enrichment axis
labs(
title = "Gene Ontology all",
subtitle = 'BH-adjusted',
caption = '',
color="Adjusted P-value", #label the aacolor
size="count") + #label dot size
theme_bw(base_size = 24) +
theme(
legend.position = 'right',
legend.background = element_rect(),
plot.title = element_text(angle = 0, size = 16, face = 'bold', vjust = 1),
plot.subtitle = element_text(angle = 0, size = 14, face = 'bold', vjust = 1),
plot.caption = element_text(angle = 0, size = 12, face = 'bold', vjust = 1),
axis.text.x = element_text(angle = 0, size = 12, face = 'bold', hjust = 1.10),
axis.text.y = element_text(angle = 0, size = 12, face = 'bold', vjust = 0.5),
axis.title = element_text(size = 12, face = 'bold'),
axis.title.x = element_text(size = 12, face = 'bold'),
axis.title.y = element_text(size = 12, face = 'bold'),
axis.line = element_line(colour = 'black'),
#Legend
legend.key = element_blank(), # removes the border
legend.key.size = unit(1, "cm"), # Sets overall area/size of the legend
legend.text = element_text(size = 14, face = "bold"), # Text size
title = element_text(size = 14, face = "bold")) +
coord_flip()
gg1
I think what you're looking for are guides(size = guide_legend(override.aes(BLABLA))) and scale_size(breaks = c(BLABLA))
gg1 +
guides(size = guide_legend(override.aes = list(colour = "red"))) +
scale_size(limits = c(1, 1000), breaks = c(10, 500, 1000))
Created on 2021-11-18 by the reprex package (v2.0.1)

Access variable from method of class Ui_MainWindow(object)

I have created a GUI that ask for files to index, search within it and spit out the results.
I am stuck with the last bit that is to show the excerpt of the documents retrieved.
I need to populate the tableWidget with the results of a search engine embedded in the same class. I Thought that the variables were reachable from everywhere within the class is labeled with self, but I was wrong.
This is my latest code I have tried tried so far:
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1126, 879)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(40, 30, 100, 30))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(180, 30, 120, 30))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(620, 30, 80, 30))
self.pushButton_3.setObjectName("pushButton_3")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(380, 60, 191, 21))
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_2.setGeometry(QtCore.QRect(40, 90, 50, 21))
self.lineEdit_2.setObjectName("lineEdit_2")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(380, 30, 50, 35))
font = QtGui.QFont()
font.setPointSize(10)
self.label.setFont(font)
self.label.setObjectName("label")
self.label2 = QtWidgets.QLabel(self.centralwidget)
self.label2.setGeometry(QtCore.QRect(40, 70, 150, 16))
font = QtGui.QFont()
font.setPointSize(10)
self.label2.setFont(font)
self.label2.setObjectName("label")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(0, 120, 1121, 721))
self.tableWidget.setObjectName("tableWidget")
data = self.data()
numrows = len(data)
numcols = len(data[0])
self.tableWidget.setColumnCount(numcols)
self.tableWidget.setRowCount(numrows)
for row in range(numrows):
for column in range(numcols):
self.tableWidget.setItem(row, column, QTableWidgetItem((data[row][column])))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1126, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
The function related to the results is as follow:
def search(self):
os.chdir(self.folder_path)
self.ix = open_dir("indexdir")
MYDIR = ("Results")
CHECK_FOLDER = os.path.isdir(MYDIR)
if not CHECK_FOLDER:
os.makedirs(MYDIR)
self.text = self.lineEdit.text()
self.query_str = self.text
self.query = qparser.QueryParser("textdata", schema = self.ix.schema)
self.q = self.query.parse(self.query_str)
self.topN = self.lineEdit_2.text()
if self.lineEdit_2.text() == "":
self.topN = 1000
else:
self.topN = int(self.lineEdit_2.text())
self.data=[]
with self.ix.searcher() as searcher:
self.results = searcher.search(self.q, terms=True, limit=self.topN)
Upper = highlight.UppercaseFormatter()
self.results.formatter = Upper
my_cf = highlight.ContextFragmenter(maxchars=500, surround=300)
self.results.fragmenter = my_cf
for self.i in self.results:
self.data.append({"title": self.i['title'], "text": self.i.highlights('textdata')})
return self.data
I got this error: AttributeError: 'Ui_MainWindow' object has no attribute 'folder_path'.
How I can access the self.data to populate the table?
It appears that you're trying to use the "folder_path" attribute without having created it first.
Before you use the your search function, add this line to your class:
self.folder_path = add/your/path/
I'll also note that in the code you provided, it appears that the search function is defined outside of the class (this may just be the effect of auto-formatting on stack overflow). In order for to make your self.folder_path variable usable as-named, double check that you've properly indented it as to make it a class method.
I overcame the issue by cleaning up SetupUI and creating a function that runs once I click within the editline.
self.lineEdit.returnPressed.connect(self.datatable)
def datatable(self):
data = self.data
numrows = len(self.data)
numcols = len(self.data[0])
self.tableWidget.setColumnCount(numcols)
self.tableWidget.setRowCount(numrows)
self.tableWidget.setHorizontalHeaderLabels((list(self.data[0].keys())))
self.tableWidget.resizeColumnsToContents()
self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
self.tableWidget.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
for row in range(numrows):
for column in range(numcols):
item = (list(self.data[row].values())[column])
self.tableWidget.setItem(row, column, QTableWidgetItem(item))

OOP GUI Error: main.lua:4: attempt to index local (a boolean value)... Issue with modules

Today, I was messing around with trying to make a gui class for game I'd like to start making in LOVE2D. I decided to try and use OOP to make creating new menus easier in the future. The OOP works great until I try and put it into it's own module, where it gives me the error above. I've double and triple checked my code against similar code and I can't find the problem. I've also looked it up and there are similar threads, but nothing that helps my problem. Here is the relevant code...
From the main.lua
local gui = {
x = 0, y = 0,
width = 0, height = 0,
popupSpeed = 300,
active = false,
color = {red = 0, blue = 0, green = 0, alpha = 0},
menuType = "",
--buttons = require "Game/buttons"
}
And from the gui.lua...
local newGUI = require "Game/gui"
local menus = {
playerInv = newGUI.new()
}
function love.load()
menus.playerInv:createDropDown("right" , _, 30, 100, love.graphics.getHeight() - 60, 50, 128, 50, 255)
end
function gui.new()
newMenu = {}
for k, v in pairs(gui) do
newMenu[k] = v
end
return newMenu
end
function gui:createDropDown(direction, x, y, width, height, red, blue, green, alpha)
self.red = red
self.blue = blue
self.green = green
self.alpha = alpha
if direction == "right" then
self.x = love.graphics.getWidth() - width
self.y = y
self.width = width
self.height = height
self.menuType = "rightDropDown"
elseif direction == "left" then
self.x = 0
self.y = y
self.widthMax = width
self.height = height
self.menuType = "leftDropDown"
elseif direction == "down" then
self.x = x
self.y = y
self.width = width
self.heightMax = height
self.menuType = "regDropDown"
end
end
function gui:drawGui()
if self.active == true then
love.graphics.setColor(self.red, self.blue, self.green, self.alpha)
love.graphics.rectangle("fill", self.x, self.y, self.width, self.height, 10, 10, 6)
end
end
I'm assuming the first snippet is Game/gui and that the second part is main.lua, if this is so, You are attempting to call .new() function which is clearly absent on your Game/gui file. You need to move all of gui's functions to it's own file as well, this includes gui.new(), gui:createDropDown and gui:drawGui() last but not least, you have to return gui at the end of it's own file.
Your main file should end up somewhat like this:
local newGUI = require "Game/gui"
local menus = {
playerInv = newGUI.new()
}
function love.load()
menus.playerInv:createDropDown("right" , _, 30, 100, love.graphics.getHeight() - 60, 50, 128, 50, 255)
end
and Game/gui somewhat like this:
local gui = {} -- With all the stuff inside
function gui.new()
-- With all the stuff it had inside
end
function gui:createDropDown()
-- With all the stuff it had inside
end
function gui:drawGui()
-- With all the stuff it had inside
end
return gui
You see, you forgot to move its functions to its own file, and return gui itself. Don't forget to replace what i omitted on Game/gui!