<commit_before>'''
Created on 21 Jun 2011

@author: euan
'''
from django import db
from django.conf import settings
from django.contrib.contenttypes.models import ContentType

from contentpublisher.models import ContentUpgrade, ContentM2MUpgrade

#------------------------------------------------------------------------------
def check_sql(sql):
    return not sql.startswith('SELECT') and \
        not sql.startswith('INSERT INTO "django_admin_log"') and \
        not 'contentpublisher_contentupgrade' in sql and \
        not 'SAVEPOINT' in sql

#------------------------------------------------------------------------------
def track_object(instance):
    sqls = []
    if settings.CONTENT_STAGING:
        for q in db.connection.queries:
            if check_sql(q['sql']) and q['sql'] not in sqls:
                sqls.append(q['sql'])

        db.reset_queries()

    if sqls:
        try:
            cu = ContentUpgrade.objects.get(object_content_type=ContentType.objects.get_for_model(instance.__class__),
                                      object_id=instance.id)
            cu.sql = '%s;' % ';\n'.join(sqls)
            cu.must_publish = True
            cu.save()

        except ContentUpgrade.DoesNotExist:
            ContentUpgrade.objects.create(object_content_type=ContentType.objects.get_for_model(instance.__class__),
                                          object_id=instance.id,
                                          sql='%s;' % ';\n'.join(sqls))

#------------------------------------------------------------------------------
def track_saved_object(sender, instance, created, **kwargs):
    """
    Track a saved object
    """
    track_object(instance)

#------------------------------------------------------------------------------
def track_m2m_changed_object(sender, instance, **kwargs):
    """
    Track a saved object
    """
    sqls = []
    if settings.CONTENT_STAGING:
        for q in db.connection.queries:
            if check_sql(q['sql']) and q['sql'] not in sqls:
                sqls.append(q['sql'])

        db.reset_queries()

    if sqls:
        try:
            cu = ContentM2MUpgrade.objects.get(object_content_type=ContentType.objects.get_for_model(instance.__class__),
                                      object_id=instance.id)
            cu.sql = '%s;' % ';\n'.join(sqls)
            cu.must_publish = True
            cu.save()

        except ContentM2MUpgrade.DoesNotExist:
            ContentM2MUpgrade.objects.create(object_content_type=ContentType.objects.get_for_model(instance.__class__),
                                          object_id=instance.id,
                                          sql='%s;' % ';\n'.join(sqls))

#------------------------------------------------------------------------------
def track_deleted_object(sender, instance, **kwargs):
    """
    Track a deleted object
    """
    track_object(instance)
<commit_msg>Fixed bug in tracking task.<commit_after>'''
Created on 21 Jun 2011

@author: euan
'''
from django import db
from django.conf import settings
from django.contrib.contenttypes.models import ContentType

from contentpublisher.models import ContentUpgrade, ContentM2MUpgrade

#------------------------------------------------------------------------------
def check_sql(sql):
    return not sql.startswith('SELECT') and \
        not sql.startswith('INSERT INTO "django_admin_log"') and \
        not 'contentpublisher_contentupgrade' in sql and \
        not 'contentpublisher_contentm2mupgrade' in sql and \
        not 'SAVEPOINT' in sql

#------------------------------------------------------------------------------
def track_object(instance):
    sqls = []
    if settings.CONTENT_STAGING:
        for q in db.connection.queries:
            if check_sql(q['sql']) and q['sql'] not in sqls:
                sqls.append(q['sql'])

        db.reset_queries()

    if sqls:
        try:
            cu = ContentUpgrade.objects.get(object_content_type=ContentType.objects.get_for_model(instance.__class__),
                                      object_id=instance.id)
            cu.sql = '%s;' % ';\n'.join(sqls)
            cu.must_publish = True
            cu.save()

        except ContentUpgrade.DoesNotExist:
            ContentUpgrade.objects.create(object_content_type=ContentType.objects.get_for_model(instance.__class__),
                                          object_id=instance.id,
                                          sql='%s;' % ';\n'.join(sqls))

#------------------------------------------------------------------------------
def track_saved_object(sender, instance, created, **kwargs):
    """
    Track a saved object
    """
    track_object(instance)

#------------------------------------------------------------------------------
def track_m2m_changed_object(sender, instance, **kwargs):
    """
    Track a saved object
    """
    sqls = []
    if settings.CONTENT_STAGING:
        for q in db.connection.queries:
            if check_sql(q['sql']) and q['sql'] not in sqls:
                sqls.append(q['sql'])

        db.reset_queries()

    if sqls:
        try:
            cu = ContentM2MUpgrade.objects.get(object_content_type=ContentType.objects.get_for_model(instance.__class__),
                                      object_id=instance.id)
            cu.sql = '%s;' % ';\n'.join(sqls)
            cu.must_publish = True
            cu.save()

        except ContentM2MUpgrade.DoesNotExist:
            ContentM2MUpgrade.objects.create(object_content_type=ContentType.objects.get_for_model(instance.__class__),
                                          object_id=instance.id,
                                          sql='%s;' % ';\n'.join(sqls))

#------------------------------------------------------------------------------
def track_deleted_object(sender, instance, **kwargs):
    """
    Track a deleted object
    """
    track_object(instance)
<|endoftext|>


<commit_before>"""

  fs.remote:  utilities for interfacing with remote filesystems

This module provides reusable utility functions that can be used to construct
FS subclasses interfacing with a remote filesystem.  These include:

  RemoteFileBuffer:  a file-like object that locally buffers the contents
                     of a remote file, writing them back on flush() or close().

  ConnectionManagerFS:  a WrapFS subclass that tracks the connection state
                        of a remote FS, and allows client code to wait for
                        a connection to be re-established.

  CacheFS:  a WrapFS subclass that caces file and directory meta-data in
            memory, to speed access to a remote FS.

"""

import time
import copy

from fs.base import FS, threading
from fs.wrapfs import WrapFS, wrap_fs_methods
from fs.path import *
from fs.errors import *

try:
   from tempfile import SpooledTemporaryFile as TempFile
except ImportError:
   from tempfile import NamedTemporaryFile as TempFile

class RemoteFileBuffer(object):
    """File-like object providing buffer for local file operations.

    Instances of this class manage a local tempfile buffer corresponding
    to the contents of a remote file.  All reads and writes happen locally,
    with the content being copied to the remote file only on flush() or
    close().  Writes to the remote file are performed using the setcontents()
    method on the owning FS object.

    The intended use-case is for a remote filesystem (e.g. S3FS) to return
    instances of this class from its open() method, and to provide the
    file-uploading logic in its setcontents() method, as in the following
    pseudo-code:

        def open(self,path,mode="r"):
            rf = self._get_remote_file(path)
            return RemoteFileBuffer(self,path,mode,rf)

        def setcontents(self,path,file):
            self._put_remote_file(path,file)

    The current implementation reads the entire contents of the file into
    the buffer before returning.  Future implementations may pull data into
    the buffer on demand.
    """

    def __init__(self,fs,path,mode,rfile=None):
        """RemoteFileBuffer constructor.

        The owning filesystem, path and mode must be provided.  If the
        optional argument 'rfile' is provided, it must be a read()-able
        object or a string containing the initial file contents.
        """
        self.file = TempFile()
        self.fs = fs
        self.path = path
        self.mode = mode
        self.closed = False
        self._flushed = False
        if hasattr(fs,"_lock"):
            self._lock = fs._lock.__class__()
        else:
            self._lock = threading.RLock()
        if rfile is not None:
            if hasattr(rfile,"read"):
                data = rfile.read(1024*256)
                while data:
                    self.file.write(data)
                    data = rfile.read(1024*256)
            else:
                self.file.write(str(rfile))
            if "a" not in mode:
                self.file.seek(0)

    def __del__(self):
        if not self.closed:
            self.close()

    def __getattr__(self,name):
        file = self.__dict__['file']
        a = getattr(file, name)
        if not callable(a):
            return a
        @wraps(a)
        def call_with_lock(*args,**kwds):
            self._lock.acquire()
            try:
                self._flushed = False
                return a(*args,**kwds)
            finally:
                self._lock.release()
        setattr(self, name, call_with_lock)
        return call_with_lock

    def __enter__(self):
        self.file.__enter__()
        return self

    def __exit__(self,exc,value,tb):
        self.close()
        return False

    def __iter__(self):
        return iter(self.file)

    def truncate(self,size=None):
        self._lock.acquire()
        try:
            self.file.truncate(size)
            self.flush()
        finally:
            self._lock.release()

    def flush(self):
        self._lock.acquire()
        try:
            self.file.flush()
            if "w" in self.mode or "a" in self.mode or "+" in self.mode:
                pos = self.file.tell()
                self.file.seek(0)
                self.fs.setcontents(self.path,self.file)
                self.file.seek(pos)
                self._flushed = True
        finally:
            self._lock.release()

    def close(self):
        self._lock.acquire()
        try:
            self.closed = True
            if "w" in self.mode or "a" in self.mode or "+" in self.mode:
                self.file.seek(0)
                self.fs.setcontents(self.path,self.file)
            self.file.close()
        finally:
            self._lock.release()

