Foreign Threats, Technological Progress and the Rise and Decline of Imperial China