class TransactionSettings(namedtuple('TransactionSettings', (
        'distributed_transaction_timeout', 'durability',
        'transaction_latency_count', 'transaction_latency_timeout'))):
    """
    A named tuple encapsulating a set of distributed transaction parameters.

    Each parameter here can be set to ``None``, in which case the actual value
    of that setting will be determined by the server.

    When creating a new instance not all arguments have to be specified,
    the default value for all settings is ``None``.

    Attributes:
        durability: (int|str):
            The durability is a positive integer value that specifies how many
            instances must have a commit ingested in order for that commit to be
            considered durable. The count includes the instance that made
            the commit.

            A durability setting of 1 means that when an instance makes a commit that
            commit is immediately considered durable before even being sent to any other
            instance (the commit will still be sent to the other instances after it's
            considered durable).

            A value that equals the total number of nodes in the cluster means that every
            instance must have ingested the commit before it's considered durable.
            If one or more instances are stopped at the moment then the commit will not
            become durable until the stopped instances are restarted.

            Three symbolic values (strings) may be used instead of numbers:
                - 'min', which simply means 1.
                - 'max', which means that all instances in the cluster must
                  ingest a commit before it is considered durable.
                - 'quorum', which means that more than a half of instances
                  must ingest a commit for it to be considered durable.

        distributed_transaction_timeout (int|datetime.timedelta):
            Use this setting to specify how long a commit call will wait for
            the commit to become durable. It's a non-negative integer
            (number of seconds).

            If the durability is greater than one then the committing process
            has to wait for acknowledgements from the other servers that the
            transaction was committed. The committing process returns to the
            caller when the durability has been reached or the distributed
            transaction timeout seconds has passed, whichever comes first.

            When the commit returns the caller does not know if durability has
            been reached.

        transaction_latency_count (int):
            Number of commits. Use this setting to limit the number of non-durable
            (pending) commits that can be active on the cluster. If this limit is
            reached all new commits will signal an error (and have to be retried).

            When a commit is done the committing process tries to wait until the
            commit is durable but if that takes too long (see
            distributed_transaction_timeout) then commit will return with the
            system still working on making that transaction durable.

            If the latency count is 4 then even if the last four commits are not yet
            durable it is possible to do one more commit. But if there are five
            pending transactions then any attempt to commit will result in an error.

            Another example: If you set the latency count to zero then each commit must
            be durable before the next commit can be ingested.

        transaction_latency_timeout (int|datetime.timedelta):
            Use this setting to specify how long a commit operation should wait for the
            transaction_Latency_count to be satisfied before throwing an error.

    """
    __slots__ = ()

    def __new__(cls, *args, **kwargs):
        """
        A constructor that provides default values.

        by default a named tuple requires all fields to be provided, this
        constructor will treat all missing values as ``None``.
        """
        params = dict(zip_longest(TransactionSettings._fields, args))
        params.update(kwargs)
        return super(TransactionSettings, cls).__new__(cls, **params) DEFAULT_TRANSACTION_SETTINGS = TransactionSettings() class IllegalOptionException(Exception):
    pass class IllegalArgumentException (Exception):
    pass class Statement(object):
    """
    Wraps a triple or a quad. Might also contain an id.
    """
    __slots__ = ('subject', 'predicate', 'object', 'context', 'id', '_hash')

    def __init__(self, subject, predicate, object, context=None, id=None):
        """
        Create a statement.

        Each component can be either a Value object or a string in N-Triples format.
        Strings will be parsed lazily the first time a component is accessed.
        Accessors will always return Value objects.

        :param subject: Subject component - URI, blank node or a string
                        in N-Triples format.
        :type subject: URI|BNode|str
        :param predicate: Predicate component. Either a URI or a string
                          in N-Triples format.
        :type predicate: URI|str
        :param object: Subject component. Either a Value or a string
                       in N-Triples format.
        :type object: Value|str
        :param context: Graph component (optional). Can be a URI or
                        a string in N-Triples format.
        :type context: URI|str
        :param id: Statement id (optional).
        :type id: int|str
        """
        self.subject = subject
        self.predicate = predicate
        self.object = object
        self.context = context
        self.id = id
        self._hash = None

    def __eq__(self, other):
        if not isinstance(other, Statement):
            return NotImplemented

        # The object is potentially the cheapest to check, as types
        # of these references might be different.
        # In general the number of different predicates in sets of
        # statements is the smallest, so predicate equality is checked
        # last.
        if self.getObject() == other.getObject() and self.getSubject() == other.getSubject() \
                and self.getPredicate() == other.getPredicate():
            if self.context:
                return self.getContext() == other.getContext()
            else:
                return not other.getContext()
        else:
            return False

    def __hash__(self):
        if self._hash is None:
            self._hash = hash((self.getSubject(), self.getPredicate(), self.getObject(), self.getContext()))
        return self._hash

    def __str__(self):
        elements = [self.getSubject(), self.getPredicate(), self.getObject(), self.getContext(), self.getTripleID()]
        while len(elements) > 3 and elements[-1] is None:
            elements.pop()
        return '(' + ', '.join(map(str, elements)) + ')'

    def __len__(self):
        return 3 if self.context is None else 4

    def __getitem__(self, index):
        if index == 0: return self.getSubject()
        elif index == 1: return self.getPredicate()
        elif index == 2: return self.getObject()
        elif index == 3: return self.getContext()
        else:
            raise IndexError('Illegal index (%d), must be < 4' % index)

    def getSubject(self):
        """
        Get the subject (the first element of the statement).

        :return: Subject.
        :rtype: Value
        """
        # Lazily parse and replace the value if needed.
        if isinstance(self.subject, basestring):
            self.subject = parse_term(self.subject)
        return self.subject
    
    def setSubject(self, subject):
        self.subject = subject
    
    def getPredicate(self):
        """
        Get the predicate (the second element of the statement).

        :return: Predicate.
        :rtype: URI
        """
        # Lazily parse and replace the value if needed.
        if isinstance(self.predicate, basestring):
            self.predicate = parse_term(self.predicate)
        return self.predicate
     
    def setPredicate(self, predicate):
        self.predicate = predicate
    
    def getObject(self):
        """
        Get the object (the third element of the statement).

        :return: Object.
        :rtype: Value
        """
        # Lazily parse and replace the value if needed.
        if isinstance(self.object, basestring):
            self.object = parse_term(self.object)
        return self.object
    
    def setObject(self, object):
        self.object = object
    
    def getContext(self):
        """
        Get the graph (the fourth, optional element of the statement).

        :return: Graph URI.
        :rtype: URI
        """
        # Lazily parse and replace the value if needed.
        if isinstance(self.context, basestring):
            self.context = parse_term(self.context)
        return self.context
    
    def setContext(self, context):
        self.context = context

    def getTripleID(self):
        """
        Get the statement id.

        Note that this field might not present, depending on the way in which
        the statement has been created.

        :return: A numerical id.
        :rtype: int
        """
        # Lazily parse and replace the value if needed.
        if isinstance(self.id, basestring):
            self.id = int(self.id)
        return self.id class Value(object):
    """
    Top class in the org.openrdf.model interfaces.
    """
    __slots__ = ('__weakref__',)

    def __str__(self):
        return self.toNTriples()

    def __repr__(self):
        result = self.toNTriples()
        # Return an ascii string on Python 2, otherwise pytest gets confused
        if sys.version_info < (3,):
            result = result.encode('unicode-escape')
        return result

    def get_cmp_key(self):
        """
        Return a key that will be used to compare and hash this object.
        """
        raise NotImplementedError()

    # Comparison methods rely on get_cmp_key.
    def __eq__(self, other):
        return self is other or (isinstance(other, Value)
                                 and self.get_cmp_key() == other.get_cmp_key())

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(self.get_cmp_key())

    def __lt__(self, other):
        return self.get_cmp_key() < other.get_cmp_key()

    def __gt__(self, other):
        return self.get_cmp_key() > other.get_cmp_key()

    def __le__(self, other):
        return not self > other

    def __ge__(self, other):
        return not self < other

    def toNTriples(self):
        """
        Return an NTriples representation of an open rdf term
        """
        raise NotImplementedError("Failed to implement 'toNTriples' on instance of type %s" % type(self).__name__) class URI(Resource):
    """
    Lightweight implementation of the class 'URI'.
    """
    __slots__ = ('_uri', '_is_canonical')

    _instances = weakref.WeakValueDictionary()

    def __new__(cls, uri=None, namespace=None, localname=None, canonical=True):
        if isinstance(uri, URI):
            if not canonical or uri._is_canonical:
                return uri
            uri = uri.uri
        elif uri is None and namespace is not None:
            uri = namespace + (localname or '')

        if uri is None:
            raise ValueError('Either URI or namespace is required.')

        if canonical:
            result = URI._instances.get(uri)
            if result is not None:
                return result

        result = super(URI, cls).__new__(cls)
        if canonical:
            URI._instances[uri] = result
        return result

    def __init__(self, uri=None, namespace=None, localname=None, canonical=False):
        if isinstance(uri, URI):
            uri = uri.uri

        if uri is None and namespace is not None:
            uri = namespace + (localname or '')

        if uri and uri[0] == '<' and uri[len(uri) - 1] == '>':
            # be kind and trim the uri:
            uri = uri[1:-1]
        self._uri = uri
        self._is_canonical = canonical

    def get_cmp_key(self):
        return URI_CMP_KEY, self.uri
    
    def getURI(self):
        """
        Return the URI (string) for 'self'.  This method is typically
        overloaded by subclasses, which may use lazy evaluation to
        retrieve the string.
        """
        return self._uri

    uri = property(getURI)
    
    def getValue(self):
        return self.getURI()

    value = property(getValue)
    
    def getLocalName(self):
        pos = uris.getLocalNameIndex(self.getURI())
        return self.uri[pos:]
    
    localname = property(getLocalName)

    def getNamespace(self):
        pos = uris.getLocalNameIndex(self.getURI())
        return self.uri[:pos]

    def split(self):
        """
        Split into a namespace + local name pair.
        """
        pos = uris.getLocalNameIndex(self.uri)
        return self.uri[:pos], self.uri[pos:]

    namespace = property(getNamespace)

    def toNTriples(self):
        """
        Return an NTriples representation of a resource, in this case, wrap
        it in angle brackets.
        """
        return strings.encode_ntriple_uri(self.uri)

    def to_json_ld_key(self):
        """ Converts to a string to be used as a JSON-LD key. """
        return self.uri

    def to_json_ld(self):
        """ Converts to an object to be used as a JSON-LD value. """
        return {"@id": self.uri} class RangeLiteral(CompoundLiteral):
    """
    A range represents an interval between to scalar values.
    """
    def __init__(self, lowerBound=None, upperBound=None):
        self.lowerBound = lowerBound # should be a LiteralImpl
        self.upperBound = upperBound # should be a LiteralImpl
    
    def getLowerBound(self):
        return self.lowerBound
    
    def getUpperBound(self):
        return self.upperBound class GeoCoordinate(CompoundLiteral):
    """
    Define either a cartesian coordinate or a spherical coordinate.  For the
    latter, nit can be 'km', 'mile', 'radian', or 'degree'
    """
    def __init__(self, x, y, unit=None, geoType=None):
        self.xcoor = x
        self.ycoor = y
        self.unit = unit
        self.geoType = geoType
    
    def __str__(self):
        return "|COOR|(%i, %i)" % (self.xcoor, self.ycoor) class GeoSpatialRegion(CompoundLiteral):
    pass class GeoBox(GeoSpatialRegion):
    def __init__(self, xMin, xMax, yMin, yMax, unit=None, geoType=None):
        self.xMin = xMin
        self.xMax = xMax
        self.yMin = yMin
        self.yMax = yMax
        self.unit = unit
        self.geoType = geoType
    
    def __str__(self): return "|Box|%s,%s %s,%s" % (self.xMin, self.xMax, self.yMin, self.yMax) class GeoCircle(GeoSpatialRegion):
    def __init__(self, x, y, radius, unit=None, geoType=None):
        self.x = x
        self.y = y
        self.radius = radius
        self.unit = unit
        self.geoType=geoType
        
    def __str__(self): return "|Circle|%i,%i, radius=%i" % (self.x, self.y, self.radius) class GeoPolygon(GeoSpatialRegion):
    def __init__(self, vertices, uri=None, geoType=None):
        self.vertices = vertices
        self.geoType = geoType
        self.uri = uri
        self.resource = None
        self.miniPolygon = None
        
    def getVertices(self): return self.vertices
    
    def getResource(self): return self.resource
    
    def __str__(self): return "|Polygon|%s" % self.vertices class Literal(Value):
    """
    Implementation of the Literal class.
    """
    
    def __init__(self, label, datatype=None, language=None):
        Value.__init__(self)
        
        # Uses the properties to set the real values
        self.label, self.datatype = datatype_from_python(label, datatype)
        self.language = language

    def getDatatype(self):
        """The URI representing the datatype for this literal, if there is one""" 
        return self._datatype
    
    def setDatatype(self, datatype):
        """Sets the datatype of the value"""
        if isinstance(datatype, bytes):
            datatype = unicode(datatype, "utf-8")
        if isinstance(datatype, unicode):
            if datatype[0] == '<':
                datatype = datatype[1:-1]
            datatype = URI(datatype)
        elif datatype is not None:
            if not isinstance(datatype, URI):
                datatype = URI(datatype)
            elif datatype.uri is None:
                datatype = None

        self._datatype = datatype # pylint: disable-msg=W0201

    datatype = property(getDatatype, setDatatype)

    def getLanguage(self):
        """The language for this Literal"""
        return self._language
    
    def setLanguage(self, language):
        """Set the language for this Literal"""
        self._language = language.lower() if language else None # pylint: disable-msg=W0201

    language = property(getLanguage, setLanguage)

    def getLabel(self):
        """The label/value for this Literal"""
        return self._label
    
    def setLabel(self, label):
        """Set the label for this Literal"""
        self._label = label # pylint: disable-msg=W0201
    
    def getValue(self):
        """The label/value"""
        return self.label

    label = property(getLabel, setLabel)

    def get_cmp_key(self):
        return LITERAL_CMP_KEY, self.label, self.datatype, self.language
    
    def intValue(self):
        """Convert to int"""
        return int(self._label)
    
    def longValue(self):
        """Convert to long"""
        return long(self._label)
    
    def floatValue(self):
        """Convert to float"""
        return float(self._label)
    
    def booleanValue(self):
        """Convert to bool"""
        return self._label == 'true'
    
    def decimalValue(self):
        """Convert to a decimal"""
        return Decimal(self._label)
    
    def dateValue(self):
        """Convert to date"""
        # iso8601 can parse a date, but it will still be
        # returned as a datetime.datetime object. So we have
        # to extract the date (as a datetime.date object) from it.
        return iso8601.parse_date(self._label).date()

    def datetimeValue(self):
        """Convert to datetime"""
        return iso8601.parse_date(self._label, default_timezone=None)

    def timeValue(self):
        """Convert to time"""
        # iso8601 can't parse a time
        # We trick it by prepending a random date,
        # parsing the result as a datetime and extracting
        # the time from that.
        label = RANDOM_DAY_STRING + 'T' + self._label
        # Return a naive time if there is no timezone.
        # The default is UTC.
        dt = iso8601.parse_date(label, default_timezone=None)
        # Note that time() strips the time zone
        return dt.time().replace(tzinfo=dt.tzinfo)

    ## Returns the {@link XMLGregorianCalendar} value of this literal. A calendar
    ## representation can be given for literals whose label conforms to the
    ## syntax of the following <a href="http://www.w3.org/TR/xmlschema-2/">XML
    ## Schema datatypes</a>: <tt>dateTime</tt>, <tt>time</tt>,
    ## <tt>date</tt>, <tt>gYearMonth</tt>, <tt>gMonthDay</tt>,
    ## <tt>gYear</tt>, <tt>gMonth</tt> or <tt>gDay</tt>.
    def calendarValue(self):
        """calendarValue not useful for Python."""
        raise NotImplementedError("calendarValue")

    def toNTriples(self):
        """
        Return an NTriples representation for this Literal.
        """
        sb = []
        sb.append('"')
        sb.append(strings.encode_ntriple_string(self.getLabel()))
        sb.append('"')
        if self.language:
            sb.append('@')
            sb.append(self.language)
        if self.datatype:
            sb.append("^^")
            sb.append(self.datatype.toNTriples())
        return ''.join(sb)

    def to_json_ld(self):
        """ Converts to an object to be used as a JSON-LD value. """
        if self.language:
            return OrderedDict([
                ('@value', self.label),
                ('@language', self.language)
            ])

        if self.datatype is None or self.datatype == XMLSchema.STRING:
            return self.label

        if self.datatype == XMLSchema.INTEGER:
            return int(self.label)

        return OrderedDict([
            ('@value', self.label),
            ('@type', self.datatype.to_json_ld_key())
        ])