class ConnectionManagerFS(WrapFS):
    """FS wrapper providing simple connection management of a remote FS.

    The ConnectionManagerFS class is designed to wrap a remote FS object
    and provide some convenience methods for dealing with its remote
    connection state.

    The boolean attribute 'connected' indicates whether the remote fileystem
    has an active connection, and is initially True.  If any of the remote
    filesystem methods raises a RemoteConnectionError, 'connected' will
    switch to False and remain so until a successful remote method call.

    Application code can use the method 'wait_for_connection' to block
    until the connection is re-established.  Currently this reconnection
    is checked by a simple polling loop; eventually more sophisticated
    operating-system integration may be added.

    Since some remote FS classes can raise RemoteConnectionError during
    initialisation, this class also provides a simple "lazy initialisation"
    facility.  The remote FS can be specified as an FS instance, an FS
    subclass, or a (class,args) or (class,args,kwds) tuple. For example:

        >>> fs = ConnectionManagerFS(MyRemoteFS("http://www.example.com/"))
        Traceback (most recent call last):
            ...
        RemoteConnectionError: couldn't connect to "http://www.example.com/"
        >>> fs = ConnectionManagerFS((MyRemoteFS,["http://www.example.com/"]))
        >>> fs.connected
        False
        >>>

    """

    poll_interval = 1

    def __init__(self,fs,poll_interval=None,connected=True):
        if poll_interval is not None:
            self.poll_interval = poll_interval
        if isinstance(fs,FS):
            self.__dict__["wrapped_fs"] = fs
        elif isinstance(fs,type):
            self._fsclass = fs
            self._fsargs = []
            self._fskwds = {}
        else:
            self._fsclass = fs[0]
            try:
                self._fsargs = fs[1]
            except IndexError:
                self._fsargs = []
            try:
                self._fskwds = fs[2]
            except IndexError:
                self._fskwds = {}
        self._connection_cond = threading.Condition()
        self._poll_thread = None
        self._poll_sleeper = threading.Event()
        self.connected = connected

    @property
    def wrapped_fs(self):
        try:
            return self.__dict__["wrapped_fs"]
        except KeyError:
            self._connection_cond.acquire()
            try:
                try:
                    return self.__dict__["wrapped_fs"]
                except KeyError:
                    fs = self._fsclass(*self._fsargs,**self._fskwds)
                    self.__dict__["wrapped_fs"] = fs
                    return fs
            finally:
                self._connection_cond.release()

    def __getstate__(self):
        state = super(ConnectionManagerFS,self).__getstate__()
        del state["_connection_cond"]
        del state["_poll_sleeper"]
        state["_poll_thread"] = None
        return state

    def __setstate__(self,state):
        super(ConnectionManagerFS,self).__setstate__(state)
        self._connection_cond = threading.Condition()
        self._poll_sleeper = threading.Event()

    def wait_for_connection(self,timeout=None):
        self._connection_cond.acquire()
        try:
            if not self.connected:
                if not self._poll_thread:
                    target = self._poll_connection
                    self._poll_thread = threading.Thread(target=target)
                    self._poll_thread.start()
                self._connection_cond.wait(timeout)
        finally:
            self._connection_cond.release()

    def _poll_connection(self):
        while not self.connected:
            try:
                self.wrapped_fs.isdir("")
            except RemoteConnectionError:
                self._poll_sleeper.wait(self.poll_interval)
                self._poll_sleeper.clear()
            except FSError:
                break
            else:
                break
        self._connection_cond.acquire()
        try:
            self.connected = True
            self._poll_thread = None
            self._connection_cond.notifyAll()
        finally:
            self._connection_cond.release()

    def close(self):
        # Don't close if we haven't created it
        try:
            fs = self.__dict__["wrapped_fs"]
        except KeyError:
            pass
        else:
            try:
                fs.close()
            except (RemoteConnectionError,AttributeError):
                pass
            if self._poll_thread:
                self.connected = True
                self._poll_sleeper.set()
                self._poll_thread.join()
                self._poll_thread = None

def _ConnectionManagerFS_method_wrapper(func):
    """Method wrapper for ConnectionManagerFS.

    This method wrapper keeps an eye out for RemoteConnectionErrors and
    adjusts self.connected accordingly.
    """
    @wraps(func)
    def wrapper(self,*args,**kwds):
        try:
            result = func(self,*args,**kwds)
        except RemoteConnectionError:
            self.connected = False
            raise
        except FSError:
            self.connected = True
            raise
        else:
            self.connected = True
            return result
    return wrapper

wrap_fs_methods(_ConnectionManagerFS_method_wrapper,ConnectionManagerFS)

def _cached_method(func):
    """Method decorator that caches results for CacheFS."""
    @wraps(func)
    def wrapper(self,path="",*args,**kwds):
        try:
            (success,result) = self._cache_get(path,func.__name__,args,kwds)
        except KeyError:
            try:
                res = func(self,path,*args,**kwds)
            except Exception, e:
                self._cache_set(path,func.__name__,args,kwds,(False,e))
                raise
            else:
                self._cache_set(path,func.__name__,args,kwds,(True,res))
                return copy.copy(res)
        else:
            if not success:
                raise result
            else:
                return copy.copy(result)
    return wrapper

class CacheFS(WrapFS):
    """Simple wrapper to cache meta-data of a remote filesystems.

    This FS wrapper implements a simplistic cache that can help speed up
    access to a remote filesystem.  File and directory meta-data is cached
    but the actual file contents are not.
    """

    def __init__(self,fs,timeout=1):
        """CacheFS constructor.

        The optional argument 'timeout' specifies the cache timeout in
        seconds.  The default timeout is 1 second.  To prevent cache
        entries from ever timing out, set it to None.
        """
        self.timeout = timeout
        self._cache = {"":{}}
        super(CacheFS,self).__init__(fs)

    def _path_cache(self,path):
        cache = self._cache
        for name in iteratepath(path):
            cache = cache.setdefault(name,{"":{}})
        return cache

    def _cache_get(self,path,func,args,kwds):
        now = time.time()
        cache = self._path_cache(path)
        key = (tuple(args),tuple(sorted(kwds.iteritems())))
        (t,v) = cache[""][func][key]
        if self.timeout is not None:
            if t < now - self.timeout:
                raise KeyError
        return v

    def _cache_set(self,path,func,args,kwds,v):
        t = time.time()
        cache = self._path_cache(path)
        key = (tuple(args),tuple(sorted(kwds.iteritems())))
        cache[""].setdefault(func,{})[key] = (t,v)

    def _uncache(self,path,added=False,removed=False,unmoved=False):
        cache = self._cache
        names = list(iteratepath(path))
        # If it's not the root dir, also clear some items for ancestors
        if names:
            # Clear cached 'getinfo' and 'getsize' for all ancestors
            for name in names[:-1]:
                cache[""].pop("getinfo",None)
                cache[""].pop("getsize",None)
                cache = cache.get(name,None)
                if cache is None:
                    return
            # Adjust cached 'listdir' for parent directory.
            # TODO: account for whether it was added, removed, or unmoved
            cache[""].pop("getinfo",None)
            cache[""].pop("getsize",None)
            cache[""].pop("listdir",None)
        # Clear all cached info for the path itself.
        cache[names[-1]] = {"":{}}

    @_cached_method
    def exists(self,path):
        return super(CacheFS,self).exists(path)

    @_cached_method
    def isdir(self,path):
        return super(CacheFS,self).isdir(path)

    @_cached_method
    def isfile(self,path):
        return super(CacheFS,self).isfile(path)

    @_cached_method
    def listdir(self,path="",**kwds):
        return super(CacheFS,self).listdir(path,**kwds)

    @_cached_method
    def getinfo(self,path):
        return super(CacheFS,self).getinfo(path)

    @_cached_method
    def getsize(self,path):
        return super(CacheFS,self).getsize(path)

    @_cached_method
    def getxattr(self,path,name):
        return super(CacheFS,self).getxattr(path,name)

    @_cached_method
    def listxattrs(self,path):
        return super(CacheFS,self).listxattrs(path)

    def open(self,path,mode="r"):
        f = super(CacheFS,self).open(path,mode)
        self._uncache(path,unmoved=True)
        return f

    def setcontents(self,path,contents):
        res = super(CacheFS,self).setcontents(path,contents)
        self._uncache(path,unmoved=True)
        return res

    def getcontents(self,path):
        res = super(CacheFS,self).getcontents(path)
        self._uncache(path,unmoved=True)
        return res

    def makedir(self,path,**kwds):
        super(CacheFS,self).makedir(path,**kwds)
        self._uncache(path,added=True)

    def remove(self,path):
        super(CacheFS,self).remove(path)
        self._uncache(path,removed=True)

    def removedir(self,path,**kwds):
        super(CacheFS,self).removedir(path,**kwds)
        self._uncache(path,removed=True)

    def rename(self,src,dst):
        super(CacheFS,self).rename(src,dst)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def copy(self,src,dst,**kwds):
        super(CacheFS,self).copy(src,dst,**kwds)
        self._uncache(dst,added=True)

    def copydir(self,src,dst,**kwds):
        super(CacheFS,self).copydir(src,dst,**kwds)
        self._uncache(dst,added=True)

    def move(self,src,dst,**kwds):
        super(CacheFS,self).move(src,dst,**kwds)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def movedir(self,src,dst,**kwds):
        super(CacheFS,self).movedir(src,dst,**kwds)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def setxattr(self,path,name,value):
        self._uncache(path,unmoved=True)
        return super(CacheFS,self).setxattr(path,name,value)

    def delxattr(self,path,name):
        self._uncache(path,unmoved=True)
        return super(CacheFS,self).delxattr(path,name)

<commit_msg>RemoteFileBuffer:  try harder to avoid unnecessary flushes<commit_after>"""

  fs.remote:  utilities for interfacing with remote filesystems

This module provides reusable utility functions that can be used to construct
FS subclasses interfacing with a remote filesystem.  These include:

  RemoteFileBuffer:  a file-like object that locally buffers the contents
                     of a remote file, writing them back on flush() or close().

  ConnectionManagerFS:  a WrapFS subclass that tracks the connection state
                        of a remote FS, and allows client code to wait for
                        a connection to be re-established.

  CacheFS:  a WrapFS subclass that caces file and directory meta-data in
            memory, to speed access to a remote FS.

"""

import time
import copy

from fs.base import FS, threading
from fs.wrapfs import WrapFS, wrap_fs_methods
from fs.path import *
from fs.errors import *

