In the case of the pencil in glass, the light from the pencil strikes the surface of the water at an angle. This causes the light to bend and change direction. The light then travels through the water and strikes the surface of the glass at an angle. This causes the light to bend again and change direction. The net effect is that the pencil appears to be bent at the point where it enters the water and again at the point where it enters the glass.