<commit_before># Copyright 2013-2016 DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import atexit
from collections import deque
from functools import partial
import logging
import os
import socket
import sys
from threading import Lock, Thread
import time
import weakref

from six.moves import range

try:
    from weakref import WeakSet
except ImportError:
    from cassandra.util import WeakSet  # noqa

import asyncore
from errno import EWOULDBLOCK

try:
    import ssl
except ImportError:
    ssl = None  # NOQA

from cassandra.connection import (Connection, ConnectionShutdown,
                                  ConnectionException, NONBLOCKING,
                                  Timer, TimerManager)

log = logging.getLogger(__name__)


def _cleanup(loop_weakref):
    try:
        loop = loop_weakref()
    except ReferenceError:
        return

    loop._cleanup()


class _PipeWrapper(object):

    def __init__(self, fd):
        self.fd = fd

    def fileno(self):
        return self.fd


class _AsyncoreDispatcher(asyncore.dispatcher):

    def __init__(self, socket):
        asyncore.dispatcher.__init__(self)
        # inject after to avoid base class validation
        self.set_socket(socket)
        self._notified = False

    def writable(self):
        return False

    def validate(self):
        assert not self._notified
        self.notify_loop()
        assert self._notified
        self.loop(0.1)
        assert not self._notified

    def loop(self, timeout):
        asyncore.loop(timeout=timeout, use_poll=True, count=1)


class _AsyncorePipeDispatcher(_AsyncoreDispatcher):

    def __init__(self):
        self.read_fd, self.write_fd = os.pipe()
        _AsyncoreDispatcher.__init__(self, _PipeWrapper(self.read_fd))

    def writable(self):
        return False

    def handle_read(self):
        while len(os.read(self.read_fd, 4096)) == 4096:
            pass
        self._notified = False

    def notify_loop(self):
        if not self._notified:
            self._notified = True
            os.write(self.write_fd, 'x')


class _AsyncoreUDPDispatcher(_AsyncoreDispatcher):
    """
    Experimental alternate dispatcher for avoiding busy wait in the asyncore loop. It is not used by default because
    it relies on local port binding.
    Port scanning is not implemented, so multiple clients on one host will collide. This address would need to be set per
    instance, or this could be specialized to scan until an address is found.
    """
    bind_address = ('localhost', 10000)

    def __init__(self):
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._socket.bind(self.bind_address)
        self._socket.setblocking(0)
        _AsyncoreDispatcher.__init__(self, self._socket)

    def handle_read(self):
        try:
            d = self._socket.recvfrom(1)
            while d and d[1]:
                d = self._socket.recvfrom(1)
        except socket.error as e:
            pass
        self._notified = False

    def notify_loop(self):
        if not self._notified:
            self._notified = True
            self._socket.sendto(b'', self.bind_address)

    def loop(self, timeout):
        asyncore.loop(timeout=timeout, use_poll=False, count=1)


class _BusyWaitDispatcher(object):

    max_write_latency = 0.001
    """
    Timeout pushed down to asyncore select/poll. Dictates the amount of time it will sleep before coming back to check
    if anything is writable.
    """

    def notify_loop(self):
        pass

    def loop(self, timeout):
        if not asyncore.socket_map:
            time.sleep(0.005)
        count = timeout // self.max_write_latency
        asyncore.loop(timeout=self.max_write_latency, use_poll=True, count=count)


class AsyncoreLoop(object):

    timer_resolution = 0.1  # used as the max interval to be in the io loop before returning to service timeouts

    _loop_dispatch_class = _AsyncorePipeDispatcher

    def __init__(self):
        self._pid = os.getpid()
        self._loop_lock = Lock()
        self._started = False
        self._shutdown = False

        self._thread = None

        self._timers = TimerManager()

        try:
            dispatcher = self._loop_dispatch_class()
            dispatcher.validate()
            log.debug("Validated loop dispatch with %s", self._loop_dispatch_class)
        except Exception:
            log.exception("Failed validating loop dispatch with %s. Using busy wait execution instead.", self._loop_dispatch_class)<commit_msg>validate for ayncore _BusyWaitDispatcher<commit_after># Copyright 2013-2016 DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import atexit