try:
   from tempfile import SpooledTemporaryFile as TempFile
except ImportError:
   from tempfile import NamedTemporaryFile as TempFile

class RemoteFileBuffer(object):
    """File-like object providing buffer for local file operations.

    Instances of this class manage a local tempfile buffer corresponding
    to the contents of a remote file.  All reads and writes happen locally,
    with the content being copied to the remote file only on flush() or
    close().  Writes to the remote file are performed using the setcontents()
    method on the owning FS object.

    The intended use-case is for a remote filesystem (e.g. S3FS) to return
    instances of this class from its open() method, and to provide the
    file-uploading logic in its setcontents() method, as in the following
    pseudo-code:

        def open(self,path,mode="r"):
            rf = self._get_remote_file(path)
            return RemoteFileBuffer(self,path,mode,rf)

        def setcontents(self,path,file):
            self._put_remote_file(path,file)

    The current implementation reads the entire contents of the file into
    the buffer before returning.  Future implementations may pull data into
    the buffer on demand.
    """

    def __init__(self,fs,path,mode,rfile=None):
        """RemoteFileBuffer constructor.

        The owning filesystem, path and mode must be provided.  If the
        optional argument 'rfile' is provided, it must be a read()-able
        object or a string containing the initial file contents.
        """
        self.file = TempFile()
        self.fs = fs
        self.path = path
        self.mode = mode
        self.closed = False
        self._flushed = False
        if getattr(fs,"_lock",None) is not None:
            self._lock = fs._lock.__class__()
        else:
            self._lock = threading.RLock()
        if "r" in mode or "+" in mode:
            if rfile is not None:
                if hasattr(rfile,"read"):
                    data = rfile.read(1024*256)
                    while data:
                        self.file.write(data)
                        data = rfile.read(1024*256)
                else:
                    self.file.write(str(rfile))
                if "a" not in mode:
                    self.file.seek(0)

    def __del__(self):
        if not self.closed:
            self.close()

    def __getattr__(self,name):
        file = self.__dict__['file']
        a = getattr(file, name)
        if not callable(a):
            return a
        @wraps(a)
        def call_with_lock(*args,**kwds):
            self._lock.acquire()
            try:
                if "write" in name:
                    self._flushed = False
                return a(*args,**kwds)
            finally:
                self._lock.release()
        setattr(self, name, call_with_lock)
        return call_with_lock

    def __enter__(self):
        self.file.__enter__()
        return self

    def __exit__(self,exc,value,tb):
        self.close()
        return False

    def __iter__(self):
        return iter(self.file)

    def truncate(self,size=None):
        self._lock.acquire()
        try:
            self.file.truncate(size)
            self.flush()
        finally:
            self._lock.release()

    def flush(self):
        self._lock.acquire()
        try:
            self.file.flush()
            if "w" in self.mode or "a" in self.mode or "+" in self.mode:
                if not self._flushed:
                    pos = self.file.tell()
                    self.file.seek(0)
                    self.file.seek(0)
                    self.fs.setcontents(self.path,self.file)
                    self.file.seek(pos)
                    self._flushed = True
        finally:
            self._lock.release()

    def close(self):
        self._lock.acquire()
        try:
            if not self.closed:
                self.closed = True
                if "w" in self.mode or "a" in self.mode or "+" in self.mode:
                    if not self._flushed:
                        self.file.seek(0)
                        self.file.seek(0)
                        self.fs.setcontents(self.path,self.file)
                self.file.close()
        finally:
            self._lock.release()

class ConnectionManagerFS(WrapFS):
    """FS wrapper providing simple connection management of a remote FS.

    The ConnectionManagerFS class is designed to wrap a remote FS object
    and provide some convenience methods for dealing with its remote
    connection state.

    The boolean attribute 'connected' indicates whether the remote fileystem
    has an active connection, and is initially True.  If any of the remote
    filesystem methods raises a RemoteConnectionError, 'connected' will
    switch to False and remain so until a successful remote method call.

    Application code can use the method 'wait_for_connection' to block
    until the connection is re-established.  Currently this reconnection
    is checked by a simple polling loop; eventually more sophisticated
    operating-system integration may be added.

    Since some remote FS classes can raise RemoteConnectionError during
    initialisation, this class also provides a simple "lazy initialisation"
    facility.  The remote FS can be specified as an FS instance, an FS
    subclass, or a (class,args) or (class,args,kwds) tuple. For example:

        >>> fs = ConnectionManagerFS(MyRemoteFS("http://www.example.com/"))
        Traceback (most recent call last):
            ...
        RemoteConnectionError: couldn't connect to "http://www.example.com/"
        >>> fs = ConnectionManagerFS((MyRemoteFS,["http://www.example.com/"]))
        >>> fs.connected
        False
        >>>

    """

    poll_interval = 1

    def __init__(self,fs,poll_interval=None,connected=True):
        if poll_interval is not None:
            self.poll_interval = poll_interval
        if isinstance(fs,FS):
            self.__dict__["wrapped_fs"] = fs
        elif isinstance(fs,type):
            self._fsclass = fs
            self._fsargs = []
            self._fskwds = {}
        else:
            self._fsclass = fs[0]
            try:
                self._fsargs = fs[1]
            except IndexError:
                self._fsargs = []
            try:
                self._fskwds = fs[2]
            except IndexError:
                self._fskwds = {}
        self._connection_cond = threading.Condition()
        self._poll_thread = None
        self._poll_sleeper = threading.Event()
        self.connected = connected

    @property
    def wrapped_fs(self):
        try:
            return self.__dict__["wrapped_fs"]
        except KeyError:
            self._connection_cond.acquire()
            try:
                try:
                    return self.__dict__["wrapped_fs"]
                except KeyError:
                    fs = self._fsclass(*self._fsargs,**self._fskwds)
                    self.__dict__["wrapped_fs"] = fs
                    return fs
            finally:
                self._connection_cond.release()

    def __getstate__(self):
        state = super(ConnectionManagerFS,self).__getstate__()
        del state["_connection_cond"]
        del state["_poll_sleeper"]
        state["_poll_thread"] = None
        return state

    def __setstate__(self,state):
        super(ConnectionManagerFS,self).__setstate__(state)
        self._connection_cond = threading.Condition()
        self._poll_sleeper = threading.Event()

    def wait_for_connection(self,timeout=None):
        self._connection_cond.acquire()
        try:
            if not self.connected:
                if not self._poll_thread:
                    target = self._poll_connection
                    self._poll_thread = threading.Thread(target=target)
                    self._poll_thread.start()
                self._connection_cond.wait(timeout)
        finally:
            self._connection_cond.release()

    def _poll_connection(self):
        while not self.connected:
            try:
                self.wrapped_fs.isdir("")
            except RemoteConnectionError:
                self._poll_sleeper.wait(self.poll_interval)
                self._poll_sleeper.clear()
            except FSError:
                break
            else:
                break
        self._connection_cond.acquire()
        try:
            self.connected = True
            self._poll_thread = None
            self._connection_cond.notifyAll()
        finally:
            self._connection_cond.release()

    def close(self):
        # Don't close if we haven't created it
        try:
            fs = self.__dict__["wrapped_fs"]
        except KeyError:
            pass
        else:
            try:
                fs.close()
            except (RemoteConnectionError,AttributeError):
                pass
            if self._poll_thread:
                self.connected = True
                self._poll_sleeper.set()
                self._poll_thread.join()
                self._poll_thread = None

def _ConnectionManagerFS_method_wrapper(func):
    """Method wrapper for ConnectionManagerFS.

    This method wrapper keeps an eye out for RemoteConnectionErrors and
    adjusts self.connected accordingly.
    """
    @wraps(func)
    def wrapper(self,*args,**kwds):
        try:
            result = func(self,*args,**kwds)
        except RemoteConnectionError:
            self.connected = False
            raise
        except FSError:
            self.connected = True
            raise
        else:
            self.connected = True
            return result
    return wrapper

wrap_fs_methods(_ConnectionManagerFS_method_wrapper,ConnectionManagerFS)

def _cached_method(func):
    """Method decorator that caches results for CacheFS."""
    @wraps(func)
    def wrapper(self,path="",*args,**kwds):
        try:
            (success,result) = self._cache_get(path,func.__name__,args,kwds)
        except KeyError:
            try:
                res = func(self,path,*args,**kwds)
            except Exception, e:
                self._cache_set(path,func.__name__,args,kwds,(False,e))
                raise
            else:
                self._cache_set(path,func.__name__,args,kwds,(True,res))
                return copy.copy(res)
        else:
            if not success:
                raise result
            else:
                return copy.copy(result)
    return wrapper

