MicroPython 1.19.1, RP2040, Periodic Timer Execution only runs Once, then 'NoneType' object isn't callable - timer

Using a RaspberryPi Pico, V1.19.1.
When I define my timer the first execution works fine, however subsequent periods fail with 'TypeError: 'NoneType' object isn't callable.
Edited; to simplify post.
import machine, time
from machine import Timer
class app():
def __init__(self):
self.pulse = machine.Timer(-1)
self.pulse.init(mode=Timer.PERIODIC, period=1000, callback=self.cb_pulse())
def cb_pulse(self):
print("whai!")
app()

You must specify the callback function themself, so without the ()
# Good
self.pulse.init(mode=Timer.PERIODIC, period=200, callback=self.cb_pulse)
# Bad
self.pulse.init(mode=Timer.PERIODIC, period=200, callback=self.cb_pulse())
With the added (), you are actually passing the result/output of the callback method to the timer.
And as that returns nothing == None, so the timer tries to call 'None', which is indeed not a callable.
Working sample in simulator: https://wokwi.com/projects/354050429354521601

Related

scala - Gatling - I can't seem to use Session Variables stored from a request in a subsequent Request

The code:
package simulations
import io.gatling.core.Predef._
import io.gatling.http.Predef._
class StarWarsBasicExample extends Simulation
{
// 1 Http Conf
val httpConf = http.baseUrl("https://swapi.dev/api/films/")
// 2 Scenario Definition
val scn = scenario("Star Wars API")
.exec(http("Get Number")
.get("4")
.check(jsonPath("$.episode_id")
.saveAs("episodeId"))
)
.exec(session => {
val movie = session("episodeId").as[String]
session.set("episode",movie)
}).pause(4)
.exec(http("$episode")
.get("$episode"))
// 3 Load Scenario
setUp(
scn.inject(atOnceUsers(1)))
.protocols(httpConf)
}
Trying to grab a variable from the first Get request, and inject that variable into a second request, but unable to do so despite using the documentation. There might be something I'm not understanding.
When I use breakpoints, and navigate through the process, it appears the session execution happens AFTER both of the other requests have been completed (by which time is too late). Can't seem to make that session execution happen between the two requests.
Already answered on Gatling's community mailing list.
"$episode" is not correct Gatling Expression Language syntax. "${episode}" is correct.

Sentinel import inside Terraform Cloud confusion: key "find_resources" doesn't support function calls

I'm using a Sentinel policy inside a Terraform Cloud workspace. My policy is rather simple:
import "tfplan/v2" as tfplan
allBDs = tfplan.find_resources("aci_bridge_domain")
violatingBDs = tfplan.filter_attribute_does_not_match_regex(allBDs,
"description", "^demo(.+)", true)
main = rule {
length(violatingBDs["messages"]) is 0
}
Unfortunately, it fails when invoked with this message:
An error occurred: 1 error occurred:
* ./allowed-terraform-version.sentinel:3:10: key "find_resources" doesn't support function calls
The documentation and source for find_resources (doc) expects a string, yet the Sentinel interpreter seems to think I'm invoking a method of tfplan? It's quite unclear why that is, and the documentation doesn't really help.
Any ideas?
OK I found the issue. If I paste the code for find_resources and its dependencies (to_string, evaluate_attribute) then everything works as expected.
So I have a simple import problem and need to figure out how to properly import https://raw.githubusercontent.com/hashicorp/terraform-guides/master/governance/third-generation/common-functions/tfplan-functions/tfplan-functions.sentinel

How to access slots using add_directive with an updated intent [python]

This is my code that should go to another intent handler.
return handler_input.response_builder\
.add_directive(DelegateDirective(updated_intent="Intent2"))\
.speak(speech_text)\
.set_should_end_session(False)\
.response
And this is my second intent handler code:
#sb.request_handler(can_handle_func=is_intent_name("Intent2"))
def intent2_handler(handler_input):
"""Handler for Cancel Home Tour Intent."""
slots = handler_input.request_envelope.request.intent.slots
session_attr = handler_input.attributes_manager.session_attributes
x = slots["my_slot"] <--- causes error
I'm getting TypeError: 'NoneType' object is not subscriptable . It seems like I can't access my slots. Am I using add_directive(DelegateDirective(updated_intent="Intent2")) right?

