Stability theory and the existence of periodic solutions and almost periodic solutions