class CacheFS(WrapFS):
    """Simple wrapper to cache meta-data of a remote filesystems.

    This FS wrapper implements a simplistic cache that can help speed up
    access to a remote filesystem.  File and directory meta-data is cached
    but the actual file contents are not.
    """

    def __init__(self,fs,timeout=1):
        """CacheFS constructor.

        The optional argument 'timeout' specifies the cache timeout in
        seconds.  The default timeout is 1 second.  To prevent cache
        entries from ever timing out, set it to None.
        """
        self.timeout = timeout
        self._cache = {"":{}}
        super(CacheFS,self).__init__(fs)

    def _path_cache(self,path):
        cache = self._cache
        for name in iteratepath(path):
            cache = cache.setdefault(name,{"":{}})
        return cache

    def _cache_get(self,path,func,args,kwds):
        now = time.time()
        cache = self._path_cache(path)
        key = (tuple(args),tuple(sorted(kwds.iteritems())))
        (t,v) = cache[""][func][key]
        if self.timeout is not None:
            if t < now - self.timeout:
                raise KeyError
        return v

    def _cache_set(self,path,func,args,kwds,v):
        t = time.time()
        cache = self._path_cache(path)
        key = (tuple(args),tuple(sorted(kwds.iteritems())))
        cache[""].setdefault(func,{})[key] = (t,v)

    def _uncache(self,path,added=False,removed=False,unmoved=False):
        cache = self._cache
        names = list(iteratepath(path))
        # If it's not the root dir, also clear some items for ancestors
        if names:
            # Clear cached 'getinfo' and 'getsize' for all ancestors
            for name in names[:-1]:
                cache[""].pop("getinfo",None)
                cache[""].pop("getsize",None)
                cache = cache.get(name,None)
                if cache is None:
                    return
            # Adjust cached 'listdir' for parent directory.
            # TODO: account for whether it was added, removed, or unmoved
            cache[""].pop("getinfo",None)
            cache[""].pop("getsize",None)
            cache[""].pop("listdir",None)
        # Clear all cached info for the path itself.
        cache[names[-1]] = {"":{}}

    @_cached_method
    def exists(self,path):
        return super(CacheFS,self).exists(path)

    @_cached_method
    def isdir(self,path):
        return super(CacheFS,self).isdir(path)

    @_cached_method
    def isfile(self,path):
        return super(CacheFS,self).isfile(path)

    @_cached_method
    def listdir(self,path="",**kwds):
        return super(CacheFS,self).listdir(path,**kwds)

    @_cached_method
    def getinfo(self,path):
        return super(CacheFS,self).getinfo(path)

    @_cached_method
    def getsize(self,path):
        return super(CacheFS,self).getsize(path)

    @_cached_method
    def getxattr(self,path,name):
        return super(CacheFS,self).getxattr(path,name)

    @_cached_method
    def listxattrs(self,path):
        return super(CacheFS,self).listxattrs(path)

    def open(self,path,mode="r"):
        f = super(CacheFS,self).open(path,mode)
        self._uncache(path,unmoved=True)
        return f

    def setcontents(self,path,contents):
        res = super(CacheFS,self).setcontents(path,contents)
        self._uncache(path,unmoved=True)
        return res

    def getcontents(self,path):
        res = super(CacheFS,self).getcontents(path)
        self._uncache(path,unmoved=True)
        return res

    def makedir(self,path,**kwds):
        super(CacheFS,self).makedir(path,**kwds)
        self._uncache(path,added=True)

    def remove(self,path):
        super(CacheFS,self).remove(path)
        self._uncache(path,removed=True)

    def removedir(self,path,**kwds):
        super(CacheFS,self).removedir(path,**kwds)
        self._uncache(path,removed=True)

    def rename(self,src,dst):
        super(CacheFS,self).rename(src,dst)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def copy(self,src,dst,**kwds):
        super(CacheFS,self).copy(src,dst,**kwds)
        self._uncache(dst,added=True)

    def copydir(self,src,dst,**kwds):
        super(CacheFS,self).copydir(src,dst,**kwds)
        self._uncache(dst,added=True)

    def move(self,src,dst,**kwds):
        super(CacheFS,self).move(src,dst,**kwds)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def movedir(self,src,dst,**kwds):
        super(CacheFS,self).movedir(src,dst,**kwds)
        self._uncache(src,removed=True)
        self._uncache(dst,added=True)

    def setxattr(self,path,name,value):
        self._uncache(path,unmoved=True)
        return super(CacheFS,self).setxattr(path,name,value)

    def delxattr(self,path,name):
        self._uncache(path,unmoved=True)
        return super(CacheFS,self).delxattr(path,name)

<|endoftext|>


<commit_before>#!/usr/bin/env python
# encoding: utf-8

from __future__ import unicode_literals
from bs4 import BeautifulSoup
from datetime import date, time, datetime
from pytz import timezone
from icalendar import Calendar, Event
from StringIO import StringIO
import copy
import re

class Lesson(object):
    subject = ""
    kind = ""
    group = ""
    room = ""
    date_start = ""
    date_end = ""
    raw_data = ""

    def __key(self):
        return (self.subject, self.kind, self.group, self.room, self.date_start, self.date_end)

    def __hash__(self):
        # As suggested in: http://stackoverflow.com/a/2909119
        return hash(self.__key())

    def __eq__(self, other):
        if type(other) is type(self):
            return other.__key() == self.__key()
        return False

    def __ne__(self, other):
        return not self.__eq__(other)

    def __str__(self):
        rep = "<Lesson object>\n"
        rep += "subject: " + repr(self.subject) + "\n"
        rep += "kind: " + repr(self.kind) + "\n"
        rep += "group: " + repr(self.group) + "\n"
        rep += "room: " + repr(self.room) + "\n"
        rep += "date_start: " + repr(self.date_start) + "\n"
        rep += "date_end: " + repr(self.date_end) + "\n"
        #return rep
        return self.raw_data

    def __repr__(self):
        return self.raw_data

    def copy(self):
        return copy.deepcopy(self)

def parsedays(row):
    days = []
    for numcell, cell in enumerate(row.find_all("td")):
        if numcell == 0:
            days.append(None)
            continue
        day_list = [int(data) for data in cell.get_text().split("/")]
        day_list.reverse()
        day = date(*day_list)
        days.append(day)
    return days

def parsehours(text):
    tz = timezone('Europe/Madrid')
    hours_str = text.strip().replace('.', ':').split("-")
    h_init_list = [int(data) for data in hours_str[0].split(":")]
    h_end_list = [int(data) for data in hours_str[1].split(":")]
    h_init = time(*h_init_list, tzinfo=tz)
    h_end = time(*h_end_list, tzinfo=tz)
    return h_init, h_end

def parselesson(cell, h_init, h_end, day):
    lessons = []
    buf = StringIO(cell.get_text().strip())
    c = Lesson()
    c.raw_data = cell.get_text().strip()
    # This finds any string followed by :, any number of spaces and
    # 2 digits separated by a point. The second digit might be preceded by any number of letters.
    group_regex = re.compile(r"(\w+\s*\w*):?\s+(\d{2}[\.|\,]\w*\d+)")
    for line in buf:
        line = line.strip()
        while line == "":
            line = buf.readline().strip()
        c.subject = line
        for line in buf:
            line = line.strip()
            c.kind = line
            if c.kind != "":
                break
        c.date_start = datetime.combine(day, h_init)
        c.date_end = datetime.combine(day, h_end)
        for line in buf:
            line = line.strip()
            if "----------------" in line:
                break
            if line == "":
                continue
            if " - " in line:
                h_init, h_end = parsehours(line)
                c.date_start = datetime.combine(day, h_init)
                c.date_end = datetime.combine(day, h_end)
                continue
            g = group_regex.match(line)
            if g is not None:
                group = g.groups()[0]
                room = g.groups()[1]
                if "aula" in group.lower():
                    group = ""
                c.group = group
                c.room = room
                lessons.append(c)
                c = c.copy()
    return lessons

def createcalendar(lessons):
    cal = Calendar()
    cal.add('prodid', '-//My calendar product//mxm.dk//')
    cal.add('version', '2.0')

    for entry in lessons:
        event = Event()
        summary = u" ".join([entry.subject, entry.kind, entry.group])
        event.add('summary', summary)
        event.add('dtstart', entry.date_start)
        event.add('dtend', entry.date_end)
        event.add('location', entry.room)
        cal.add_component(event)
    f = open('example.ics', 'wb')
    f.write(cal.to_ical())
    f.close()

    pass

def parse(html):
    lessons = []
    soup = BeautifulSoup(html)
    for table in soup.find_all("table"):
        for numrow, row in enumerate(table.find_all("tr")):
            if numrow == 0:
                continue
            if numrow == 1:
                days = parsedays(row)
                continue
            h_init = None
            h_end = None
            for numcell, cell in enumerate(row.find_all("td")):
                if numcell == 0:
                    h_init, h_end = parsehours(cell.get_text().strip())
                else:
                    day = days[numcell]
                    lessons.extend(parselesson(cell, h_init, h_end, day))
    return lessons
<commit_msg>solved TimeZone bug that made the events appear 2h after they started.<commit_after>#!/usr/bin/env python
# encoding: utf-8

from __future__ import unicode_literals
from bs4 import BeautifulSoup
from datetime import date, time, datetime
from icalendar import Calendar, Event
from StringIO import StringIO
import copy
import re

class Lesson(object):
    subject = ""
    kind = ""
    group = ""
    room = ""
    date_start = ""
    date_end = ""
    raw_data = ""

    def __key(self):
        return (self.subject, self.kind, self.group, self.room, self.date_start, self.date_end)

    def __hash__(self):
        # As suggested in: http://stackoverflow.com/a/2909119
        return hash(self.__key())

    def __eq__(self, other):
        if type(other) is type(self):
            return other.__key() == self.__key()
        return False

    def __ne__(self, other):
        return not self.__eq__(other)

    def __str__(self):
        rep = "<Lesson object>\n"
        rep += "subject: " + repr(self.subject) + "\n"
        rep += "kind: " + repr(self.kind) + "\n"
        rep += "group: " + repr(self.group) + "\n"
        rep += "room: " + repr(self.room) + "\n"
        rep += "date_start: " + repr(self.date_start) + "\n"
        rep += "date_end: " + repr(self.date_end) + "\n"
        #return rep
        return self.raw_data

    def __repr__(self):
        return self.raw_data

    def copy(self):
        return copy.deepcopy(self)

def parsedays(row):
    days = []
    for numcell, cell in enumerate(row.find_all("td")):
        if numcell == 0:
            days.append(None)
            continue
        day_list = [int(data) for data in cell.get_text().split("/")]
        day_list.reverse()
        day = date(*day_list)
        days.append(day)
    return days

def parsehours(text):
    hours_str = text.strip().replace('.', ':').split("-")
    h_init_list = [int(data) for data in hours_str[0].split(":")]
    h_end_list = [int(data) for data in hours_str[1].split(":")]
    h_init = time(*h_init_list)
    h_end = time(*h_end_list)
    return h_init, h_end

