Displaying image buttons to replicate app icons - Corona SDK - button

I need to display images so that they mimic the layout of iOS app icons on the various "home" pages. I have the code written to display the various images; however, I cannot figure out how to return a value which corresponds with each individual image on a click event.
Here's my code so far:
plates = {
"fat-burning-foods.jpg",
"fresh_food.jpg",
"fat-burning-foods.jpg",
"star.png",
"fat-burning-foods.jpg",
"star.png",
"fat-burning-foods.jpg",
"fresh_food.jpg",
"fat-burning-foods.jpg",
"star.png",
"fat-burning-foods.jpg",
"fresh_food.jpg",
"fat-burning-foods.jpg",
"star.png"
}
-- The PlateId will have corosponding indexes with the plates array. It will be used to query plate information
plateId = {1,2,3,4}
plateIdRef = {}
index = 1
platesIsh = {1,2,3,4,5,6,7,8}
local anX = 20
local anY = 120
for i=1, #plates do
local bufferY = 20
if index == 4 then
bufferY = 110
anX = 20
elseif index > 4 then
bufferY = 110
end
if index == 7 then
bufferY = 200
anX = 20
elseif index > 7 then
bufferY = 200
if index == 10 then
bufferY = 290
anX = 20
elseif index > 10 then
bufferY = 290
end
end
local dummyVar = math.random()
dummyVar = display.newImageRect(plates[index],80, 80)
sceneGroup:insert(dummyVar)
dummyVar.x = anX + 30
dummyVar.y = anY + bufferY
table.insert(plateIdRef, index)
function dummyVar:touch( event )
if event.phase == "began" then
local alert = native.showAlert( "Corona", event.target, { "OK", "Learn More" } )
--print( "You touched "..dummyVar)
return true
end
end
dummyVar:addEventListener( "touch", dummyVar )
anX = anX + 110
index = index + 1
end
Any ideas?

Ok, an example to see how it works:
local plates = {}
local function plateTouch( self, event )
local phase = event.phase
if phase == "ended" then
print( "You touched ".. self.id)
end
return true
end
for i=1, 3 do
plates[i] = display.newImageRect("test.png",80, 80)
plates[i].id = "plate " .. i
plates[i].x = 90 * i
plates[i].y = 90
plates[i].touch = plateTouch
plates[i]:addEventListener( "touch", plates[i] )
end
When you create each plate you can define an id property to know what button was pressed, also you can add any other properties you need.
You can see the API docs for touch event and see the example with table listeners.
Other approach could be object oriented solution, where you define a class to create new plates, but maybe first you need to understand the example.

Related

Object Shell.Application Open Folder In Same Explorer Window

