<commit_before># -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 <NAME>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.

"""Python client API for CouchDB.

>>> server = Server()
>>> db = server.create('python-tests')
>>> doc_id, doc_rev = db.save({'type': 'Person', 'name': '<NAME>'})
>>> doc = db[doc_id]
>>> doc['type']
u'Person'
>>> doc['name']
u'<NAME>'
>>> del db[doc.id]
>>> doc.id in db
False

>>> del server['python-tests']
"""

import itertools
import mimetypes
import os
from types import FunctionType
from inspect import getsource
from textwrap import dedent
import warnings
import sys
import socket

from couchdb import http, json, util

__all__ = ['Server', 'Database', 'Document', 'ViewResults', 'Row']
__docformat__ = 'restructuredtext en'


DEFAULT_BASE_URL = os.environ.get('COUCHDB_URL', 'http://localhost:5984/')


class Server(object):
    """Representation of a CouchDB server.

    >>> server = Server() # connects to the local_server
    >>> remote_server = Server('http://example.com:5984/')
    >>> secure_remote_server = Server('https://username:password@example.com:5984/')

    This class behaves like a dictionary of databases. For example, to get a
    list of database names on the server, you can simply iterate over the
    server object.

    New databases can be created using the `create` method:

    >>> db = server.create('python-tests')
    >>> db
    <Database 'python-tests'>

    You can access existing databases using item access, specifying the database
    name as the key:

    >>> db = server['python-tests']
    >>> db.name
    'python-tests'

    Databases can be deleted using a ``del`` statement:

    >>> del server['python-tests']
    """

    def __init__(self, url=DEFAULT_BASE_URL, full_commit=True, session=None):
        """Initialize the server object.

        :param url: the URI of the server (for example
                    ``http://localhost:5984/``)
        :param full_commit: turn on the X-Couch-Full-Commit header
        :param session: an http.Session instance or None for a default session
        """
        if isinstance(url, util.strbase):
            self.resource = http.Resource(url, session or http.Session())
        else:
            self.resource = url # treat as a Resource object
        if not full_commit:
            self.resource.headers['X-Couch-Full-Commit'] = 'false'

    def __contains__(self, name):
        """Return whether the server contains a database with the specified
        name.

        :param name: the database name
        :return: `True` if a database with the name exists, `False` otherwise
        """
        try:
            self.resource.head(name)
            return True
        except (socket.error, http.ResourceNotFound):
            return False

    def __iter__(self):
        """Iterate over the names of all databases."""
        status, headers, data = self.resource.get_json('_all_dbs')
        return iter(data)

    def __len__(self):
        """Return the number of databases."""
        status, headers, data = self.resource.get_json('_all_dbs')
        return len(data)

    def __nonzero__(self):
        """Return whether the server is available."""
        try:
            self.resource.head()
            return True
        except (socket.error, http.ResourceNotFound):
            return False

    def __bool__(self):
        return self.__nonzero__()

    def __repr__(self):
        return '<%s %r>' % (type(self).__name__, self.resource.url)

    def __delitem__(self, name):
        """Remove the database with the specified name.

        :param name: the name of the database
        :raise ResourceNotFound: if no database with that name exists
        """
        self.resource.delete_json(name)

    def __getitem__(self, name):
        """Return a `Database` object representing the database with the
        specified name.

        :param name: the name of the database
        :return: a `Database` object representing the database
        :rtype: `Database`
        :raise ResourceNotFound: if no database with that name exists
        """
        db = Database(self.resource(name), name)
        db.resource.head() # actually make a request to the database
        return db

    def config(self):
        """The configuration of the CouchDB server.

        The configuration is represented as a nested dictionary of sections and
        options from the configuration files of the server, or the default
        values for options that are not explicitly configured.

        :rtype: `dict`
        """
        status, headers, data = self.resource.get_json('_config')
        return data

    def version(self):
        """The version string of the CouchDB server.

        Note that this results in a request being made, and can also be used
        to check for the availability of the server.

        :rtype: `unicode`"""
        status, headers, data = self.resource.get_json()
        return data['version']

    def stats(self, name=None):
        """Server statistics.

        :param name: name of single statistic, e.g. httpd/requests
                     (None -- return all statistics)
        """
        if not name:
            resource = self.resource('_stats')
        else:
            resource = self.resource('_stats', *name.split('/'))<commit_msg>Enable querying the version of CouchDB server<commit_after># -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 <NAME>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.

"""Python client API for CouchDB.

>>> server = Server()
>>> db = server.create('python-tests')
>>> doc_id, doc_rev = db.save({'type': 'Person', 'name': '<NAME>'})
>>> doc = db[doc_id]
>>> doc['type']
u'Person'
>>> doc['name']
u'<NAME>'
>>> del db[doc.id]
>>> doc.id in db
False

>>> del server['python-tests']
"""