def parselesson(cell, h_init, h_end, day):
    lessons = []
    buf = StringIO(cell.get_text().strip())
    c = Lesson()
    c.raw_data = cell.get_text().strip()
    # This finds any string followed by :, any number of spaces and
    # 2 digits separated by a point. The second digit might be preceded by any number of letters.
    group_regex = re.compile(r"(\w+\s*\w*):?\s+(\d{2}[\.|\,]\w*\d+)")
    for line in buf:
        line = line.strip()
        while line == "":
            line = buf.readline().strip()
        c.subject = line
        for line in buf:
            line = line.strip()
            c.kind = line
            if c.kind != "":
                break
        c.date_start = datetime.combine(day, h_init)
        c.date_end = datetime.combine(day, h_end)
        for line in buf:
            line = line.strip()
            if "----------------" in line:
                break
            if line == "":
                continue
            if " - " in line:
                h_init, h_end = parsehours(line)
                c.date_start = datetime.combine(day, h_init)
                c.date_end = datetime.combine(day, h_end)
                continue
            g = group_regex.match(line)
            if g is not None:
                group = g.groups()[0]
                room = g.groups()[1]
                if "aula" in group.lower():
                    group = ""
                c.group = group
                c.room = room
                lessons.append(c)
                c = c.copy()
    return lessons

def createcalendar(lessons):
    cal = Calendar()
    cal.add('prodid', '-//My calendar product//mxm.dk//')
    cal.add('version', '2.0')

    for entry in lessons:
        event = Event()
        summary = u" ".join([entry.subject, entry.kind, entry.group])
        event.add('summary', summary)
        event.add('dtstart', entry.date_start)
        event.add('dtend', entry.date_end)
        event.add('location', entry.room)
        cal.add_component(event)
    f = open('example.ics', 'wb')
    f.write(cal.to_ical())
    f.close()

    pass

def parse(html):
    lessons = []
    soup = BeautifulSoup(html)
    for table in soup.find_all("table"):
        for numrow, row in enumerate(table.find_all("tr")):
            if numrow == 0:
                continue
            if numrow == 1:
                days = parsedays(row)
                continue
            h_init = None
            h_end = None
            for numcell, cell in enumerate(row.find_all("td")):
                if numcell == 0:
                    h_init, h_end = parsehours(cell.get_text().strip())
                else:
                    day = days[numcell]
                    lessons.extend(parselesson(cell, h_init, h_end, day))
    return lessons
<|endoftext|>


<commit_before>#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.

import argparse
import base64
import dzclient
import json
import logging
import os
import time

import stoneridge

class StoneRidgeReporter(stoneridge.QueueListener):
    def setup(self):
        self.host = stoneridge.get_config('report', 'host')
        self.project = stoneridge.get_config('report', 'project')
        self.key = stoneridge.get_config('report', 'key')
        self.secret = stoneridge.get_config('report', 'secret')
        self.archives = stoneridge.get_config('stoneridge', 'archives')

        logging.debug('report host: %s' % (self.host,))
        logging.debug('project: %s' % (self.project,))
        logging.debug('oauth key: %s' % (self.key,))
        logging.debug('oauth secret: %s' % (self.secret,))
        logging.debug('archives: %s' % (self.archives,))

    def save_data(self, srid, results, metadata_b64):
        archivedir = os.path.join(self.archives, srid)
        if os.path.exists(archivedir):
            # Don't overwrite previous archives, just make yet another
            # directory for the new run of this srid
            archivedir = '%s_%s' % (archivedir, int(time.time()))
        os.makedirs(archivedir)

        results_file = os.path.join(archivedir, 'results.json')
        with file(results_file, 'w') as f:
            json.dump(results, f)

        metadata = base64.b64decode(metadata_b64)
        metadata_file = os.path.join(archivedir, 'metadata.zip')
        with file(metadata_file, 'wb') as f:
            f.write(metadata)

    def handle(self, srid, results, metadata_b64):
        logging.debug('uploading results for %s' % (srid,))

        for name in results:
            dataset = results[name]
            if not isinstance(dataset, dict):
                # This one is crap, ignore it
                logging.error('bad json: %s' % (contents,))
                continue

            logging.debug('uploading data')
            request = dzclient.DatazillaRequest('https', self.host,
                    self.project, self.key, self.secret)
            response = request.send(dataset)
            logging.debug('got status code %s' % (response.status,))
            if response.status != 200:
                logging.error('bad http status %s for %s' % (response.status, srid))

            try:
                result = json.load(response)
            except:
                result = ''
            logging.debug('got result %s' % (result,))
            if result['status'] != 'well-formed JSON stored':
                logging.error('bad status for %s: %s' % (srid, result['status']))

        self.save_data(srid, results, metadata_b64)

def daemon():
    reporter = StoneRidgeReporter(stoneridge.OUTGOING_QUEUE)
    reporter.run()

@stoneridge.main
def main():
    parser = stoneridge.DaemonArgumentParser()
    args = parser.parse_args()

    parser.start_daemon(daemon)
<commit_msg>Add unit test support to reporter<commit_after>#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.

import argparse
import base64
import dzclient
import json
import logging
import os
import time

import stoneridge

class StoneRidgeReporter(stoneridge.QueueListener):
    def setup(self):
        self.host = stoneridge.get_config('report', 'host')
        self.project = stoneridge.get_config('report', 'project')
        self.key = stoneridge.get_config('report', 'key')
        self.secret = stoneridge.get_config('report', 'secret')
        self.archives = stoneridge.get_config('stoneridge', 'archives')
        self.unittest = stoneridge.get_config_bool('stoneridge', 'unittest')

        logging.debug('report host: %s' % (self.host,))
        logging.debug('project: %s' % (self.project,))
        logging.debug('oauth key: %s' % (self.key,))
        logging.debug('oauth secret: %s' % (self.secret,))
        logging.debug('archives: %s' % (self.archives,))
        logging.debug('unittest: %s' % (self.unittest,))

    def save_data(self, srid, results, metadata_b64):
        archivedir = os.path.join(self.archives, srid)
        if os.path.exists(archivedir):
            # Don't overwrite previous archives, just make yet another
            # directory for the new run of this srid
            archivedir = '%s_%s' % (archivedir, int(time.time()))
        os.makedirs(archivedir)

        results_file = os.path.join(archivedir, 'results.json')
        with file(results_file, 'w') as f:
            json.dump(results, f)

        metadata = base64.b64decode(metadata_b64)
        metadata_file = os.path.join(archivedir, 'metadata.zip')
        with file(metadata_file, 'wb') as f:
            f.write(metadata)

    def handle(self, srid, results, metadata_b64):
        logging.debug('uploading results for %s' % (srid,))

        for name in results:
            dataset = results[name]
            if not isinstance(dataset, dict):
                # This one is crap, ignore it
                logging.error('bad json: %s' % (contents,))
                continue

            if self.unittest:
                logging.debug('would upload data via https to %s, project %s' %
                        (self.host, self.project))
                logging.debug('dataset: %s' % (dataset,))
            else:
                logging.debug('uploading data')
                request = dzclient.DatazillaRequest('https', self.host,
                        self.project, self.key, self.secret)
                response = request.send(dataset)
                logging.debug('got status code %s' % (response.status,))
                if response.status != 200:
                    logging.error('bad http status %s for %s' % (response.status, srid))

                try:
                    result = json.load(response)
                except:
                    result = ''
                logging.debug('got result %s' % (result,))
                if result['status'] != 'well-formed JSON stored':
                    logging.error('bad status for %s: %s' % (srid, result['status']))

        self.save_data(srid, results, metadata_b64)

def daemon():
    reporter = StoneRidgeReporter(stoneridge.OUTGOING_QUEUE)
    reporter.run()

@stoneridge.main
def main():
    parser = stoneridge.DaemonArgumentParser()
    args = parser.parse_args()

    parser.start_daemon(daemon)
<|endoftext|>


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

'''
This code was inspired by the third python coding example on
http://picamera.readthedocs.io/en/release-1.10/recipes1.html#recording-to-a-network-stream
However, multiple customizations were applied and thus only the basic setup is
identical.

2017 Strahlenschutzkommando@Github
'''

import socket
import picamera

with picamera.PiCamera() as cam:
    cam.resolution = (960, 720)
    cam.framerate = 1/60

    server_socket = socket.socket()
    server_socket.bind(('0.0.0.0', 8000))
    server_socket.listen(0)

    # Accept exactly one connection once and convert stream to file-like object
    connection = server_socket.accept()[0].makefile('wb')
    try:
        cam.start_recording(connection, format='h264')
        cam.wait_recording(60)
        cam.stop_recording()
    finally:
        connection.close()
        server_socket.close()
<commit_msg>Added in-line license information in main script file @streamPiCam.py: @l.10<commit_after>#!/usr/bin/env python3

'''
This code was inspired by the third python coding example on
http://picamera.readthedocs.io/en/release-1.10/recipes1.html#recording-to-a-network-stream
However, multiple customizations were applied and thus only the basic setup is
identical.

Availible under the MIT license.
2017 Strahlenschutzkommando@Github
'''

import socket
import picamera

with picamera.PiCamera() as cam:
    cam.resolution = (960, 720)
    cam.framerate = 1/60

    server_socket = socket.socket()
    server_socket.bind(('0.0.0.0', 8000))
    server_socket.listen(0)

    # Accept exactly one connection once and convert stream to file-like object
    connection = server_socket.accept()[0].makefile('wb')
    try:
        cam.start_recording(connection, format='h264')
        cam.wait_recording(60)
        cam.stop_recording()
    finally:
        connection.close()
        server_socket.close()
<|endoftext|>


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

import os
import time
import tempfile

from fs.osfs import OSFS
from fs.errors import *