from collections import deque
from functools import partial
import logging
import os
import socket
import sys
from threading import Lock, Thread
import time
import weakref

from six.moves import range

try:
    from weakref import WeakSet
except ImportError:
    from cassandra.util import WeakSet  # noqa

import asyncore
from errno import EWOULDBLOCK

try:
    import ssl
except ImportError:
    ssl = None  # NOQA

from cassandra.connection import (Connection, ConnectionShutdown,
                                  ConnectionException, NONBLOCKING,
                                  Timer, TimerManager)

log = logging.getLogger(__name__)


def _cleanup(loop_weakref):
    try:
        loop = loop_weakref()
    except ReferenceError:
        return

    loop._cleanup()


class _PipeWrapper(object):

    def __init__(self, fd):
        self.fd = fd

    def fileno(self):
        return self.fd


class _AsyncoreDispatcher(asyncore.dispatcher):

    def __init__(self, socket):
        asyncore.dispatcher.__init__(self)
        # inject after to avoid base class validation
        self.set_socket(socket)
        self._notified = False

    def writable(self):
        return False

    def validate(self):
        assert not self._notified
        self.notify_loop()
        assert self._notified
        self.loop(0.1)
        assert not self._notified

    def loop(self, timeout):
        asyncore.loop(timeout=timeout, use_poll=True, count=1)


class _AsyncorePipeDispatcher(_AsyncoreDispatcher):

    def __init__(self):
        self.read_fd, self.write_fd = os.pipe()
        _AsyncoreDispatcher.__init__(self, _PipeWrapper(self.read_fd))

    def writable(self):
        return False

    def handle_read(self):
        while len(os.read(self.read_fd, 4096)) == 4096:
            pass
        self._notified = False

    def notify_loop(self):
        if not self._notified:
            self._notified = True
            os.write(self.write_fd, 'x')


class _AsyncoreUDPDispatcher(_AsyncoreDispatcher):
    """
    Experimental alternate dispatcher for avoiding busy wait in the asyncore loop. It is not used by default because
    it relies on local port binding.
    Port scanning is not implemented, so multiple clients on one host will collide. This address would need to be set per
    instance, or this could be specialized to scan until an address is found.
    """
    bind_address = ('localhost', 10000)

    def __init__(self):
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._socket.bind(self.bind_address)
        self._socket.setblocking(0)
        _AsyncoreDispatcher.__init__(self, self._socket)

    def handle_read(self):
        try:
            d = self._socket.recvfrom(1)
            while d and d[1]:
                d = self._socket.recvfrom(1)
        except socket.error as e:
            pass
        self._notified = False

    def notify_loop(self):
        if not self._notified:
            self._notified = True
            self._socket.sendto(b'', self.bind_address)

    def loop(self, timeout):
        asyncore.loop(timeout=timeout, use_poll=False, count=1)


class _BusyWaitDispatcher(object):

    max_write_latency = 0.001
    """
    Timeout pushed down to asyncore select/poll. Dictates the amount of time it will sleep before coming back to check
    if anything is writable.
    """

    def notify_loop(self):
        pass

    def loop(self, timeout):
        if not asyncore.socket_map:
            time.sleep(0.005)
        count = timeout // self.max_write_latency
        asyncore.loop(timeout=self.max_write_latency, use_poll=True, count=count)

    def validate(self):
        pass


class AsyncoreLoop(object):

    timer_resolution = 0.1  # used as the max interval to be in the io loop before returning to service timeouts

    _loop_dispatch_class = _AsyncorePipeDispatcher

    def __init__(self):
        self._pid = os.getpid()
        self._loop_lock = Lock()
        self._started = False
        self._shutdown = False

        self._thread = None

        self._timers = TimerManager()

        try:
            dispatcher = self._loop_dispatch_class()
            dispatcher.validate()
            log.debug("Validated loop dispatch with %s", self._loop_dispatch_class)
        except Exception:
            log.exception("Failed validating loop dispatch with %s. Using busy wait execution instead.", self._loop_dispatch_class)
{'fraction_non_alphanumeric': 0.07486895460389674, 'fraction_numerical': 0.008505587973494214, 'mean_word_length': 2.666424945612763, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2952015', 'n_tokens_mistral': 2932, 'n_tokens_neox': 2784, 'n_words': 901}