I want to ask you a question regarding Shell.Application COM Object. The programming language I work in is AutoIT. I would like to know, how can I open a folder in the exact same Window a previous folder has been opened.
For instance, if I open the C:\Folder in a Window and it has a subfolder, then how can I make the Script open that subfolder in the same window the "parent folder" has been opened, without creating a new window for that. The only way I can open a Folder is like this:
global $ShellApplication = ObjCreate("Shell.Application")
$ShellApplication.Explore("C:\Folder")
Sleep(100)
$ShellApplication.Explore("C:\Folder\Subfolder")
but this way is the wrong way. I hope someone has got any idea about how this could be achieved.
I don't know whether this is what you want, but you can automate the current window like this:
#include <Array.au3>
Opt("SendKeyDelay", 1) ;5 milliseconds
Opt("SendKeyDownDelay", 1) ;1 millisecond
$pid = ShellExecute("explorer.exe ", #DesktopDir)
Sleep(300)
;~ $aWinList=WinList("[REGEXPCLASS:(Explore|Cabinet)WClass]")
;~ _ArrayDisplay($aWinList)
ConsoleWrite($pid & #CRLF)
$handle = _WinGetHandleByPID($pid)
Sleep(2000)
SendKeepActive($handle)
Send('{F4}')
Send('^a')
Send(#AppDataCommonDir & "{ENTER}")
Func _WinGetHandleByPID($vProcess, $nShow = 1)
; Get Window Handle by PID
; Author Hubertus
; derived from Smoke_N's script with the same name,
; but to handle more than one process with the same name
; and to return handle of newest window ($nShow = 2).
;
; $vProcess = Processname(e.g. "Notepad.exe") or Processnumber(e.g. 4711 )
; $nShow = -1 "All (Visble or not)", $nShow = 0 "Not Visible Only", $nShow = 1 "Visible Only", $nShow = 2 "return handle of newest window "
; #error = 0 Returns array of matches. Array[0][0] and #extended shows number of matches.
; #error = 0 and $nShow = 2 return handle of newest window
; Array[n][0] shows windows title. Array[n][1] shows windows handle. n = 1 to #extended
; #error = 1 Process not found.
; #error = 2 Window not found.
If Not ProcessExists($vProcess) Then Return SetError(1, 0, 0) ; no matching process
Local $iWinList, $aWinList = WinList()
Local $iResult, $aResult[UBound($aWinList)][2]
Local $iProcessList, $aProcessList = ProcessList($vProcess)
If $aProcessList[0][0] = 0 Then Local $aProcessList[2][2] = [[1, 0], ["", $vProcess]]
For $iWinList = 1 To $aWinList[0][0]
For $iProcessList = 1 To $aProcessList[0][0]
If WinGetProcess($aWinList[$iWinList][1]) = $aProcessList[$iProcessList][1] Then
If $nShow > -1 And Not $nShow = (2 = BitAND(WinGetState($aWinList[$iWinList][1]), 2)) Then ContinueLoop
$iResult += 1
$aResult[$iResult][0] = $aWinList[$iWinList][0]
$aResult[$iResult][1] = $aWinList[$iWinList][1]
EndIf
Next
Next
If $iResult = 0 Then Return SetError(2, 0, 0) ; no window found
ReDim $aResult[$iResult + 1][2]
$aResult[0][0] = $iResult
If $nShow = 2 Then Return SetError(0, $iResult, $aResult[1][1])
Return SetError(0, $iResult, $aResult)
EndFunc ;==>_WinGetHandleByPID

Round Off time to the upcoming nearest 15 minutes time using Groovy

I am trying to round off time to the upcoming 15 minutes time.
e.g :
2017-12-11T13:11:51.728Z to 2017-12-11T13:15:00.000Z
2017-12-11T13:21:51.728Z to 2017-12-11T13:30:00.000Z
Groovy code :
def currentTime = context.expand('${#Project#currentTime}')
log.info currentTime
date1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(currentTime)
//Round off the time nearest to the mod 15
Calendar calendar = Calendar.getInstance();
calendar.setTime(date1);
int unroundedMinutes = calendar.get(Calendar.MINUTE);
int mod = unroundedMinutes % 15;
log.info calendar.add(Calendar.MINUTE, mod < 8 ? -mod : (15-mod));
Output :
Mon Dec 11 14:32:32 IST 2017:INFO:2017-12-11T14:32:32.690Z
Mon Dec 11 14:32:32 IST 2017:INFO:null
Here you go:
In order to get the difference minutes, created a closure.
The closure gets called recursively if needed.
If the current minutes is divisible by 15, it won't adjust the time; that is the reason for adding third value in the list.
To be able to test with multiple values, used list of dates. You may use it for single value as well.
def timez = ['2017-12-11T13:11:51.728Z', '2017-12-11T13:21:51.728Z', '2017-12-11T13:30:00.000Z']
def dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
def roundValue = 15
//Change timezone if needed
def tz = 'IST'
TimeZone.setDefault(TimeZone.getTimeZone(tz))
Calendar calendar = Calendar.getInstance()
def getNearestMinutes
//Closure which gets called recursive
getNearestMinutes = { cmin, nearMin = roundValue ->
def tempResult = cmin % nearMin
if ( tempResult < nearMin && (0 < (nearMin - cmin)) ) {
return (nearMin - cmin)
} else {
return getNearestMinutes(cmin, nearMin+roundValue)
}
}
//Loop thru times and round the time
timez.each {
calendar.time = Date.parse(dateFormat,it)
def currentMinute = calendar.get(Calendar.MINUTE)
def cof = currentMinute % roundValue
if (cof) {
currentMinute += getNearestMinutes(currentMinute)
calendar.set(Calendar.MINUTE, currentMinute )
}
calendar.set(Calendar.SECOND, 0)
calendar.set(Calendar.MILLISECOND, 0)
log.info calendar.time.format(dateFormat)
}
You can quickly try it online demo
EDIT: Felt that the solution could be made something more simple than applying above difficult conditions.
Here is another solution to round time to near future 15 min.
Yet, easy to read code unlike multiple conditions in the first solution.
This is simple one using Switch statement
def timez = ['2017-12-11T13:11:51.728Z', '2017-12-11T13:21:51.728Z', '2017-12-11T13:30:00.000Z', '2017-12-11T13:46:00.000Z']
def dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
def roundValue = 15
//Change timezone if needed
def tz = 'IST'
TimeZone.setDefault(TimeZone.getTimeZone(tz))
Calendar calendar = Calendar.getInstance()
def getNexTime = { min ->
def result
switch(min) {
case 1..15:
result = 15
break
case 16..30:
result = 30
break
case 31..45:
result = 45
break
case 46..60:
result = 60
break
default:
result = 0
break
}
result
}
//Loop thru times and round the time
timez.each {
calendar.time = Date.parse(dateFormat,it)
def currentMinute = calendar.get(Calendar.MINUTE)
if (0 != getNexTime(currentMinute)) {
calendar.set(Calendar.MINUTE, getNexTime(currentMinute) )
}
calendar.set(Calendar.SECOND, 0)
calendar.set(Calendar.MILLISECOND, 0)
println calendar.time.format(dateFormat)
}

Arrays and variables clears itself after a end sub in VB.net

I am writing a times tables program in ASP.net and I need some help. The problem I am experiencing is that when the button sub ends and the screen pops up again for user input, all the arrays and variables are now set to nothing or 0.
Is there are way to keep all the values for variables after a sub ends and to use them later on?
Any help will be appreciated.
Public Class PickTimesTables
Inherits System.Web.UI.Page
Dim count As Integer = 0
Dim NumberQ As Integer
Dim RandomN As Integer
Dim FirstNumber() As Integer
Dim FirstNumberTemp() As Integer
Dim SecondNumber() As Integer
Dim correctAnswers As Integer
Dim inc As Integer = 0
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
PanelQuestion.Visible = False
PanelAnalysis.Visible = False
End Sub
Protected Sub btnTest_Click(sender As Object, e As EventArgs) Handles btnTest.Click
PanelQuestion.Visible = True
lblOperator.Text = "X"
If chktimes1.Checked = False And chktimes2.Checked = False And chktimes3.Checked = False And chktimes4.Checked = False And chktimes5.Checked = False And chktimes6.Checked = False And chktimes7.Checked = False And chktimes8.Checked = False And chktimes9.Checked = False And chktimes10.Checked = False And chktimes11.Checked = False And chktimes12.Checked = False Then
MsgBox("Pick a Times Table to be Tested for..")
ElseIf txtNoQuestion.Text = "" Then
MsgBox("Pick the Number of Question for the test")
Else
NumberQ = txtNoQuestion.Text
count = 0
If chktimes1.Checked Then
count = count + 1
End If
If chktimes2.Checked Then
count = count + 1
End If
If chktimes3.Checked Then
count = count + 1
End If
If chktimes4.Checked Then
count = count + 1
End If
If chktimes5.Checked Then
count = count + 1
End If
If chktimes6.Checked Then
count = count + 1
End If
If chktimes7.Checked Then
count = count + 1
End If
If chktimes8.Checked Then
count = count + 1
End If
If chktimes9.Checked Then
count = count + 1
End If
If chktimes10.Checked Then
count = count + 1
End If
If chktimes11.Checked Then
count = count + 1
End If
If chktimes12.Checked Then
count = count + 1
End If
If txtNoQuestion.Text = 0 Then
MsgBox("You cannot have a test with 0 Questions")
Else
ReDim FirstNumberTemp(count - 1)
For i = 0 To count - 1
If chktimes1.Checked Then
FirstNumberTemp(i) = 1
chktimes1.Checked = False
ElseIf chktimes2.Checked Then
FirstNumberTemp(i) = 2
chktimes2.Checked = False
ElseIf chktimes3.Checked Then
FirstNumberTemp(i) = 3
chktimes3.Checked = False
ElseIf chktimes4.Checked Then
FirstNumberTemp(i) = 4
chktimes4.Checked = False
ElseIf chktimes5.Checked Then
FirstNumberTemp(i) = 5
chktimes5.Checked = False
ElseIf chktimes6.Checked Then
FirstNumberTemp(i) = 6
chktimes6.Checked = False
ElseIf chktimes7.Checked Then
FirstNumberTemp(i) = 7
chktimes7.Checked = False
ElseIf chktimes8.Checked Then
FirstNumberTemp(i) = 8
chktimes8.Checked = False
ElseIf chktimes9.Checked Then
FirstNumberTemp(i) = 9
chktimes9.Checked = False
ElseIf chktimes10.Checked Then
FirstNumberTemp(i) = 10
chktimes10.Checked = False
ElseIf chktimes11.Checked Then
FirstNumberTemp(i) = 11
chktimes11.Checked = False
ElseIf chktimes12.Checked Then
FirstNumberTemp(i) = 12
chktimes12.Checked = False
End If
Next
ReDim FirstNumber(NumberQ - 1)
For i = 0 To NumberQ - 1
Randomize()
RandomN = FirstNumberTemp(Int(Rnd() * count))
FirstNumber(i) = RandomN
Next
ReDim SecondNumber(NumberQ - 1)
For i = 0 To NumberQ - 1
Dim rn As New Random(Now.Millisecond)
RandomN = rn.Next(1, 13)
SecondNumber(i) = RandomN
Next
lblFirstN.Text = FirstNumber(0)
lblSecondN.Text = SecondNumber(0)
End If
End If
End Sub
Protected Sub txtInput_TextChanged(sender As Object, e As EventArgs) Handles txtInput.TextChanged
NumberQ = txtNoQuestion.Text
If txtInput.Text = FirstNumber(inc) * SecondNumber(inc) Then
lblFirstN.Text = FirstNumber(inc + 1)
lblSecondN.Text = SecondNumber(inc + 1)
correctAnswers = correctAnswers + 1
txtInput.BackColor = Drawing.Color.Green
Else
txtInput.BackColor = Drawing.Color.Red
lblFirstN.Text = FirstNumber(inc + 1)
lblSecondN.Text = SecondNumber(inc + 1)
End If
End Sub
End Class
This is a common mistake for newcomers to ASP.Net Webforms. There is this idea that your page class instance lives for an entire session, for all of a user's interactions with the page in the browser. This does not happen. Any interaction with your page that causes an event to fire creates a new postback from the client to the server, and every postback uses a brand new instance of the Page class. By the time the user sees your page in their browser, whatever Page object you used to render the html for that view has already been destroyed and garbage collected.
There are some things you can do to get around this, like putting variables in the Session, URL, or ViewState, but often you need to completely re-think your approach to something that is more natural for a web site.
Additionally, you'll want to re-think handling a TextChanged event in your VB.Net code. Generally speaking, TextChanged events need to return to the user in 25-40 milliseconds, or the view will feel extremely sluggish. It's not usually a problem when the program is running right there on the user's computer, and has all the memory and CPU power of that workstation available. It's a whole other story for web sites, where you might have an 80ms delay before the request even reaches the server and another 80ms for the response, all before doing any processing, and the server is sharing it's CPU and memory resources to support as many users as you can fit.
Instead, look into using a javascript event for that processing, and only validate the text in your VB.Net code when the user finally tries to submit or save the end result.
Finally, those calls to the MsgBox() function need to go, too. It only seems to work on your system because your web server is on the same machine as the web browser. When you go to actually put this on a real server and test from a different place, those message will display on the server, not in the user's web browser.
They'll all be reset because that's the stateless nature of the web. They don't keep their values because each subsequent time you view that page (or step through it using the debugger), it's a new request.
You should google storing asp.net variables in ViewState or Session, i.e. ViewState-backed properties.

Problems with TCP in VACaMobil

I am having some problems with TCP in VACaMobil.
I am using two TCP modules built up in Inet: TCPBasicClientApp and TCPEchoApp.
The former works as a client and the former works as a server.
The number of cars (the module name is "coche") in the simulation is 100, and there are five concurrent transmissions:
CLIENT SERVER
Car 0 --> Car 99
Car 1 --> Car 98
Car 2 --> Car 97
Car 3 --> Car 96
Car 4 --> Car 95
I am also using three routing protocols: AODV, DYMO and OLSR.
However, regardless of the configuration that I run, errors like this ocurr in the simulation:
Error in module (TCPBasicClientApp) Highway.coche[*].tcpApp[0] (id = 35) at event #49519, t = 166: IPvXAddressResolver: module 'coche[98]' not found.
In this case, using AODV, the car 1 cannot communicate with the car 98. I learned that VACaMobil, after a time, deletes some cars while it is creating others beyond 100,
such as "coche[110]", "coche[115]", etc.
I don't understand why it keeps deleting and creating nodes; I thought that VACaMobil really generated a constant number of vehicles.
How can I fix this? Any help is appreciated.
Here is the omnetpp.ini:
[General]
network = Highway
debug-on-errors = false
cmdenv-express-mode = true
cmdenv-autoflush = true
cmdenv-status-frequency = 10000000s
#repeat = 10
tkenv-plugin-path = ../../../etc/plugins
tkenv-image-path = bitmaps
check-signals = true
**.manager.**.scalar-recording = true
**.manager.**.vector-recording = true
**.manetrouting.**.scalar-recording = true
**.movStats.**.scalar-recording = true
**.movStats.**.vector-recording = true
**.mac.**.scalar-recording = true
**.mac.**.vector-recording = true
**.scalar-recording = true
**.vector-recording = true
#ChannelControl
*.channelControl.carrierFrequency = 2.4GHz
*.channelControl.pMax = 2mW
*.channelControl.sat = -110dBm
*.channelControl.alpha = 2
*.channelControl.numChannels = 1
# TraCIScenarioManagerLaunchd
*.manager.updateInterval = 1s
*.manager.host = "localhost"
*.manager.port = 9999
*.manager.moduleType = "rcdp9.TAdhocHost"
*.manager.moduleName = "coche"
*.manager.moduleDisplayString = ""
*.manager.autoShutdown = true
*.manager.margin = 25
*.manager.warmUpSeconds = 0
*.manager.launchConfig = xmldoc("VACaMobil/Milan/downtown.launch.xml")
*.manager.getStatistics = true
*.manager.statFiles = "${resultdir}/${configname}-${runnumber}-"
# nic settings
**.wlan[*].bitrate = 24Mbps
**.wlan[*].opMode = "g"
**.wlan[*].mgmt.frameCapacity = 10
**.wlan[*].mgmtType = "Ieee80211MgmtAdhoc"
**.wlan[*].mac.basicBitrate = 24Mbps
**.wlan[*].mac.controlBitrate = 24Mbps
**.wlan[*].mac.address = "auto"
**.wlan[*].mac.maxQueueSize = 14
**.wlan[*].mac.rtsThresholdBytes = 3000B
**.wlan[*].mac.retryLimit = 7
**.wlan[*].mac.cwMinData = 7
**.wlan[*].radio.transmitterPower = 2mW
**.wlan[*].radio.thermalNoise = -110dBm
**.wlan[*].radio.sensitivity = -85dBm
**.wlan[*].radio.pathLossAlpha = 2
**.wlan[*].radio.snirThreshold = 4dB
**.channelNumber = 0
**.coche.networkLayer.configurator.networkConfiguratorModule = "configurator"
# manet routing
**.routingProtocol = ${"AODVUU", "DYMO", "OLSR"}
**.tcpAlgorithmClass = "TCPNewReno"
**.coche[0..4].numTcpApps = 1
**.coche[0..4].tcpApp[*].typename = "TCPBasicClientApp"
**.coche[0..4].tcpApp[*].localPort = -1
**.coche[0..4].tcpApp[*].connectPort = 1000
**.coche[0..4].tcpApp[*].dataTransferMode = "bytecount"
**.coche[0..4].tcpApp[*].startTime = 10s
**.coche[0..4].tcpApp[*].thinkTime = 1s
**.coche[0..4].tcpApp[*].idleInterval = 3s
**.coche[0..4].tcpApp[*].requestLength = 5000000B
**.coche[5..94].numTcpApps = 0
**.coche[95..99].numTcpApps = 1
**.coche[95..99].tcpApp[*].typename = "TCPEchoApp"
**.coche[95..99].tcpApp[*].localPort = 1000
**.coche[95..99].tcpApp[*].dataTransferMode = "bytecount"
**.coche[0].tcpApp[*].connectAddress = "coche[99]"
**.coche[1].tcpApp[*].connectAddress = "coche[98]"
**.coche[2].tcpApp[*].connectAddress = "coche[97]"
**.coche[3].tcpApp[*].connectAddress = "coche[96]"
**.coche[4].tcpApp[*].connectAddress = "coche[95]"
**.meanNumberOfCars = 100
**.autoShutdown = false
Here is TAdhocHost.ned:
package rcdp9;
import inet.networklayer.IManetRouting;
import inet.networklayer.autorouting.ipv4.HostAutoConfigurator2;
import inet.nodes.inet.AdhocHost;
module TAdhocHost extends AdhocHost
{
parameters:
#display("i=device/cellphone");
mobilityType = default("TraCIMobility");
IPForward = true;
submodules:
ac_wlan: HostAutoConfigurator2 {
#display("p=127,240");
}
connections:
}
Here is Highway.ned:
package rcdp9;
import inet.world.VACaMobil.VACaMobil;
import inet.networklayer.autorouting.ipv4.IPv4NetworkConfigurator;
import inet.networklayer.autorouting.ipv4.HostAutoConfigurator;
import inet.nodes.inet.AdhocHost;
import inet.world.radio.ChannelControl;
import inet.world.traci.TraCIScenarioManagerLaunchd;
network Highway
{
submodules:
configurator: IPv4NetworkConfigurator {
#display("p=396,221");
}
channelControl: ChannelControl {
#display("p=396,310");
}
manager: VACaMobil {
#display("p=322,405");
}
connections allowunconnected:
}
From what I understand, VACaMobil is built on Veins.
Veins creates a new network node for every vehicle that starts driving. When the corresponding vehicle stops driving (having arrived at its destination) Veins deletes the network node. It never re-uses the same node index.
Thus, in your example, the first vehicle that starts driving will be coche[0]. The next vehicle that starts driving will be coche[1] - independent of whether coche[0] already arrived or is still driving.

Score activated when button is pressed does not work, Corona sdk

I would like the score to increase only when this button is pressed. However when I tried running my code the score did not change... Any ideas?
thanks in advance!
here is my code:
score = 0
local scoreNumber = display.newText(score, 200, 30, nil, 20)
scoreNumber.xScale = 1.2
scoreNumber.yScale = 1.2
local scoreText = display.newText("score:", 150, 30, nil, 20)
scoreText.xScale = 1.2
scoreText.yScale = 1.2
local buttonPressed = false
local myButton = display.newRect(50,50,100,100)
local function scoretimer(event)
if buttonPressed then
score = score + 1
scoreNumber.text = score
end
end
local function buttonPressed(event)
if event.phase == "began" then
buttonPressed = true
elseif event.phase == "ended" then
buttonPressed = false
end
return true
end
myButton:addEventListener("touch", buttonPressed)
Runtime:addEventListener("enterFrame", scoretimer)
First you declare:
local buttonPressed = false
end then you declare it again as a function:
local function buttonPressed(event)
Rename your function and everything should go fine

Resources