class TempFS(OSFS):

    """Create a Filesystem in a tempory directory (with tempfile.mkdtemp),
    and removes it when the TempFS object is cleaned up."""

    def __init__(self, identifier=None, temp_dir=None, dir_mode=0700, thread_synchronize=True):
        """Creates a temporary Filesystem

        identifier -- A string that is included in the name of the temporary directory,
        default uses "TempFS"

        """
        self._temp_dir = tempfile.mkdtemp(identifier or "TempFS",dir=temp_dir)
        self._cleaned = False
        OSFS.__init__(self, self._temp_dir, dir_mode=dir_mode, thread_synchronize=thread_synchronize)

    def __str__(self):
        return '<TempFS: %s>' % self._temp_dir

    __repr__ = __str__

    def __unicode__(self):
        return unicode(self.__str__())

    def close(self):
        """Removes the temporary directory.

        This will be called automatically when the object is cleaned up by
        Python. Note that once this method has been called, the FS object may
        no longer be used.
        """
        #  Depending on how resources are freed by the OS, there could
        #  be some transient errors when freeing a TempFS soon after it
        #  was used.  If they occur, do a small sleep and try again.
        try:
            self._close()
        except (ResourceLockedError,ResourceInvalidError):
            time.sleep(0.5)
            self._close()

    @convert_os_errors
    def _close(self):
        """Actual implementation of close().

        This is a separate method so it can be re-tried in the face of
        transient errors.
        """
        if not self._cleaned and self.exists("/"):
            self._lock.acquire()
            try:
                # shutil.rmtree doesn't handle long paths on win32,
                # so we walk the tree by hand.
                entries = os.walk(self.root_path,topdown=False)
                for (dir,dirnames,filenames) in entries:
                    for filename in filenames:
                        os.remove(os.path.join(dir,filename))
                    for dirname in dirnames:
                        os.rmdir(os.path.join(dir,dirname))
                os.rmdir(self.root_path)
                self._cleaned = True
            finally:
                self._lock.release()
        super(TempFS,self).close()

<commit_msg>TempFS.close:  more robust deletion in the face of simultaneous closes<commit_after>#!/usr/bin/env python

import os
import time
import tempfile

from fs.osfs import OSFS
from fs.errors import *

class TempFS(OSFS):

    """Create a Filesystem in a tempory directory (with tempfile.mkdtemp),
    and removes it when the TempFS object is cleaned up."""

    def __init__(self, identifier=None, temp_dir=None, dir_mode=0700, thread_synchronize=True):
        """Creates a temporary Filesystem

        identifier -- A string that is included in the name of the temporary directory,
        default uses "TempFS"

        """
        self._temp_dir = tempfile.mkdtemp(identifier or "TempFS",dir=temp_dir)
        self._cleaned = False
        OSFS.__init__(self, self._temp_dir, dir_mode=dir_mode, thread_synchronize=thread_synchronize)

    def __str__(self):
        return '<TempFS: %s>' % self._temp_dir

    __repr__ = __str__

    def __unicode__(self):
        return unicode(self.__str__())

    def close(self):
        """Removes the temporary directory.

        This will be called automatically when the object is cleaned up by
        Python. Note that once this method has been called, the FS object may
        no longer be used.
        """
        #  Depending on how resources are freed by the OS, there could
        #  be some transient errors when freeing a TempFS soon after it
        #  was used.  If they occur, do a small sleep and try again.
        try:
            self._close()
        except (ResourceLockedError,ResourceInvalidError):
            time.sleep(0.5)
            self._close()

    @convert_os_errors
    def _close(self):
        """Actual implementation of close().

        This is a separate method so it can be re-tried in the face of
        transient errors.
        """
        os_remove = convert_os_errors(os.remove)
        os_rmdir = convert_os_errors(os.rmdir)
        if not self._cleaned and self.exists("/"):
            self._lock.acquire()
            try:
                # shutil.rmtree doesn't handle long paths on win32,
                # so we walk the tree by hand.
                entries = os.walk(self.root_path,topdown=False)
                for (dir,dirnames,filenames) in entries:
                    for filename in filenames:
                        try:
                            os_remove(os.path.join(dir,filename))
                        except ResourceNotFoundError:
                            pass
                    for dirname in dirnames:
                        try:
                            os_rmdir(os.path.join(dir,dirname))
                        except ResourceNotFoundError:
                            pass
                os.rmdir(self.root_path)
                self._cleaned = True
            finally:
                self._lock.release()
        super(TempFS,self).close()

<|endoftext|>


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

from osfs import OSFS
import tempfile
from shutil import rmtree

class TempFS(OSFS):

    """Create a Filesystem in a tempory directory (with tempfile.mkdtemp),
    and removes it when the TempFS object is cleaned up."""

    def __init__(self, identifier=None, temp_dir=None, dir_mode=0700, thread_synchronize=True):
        """Creates a temporary Filesystem

        identifier -- A string that is included in the name of the temporary directory,
        default uses "TempFS"

        """
        self._temp_dir = tempfile.mkdtemp(identifier or "TempFS",dir=temp_dir)
        self._cleaned = False
        OSFS.__init__(self, self._temp_dir, dir_mode=dir_mode, thread_synchronize=thread_synchronize)

    def __str__(self):
        return '<TempFS: %s>' % self._temp_dir

    __repr__ = __str__

    def __unicode__(self):
        return unicode(self.__str__())

    def close(self):
        """Removes the temporary directory.
        This will be called automatically when the object is cleaned up by Python.
        Note that once this method has been called, the FS object may no longer be used."""

        if not self._cleaned and self.exists("/"):
            self._lock.acquire()
            try:
                rmtree(self._temp_dir)
                self._cleaned = True
            finally:
                self._lock.release()

    def __del__(self):
        self.close()

<commit_msg>documentation formatting cleanup<commit_after>#!/usr/bin/env python

from osfs import OSFS
import tempfile
from shutil import rmtree

class TempFS(OSFS):

    """Create a Filesystem in a tempory directory (with tempfile.mkdtemp),
    and removes it when the TempFS object is cleaned up."""

    def __init__(self, identifier=None, temp_dir=None, dir_mode=0700, thread_synchronize=True):
        """Creates a temporary Filesystem

        identifier -- A string that is included in the name of the temporary directory,
        default uses "TempFS"

        """
        self._temp_dir = tempfile.mkdtemp(identifier or "TempFS",dir=temp_dir)
        self._cleaned = False
        OSFS.__init__(self, self._temp_dir, dir_mode=dir_mode, thread_synchronize=thread_synchronize)

    def __str__(self):
        return '<TempFS: %s>' % self._temp_dir

    __repr__ = __str__

    def __unicode__(self):
        return unicode(self.__str__())

    def close(self):
        """Removes the temporary directory.
        This will be called automatically when the object is cleaned up by
        Python. Note that once this method has been called, the FS object may
        no longer be used.
        """
        if not self._cleaned and self.exists("/"):
            self._lock.acquire()
            try:
                rmtree(self._temp_dir)
                self._cleaned = True
            finally:
                self._lock.release()

    def __del__(self):
        self.close()

<|endoftext|>


<commit_before>##-*- coding: utf-8 -*-
#!/usr/bin/python
"""
Utilities related to String.
"""

__author__ = 'SeomGi, Han'
__credits__ = ['SeomGi, Han']
__copyright__ = 'Copyright 2015 SeomGi, Han, Python Utils Project'

__license__ = 'MIT'
__version__ = '1.0.1'
__maintainer__ = 'SeomGi, Han'
__email__ = 'iandmyhand@gmail.com'
__status__ = 'Production'

class NotSupportedException(Exception):

    def __init__(self, message, errors):
        super(NotSupportedException, self).__init__(message)
        self.errors = errors

class StringUtils:

    _string_value = ''
    _len_string_value = 0

    def __init__(self, string_value=''):
        self._string_value = str(string_value)
        self._len_string_value = len(self._string_value)

    def __del__(self):
        self._string_value = ''
        self._len_string_value = 0

    def extract_file_name(self):
        """
        usage:
            StringUtils('/path/to/filename.py').extract_file_name() returns 'filename.py'
        """
        result = ''
        if self._string_value:
            arr = self._string_value.split('/')
            result += arr[len(arr) - 1]

        return result

    def extract_extension(self):
        """
        usage:
            StringUtils('/path/to/filename.py').extract_extension() returns 'py'
        """
        arr = self._string_value.split('.')
        extension = arr[len(arr) - 1]
        return extension

    def extract_directory(self):
        """
        usage:
            StringUtils('/path/to/filename.py').extract_extension() returns '/path/to/'
        """
        return self._string_value[:self._string_value.rfind('/') + 1]

    def get_content_type(self):
        """
        usage:
            StringUtils('filename.png').get_content_type() returns 'image/png'
        """
        extension = self.extract_extension()
        if 'png' == extension:
            return 'image/png'
        elif 'jpg' == extension:
            return 'image/jpg'
        elif 'jpeg' == extension:
            return 'image/jpeg'
        elif 'gif' == extension:
            return 'image/gif'
        elif 'bmp' == extension:
            return 'image/bmp'
        elif 'tif' == extension or 'tiff' == extension:
            return 'image/tiff'
        elif 'pdf' == extension:
            return 'application/pdf'
        elif 'zip' == extension:
            return 'application/zip'

        raise NotSupportedException(
            message='This extension[' + str(extension) + '] is not supported.',
            errors={'code': 'NOT_SUPPORTED_EXTENSION'})
<commit_msg>Add exclude_extension function and some test cases.<commit_after>##-*- coding: utf-8 -*-
#!/usr/bin/python
"""
Utilities related to String.
"""
import unittest

__author__ = 'SeomGi, Han'
__credits__ = ['SeomGi, Han']
__copyright__ = 'Copyright 2015 SeomGi, Han, Python Utils Project'

