I am trying to subtract 10 minutes from the current time, but I cant find the proper syntax in the documentation I have looked up
I have this so far
def deltaMinutes = 10
use(TimeCategory) {
def nowTime = new Date() - deltaMinutes.minutes
log.debug nowTime
}
and get this in the SmartThings IDE
java.lang.NullPointerException # line 53
Perhaps the IDE doesnt support this library? What would be the next best method for calculating this?
10.minutes.ago should give what you are looking for
use( groovy.time.TimeCategory ) {
println 10.minutes.ago
}
Related
I am doing an activity to learn Kotlin where I am completely stuck. I am new to coding and Kotlin so excuse me for my mistakes and lack of knowledge.
This is the description of the activity:
You need to write a program that prints date and time in a special format. Hours, minutes and seconds are split by a colon, and day, month and year are split by a slash. For example:
Sample Input 1:
23 59 59
12 12 2018
Sample Output 1:
23:59:59 12/12/2018
I have been trying a lot of different things, but I'm lost. This is the path that I was trying to take:
fun main() {
val time = readLine()?.split("")
val date = readLine()?.split("")
println("$time $date")
}
I know the code is wrong, as I don't know how to do it, I am simply posting the path or idea that I was following. If someone could explain me what I have to do, I would really appreciate it. Thanks!
Try to edit your code like this
fun main() {
val time = readLine()?.split(" ")?.joinToString(":") ?: ""
val date = readLine()?.split(" ")?.joinToString("/") ?: ""
println("$time $date")
}
If you'd like to check if the read line is actually a date you can use DateTimeFormatter
private fun parseDate(arg: String) {
try {
val timeString = arg.split(" ").take(3).joinToString(":")
val dateString = arg.split(" ").takeLast(3).joinToString("/")
val parser = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")
parser.parse("$dateString $timeString")
println("$dateString $timeString")
} catch (e: Exception) {
println("[ERR] - Error parsing argument: $arg")
}
}
fun main() {
parseDate(readLine())
}
I try to create a Voice Assistant on python3
This is my function Speak (with pyttsx):
def speak(what):
print("Gosha: " + what)
speak_engine.say( what )
speak_engine.runAndWait()
speak_engine.stop()
in the main body it works fine, but in function execute_cmd, after Speak function my code stucks.
One part of execute_cmd:
def execute_cmd(cmd, voice):
global finished
finished = False
#import debug
if cmd == 'ctime':
now = datetime.datetime.now()
hours = str(now.hour)
minutes = str(now.minute)
if (now.minute < 10): minutes = '0' + minutes
speak("Now " + hours + ":" + minutes)
finished = True
finished will never True
This happens anywhere in the function
pls help me
(sorry for my eng, I'm from Russia)
UPD: I debugged my code and noticed, my code get stuck on speak_engine.runAndWait()
I know, many people have same problem, but their solutions didn't help me
I'm not sure I understand you problem. What exactly do you mean by your code getting "Stuck"? Since you said that your finished variable will never be False, I assume that the code runs through and doesn't get stuck. My best guess is that your code simply doesn't produce sound.
If that's the case, I could imagine it's due to the previous loop still being active. So maybe try adding the following to your speak() function:
ef speak(what):
print("Gosha: " + what)
try:
speak_engine.endLoop()
except Exception as e:
pass
speak_engine.say( what )
speak_engine.runAndWait()
speak_engine.stop()
def waktusekarang
SimpleDateFormat abc = new SimpleDateFormat("HHmm")
waktusekarang = abc.format(new Date())
if current time is 13:58, then it will be become 1358 because (SimpleDateFormat is HHmm). then how to +2 minutes to the current time then the result become 1400.
i try new Date()+2 but its not success and the result become 13581,and i also try to parseInteger but its not success too.
please help my problem , how can i +1 or +2 minutes to current time if current minute is 59.because if minute is 59 then +1 will be 60 ,it must be 00
Use can use Calendar to add minutes to your time, appropriately your time would be incremented:
SimpleDateFormat abc = new SimpleDateFormat("HHmm");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 2);
String waktusekarang = abc.format(cal.getTime());
System.out.println(waktusekarang);
A Groovy solution would be:
Date in2mins = use( groovy.time.TimeCategory ) {
new Date() + 2.minutes
}
String waktusekarang = in2mins.format( 'HHmm' )
println waktusekarang
Dont use format(Date). Use format(int) and then call System.currentTimeMillis() and add 120000 ms = 2 mins. Thats a way to do it without calendar. But you should think of using calendar.
SimpleDateFormat abc = new SimpleDateFormat("HHmm");
waktusekarang = abc.format(System.currentTimeMillis()+120000);
When try this sample code:
use(groovy.time.TimeCategory) {
800.millisecond + 300.millisecond
}
in groovy web console, I get a funny result:
0.1100 seconds
Does any one know why this happens or how to fix it?
That looks like a bug, the TimeDuration contains 1100 milliseconds, but when it prints it out, it converts it wrongly to seconds.
I've added it to the Groovy JIRA as a bug EDIT It's now marked as FIXED for versions 2.0.6, 1.8.9 and 2.1.0
In the mean time, I guess you'll need to do your own converter from TimeDuration to String :-/
Edit
You could do something like this (and there is probably a neater way of doing it)
groovy.time.TimeDuration.metaClass.normalize = { ->
def newdmap = ['days','hours','minutes','seconds','millis'].collectEntries {
[ (it):delegate."$it" ]
}.with { dmap ->
[millis:1000,seconds:60,minutes:60,hours:24,days:-1].inject( [ dur:[ days:0, hours:0, minutes:0, seconds:0, millis:0 ], roll:0 ] ) { val, field ->
val.dur."$field.key" = dmap."$field.key" + val.roll
val.roll = val.dur."$field.key".intdiv( field.value )
val.dur."$field.key" = field.value < 0 ?
val.dur."$field.key" :
val.dur."$field.key" % field.value
val
}.dur
}
new TimeDuration( newdmap.days, newdmap.hours, newdmap.minutes, newdmap.seconds, newdmap.millis )
}
That adds a normalize method to TimeDuration, so then doing:
use(groovy.time.TimeCategory) {
800.millisecond + 300.millisecond
}.normalize()
Shows 1.100 seconds
I haven't done a huge amount of testing on that method, so be warned it could do with some unit tests to make sure it doesn't fall over with other situations.
Just started learning Groovy, got the PragProg book "Programming Groovy" and had a problem compiling one of the sample scripts:
class GCar2 {
final miles = 0
def getMiles() {
println "getMiles called"
miles
}
def drive(dist) {
if (dist > 0) {
miles += dist
}
}
}
def car = new GCar2()
println "Miles: $car.miles"
println 'Driving'
car.drive(10)
println "Miles: $car.miles"
try {
print 'Can I see the miles? '
car.miles = 12
} catch (groovy.lang.ReadOnlyPropertyException ex) {
println ex.message
GroovyCar2.groovy: 20: cannnot access final field or property outside of constructor.
# line 20, column 35.
def drive(dist) { if (dist > 0) miles += dist }
^
Groovy versions prior to 1.7 do not give an error. I looked through whatever documentation I could find and did not see the issue discussed. What is going on here?
Aaron
I don't know much about Groovy 1.7, but it looks like a bug in earlier versions which has now been fixed - if a variable is final, you shouldn't be able to assign to it outside the constructor (or its declaration). If you can, what's the point of making it final?
I doubt that it'll stop you from reading it outside the constructor though...
You shouldn't be able to assign to a final variable in a normal method. It was a bug in groovy, fixed in 1.7.