###############################################################################
## Automatic conversion from Literal to Python object
###############################################################################
    def toPython(self):
        """
        Return a Python object representation of this literal.   
        Slightly silly implementation because we implement a conversion table
        and then don't use the conversion functions.     
        """
        return XSDToPython[getattr(self.datatype, "uri", None)](self) ALL_CONTEXTS = 'ALL_CONTEXTS' MINI_NULL_CONTEXT = 'null' class Query(object):
    """
    A query on a repository that can be formulated in one of the
    supported query languages (for example SeRQL or SPARQL). It allows one to
    predefine bindings in the query to be able to reuse the same query with
    different bindings.
    """
    def __init__(self, queryLanguage=QueryLanguage.SPARQL,
                 query=None, baseURI=None, queryString=None):
        """
        Initialize a query object.

        :param queryLanguage: Query syntax - the default is SPARQL.
        :type queryLanguage: QueryLanguage
        :param query: Query text
        :type query: string
        :param baseURI: Prefix used to relsove relative URIs.
                        Default: chosen by the server.
        :type baseURI: URI
        :param queryString: Legacy name of the 'query' parameter.
        :type queryString: string
        """
        if query is None:
            raise TypeError('query argument is missing.')
        self.queryLanguage = Query._check_language(queryLanguage)
        self.queryString = query or queryString
        self.baseURI = baseURI
        self.dataset = None
        self.includeInferred = False
        self.bindings = {}
        self.connection = None
        self.checkVariables = False
        ## CommonLogic parameters:
        self.preferred_execution_language = None
        self.actual_execution_language = None
        self.subject_comes_first = False

    def setBinding(self, name, value):
        """
        Binds the specified variable to the supplied value. Any value that was
        previously bound to the specified value will be overwritten.

        :param name: Variable name.
        :type name: string
        :param value: New value for the variable. If a string is passed it will
                      be converted to a literal.
        :type value: Value|basestring
        """
        if isinstance(value, basestring):
            value = self._get_connection().createLiteral(value)
        self.bindings[name] = value
        
    def setBindings(self, dict):
        """
        Set multiple variable bindings.

        :param dict: A dictionary of bindings.
        :type dict: dict[string, Value]
        """
        if not dict: return
        for key, value in iteritems(dict):
            self.setBinding(key, value)

    def removeBinding(self, name):
        """ 
        Removes a previously set binding on the supplied variable. Calling this
        method with an unbound variable name has no effect.

        :param name: Variable name.
        :type name: string
        """
        self.bindings.pop(name)

    def getBindings(self):
        """
        Retrieve the bindings that have been set on this query.

        :return: A dictionary of bindings.
        :rtype: dict[string, Value]
        """ 
        return self.bindings

    def setDataset(self, dataset):
        """
        Select the dataset against which to evaluate this query, overriding any
        dataset that is specified in the query itself.

        :param dataset: A dataset object.
        :type dataset: Dataset
        """ 
        self.dataset = dataset
     
    def getDataset(self):
        """
        Get the dataset against which this query will operate.

        :return: Dataset.
        :rtype: Dataset
        """ 
        return self.dataset
    
    def setContexts(self, contexts):
        """
        Assert a set of contexts (named graphs) that filter all triples.

        :param contexts: List of graph URIs.
        :type contexts: list[URI|string]
        """
        if not contexts: return
        ds = Dataset()
        for cxt in contexts:
            if isinstance(cxt, basestring): cxt = self._get_connection().createURI(cxt)
            ds.addNamedGraph(cxt)
        self.setDataset(ds)
     
    def setIncludeInferred(self, includeInferred):
        """
        Determine whether evaluation results of this query should include inferred
        statements.

        The default setting is ``True``.

        :param includeInferred: If ``True`` include inferred triples in query results.
        :type includeInferred: bool
        """
        self.includeInferred = includeInferred

    def getIncludeInferred(self):
        """
        Check whether this query will return inferred statements.
        :return: ``True`` if inferred triples are included, ``False`` otherwise.
        :rtype: bool
        """ 
        return self.includeInferred
    
    def setCheckVariables(self, setting):
        """
        Determine whether the presence of variables in the select clause not referenced
        in a triple is flagged.

        :param setting: ``True`` if variables should be checked, ``False`` otherwise.
        :type setting: bool
        """
        self.checkVariables = setting
    
    def setConnection(self, connection):
        """
        Internal call to embed the connection into the query.
        """
        self.connection = connection
        
    def _get_connection(self):
        return self.connection
    
    def evaluate_generic_query(self, count=False, accept=None, callback=None,
                               analyze=False, analysisTechnique=None, analysisTimeout=None,
                               update=False):
        """
        Evaluate a SPARQL or PROLOG query, which may be a 'select', 'construct', 'describe'
        or 'ask' query (in the SPARQL case). Return an appropriate response.

        :param count: If ``True`` return only the count of the query results.
        :type count: bool
        :param accept: Set to ``'application/sparql-results+xml'`` or ``'application/sparql-results+json'``
                       to retrieve the result as a string in the specified format.
                       The default is to return a :class:`QueryResult` object.
        :type accept: string
        :param analyze: If ``True`` perform query analysis for SPARQL queries.
        :type analyze: bool
        :param analysisTechnique: Control the method of analysis. Can be either `"executed"` (default).
                                  meaning that the query will be executed to perform dynamic analysis,
                                  or ``"static"``.
        :type analysisTechnique: string
        :param analysisTimeout: Number of second to run the query if executed for analysis.
        :type analysisTimeout: float
        :param update: If ``True`` this is an update query and the result will be a boolean.
        :type update: bool
        :return: The result can be either:
                    - A boolean (for update queries).
                    - A dictionary containing the results.
                    - A string (if ``accept`` was passed).
                    - An integer (if ``count=True``).
        :rtype: dict|string|int|bool
        """
        conn = self._get_connection()
        namedContexts = conn._contexts_to_ntriple_contexts(
                        self.dataset.getNamedGraphs() if self.dataset else None)
        regularContexts = conn._contexts_to_ntriple_contexts(
                self.dataset.getDefaultGraphs() if self.dataset else ALL_CONTEXTS)
        bindings = None
        if self.bindings:
            bindings = {}
            for vbl, val in list(self.bindings.items()):
                bindings[vbl] = conn._convert_term_to_mini_term(val)
        mini = conn._get_mini_repository()
        if self.queryLanguage == QueryLanguage.SPARQL:  
            response = mini.evalSparqlQuery(self.queryString, context=regularContexts, namedContext=namedContexts, 
                                            infer=self.includeInferred, bindings=bindings,
                                            checkVariables=self.checkVariables, count=count,
                                            accept=accept, callback=callback,
                                            analyze=analyze, analysisTechnique=analysisTechnique,
                                            analysisTimeout=analysisTimeout, update=update)
        elif self.queryLanguage == QueryLanguage.PROLOG:
            if namedContexts:
                raise QueryMissingFeatureException("Prolog queries do not support the datasets (named graphs) option.")
            if analyze:
                raise QueryMissingFeatureException("Prolog queries do not support analysis.")
            # evalPrologQuery is already always done as if update=True
            response = mini.evalPrologQuery(self.queryString,
                                            infer=self.includeInferred, count=count, accept=accept,
                                            callback=callback)
        else:
            raise ValueError('Unsupported query language: %s' % self.queryLanguage)
        return response

    @staticmethod
    def _check_language(queryLanguage):
        if queryLanguage == 'SPARQL':
            return QueryLanguage.SPARQL

        if queryLanguage == 'PROLOG':
            return QueryLanguage.PROLOG

        if not queryLanguage in [QueryLanguage.SPARQL, QueryLanguage.PROLOG]:
            raise IllegalOptionException("Can't evaluate the query language '%s'.  Options are: SPARQL and PROLOG."
                                         % queryLanguage)
        return queryLanguage class TupleQuery(Query):
    """
    A query that returns tuples (i.e. sets of variable bindings).
    """
    def evaluate(self, count=False, output=None,
                 output_format=TupleFormat.TABLE):
        """Execute the embedded query against the RDF store.

        Return an iterator that produces for each step a tuple of values
        (resources and literals) corresponding to the variables or
        expressions in a 'select' clause (or its equivalent).

        :param count: If ``True`` return the number of result rows
                      instead of the usual iterator.
        :type count: bool
        :param output: A file name, file descriptor or a file-like
                       object to save the results to
                       (optional). ``True`` can be used as a synonym
                       for stdout.
        :type output: str|file|int|bool
        :param output_format: Serialization format for ``output``.
                              The default is TABLE.
        :type output_format: RDFFormat
        :return: Either an iterator over results, 
                 an integer (the number of results, if ``count`` is used) 
                 or ``None`` (if ``output`` is used).
        :rtype: TupleQueryResult|int
        """

        with output_to(output) as out:
            callback = None if output is None else out.write
            accept = None if output is None else TupleFormat.mime_type_for_format(output_format)
            response = self.evaluate_generic_query(
                count=count, accept=accept, callback=callback)

            if count:
                return response

            if output is not None:
                return None

            return TupleQueryResult(response['names'], response['values'], response.get('queryInfo'))

    def analyze(self, analysisTechnique=None, analysisTimeout=None):
        """
        Analyze the query.

        Analysis is only available for SPARQL queries.

        :param analysisTechnique: Control the method of analysis. Can be either `"executed"` (default).
                                  meaning that the query will be executed to perform dynamic analysis,
                                  or ``"static"``.
        :type analysisTechnique: string
        :param analysisTimeout: Number of second to run the query if executed for analysis.
        :type analysisTimeout: float
        :return: Analysis result as a dictionary.
        :rtype: dict
        """
        response = self.evaluate_generic_query(analyze=True, analysisTechnique=analysisTechnique,
            analysisTimeout=analysisTimeout)
        return response class UpdateQuery(Query):
    """
    An update query.
    """
    def evaluate(self):
        """
        Execute the embedded update against the RDF store.

        :return: ``True`` if the query changed the store, ``False`` otherwise.
        :rtype: bool
        """
        return self.evaluate_generic_query(update=True) class GraphQuery(Query):
    """
    A query that returns statements (see :class:`Statement`).
    """
    def evaluate(self, output=None, output_format=RDFFormat.TABLE):
        """
        Execute the embedded query against the RDF store.

        :param output: A file name, file descriptor or a file-like
                       object to save the results to
                       (optional). ``True`` can be used as a synonym
                       for stdout.
        :type output: str|file|int|bool
        :param output_format: Serialization format for ``output``.
                              The default is TABLE.
        :type output_format: RDFFormat
        :return: An iterator over statements or None (if ``output`` is used)..
        :rtype: GraphQueryResult
        """
        with output_to(output) as out:
            callback = None if output is None else out.write
            accept = None if output is None else RDFFormat.mime_type_for_format(output_format)
            response = self.evaluate_generic_query(accept=accept, callback=callback)
            if output is None:
                return GraphQueryResult(response)
            else:
                return None class BooleanQuery(Query):
    """
    A query that returns a boolean.
    """
    def evaluate(self):
        """
        Execute the embedded query against the RDF store.

        :return: A boolean.
        :rtype: bool
        """
        return self.evaluate_generic_query() class QueryLanguage(object):
    registered_languages = []
    SPARQL = None
    PROLOG = None

    def __init__(self, name):
        self.name = name
        QueryLanguage.registered_languages.append(self)

    def __str__(self):
        return self.name

    def __repr__(self):
        return 'QueryLanguage.' + self.name

    def getName(self):
        return self.name

    @staticmethod
    def values(): return QueryLanguage.registered_languages[:]
    
    @staticmethod
    def valueOf(name): 
        for ql in QueryLanguage.registered_languages:
            if ql.name.lower() == name.lower():
                return ql
        return None class RDFFormat(Format):
    """
    Represents the concept of an RDF data serialization format. RDF formats are
    identified by a name and can have one or more associated
    MIME types, zero or more associated file extensions and can specify a
    default character encoding. Some formats are able to encode context
    information while others are not; this is indicated by the value of
    supports_contexts field. Similaraly, formats for which the
    supports_attributes flag is `True` are capable of encoding triple 
    attributes.
    """
    # A global dictionary mapping extensions to formats
    # Used by Format.format_for_file_name
    _ext_map = {}

    def __init__(self, name, mime_types=None, charset="UTF-8",
                 file_extensions=None, supports_namespaces=False,
                 supports_contexts=False, supports_attributes=False,
                 register=True):
        """
        Initialize a new RDF format object.

        :param name: Human-readable name of the format.
        :param mime_types: A list of MIME types used for this format.
                           The first element of this list will be used
                           as the content-type header during uploads.
        :param charset: Character set used by the format.
        :param file_extensions: List of file extensions for this format.
        :param supports_namespaces: If true, the format supports namespaces
                                    and qualified names. This has no impact
                                    on the Python API.
        :param supports_contexts: If True the format can store quads
                                  (and not just triples).
        :param supports_attributes: If True the format can represent triple
                                    attributes.
        :param register: If True file extensions will be added to the map
                         used by :meth:`Format.format_for_file_name`.
        """
        Format.__init__(self, name, mime_types, charset, file_extensions, register)
        self.supports_namespaces = supports_namespaces
        self.supports_contexts = supports_contexts
        self.supports_attributes = supports_attributes

    # These will be automatically converted to RDFFormat instances
        
    RDFXML = dict(
        name="RDF/XML",
        mime_types=["application/rdf+xml", "application/xml"],
        file_extensions=["rdf", "rdfs", "owl", "xml"],
        supports_namespaces=True, supports_contexts=False)

    NTRIPLES = dict(
        name="N-Triples",
        mime_types=["application/n-triples", "text/plain"],
        file_extensions=["nt", "ntriples"],
        supports_namespaces=False, supports_contexts=False)

    NQUADS = dict(
        name="N-Quads",
        mime_types=["application/n-quads"],
        file_extensions=["nq", "nquads"],
        supports_namespaces=False, supports_contexts=True)

    NQX = dict(
        name="Extended N-Quads (with attributes)",
        mime_types=["application/x-extended-nquads"],
        file_extensions=["nqx"],
        supports_namespaces=False, supports_contexts=True,
        supports_attributes=True)

    TURTLE = dict(
        name="Turtle",
        mime_types=["text/turtle"],
        file_extensions=["ttl", "turtle"],
        supports_namespaces=True,
        supports_contexts=False)

    TRIG = dict(
        name="TriG",
        mime_types=["application/trig"],
        file_extensions=["trig"],
        supports_namespaces=True,
        supports_contexts=True)

    TRIX = dict(
        name="TriX",
        mime_types=["application/trix"],
        file_extensions=["trix"],
        supports_namespaces=True,
        supports_contexts=True)

    TABLE = dict(
        name="Table",
        mime_types=["text/table"],
        file_extensions=[],
        supports_namespaces=False,
        supports_contexts=True)

    JSONLD = dict(
        name="JSON-LD",
        mime_types=["application/ld+json"],
        file_extensions=["json", "jsonld"],
        supports_namespaces=True,
        supports_contexts=True) def getLocalNameIndex(uri):