__license__ = 'MIT'
__version__ = '1.0.2'
__maintainer__ = 'SeomGi, Han'
__email__ = 'iandmyhand@gmail.com'
__status__ = 'Production'

class NotSupportedException(Exception):

    def __init__(self, message, errors):
        super(NotSupportedException, self).__init__(message)
        self.errors = errors

class TestStringUtils(unittest.TestCase):

    def test_extract_file_name(self):
        self.assertTrue('filename.py' == StringUtils('/path/to/filename.py').extract_file_name())

    def test_extract_extension(self):
        self.assertTrue('py' == StringUtils('/path/to/filename.py').extract_extension())

    def test_exclude_extension(self):
        self.assertTrue('filename' == StringUtils('filename.py').exclude_extension())

    def test_extract_directory(self):
        self.assertTrue('/path/to/' == StringUtils('/path/to/filename.py').extract_directory())

    def test_get_content_type(self):
        self.assertTrue('image/png' == StringUtils('filename.png').get_content_type())

class StringUtils:

    _string_value = ''
    _len_string_value = 0

    def __init__(self, string_value=''):
        self._string_value = str(string_value)
        self._len_string_value = len(self._string_value)

    def __del__(self):
        self._string_value = ''
        self._len_string_value = 0

    def extract_file_name(self):
        """
        usage:
            StringUtils('/path/to/filename.py').extract_file_name() returns 'filename.py'
        """
        result = ''
        if self._string_value:
            arr = self._string_value.split('/')
            result += arr[len(arr) - 1]

        return result

    def extract_extension(self):
        """
        usage:
            StringUtils('/path/to/filename.py').extract_extension() returns 'py'
        """
        arr = self._string_value.split('.')
        extension = arr[len(arr) - 1]
        return extension

    def exclude_extension(self):
        """
        usage:
            StringUtils('filename.py').exclude_extension() returns 'filename'
        """
        extension = self.extract_extension()
        if not extension:
            return None
        arr = self._string_value.split(extension)
        filename = arr[0][:-1]
        return filename

    def extract_directory(self):
        """
        usage:
            StringUtils('/path/to/filename.py').extract_extension() returns '/path/to/'
        """
        return self._string_value[:self._string_value.rfind('/') + 1]

    def get_content_type(self):
        """
        usage:
            StringUtils('filename.png').get_content_type() returns 'image/png'
        """
        extension = self.extract_extension()
        if 'png' == extension:
            return 'image/png'
        elif 'jpg' == extension:
            return 'image/jpg'
        elif 'jpeg' == extension:
            return 'image/jpeg'
        elif 'gif' == extension:
            return 'image/gif'
        elif 'bmp' == extension:
            return 'image/bmp'
        elif 'tif' == extension or 'tiff' == extension:
            return 'image/tiff'
        elif 'pdf' == extension:
            return 'application/pdf'
        elif 'zip' == extension:
            return 'application/zip'

        raise NotSupportedException(
            message='This extension[' + str(extension) + '] is not supported.',
            errors={'code': 'NOT_SUPPORTED_EXTENSION'})

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>"""
This module contains variables with global |jedi| setting. To change the
behavior of |jedi|, change the variables defined in
:mod:`jedi.settings`.

Plugins should expose an interface so that the user can adjust the
configuration.

Example usage::

    from jedi import settings
    settings.case_insensitive_completion = True

Completion output
~~~~~~~~~~~~~~~~~

.. autodata:: case_insensitive_completion
.. autodata:: add_dot_after_module
.. autodata:: add_bracket_after_function
.. autodata:: no_completion_duplicates

Filesystem cache
~~~~~~~~~~~~~~~~

.. autodata:: jedi_cache_directory
.. autodata:: use_fs_cache

Parser
~~~~~~

.. autodata:: fast_parser
.. autodata:: fast_parser_always_reparse
.. autodata:: use_get_in_function_call_cache

Dynamic stuff
~~~~~~~~~~~~~

.. autodata:: dynamic_arrays_instances
.. autodata:: dynamic_array_additions
.. autodata:: dynamic_params
.. autodata:: dynamic_params_for_other_modules
.. autodata:: additional_dynamic_modules

Recursions
~~~~~~~~~~

Recursion settings are important if you don't want extremly
recursive python code to go absolutely crazy. First of there is a
global limit :data:`max_executions`. This limit is important, to set
a maximum amount of time, the completion may use.

The default values are based on experiments while completing the |jedi| library
itself (inception!). But I don't think there's any other Python library that
uses recursion in a similarly extreme way. These settings make the completion
definitely worse in some cases. But a completion should also be fast.

.. autodata:: max_until_execution_unique
.. autodata:: max_function_recursion_level
.. autodata:: max_executions_without_builtins
.. autodata:: max_executions
.. autodata:: scale_get_in_function_call

Caching
~~~~~~~

.. autodata:: star_import_cache_validity
.. autodata:: get_in_function_call_validity

Various
~~~~~~~

.. autodata:: part_line_length

"""

# ----------------
# completion output settings
# ----------------

case_insensitive_completion = True
"""
The completion is by default case insensitive.
"""

add_dot_after_module = False
"""
Adds a dot after a module, because a module that is not accessed this way is
definitely not the normal case. However, in VIM this doesn't work, that's why
it isn't used at the moment.
"""

add_bracket_after_function = False
"""
Adds an opening bracket after a function, because that's normal behaviour.
Removed it again, because in VIM that is not very practical.
"""

no_completion_duplicates = True
"""
If set, completions with the same name don't appear in the output anymore,
but are in the `same_name_completions` attribute.
"""

# ----------------
# Filesystem cache
# ----------------

use_filesystem_cache = True
"""
Use filesystem cache to save once parsed files with pickle.
"""

jedi_cache_directory = '~/.jedi'
"""
The path where all the caches can be found.
"""

# ----------------
# parser
# ----------------

fast_parser = True
"""
Use the fast parser. This means that reparsing is only being done if
something has been changed e.g. to a function. If this happens, only the
function is being reparsed.
"""

fast_parser_always_reparse = False
"""
This is just a debugging option. Always reparsing means that the fast parser
is basically useless. So don't use it.
"""

use_get_in_function_call_cache = True
"""
Use the cache (full cache) to generate get_in_function_call's. This may fail
with multiline docstrings (likely) and other complicated changes (unlikely).
The goal is to move away from it by making the rest faster.
"""

# ----------------
# dynamic stuff
# ----------------

dynamic_arrays_instances = True
"""
Check for `append`, etc. on array instances like list()
"""

dynamic_array_additions = True
"""
check for `append`, etc. on arrays: [], {}, ()
"""

dynamic_params = True
"""
A dynamic param completion, finds the callees of the function, which define
the params of a function.
"""

dynamic_params_for_other_modules = True
"""
Do the same for other modules.
"""

additional_dynamic_modules = []
"""
Additional modules in which |jedi| checks if statements are to be found. This
is practical for IDEs, that want to administrate their modules themselves.
"""

# ----------------
# recursions
# ----------------

max_until_execution_unique = 50
"""
This limit is probably the most important one, because if this limit is
exceeded, functions can only be one time executed. So new functions will be
executed, complex recursions with the same functions again and again, are
ignored.
"""

max_function_recursion_level = 5
"""
`max_function_recursion_level` is more about whether the recursions are
stopped in deepth or in width. The ratio beetween this and
`max_until_execution_unique` is important here. It stops a recursion (after
the number of function calls in the recursion), if it was already used
earlier.
"""

max_executions_without_builtins = 200
"""
.. todo:: Document this.
"""

max_executions = 250
"""
A maximum amount of time, the completion may use.
"""

scale_get_in_function_call = 0.1
"""
Because get_in_function_call is normally used on every single key hit, it has
to be faster than a normal completion. This is the factor that is used to
scale `max_executions` and `max_until_execution_unique`:
"""

# ----------------
# various
# ----------------

part_line_length = 20
"""
Size of the current code part, which is used to speed up parsing.
"""

# ----------------
# caching validity (time)
# ----------------

star_import_cache_validity = 60.0
"""
In huge packages like numpy, checking all star imports on every completion
might be slow, therefore we do a star import caching, that lasts a certain
time span (in seconds).
"""

get_in_function_call_validity = 3.0
"""
Finding function calls might be slow (0.1-0.5s). This is not acceptible for
normal writing. Therefore cache it for a short time.
"""
<commit_msg>default directory for parser caches: HOME, #102<commit_after>"""
This module contains variables with global |jedi| setting. To change the
behavior of |jedi|, change the variables defined in
:mod:`jedi.settings`.

Plugins should expose an interface so that the user can adjust the
configuration.

Example usage::

    from jedi import settings
    settings.case_insensitive_completion = True

Completion output
~~~~~~~~~~~~~~~~~

.. autodata:: case_insensitive_completion
.. autodata:: add_dot_after_module
.. autodata:: add_bracket_after_function
.. autodata:: no_completion_duplicates

Filesystem cache
~~~~~~~~~~~~~~~~

.. autodata:: jedi_cache_directory
.. autodata:: use_fs_cache

Parser
~~~~~~

.. autodata:: fast_parser
.. autodata:: fast_parser_always_reparse
.. autodata:: use_get_in_function_call_cache

Dynamic stuff
~~~~~~~~~~~~~

.. autodata:: dynamic_arrays_instances
.. autodata:: dynamic_array_additions
.. autodata:: dynamic_params
.. autodata:: dynamic_params_for_other_modules
.. autodata:: additional_dynamic_modules

Recursions
~~~~~~~~~~

Recursion settings are important if you don't want extremly
recursive python code to go absolutely crazy. First of there is a
global limit :data:`max_executions`. This limit is important, to set
a maximum amount of time, the completion may use.

The default values are based on experiments while completing the |jedi| library
itself (inception!). But I don't think there's any other Python library that
uses recursion in a similarly extreme way. These settings make the completion
definitely worse in some cases. But a completion should also be fast.

