<commit_before>#!/usr/bin/env python

from __future__ import with_statement

import ctypes
import struct
import sys
import time

"""
Contains a bunch of functions that implement platform-specific ways to figure
out the system uptime, and one that uses all of them to figure out yours.
In principle, none of these functions create new processes or raise any
exceptions. They all return a float representing the number of seconds of
uptime, or None if they couldn't figure it out.
"""

def _uptime_linux():
    """Returns uptime in seconds or None, on Linux."""
    # With procfs
    try:
        with open('/proc/uptime', 'r') as f:
            return float(f.readline().split()[0])
    except (IOError, ValueError):
        pass

    # Without procfs (really?)
    try:
        libc = ctypes.CDLL('libc.so')
    except OSError:
        # Debian and derivatives do the wrong thing because /usr/lib/libc.so
        # is a GNU ld script rather than an ELF object. To get around this, we
        # have to be more specific.
        # We don't want to use ctypes.util.find_library because that creates a
        # new process on Linux. We also don't want to try too hard because at
        # this point we're already pretty sure this isn't Linux.
        try:
            libc = ctypes.CDLL('libc.so.6')
        except OSError:
            return None

    if not hasattr(libc, 'sysinfo'):
        # Not Linux
        return None

    buf = ctypes.create_string_buffer(128) # 64 suffices on 32-bit, whatever.
    if libc.sysinfo(buf) < 0:
        return None

    up = struct.unpack('@l', buf.raw[:struct.calcsize('@l')])[0]
    return up if up >= 0 else None

def _uptime_bsd():
    """Returns uptime in seconds or None, on BSD (including OS X)."""
    try:
        libc = ctypes.CDLL('libc.so')
    except OSError:
        # OS X; can't use ctypes.util.find_library because that creates
        # a new process on Linux, which is undesirable.
        try:
            libc = ctypes.CDLL('libc.dylib')
        except OSError:
            return None
    
    if not hasattr(libc, 'sysctlbyname'):
        # Not BSD
        return None

    # Determine how much space we need for the response
    sz = ctypes.c_uint(0)
    libc.sysctlbyname('kern.boottime', None, ctypes.byref(sz), None, 0)
    if sz.value != struct.calcsize('@LL'):
        # Unexpected, let's give up.
        return None

    # For real now
    buf = ctypes.create_string_buffer(sz.value)
    libc.sysctlbyname('kern.boottime', buf, ctypes.byref(sz), None, 0)
    sec, usec = struct.unpack('@LL', buf.raw)

    boottime = sec + usec / 1000000.
    up = time.time() - boottime
    return up if up > 0 else None

_uptime_osx = _uptime_bsd

def _uptime_plan9():
    """Returns uptime in seconds or None, on Plan 9."""
    # Apparently Plan 9 only has Python 2.2, which I'm not prepared to
    # support. Maybe some Linuxes implement /dev/time, though, someone was
    # taling about it somewhere.
    try:
        with open('/dev/time', 'r') as f:
            # The time file holds one 32-bit number representing the sec-
            # onds since start of epoch and three 64-bit numbers, repre-
            # senting nanoseconds since start of epoch, clock ticks, and
            # clock frequency.
            #  -- cons(3)<commit_msg>Now actually works on OS X.<commit_after>#!/usr/bin/env python

from __future__ import with_statement

import ctypes
import struct
import sys
import time

"""
Contains a bunch of functions that implement platform-specific ways to figure
out the system uptime, and one that uses all of them to figure out yours.
In principle, none of these functions create new processes or raise any
exceptions. They all return a float representing the number of seconds of
uptime, or None if they couldn't figure it out.
"""

def _uptime_linux():
    """Returns uptime in seconds or None, on Linux."""
    # With procfs
    try:
        with open('/proc/uptime', 'r') as f:
            return float(f.readline().split()[0])
    except (IOError, ValueError):
        pass

    # Without procfs (really?)
    try:
        libc = ctypes.CDLL('libc.so')
    except OSError:
        # Debian and derivatives do the wrong thing because /usr/lib/libc.so
        # is a GNU ld script rather than an ELF object. To get around this, we
        # have to be more specific.
        # We don't want to use ctypes.util.find_library because that creates a
        # new process on Linux. We also don't want to try too hard because at
        # this point we're already pretty sure this isn't Linux.
        try:
            libc = ctypes.CDLL('libc.so.6')
        except OSError:
            return None

    if not hasattr(libc, 'sysinfo'):
        # Not Linux
        return None

    buf = ctypes.create_string_buffer(128) # 64 suffices on 32-bit, whatever.
    if libc.sysinfo(buf) < 0:
        return None

    up = struct.unpack('@l', buf.raw[:struct.calcsize('@l')])[0]
    return up if up >= 0 else None

def _uptime_bsd():
    """Returns uptime in seconds or None, on BSD (including OS X)."""
    try:
        libc = ctypes.CDLL('libc.so')
    except OSError:
        # OS X; can't use ctypes.util.find_library because that creates
        # a new process on Linux, which is undesirable.
        try:
            libc = ctypes.CDLL('libc.dylib')
        except OSError:
            return None
    
    if not hasattr(libc, 'sysctlbyname'):
        # Not BSD
        return None

    # Determine how much space we need for the response
    sz = ctypes.c_uint(0)
    libc.sysctlbyname('kern.boottime', None, ctypes.byref(sz), None, 0)
    if sz.value != struct.calcsize('@LL'):
        # Unexpected, let's give up.
        return None

    # For real now
    buf = ctypes.create_string_buffer(sz.value)
    libc.sysctlbyname('kern.boottime', buf, ctypes.byref(sz), None, 0)
    sec, usec = struct.unpack('@LL', buf.raw)

    # OS X disagrees what that second value is
    if usec > 1000000:
        usec = 0.

    boottime = sec + usec / 1000000.
    up = time.time() - boottime
    return up if up > 0 else None

_uptime_osx = _uptime_bsd

def _uptime_plan9():
    """Returns uptime in seconds or None, on Plan 9."""
    # Apparently Plan 9 only has Python 2.2, which I'm not prepared to
    # support. Maybe some Linuxes implement /dev/time, though, someone was
    # taling about it somewhere.
    try:
        with open('/dev/time', 'r') as f:
            # The time file holds one 32-bit number representing the sec-
            # onds since start of epoch and three 64-bit numbers, repre-
            # senting nanoseconds since start of epoch, clock ticks, and
            # clock frequency.
            #  -- cons(3)
{'fraction_non_alphanumeric': 0.09464099119271534, 'fraction_numerical': 0.011046424839528288, 'mean_word_length': 2.409669211195929, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3044364', 'n_tokens_mistral': 2128, 'n_tokens_neox': 1975, 'n_words': 781}