There is no such code I'm aware of, however there are two possible answers:
The random number generator hates you. This is a known phenomenon dating all the way back to early dice games. simply put: the random number generator will seem to actively attempt to destroy you. Solution: Other than making a shrine to the RNG gods none.
Selective memory. You are simply remembering the worst times you got griefed, and not the times creepers spawned way out in the open so you could take them on easily.
The first two situations sound like you were in an enclosed, partially lit cave. this increases the spawn chance in other nearby areas. as such mobs using the "Death from above" routine is common, especially in abandoned mineshafts. the enderman case just sounds like bad luck (or see number 1)