Optimal Control Of Deterministic And Stochastic Hybrid Systems: Theory And Applications