.. autodata:: max_until_execution_unique
.. autodata:: max_function_recursion_level
.. autodata:: max_executions_without_builtins
.. autodata:: max_executions
.. autodata:: scale_get_in_function_call

Caching
~~~~~~~

.. autodata:: star_import_cache_validity
.. autodata:: get_in_function_call_validity

Various
~~~~~~~

.. autodata:: part_line_length

"""

# ----------------
# completion output settings
# ----------------

case_insensitive_completion = True
"""
The completion is by default case insensitive.
"""

add_dot_after_module = False
"""
Adds a dot after a module, because a module that is not accessed this way is
definitely not the normal case. However, in VIM this doesn't work, that's why
it isn't used at the moment.
"""

add_bracket_after_function = False
"""
Adds an opening bracket after a function, because that's normal behaviour.
Removed it again, because in VIM that is not very practical.
"""

no_completion_duplicates = True
"""
If set, completions with the same name don't appear in the output anymore,
but are in the `same_name_completions` attribute.
"""

# ----------------
# Filesystem cache
# ----------------

use_filesystem_cache = True
"""
Use filesystem cache to save once parsed files with pickle.
"""

import os
jedi_cache_directory = os.getenv('HOME') + os.path.sep + '~/.jedi'
"""
The path where all the caches can be found.
"""

# ----------------
# parser
# ----------------

fast_parser = True
"""
Use the fast parser. This means that reparsing is only being done if
something has been changed e.g. to a function. If this happens, only the
function is being reparsed.
"""

fast_parser_always_reparse = False
"""
This is just a debugging option. Always reparsing means that the fast parser
is basically useless. So don't use it.
"""

use_get_in_function_call_cache = True
"""
Use the cache (full cache) to generate get_in_function_call's. This may fail
with multiline docstrings (likely) and other complicated changes (unlikely).
The goal is to move away from it by making the rest faster.
"""

# ----------------
# dynamic stuff
# ----------------

dynamic_arrays_instances = True
"""
Check for `append`, etc. on array instances like list()
"""

dynamic_array_additions = True
"""
check for `append`, etc. on arrays: [], {}, ()
"""

dynamic_params = True
"""
A dynamic param completion, finds the callees of the function, which define
the params of a function.
"""

dynamic_params_for_other_modules = True
"""
Do the same for other modules.
"""

additional_dynamic_modules = []
"""
Additional modules in which |jedi| checks if statements are to be found. This
is practical for IDEs, that want to administrate their modules themselves.
"""

# ----------------
# recursions
# ----------------

max_until_execution_unique = 50
"""
This limit is probably the most important one, because if this limit is
exceeded, functions can only be one time executed. So new functions will be
executed, complex recursions with the same functions again and again, are
ignored.
"""

max_function_recursion_level = 5
"""
`max_function_recursion_level` is more about whether the recursions are
stopped in deepth or in width. The ratio beetween this and
`max_until_execution_unique` is important here. It stops a recursion (after
the number of function calls in the recursion), if it was already used
earlier.
"""

max_executions_without_builtins = 200
"""
.. todo:: Document this.
"""

max_executions = 250
"""
A maximum amount of time, the completion may use.
"""

scale_get_in_function_call = 0.1
"""
Because get_in_function_call is normally used on every single key hit, it has
to be faster than a normal completion. This is the factor that is used to
scale `max_executions` and `max_until_execution_unique`:
"""

# ----------------
# various
# ----------------

part_line_length = 20
"""
Size of the current code part, which is used to speed up parsing.
"""

# ----------------
# caching validity (time)
# ----------------

star_import_cache_validity = 60.0
"""
In huge packages like numpy, checking all star imports on every completion
might be slow, therefore we do a star import caching, that lasts a certain
time span (in seconds).
"""

get_in_function_call_validity = 3.0
"""
Finding function calls might be slow (0.1-0.5s). This is not acceptible for
normal writing. Therefore cache it for a short time.
"""
<|endoftext|>


<commit_before>import jsonfield
from django.db import models
from modeltree.tree import trees
from . import parsers

class AbstractDataContext(models.Model):
    """JSON object representing one or more data field conditions. The data may
    be a single condition, an array of conditions or a tree stucture.

    This corresponds to the `WHERE` statements in a SQL query.
    """
    json = jsonfield.JSONField(null=True, blank=True, default=dict,
        validators=[parsers.datacontext.validate])
    count = models.IntegerField(null=True, db_column='_count')

    class Meta(object):
        abstract = True

    def _combine(self, other, operator):
        if not isinstance(other, self.__class__):
            raise TypeError('Other object must be a DataContext instance')
        cxt = self.__class__()
        cxt.user_id = self.user_id or other.user_id
        if self.json and other.json:
            cxt.json = {
                'type': operator,
                'children': [
                    {'id': self.pk, 'composite': True},
                    {'id': other.pk, 'composite': True}
                ]
            }
        elif self.json:
            cxt.json = {'id': self.pk, 'composite': True}
        elif other.json:
            cxt.json = {'id': other.pk, 'composite': True}
        return cxt

    def __and__(self, other):
        return self._combine(other, 'and')

    def __or__(self, other):
        return self._combine(other, 'or')

    @property
    def model(self):
        "The model this context represents with respect to the count."
        if self.count is not None:
            return trees.default.root_model

    @classmethod
    def validate(cls, attrs, **context):
        "Validate `attrs` as a context."
        parsers.datacontext.validate(attrs, **context)

    def parse(self, tree=None, **context):
        "Returns a parsed node for this context."
        return parsers.datacontext.parse(self.json, tree=tree, **context)

    def apply(self, queryset=None, tree=None, **context):
        "Applies this context to a QuerySet."
        if tree is None and queryset is not None:
            tree = queryset.model
        return self.parse(tree=tree, **context).apply(queryset=queryset)

    def language(self, tree=None, **context):
        return self.parse(tree=tree, **context).language

class AbstractDataView(models.Model):
    """JSON object representing one or more data field conditions. The data may
    be a single condition, an array of conditions or a tree stucture.

    This corresponds to the `SELECT` and `ORDER BY` statements in a SQL query.
    """
    json = jsonfield.JSONField(null=True, blank=True, default=dict,
        validators=[parsers.dataview.validate])
    count = models.IntegerField(null=True, db_column='_count')

    class Meta(object):
        abstract = True

    @classmethod
    def validate(cls, attrs, **context):
        "Validates `attrs` as a view."
        parsers.dataview.validate(attrs, **context)

    def parse(self, tree=None, **context):
        "Returns a parsed node for this view."
        return parsers.dataview.parse(self.json, tree=tree, **context)

    def apply(self, queryset=None, tree=None, include_pk=True, **context):
        "Applies this context to a QuerySet."
        if tree is None and queryset is not None:
            tree = queryset.model
        return self.parse(tree=tree, **context).apply(queryset=queryset,
            include_pk=include_pk)
<commit_msg>Fix AbstractDataContext __or__ and __and__ hooks<commit_after>import jsonfield
from django.db import models
from modeltree.tree import trees
from . import parsers

class AbstractDataContext(models.Model):
    """JSON object representing one or more data field conditions. The data may
    be a single condition, an array of conditions or a tree stucture.

    This corresponds to the `WHERE` statements in a SQL query.
    """
    json = jsonfield.JSONField(null=True, blank=True, default=dict,
        validators=[parsers.datacontext.validate])
    count = models.IntegerField(null=True, db_column='_count')

    class Meta(object):
        abstract = True

    def _combine(self, other, operator):
        if not isinstance(other, self.__class__):
            raise TypeError('Other object must be a DataContext instance')
        cxt = self.__class__()
        cxt.user_id = self.user_id or other.user_id
        if self.json and other.json:
            cxt.json = {
                'type': operator,
                'children': [
                    {'composite': self.pk},
                    {'composite': other.pk}
                ]
            }
        elif self.json:
            cxt.json = {'composite': self.pk}
        elif other.json:
            cxt.json = {'composite': other.pk}
        return cxt

    def __and__(self, other):
        return self._combine(other, 'and')

    def __or__(self, other):
        return self._combine(other, 'or')

    @property
    def model(self):
        "The model this context represents with respect to the count."
        if self.count is not None:
            return trees.default.root_model

    @classmethod
    def validate(cls, attrs, **context):
        "Validate `attrs` as a context."
        parsers.datacontext.validate(attrs, **context)

    def parse(self, tree=None, **context):
        "Returns a parsed node for this context."
        return parsers.datacontext.parse(self.json, tree=tree, **context)

    def apply(self, queryset=None, tree=None, **context):
        "Applies this context to a QuerySet."
        if tree is None and queryset is not None:
            tree = queryset.model
        return self.parse(tree=tree, **context).apply(queryset=queryset)

    def language(self, tree=None, **context):
        return self.parse(tree=tree, **context).language

class AbstractDataView(models.Model):
    """JSON object representing one or more data field conditions. The data may
    be a single condition, an array of conditions or a tree stucture.

    This corresponds to the `SELECT` and `ORDER BY` statements in a SQL query.
    """
    json = jsonfield.JSONField(null=True, blank=True, default=dict,
        validators=[parsers.dataview.validate])
    count = models.IntegerField(null=True, db_column='_count')

    class Meta(object):
        abstract = True

    @classmethod
    def validate(cls, attrs, **context):
        "Validates `attrs` as a view."
        parsers.dataview.validate(attrs, **context)

    def parse(self, tree=None, **context):
        "Returns a parsed node for this view."
        return parsers.dataview.parse(self.json, tree=tree, **context)

    def apply(self, queryset=None, tree=None, include_pk=True, **context):
        "Applies this context to a QuerySet."
        if tree is None and queryset is not None:
            tree = queryset.model
        return self.parse(tree=tree, **context).apply(queryset=queryset,
            include_pk=include_pk)
<|endoftext|>