def asURIString(value):
import csv
import string
import six
import copy, sys, warnings
    import io
from future.backports import OrderedDict
from future.builtins import object
from past.builtins import map, unicode, basestring
from franz.miniclient.agjson import encode_json
from franz.openrdf.repository.attributes import AttributeDefinition
from franz.openrdf.rio.docformat import DocFormat
from franz.openrdf.util.contexts import output_to
from .repositoryresult import RepositoryResult
from .transactions import TransactionSettings, DEFAULT_TRANSACTION_SETTINGS
from ..exceptions import IllegalOptionException, IllegalArgumentException
from ..model import Statement, Value, URI
from ..model.literal import RangeLiteral, GeoCoordinate, GeoSpatialRegion, GeoBox, GeoCircle, GeoPolygon, Literal
from ..query.dataset import ALL_CONTEXTS, MINI_NULL_CONTEXT
from ..query.query import Query, TupleQuery, UpdateQuery, GraphQuery, BooleanQuery, QueryLanguage
from ..rio.rdfformat import RDFFormat
from ..util import uris
from collections import namedtuple
from contextlib import contextmanager
        Get the :class:`.ValueFactory` associated with this repository.

        Note that it is recommended to use methods defined in :class:`RepositoryConnection`
        instead of a value factory. The latter is only provided for RDF4J compatibility.

        :return: A value factory.
        :rtype: ValueFactory
        """
        return self.repository.getValueFactory()

    def close(self):
        """
        Close the connection. This also closes the session if it is active.

        It is safe to call this on a connection that has already been closed.

        Note that using ``with`` is the preferred way to manage connections.
        """
        if not self.is_closed:
            self.closeSession()
            self.is_closed = True
            if self._close_repo:
                self.repository.shutDown()

    def setAddCommitSize(self, triple_count):
        """
        Set the value of :attr:`.add_commit_size`.
        :param triple_count: Value of :attr:`.add_commit_size`.
        """
        if not triple_count or triple_count < 0:
            self._add_commit_size = None
        else:
            self._add_commit_size = int(triple_count)

    def getAddCommitSize(self):
        """
        Get the current value of :attr:`.add_commit_size`.
        :return: Value of :attr:`.add_commit_size`.
        """
        return self._add_commit_size

    add_commit_size = property(
        getAddCommitSize, setAddCommitSize,
        doc="""The threshold for commit size during triple add operations.
               Set to 0 (zero) or None to clear size-based autocommit behavior.
               When set to an integer triple_count > 0, a commit will occur every
               triple_count triples added and at the end of the triples being added.""")

    def prepareQuery(self, queryLanguage, queryString, baseURI=None):
        """
        Embed 'queryString' into a query object which can be
        executed against the RDF storage.
        """
        query = Query(queryLanguage, queryString, baseURI)
        query.setConnection(self)
        return query

    def prepareTupleQuery(self, queryLanguage=QueryLanguage.SPARQL,
                          query=None, baseURI=None, queryString=None):
        """
        Parse ``query`` into a tuple query object which can be
        executed against the triple stroe.

        :param queryLanguage: Either ``QueryLanguage.SPARQL`` or ``QueryLanguage.PROLOG``.
        :type queryLanguage: QueryLanguage
        :param query: The query string (must contain a ``SELECT`` query).
        :type query: string
        :param baseURI: An optional base used to resolve relative URIs in the query.
        :type baseURI: string|URI
        :param queryString: Legacy name of the ``query`` parameter.
        :type queryString: string

        :return: A query object.
        :rtype: TupleQuery
        """
        query = TupleQuery(queryLanguage, query or queryString, baseURI=baseURI)
        query.setConnection(self)
        return query

    def prepareUpdate(self, queryLanguage=QueryLanguage.SPARQL,
                      query=None, baseURI=None, queryString=None):
        """
        Parse ``query`` into an update query object which can be
        executed against the triple store.

        :param queryLanguage: Either ``QueryLanguage.SPARQL`` or ``QueryLanguage.PROLOG``.
        :type queryLanguage: QueryLanguage
        :param query: The query string (must contain an ``UPDATE`` query).
        :type query: string
        :param baseURI: An optional base used to resolve relative URIs in the query.
        :type baseURI: string|URI
        :param queryString: Legacy name of the ``query`` parameter.
        :type queryString: string

        :return: A query object.
        :rtype: UpdateQuery
        """
        query = UpdateQuery(queryLanguage, query or queryString,
                            baseURI=baseURI)
        query.setConnection(self)
        return query

    def prepareGraphQuery(self, queryLanguage=QueryLanguage.SPARQL,
                          query=None, baseURI=None, queryString=None):
        """
        Parse ``query`` into a graph query object which can be
        executed against the triple store.

        :param queryLanguage: Either ``QueryLanguage.SPARQL`` or ``QueryLanguage.PROLOG``.
        :type queryLanguage: QueryLanguage
        :param query: The query string (must be a``CONSTRUCT`` or ``DESCRIBE`` query).
        :type query: string
        :param baseURI: An optional base used to resolve relative URIs in the query.
        :type baseURI: string|URI
        :param queryString: Legacy name of the ``query`` parameter.
        :type queryString: string

        :return: A query object.
        :rtype: GraphQuery
        """

        query = GraphQuery(queryLanguage, query or queryString, baseURI=baseURI)