# Buggy code
def __init__(self, port, session):
    self._logger = logging.getLogger(self.__class__.__name__)

    self.port = port
    self.session = session
    self.vod_fileindex = None
    self.vod_download = None
    self.vod_info = defaultdict(
        dict
    )  # A dictionary containing info about the requested VOD streams.

    HTTPServer.__init__(self, ("127.0.0.1", self.port), VideoRequestHandler)

    self.server_thread = None

    self.daemon_threads = True
    self.allow_reuse_address = True


# Traceback (RuntimeError)
Unhandled Error
Traceback (most recent call last):
File "/home/vader/.local/lib/python2.7/site-packages/twisted/internet/base.py", line 428, in fireEvent
DeferredList(beforeResults).addCallback(self._continueFiring)
File "/home/vader/.local/lib/python2.7/site-packages/twisted/internet/defer.py", line 321, in addCallback
callbackKeywords=kw)
File "/home/vader/.local/lib/python2.7/site-packages/twisted/internet/defer.py", line 310, in addCallbacks
self._runCallbacks()
File "/home/vader/.local/lib/python2.7/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks
current.result = callback(current.result, *args, **kw)
--- <exception caught here> ---
File "/home/vader/.local/lib/python2.7/site-packages/twisted/internet/base.py", line 441, in _continueFiring
callable(*args, **kwargs)
File "run_tribler.py", line 75, in start_tribler
session.start()
File "/home/vader/src/TRIBLER/tribler_ichorid/Tribler/Core/Session.py", line 486, in start
startup_deferred = self.lm.register(self, self.session_lock)
File "/home/vader/src/TRIBLER/tribler_ichorid/Tribler/Core/APIImplementation/LaunchManyCore.py", line 183, in register
self.video_server = VideoServer(self.session.config.get_video_server_port(), self.session)
File "/home/vader/src/TRIBLER/tribler_ichorid/Tribler/Core/Video/VideoServer.py", line 34, in __init__
HTTPServer.__init__(self, ("127.0.0.1", self.port), VideoRequestHandler)
File "/usr/lib/python2.7/SocketServer.py", line 417, in __init__
self.server_bind()
File "/usr/lib/python2.7/BaseHTTPServer.py", line 108, in server_bind
SocketServer.TCPServer.server_bind(self)
File "/usr/lib/python2.7/SocketServer.py", line 431, in server_bind
self.socket.bind(self.server_address)
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use

ERROR   1543234049.51            tribler_window:83   (root)  Traceback (most recent call last):
File "/home/vader/src/TRIBLER/tribler_ichorid/TriblerGUI/core_manager.py", line 114, in on_received_state
raise RuntimeError(state['last_exception'])
RuntimeError: Unhandled Error
Traceback (most recent call last):
File "/home/vader/.local/lib/python2.7/site-packages/twisted/internet/base.py", line 428, in fireEvent
DeferredList(beforeResults).addCallback(self._continueFiring)
File "/home/vader/.local/lib/python2.7/site-packages/twisted/internet/defer.py", line 321, in addCallback
callbackKeywords=kw)
File "/home/vader/.local/lib/python2.7/site-packages/twisted/internet/defer.py", line 310, in addCallbacks
self._runCallbacks()
File "/home/vader/.local/lib/python2.7/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks
current.result = callback(current.result, *args, **kw)
--- <exception caught here> ---
File "/home/vader/.local/lib/python2.7/site-packages/twisted/internet/base.py", line 441, in _continueFiring
callable(*args, **kwargs)
File "run_tribler.py", line 75, in start_tribler
session.start()
File "/home/vader/src/TRIBLER/tribler_ichorid/Tribler/Core/Session.py", line 486, in start
startup_deferred = self.lm.register(self, self.session_lock)
File "/home/vader/src/TRIBLER/tribler_ichorid/Tribler/Core/APIImplementation/LaunchManyCore.py", line 183, in register
self.video_server = VideoServer(self.session.config.get_video_server_port(), self.session)
File "/home/vader/src/TRIBLER/tribler_ichorid/Tribler/Core/Video/VideoServer.py", line 34, in __init__
HTTPServer.__init__(self, ("127.0.0.1", self.port), VideoRequestHandler)
File "/usr/lib/python2.7/SocketServer.py", line 417, in __init__
self.server_bind()
File "/usr/lib/python2.7/BaseHTTPServer.py", line 108, in server_bind
SocketServer.TCPServer.server_bind(self)
File "/usr/lib/python2.7/SocketServer.py", line 431, in server_bind
self.socket.bind(self.server_address)
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use

# Fixed code
def __init__(self, port, session):
    self._logger = logging.getLogger(self.__class__.__name__)

    self.port = port
    self.session = session
    self.vod_fileindex = None
    self.vod_download = None
    self.vod_info = defaultdict(
        dict
    )  # A dictionary containing info about the requested VOD streams.

    for _ in xrange(10000):
        try:
            HTTPServer.__init__(self, ("127.0.0.1", self.port), VideoRequestHandler)
            self._logger.debug("Listening at %d", self.port)
            break
        except socket.error:
            self._logger.debug("Listening failed at %d", self.port)
            self.port += 1
            continue

    self.server_thread = None

    self.daemon_threads = True
    self.allow_reuse_address = True