Why does dbListTables give a warning message when called via a function? (R DBI)

I wrote a function using dbListTables from the DBI package, that throws a warning that I cannot understand. When I run the same code outside of a function, I don't get the warning message.
For info, the database used is Microsoft SQL Server.
Reproducible example
library(odbc)
library(DBI)
# dbListTables in a function: gives a warning message
dbListTablesTest <- function(dsn, userName, password){
con <- dbConnect(
odbc::odbc(),
dsn = dsn,
UID = userName,
PWD = password,
Port = 1433,
encoding = "latin1"
)
availableTables <- dbListTables(con)
}
availableTables <-
dbListTablesTest(
dsn = "myDsn"
,userName = myLogin
,password = myPassword
)
# dbListTables not within a function works fine (no warnings)
con2 <- dbConnect(
odbc::odbc(),
dsn = "myDsn",
UID = myLogin,
PWD = myPassword,
Port = 1433,
encoding = "latin1"
)
availableTables <- dbListTables(con2)
(Incidentally, I realise I should use dbDisconnect to close a connection after working with it. But that seems to throw similar warnings. So for the sake of simplicity I've omitted dbDisconnect.)
The warning message
When executing the code above, I get the following warning message when using the first option (via a function), but I do not get it when using the second option (no function).
warning messages from top-level task callback '1'
Warning message:
Could not notify connection observer. trying to get slot "info" from an object of a basic class ("character") with no slots
The warning is clearly caused by dbListTables, because it disappears when I omit that line from the above funtion.
My questions
Why am I getting this warning message?
More specifically why am I only getting it when calling dbListTables via a function?
What am I doing wrong / should I do to avoid it?
My session info
R version 3.4.2 (2017-09-28)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
Matrix products: default
locale:
[1] LC_COLLATE=Dutch_Belgium.1252 LC_CTYPE=Dutch_Belgium.1252 LC_MONETARY=Dutch_Belgium.1252 LC_NUMERIC=C LC_TIME=Dutch_Belgium.1252
attached base packages:
[1] stats graphics grDevices utils datasets tools methods base
other attached packages:
[1] DBI_0.7 odbc_1.1.3
loaded via a namespace (and not attached):
[1] bit_1.1-12 compiler_3.4.2 hms_0.3 tibble_1.3.4 Rcpp_0.12.13 bit64_0.9-7 blob_1.1.0 rlang_0.1.2
Thanks in advance for any help!
TL:DR calling odbc::dbConnect within another function causes this warning.
After a lot of digging in the odbc github, I have found the source of the warning. Calling dbConnect creates a db connection. Within this function is the following code:
# perform the connection notification at the top level, to ensure that it's had
# a chance to get its external pointer connected, and so we can capture the
# expression that created it
if (!is.null(getOption("connectionObserver"))) { # nocov start
addTaskCallback(function(expr, ...) {
tryCatch({
if (is.call(expr) && identical(expr[[1]], as.symbol("<-"))) {
# notify if this is an assignment we can replay
on_connection_opened(eval(expr[[2]]), paste(
c("library(odbc)", deparse(expr)), collapse = "\n"))
}
}, error = function(e) {
warning("Could not notify connection observer. ", e$message, call. = FALSE)
})
# always return false so the task callback is run at most once
FALSE
})
} # nocov end
This warning call should look familiar. This is what generates the warning. So why does it do that?
The snippet above is trying to do some checking on the connection object, to see if everything went well.
How it does that, is by adding a function checking this to the 'TaskCallBack'. This is a list of functions that get executed after a top-level task is completed. I am not 100% sure on this, but from what I can tell, this means that these functions are executed after the highest function in the call stack finishes.
Normally, this would be a line in your script. So for example:
library(odbc)
con <- odbc::dbConnect(odbc::odbc(), ...)
After the assignment in the second line is finished, the following function is executed:
function(expr, ...) {
tryCatch({
if (is.call(expr) && identical(expr[[1]], as.symbol("<-"))) {
# notify if this is an assignment we can replay
on_connection_opened(eval(expr[[2]]), paste(
c("library(odbc)", deparse(expr)), collapse = "\n"))
}
}, error = function(e) {
warning("Could not notify connection observer. ", e$message, call. = FALSE)
}
}
The top-level expression gets passed to the function and used to check if the connection works. Another odbc function called on_connection_opened then does some checks. If this throws an error anywhere, the warning is given, because of the tryCatch.
So why would the function on_connection_opened crash?
The function takes the following arguments:
on_connection_opened <- function(connection, code)
and one of the first things it does is:
display_name <- connection#info$dbname
Which seems to match the warning message:
trying to get slot "info" from an object of a basic class ("character") with no slots
From the name of the argument, it is clear that the function on_connection_opened expects a database connection object in its first argument. What does it get from its caller? eval(expr[[2]])
This is the lefthand side of the original call: con
In this case, this is a connection object and everything is nice.
Now we have enough information to answer your questions:
Why am I getting this warning message?
Your function creates a connection, which queues up the check connection function. If then checks for a list of tables and returns that. The check connection function then interprets the list of tables as if it is a connection, tries to check it, and fails miserably. This throws the warning.
More specifically why am I only getting it when calling dbListTables via a function?
dbListTables is not the culprit, dbConnect is. Because you are calling it from within a function, it doesn't get the connection object it is trying to check back and fails.
What am I doing wrong / should I do to avoid it?
A workaround would be to open a connection separately and pass that into your function. This way the connection gets opened in its own call, so the check works properly.
Alternatively, you can remove the TaskCallback again:
before <- getTaskCallbackNames()
con <- odbc::dbConnect(odbc::odbc(), ...)
after <- getTaskCallbackNames()
removeTaskCallback(which(!after %in% before))
Is the running is on_connection_opened essential? What does it do exactly?
As explained by the package's creator in this comment on Github, the function handles the displaying of the connection in the connections tab in RStudio. This is not that interesting to look at if you close the connection in the same function again. So this is not essential for your function.

exit() function creates 500 error (Google App Engine & Python 2.7)

I created a function which checks parameters and decide to run the rest of the code. I looks like:
def assert_something(a):
if a>3:
exit(0)
I try to use this something like:
class SomeHandler(webapp2.RequestHandler):
def get(self,parameter):
#check and if something wrong then quit
assert_something(parameter)
#otherwise do other things
the problem is exit() function always creates a response with 500 code.
How can modify this code so that I can exit from this request with 200 code for instance?
The problem is that since you are using a framework a lot of things happens under the hood, for example after one of your handlers returns the headers and other information is sent to the browser. But when you exit you interrupt the normal flow hence the internal Server Error.
What you could do is to have a decorator that asserts that the parameter is valid. Note that still you should provide the user with something useful in case the parameter is invalid.
The decorator could be something like this:
from functools import wraps
def assert_something(f):
#wraps(f)
def wrapper(*args, **kwds):
if args[1] > 3: #args[0] is self, args[1] is parameter. Better to use kwargs
return None
return f(*args, **kwds)
return wrapper
And then use it as:
#assert_something
def get(self, parameter):
...
You could use return instead:
def everything_ok(a):
return a <= 3
class SomeHandler(webapp2.RequestHandler):
def get(self,parameter):
if not everything_ok(parameter)
#if you want to return something
#self.response.out.write("")
return
#do something else
You can't exit(), that will raise an error as you have found.
You need to construct a valid response (it could be empty).
Have a read of http://webapp-improved.appspot.com/guide/response.html
And if you need to return some sort of HTTP error, you will still need to construct a valid response.

Resources