import itertools
import mimetypes
import os
from types import FunctionType
from inspect import getsource
from textwrap import dedent
import warnings
import sys
import socket

from couchdb import http, json, util

__all__ = ['Server', 'Database', 'Document', 'ViewResults', 'Row']
__docformat__ = 'restructuredtext en'


DEFAULT_BASE_URL = os.environ.get('COUCHDB_URL', 'http://localhost:5984/')


class Server(object):
    """Representation of a CouchDB server.

    >>> server = Server() # connects to the local_server
    >>> remote_server = Server('http://example.com:5984/')
    >>> secure_remote_server = Server('https://username:password@example.com:5984/')

    This class behaves like a dictionary of databases. For example, to get a
    list of database names on the server, you can simply iterate over the
    server object.

    New databases can be created using the `create` method:

    >>> db = server.create('python-tests')
    >>> db
    <Database 'python-tests'>

    You can access existing databases using item access, specifying the database
    name as the key:

    >>> db = server['python-tests']
    >>> db.name
    'python-tests'

    Databases can be deleted using a ``del`` statement:

    >>> del server['python-tests']
    """

    def __init__(self, url=DEFAULT_BASE_URL, full_commit=True, session=None):
        """Initialize the server object.

        :param url: the URI of the server (for example
                    ``http://localhost:5984/``)
        :param full_commit: turn on the X-Couch-Full-Commit header
        :param session: an http.Session instance or None for a default session
        """
        if isinstance(url, util.strbase):
            self.resource = http.Resource(url, session or http.Session())
        else:
            self.resource = url # treat as a Resource object
        if not full_commit:
            self.resource.headers['X-Couch-Full-Commit'] = 'false'
        self._version_info = None

    def __contains__(self, name):
        """Return whether the server contains a database with the specified
        name.

        :param name: the database name
        :return: `True` if a database with the name exists, `False` otherwise
        """
        try:
            self.resource.head(name)
            return True
        except (socket.error, http.ResourceNotFound):
            return False

    def __iter__(self):
        """Iterate over the names of all databases."""
        status, headers, data = self.resource.get_json('_all_dbs')
        return iter(data)

    def __len__(self):
        """Return the number of databases."""
        status, headers, data = self.resource.get_json('_all_dbs')
        return len(data)

    def __nonzero__(self):
        """Return whether the server is available."""
        try:
            self.resource.head()
            return True
        except (socket.error, http.ResourceNotFound):
            return False

    def __bool__(self):
        return self.__nonzero__()

    def __repr__(self):
        return '<%s %r>' % (type(self).__name__, self.resource.url)

    def __delitem__(self, name):
        """Remove the database with the specified name.

        :param name: the name of the database
        :raise ResourceNotFound: if no database with that name exists
        """
        self.resource.delete_json(name)

    def __getitem__(self, name):
        """Return a `Database` object representing the database with the
        specified name.

        :param name: the name of the database
        :return: a `Database` object representing the database
        :rtype: `Database`
        :raise ResourceNotFound: if no database with that name exists
        """
        db = Database(self.resource(name), name)
        db.resource.head() # actually make a request to the database
        return db

    def config(self):
        """The configuration of the CouchDB server.

        The configuration is represented as a nested dictionary of sections and
        options from the configuration files of the server, or the default
        values for options that are not explicitly configured.

        :rtype: `dict`
        """
        status, headers, data = self.resource.get_json('_config')
        return data

    def version(self):
        """The version string of the CouchDB server.

        Note that this results in a request being made, and can also be used
        to check for the availability of the server.

        :rtype: `unicode`"""
        status, headers, data = self.resource.get_json()
        return data['version']

    def version_info(self):
        """The version of the CouchDB server as a tuple of ints.

        Note that this results in a request being made only at the first call.
        Afterwards the result will be cached.

        :rtype: `tuple(int, int, int)`"""
        if self._version_info is None:
            version = self.version()
            self._version_info = tuple(map(int, version.split('.')))
        return self._version_info

    def stats(self, name=None):
        """Server statistics.

        :param name: name of single statistic, e.g. httpd/requests
                     (None -- return all statistics)
        """
        if not name:
            resource = self.resource('_stats')
        else:
            resource = self.resource('_stats', *name.split('/'))
{'fraction_non_alphanumeric': 0.10814137506593986, 'fraction_numerical': 0.004395990856339019, 'mean_word_length': 2.5849353923731484, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 115, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, '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': '6464769', 'n_tokens_mistral': 3122, 'n_tokens_neox': 3008, 'n_words': 1119}