<commit_before># -*- coding: utf-8 -*-
# Django settings for demo project.
import os
import sys

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

sys.path.insert(0, os.path.dirname(__file__))

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'db.sqlite',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en'

LANGUAGES = (
    ('en', 'English'),
    ('fr', 'Français'),
)

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '-ts#o*zbf9!8yz$+c_)43cd#+pts6m=1n+x65@kcgz3!5i@#))'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'demo.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'demo.wsgi.application'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'mail_factory',
    'comments',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}
<commit_msg>Added prefix for unicode strings in demo settings.py<commit_after># -*- coding: utf-8 -*-
# Django settings for demo project.
import os
import sys

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

sys.path.insert(0, os.path.dirname(__file__))

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'db.sqlite',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en'

LANGUAGES = (
    ('en', u'English'),
    ('fr', u'Français'),
)

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '-ts#o*zbf9!8yz$+c_)43cd#+pts6m=1n+x65@kcgz3!5i@#))'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'demo.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'demo.wsgi.application'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'mail_factory',
    'comments',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}
<|endoftext|>


<commit_before>from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
import xadmin

from xadmin.plugins import xversion
xversion.register_models()

from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^', include(xadmin.site.urls))
]
<commit_msg>删除　patterns<commit_after>from django.conf.urls import include, url

# Uncomment the next two lines to enable the admin:
import xadmin

from xadmin.plugins import xversion
xversion.register_models()

from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^', include(xadmin.site.urls))
]
<|endoftext|>


<commit_before>from typing import List
from OpenGL import GL
from demosys.opengl import Texture2D, DepthTexture
from demosys import context

WINDOW_FBO = None

class WindowFBO:
    """Fake FBO representing default render target"""
    def __init__(self, window):
        self.window = window

    def bind(self):
        """Sets the viewport back to the buffer size of the screen/window"""
        # The expected height with the current viewport width
        expected_height = int(self.window.buffer_width / self.window.aspect_ratio)
        # How much positive or negative y padding
        blank_space = self.window.buffer_height - expected_height

        GL.glViewport(0, int(blank_space / 2),
                      self.window.buffer_width, expected_height)

    def release(self):
        """Dummy release method"""
        pass

    def clear(self):
        """Dummy clear method"""
        pass

class FBO:
    """Frame buffer object"""
    stack = []

    def __init__(self):
        self.color_buffers = []
        self.depth_buffer = None
        self.fbo = None

    @staticmethod
    def create_from_textures(color_buffers: List[Texture2D], depth_buffer: DepthTexture=None):
        """
        Create FBO from existing textures

        :param color_buffers: List of textures
        :param depth_buffer: Depth texture

        :return: FBO instance
        """
        instance = FBO()
        instance.color_buffers = color_buffers
        instance.depth_buffer = depth_buffer

        instance.fbo = context.ctx().framebuffer(
            [b.mgl_instance for b in color_buffers],
            depth_buffer.mgl_instance
        )

        return instance

    @staticmethod
    def create(size, components, depth=False, dtype='f1', layers=1):
        """
        Create a single or multi layer FBO

        :param size: (tuple) with and height
        :param components: (tuple) number of components. 1, 2, 3, 4
        :param depth: (bool) Create a depth attachment
        :param layers: (int) number of color attachments

        :return: A new FBO
        """
        instance = FBO()

        # Add N layers of color attachments
        for layer in range(layers):
            c = Texture2D.create(size, components, dtype=dtype)
            instance.color_buffers.append(c)

        # Set depth attachment is specified
        if depth:
            instance.depth_buffer = DepthTexture(size)

        instance.fbo = context.ctx().framebuffer(
            [b.mgl_instance for b in instance.color_buffers],
            instance.depth_buffer.mgl_instance
        )

        return instance

    @property
    def size(self):
        """
        Attempts to determine the pixel size of the FBO.
        Currently returns the size of the first color attachment.
        If the FBO has no color attachments, the depth attachment will be used.
        Raises ```FBOError`` if the size cannot be determined.

        :return: (w, h) tuple representing the size in pixels
        """
        # FIXME: How do we deal with attachments of different sizes?
        if self.color_buffers:
            return self.color_buffers[0].size

        if self.depth_buffer:
            return self.depth_buffer.size

        raise FBOError("Cannot determine size of FBO. No attachments.")

    def __enter__(self):
        """
        Entering context manager.
        This will bind the FBO and return itself.
        """
        self.bind()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        Exit context manager.
        This will release the FBO.
        """
        self.release()

    def bind(self, stack=True):
        """
        Bind FBO adding it to the stack.

        :param stack: (bool) If the bind should push the current FBO on the stack.
        """
        self.fbo.use()

        if not stack:
            return

        FBO.stack.append(self)

        if len(FBO.stack) > 8:
            raise FBOError("FBO stack overflow. You probably forgot to release a bind somewhere.")

    def release(self, stack=True):
        """
        Bind FBO popping it from the stack

        :param stack: (bool) If the bind should be popped form the FBO stack.
        """
        GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0)
        if not stack:
            return

        # Are we trying to release an FBO that is not bound?
        if not FBO.stack:
            raise FBOError("FBO stack is already empty. You are probably releasing a FBO twice or forgot to bind.")
        fbo_out = FBO.stack.pop()

        # Make sure we released this FBO and not some other random one
        if fbo_out != self:
            raise FBOError("Incorrect FBO release order")

        # Find the parent fbo
        if FBO.stack:
            parent = FBO.stack[-1]
        else:
            parent = WINDOW_FBO

        # Bind the parent FBO
        if parent:
            parent.bind()

    def clear(self):
        """
        Clears the FBO using ``glClear``.
        """
        self.fbo.clear()
        # self.bind()
        # GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT)
        # self.release()

    def draw_color_layer(self, layer=0, pos=(0.0, 0.0), scale=(1.0, 1.0)):
        """
        Draw a color layer in the FBO.
        :param layer: Layer ID
        :param pos: (tuple) offset x, y
        :param scale: (tuple) scale x, y
        """
        self.color_buffers[layer].draw(pos=pos, scale=scale)

    def draw_depth(self, near, far, pos=(0.0, 0.0), scale=(1.0, 1.0)):
        """
        Draw a depth buffer in the FBO.

        :param near: projection near.
        :param far: projection far.
        :param pos: (tuple) offset x, y
        :param scale: (tuple) scale x, y
        """
        self.depth_buffer.draw(near, far, pos=pos, scale=scale)

    # def check_status(self):
    #     """
    #     Checks the completeness of the FBO
    #     """
    #     status = GL.glCheckFramebufferStatus(GL.GL_FRAMEBUFFER)
    #     incomplete_states = {
    #         GL.GL_FRAMEBUFFER_UNSUPPORTED: "Framebuffer unsupported. Try another format.",
    #         GL.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: "Framebuffer incomplete attachment",
    #         GL.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: "Framebuffer missing attachment",
    #         GL.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: "Framebuffer unsupported dimension.",
    #         GL.GL_FRAMEBUFFER_INCOMPLETE_FORMATS: "Framebuffer incoplete formats.",
    #         GL.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: "Framebuffer incomplete draw buffer.",
    #         GL.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: "Framebuffer incomplete read buffer",
    #     }
    #     if status == GL.GL_FRAMEBUFFER_COMPLETE:
    #         return
    #     s = incomplete_states.get(status, "Unknown error")
    #     raise FBOError(s)

    def __repr__(self):
        return "<FBO {} color_attachments={} depth_attachement={}".format(
            self.fbo,
            self.color_buffers,
            self.depth_buffer,
        )

class FBOError(Exception):
    """Generic FBO Error"""
    pass
<commit_msg>FBO components optional<commit_after>from typing import List
from OpenGL import GL
from demosys.opengl import Texture2D, DepthTexture
from demosys import context

WINDOW_FBO = None

class WindowFBO:
    """Fake FBO representing default render target"""
    def __init__(self, window):
        self.window = window

    def bind(self):
        """Sets the viewport back to the buffer size of the screen/window"""
        # The expected height with the current viewport width
        expected_height = int(self.window.buffer_width / self.window.aspect_ratio)
        # How much positive or negative y padding
        blank_space = self.window.buffer_height - expected_height

        GL.glViewport(0, int(blank_space / 2),
                      self.window.buffer_width, expected_height)

    def release(self):
        """Dummy release method"""
        pass

    def clear(self):
        """Dummy clear method"""
        pass

class FBO:
    """Frame buffer object"""
    stack = []

    def __init__(self):
        self.color_buffers = []
        self.depth_buffer = None
        self.fbo = None

    @staticmethod
    def create_from_textures(color_buffers: List[Texture2D], depth_buffer: DepthTexture=None):
        """
        Create FBO from existing textures

        :param color_buffers: List of textures
        :param depth_buffer: Depth texture

        :return: FBO instance
        """
        instance = FBO()
        instance.color_buffers = color_buffers
        instance.depth_buffer = depth_buffer

        instance.fbo = context.ctx().framebuffer(
            [b.mgl_instance for b in color_buffers],
            depth_buffer.mgl_instance
        )

        return instance

    @staticmethod
    def create(size, components=4, depth=False, dtype='f1', layers=1):
        """
        Create a single or multi layer FBO

        :param size: (tuple) with and height
        :param components: (tuple) number of components. 1, 2, 3, 4
        :param depth: (bool) Create a depth attachment
        :param dtype: (string) data type per r, g, b, a ...
        :param layers: (int) number of color attachments

        :return: A new FBO
        """
        instance = FBO()

        # Add N layers of color attachments
        for layer in range(layers):
            c = Texture2D.create(size, components, dtype=dtype)
            instance.color_buffers.append(c)

        # Set depth attachment is specified
        if depth:
            instance.depth_buffer = DepthTexture(size)

        instance.fbo = context.ctx().framebuffer(
            [b.mgl_instance for b in instance.color_buffers],
            instance.depth_buffer.mgl_instance
        )

        return instance

    @property
    def size(self):
        """
        Attempts to determine the pixel size of the FBO.
        Currently returns the size of the first color attachment.
        If the FBO has no color attachments, the depth attachment will be used.
        Raises ```FBOError`` if the size cannot be determined.

        :return: (w, h) tuple representing the size in pixels
        """
        # FIXME: How do we deal with attachments of different sizes?
        if self.color_buffers:
            return self.color_buffers[0].size

        if self.depth_buffer:
            return self.depth_buffer.size

        raise FBOError("Cannot determine size of FBO. No attachments.")

    def __enter__(self):
        """
        Entering context manager.
        This will bind the FBO and return itself.
        """
        self.bind()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        Exit context manager.
        This will release the FBO.
        """
        self.release()

    def bind(self, stack=True):
        """
        Bind FBO adding it to the stack.

        :param stack: (bool) If the bind should push the current FBO on the stack.
        """
        self.fbo.use()

        if not stack:
            return

        FBO.stack.append(self)

        if len(FBO.stack) > 8:
            raise FBOError("FBO stack overflow. You probably forgot to release a bind somewhere.")

    def release(self, stack=True):
        """
        Bind FBO popping it from the stack

        :param stack: (bool) If the bind should be popped form the FBO stack.
        """
        GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0)
        if not stack:
            return

        # Are we trying to release an FBO that is not bound?
        if not FBO.stack:
            raise FBOError("FBO stack is already empty. You are probably releasing a FBO twice or forgot to bind.")
        fbo_out = FBO.stack.pop()

        # Make sure we released this FBO and not some other random one
        if fbo_out != self:
            raise FBOError("Incorrect FBO release order")

        # Find the parent fbo
        if FBO.stack:
            parent = FBO.stack[-1]
        else:
            parent = WINDOW_FBO

        # Bind the parent FBO
        if parent:
            parent.bind()

    def clear(self):
        """
        Clears the FBO using ``glClear``.
        """
        self.fbo.clear()
        # self.bind()
        # GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT)
        # self.release()

    def draw_color_layer(self, layer=0, pos=(0.0, 0.0), scale=(1.0, 1.0)):
        """
        Draw a color layer in the FBO.
        :param layer: Layer ID
        :param pos: (tuple) offset x, y
        :param scale: (tuple) scale x, y
        """
        self.color_buffers[layer].draw(pos=pos, scale=scale)

    def draw_depth(self, near, far, pos=(0.0, 0.0), scale=(1.0, 1.0)):
        """
        Draw a depth buffer in the FBO.

        :param near: projection near.
        :param far: projection far.
        :param pos: (tuple) offset x, y
        :param scale: (tuple) scale x, y
        """
        self.depth_buffer.draw(near, far, pos=pos, scale=scale)

    # def check_status(self):
    #     """
    #     Checks the completeness of the FBO
    #     """
    #     status = GL.glCheckFramebufferStatus(GL.GL_FRAMEBUFFER)
    #     incomplete_states = {
    #         GL.GL_FRAMEBUFFER_UNSUPPORTED: "Framebuffer unsupported. Try another format.",
    #         GL.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: "Framebuffer incomplete attachment",
    #         GL.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: "Framebuffer missing attachment",
    #         GL.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: "Framebuffer unsupported dimension.",
    #         GL.GL_FRAMEBUFFER_INCOMPLETE_FORMATS: "Framebuffer incoplete formats.",
    #         GL.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: "Framebuffer incomplete draw buffer.",
    #         GL.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: "Framebuffer incomplete read buffer",
    #     }
    #     if status == GL.GL_FRAMEBUFFER_COMPLETE:
    #         return
    #     s = incomplete_states.get(status, "Unknown error")
    #     raise FBOError(s)

    def __repr__(self):
        return "<FBO {} color_attachments={} depth_attachement={}".format(
            self.fbo,
            self.color_buffers,
            self.depth_buffer,
        )

class FBOError(Exception):
    """Generic FBO Error"""
    pass
<|endoftext|>


<commit_before>import os
import textwrap

from fabric.api import put, sudo
from fabric.contrib.project import upload_project

def lazy(func):
    def wrapper(*args, **kwargs):
        return lambda: func(*args, **kwargs)
    return wrapper

def nginx_config(url, port, locations):
    config = """
        server {
            listen      %s;
            server_name %s;
            charset     utf-8;
            client_max_body_size 75M;

        %s
        }
    """

    l = '    location %s {%s}'
    locations = [l % (path, values) for path, values in locations.items()]
    config_txt = textwrap.dedent(config) % (port, url, '\n'.join(locations))
    return config_txt

@lazy
def install_nginx(nginx_file, id):
    put(nginx_file, '/etc/nginx/conf.d/depl_%s.conf' % id, use_sudo=True)
    # remove the default configuration
    sudo('rm /etc/nginx/sites-enabled/default || true')
    sudo('/etc/init.d/nginx restart')

@lazy
def move_project_to_www(local_path, remote_path):
    sudo('mkdir /var/www || true')
    depl_tmp = '/var/www/tmp_depl'
    sudo('mkdir %s || true' % depl_tmp)
    upload_project(local_path, depl_tmp, use_sudo=True)
    _, local_name = os.path.split(local_path)
    # delete all the files in the target directory that are also in the source
    # directory and move the source.
    sudo('ls -A {from_p} | xargs -I [] sh -c '
         '"rm -rf {to_p}/[] || true; mv {from_p}/[] {to_p}"'.format(
         from_p=os.path.join(depl_tmp, local_name), to_p=remote_path))
    sudo('rm -rf %s' % depl_tmp)
    sudo('chown -R www-data:www-data ' + remote_path)
<commit_msg>if deploy folder didn't exist (first deploy), deploy wouldn't work<commit_after>import os
import textwrap

from fabric.api import put, sudo
from fabric.contrib.project import upload_project

def lazy(func):
    def wrapper(*args, **kwargs):
        return lambda: func(*args, **kwargs)
    return wrapper

def nginx_config(url, port, locations):
    config = """
        server {
            listen      %s;
            server_name %s;
            charset     utf-8;
            client_max_body_size 75M;

        %s
        }
    """

    l = '    location %s {%s}'
    locations = [l % (path, values) for path, values in locations.items()]
    config_txt = textwrap.dedent(config) % (port, url, '\n'.join(locations))
    return config_txt

@lazy
def install_nginx(nginx_file, id):
    put(nginx_file, '/etc/nginx/conf.d/depl_%s.conf' % id, use_sudo=True)
    # remove the default configuration
    sudo('rm /etc/nginx/sites-enabled/default || true')
    sudo('/etc/init.d/nginx restart')

@lazy
def move_project_to_www(local_path, remote_path):
    sudo('mkdir /var/www || true')
    depl_tmp = '/var/www/tmp_depl'
    sudo('mkdir %s || true' % depl_tmp)
    upload_project(local_path, depl_tmp, use_sudo=True)
    _, local_name = os.path.split(local_path)
    # delete all the files in the target directory that are also in the source
    # directory and move the source.
    sudo('mkdir %s || true' % remote_path)
    sudo('ls -A {from_p} | xargs -I [] sh -c '
         '"rm -rf {to_p}/[] || true; mv {from_p}/[] {to_p}"'.format(
         from_p=os.path.join(depl_tmp, local_name), to_p=remote_path))
    sudo('rm -rf %s' % depl_tmp)
    sudo('chown -R www-data:www-data ' + remote_path)
<|endoftext|>


<commit_before>import os
from StringIO import StringIO
import textwrap

from fabric.api import put, sudo
from fabric.context_managers import cd, prefix

from depl.deploy._utils import nginx_config, install_nginx, move_project_to_www

def load(settings, package):
    remote_path = '/var/www/depl-' + settings['id']
    local_path = os.path.abspath('.')

    # python projects should always have a 'requirements.txt'.
    if not os.path.exists(os.path.join(local_path, 'requirements.txt')):
        raise LookupError("requirements.txt doesn't exist in your Python project (%s)."
                           % local_path)

    # configure nginx
    socket = remote_path + '/uwsgi.sock'
    uwsgi_nginx = "include uwsgi_params; uwsgi_pass unix:%s;" % socket

    locations = {'/': uwsgi_nginx}
    nginx_conf = nginx_config(settings['url'], settings['port'], locations)
    nginx_file = StringIO(nginx_conf)

    if settings['wsgi'] is None:
        raise ValueError("wsgi parameter needs to be defined to deploy python")
    uwsgi_file = _gen_uwsgi_file(settings['wsgi'], remote_path, socket)

    uwsgi_start_file = _gen_uwsgi_start_file(remote_path)

    def install_python():
        sudo('pip install virtualenv')
        with cd(remote_path):
            sudo('ls venv || virtualenv venv', user='www-data')
            with prefix('source venv/bin/activate'):
                sudo('pip install -r requirements.txt', user='www-data')
                sudo('pip install uwsgi', user='www-data')

    def setup_uwsgi():
        sudo('mkdir /etc/uwsgi && mkdir /etc/uwsgi/vassals || true')
        #logs
        sudo('mkdir /var/log/uwsgi || true')
        sudo('chown -R www-data:www-data /var/log/uwsgi')

        put(uwsgi_file, '/etc/uwsgi/vassals/depl-%s.ini' % settings['id'], use_sudo=True)
        put(uwsgi_start_file, '/etc/init/uwsgi.conf', use_sudo=True)
        sudo('service uwsgi restart')

    commands = [
        move_project_to_www(local_path, remote_path),
        install_python,
        setup_uwsgi,
        install_nginx(nginx_file, settings['id']),
    ]
    return ['pip', 'uwsgi-build-tools', 'nginx'], commands

def _gen_uwsgi_file(wsgi_file, remote_path, socket):
    # configure uwsgi
    uwsgi_config = """
    [uwsgi]
    #application's base folder
    base = {0}

    #python module to import
    app = {1}
    module = %(app)

    home = %(base)/venv
    pythonpath = %(base)

    #socket file's location
    socket = {2}

    #permissions for the socket file
    chmod-socket    = 666

    #the variable that holds a flask application inside the module imported at line #6
    callable = app

    #location of log files
    logto = /var/log/uwsgi/%n.log

    uid = www-data
    gid = www-data
    """.format(remote_path, wsgi_file, socket)

    uwsgi_file = StringIO(textwrap.dedent(uwsgi_config))
    return uwsgi_file

def _gen_uwsgi_start_file(remote_path):
    auto_start = """
    description "uWSGI"
    start on runlevel [2345]
    stop on runlevel [06]
    respawn

    env UWSGI=%s
    env LOGTO=/var/log/uwsgi/emperor.log

    exec $UWSGI --master --emperor /etc/uwsgi/vassals --die-on-term --uid www-data --gid www-data --logto $LOGTO
    """ % (remote_path + '/venv/bin/uwsgi')
    return StringIO(textwrap.dedent(auto_start))
<commit_msg>dynamic search for wsgi.py modules<commit_after>import os
from StringIO import StringIO
import textwrap

from fabric.api import put, sudo
from fabric.context_managers import cd, prefix

from depl.deploy._utils import nginx_config, install_nginx, move_project_to_www

def load(settings, package):
    remote_path = '/var/www/depl-' + settings['id']
    local_path = os.path.abspath('.')

    # python projects should always have a 'requirements.txt'.
    if not os.path.exists(os.path.join(local_path, 'requirements.txt')):
        raise LookupError("requirements.txt doesn't exist in your Python project (%s)."
                           % local_path)

    # configure nginx
    socket = remote_path + '/uwsgi.sock'
    uwsgi_nginx = "include uwsgi_params; uwsgi_pass unix:%s;" % socket

    locations = {'/': uwsgi_nginx}
    nginx_conf = nginx_config(settings['url'], settings['port'], locations)
    nginx_file = StringIO(nginx_conf)

    wsgi_path = settings['wsgi']
    if wsgi_path is None:
        # search for a file in the project named "wsgi"
        for root, dirnames, filenames in os.walk('.'):
            if not os.path.basename(root).startswith('.'):
                for filename in filenames:
                    if filename == 'wsgi.py':
                        p = os.path.join(root, filename)[2:-3]
                        wsgi_path = p.replace(os.path.sep, '.')
                        break
                if wsgi_path:
                    break
        else:
            raise ValueError('WSGI path not set and no file named wsgi.py in the project found')
    uwsgi_file = _gen_uwsgi_file(wsgi_path, remote_path, socket)

    uwsgi_start_file = _gen_uwsgi_start_file(remote_path)

    def install_python():
        sudo('pip install virtualenv')
        with cd(remote_path):
            sudo('ls venv || virtualenv venv', user='www-data')
            with prefix('source venv/bin/activate'):
                sudo('pip install -r requirements.txt', user='www-data')
                sudo('pip install uwsgi', user='www-data')

    def setup_uwsgi():
        sudo('mkdir /etc/uwsgi && mkdir /etc/uwsgi/vassals || true')
        #logs
        sudo('mkdir /var/log/uwsgi || true')
        sudo('chown -R www-data:www-data /var/log/uwsgi')

        put(uwsgi_file, '/etc/uwsgi/vassals/depl-%s.ini' % settings['id'], use_sudo=True)
        put(uwsgi_start_file, '/etc/init/uwsgi.conf', use_sudo=True)
        sudo('service uwsgi restart')

    commands = [
        move_project_to_www(local_path, remote_path),
        install_python,
        setup_uwsgi,
        install_nginx(nginx_file, settings['id']),
    ]
    return ['pip', 'uwsgi-build-tools', 'nginx'], commands

def _gen_uwsgi_file(wsgi_file, remote_path, socket):
    # configure uwsgi
    uwsgi_config = """
    [uwsgi]
    #application's base folder
    base = {0}

    #python module to import
    app = {1}
    module = %(app)

    home = %(base)/venv
    pythonpath = %(base)

    #socket file's location
    socket = {2}

    #permissions for the socket file
    chmod-socket    = 644

    #location of log files
    logto = /var/log/uwsgi/%n.log

    uid = www-data
    gid = www-data
    """.format(remote_path, wsgi_file, socket)

    uwsgi_file = StringIO(textwrap.dedent(uwsgi_config))
    return uwsgi_file

def _gen_uwsgi_start_file(remote_path):
    auto_start = """
    description "uWSGI"
    start on runlevel [2345]
    stop on runlevel [06]
    respawn

    env UWSGI=%s
    env LOGTO=/var/log/uwsgi/emperor.log

    exec $UWSGI --master --emperor /etc/uwsgi/vassals --die-on-term --uid www-data --gid www-data --logto $LOGTO
    """ % (remote_path + '/venv/bin/uwsgi')
    return StringIO(textwrap.dedent(auto_start))
<|endoftext|>


<commit_before>from abc import ABC, abstractmethod
from desc.backend import jnp
from desc.io import IOAble
from .utils import rotation_matrix, reflection_matrix

class Curve(IOAble, ABC):
    """Abstract base class for 1D curves in 3D space"""

    _io_attrs_ = ["_name", "_grid", "shift", "rotmat"]

    def __init__(self, name):
        self.shift = jnp.array([0, 0, 0])
        self.rotmat = jnp.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
        self.name = name

    @property
    def name(self):
        """Name of the curve."""
        return self._name

    @name.setter
    def name(self, new):
        self._name = new

    @property
    @abstractmethod
    def grid(self):
        """Default grid for computation"""

    @abstractmethod
    def compute_coordinates(self, params=None, grid=None, dt=0):
        """Compute real space coordinates on predefined grid"""

    @abstractmethod
    def compute_frenet_frame(self, params=None, grid=None):
        """Compute frenet frame on predefined grid"""

    @abstractmethod
    def compute_curvature(self, params=None, grid=None):
        """Compute curvature on predefined grid"""

    @abstractmethod
    def compute_torsion(self, params=None, grid=None):
        """Compute torsion on predefined grid"""

    @abstractmethod
    def compute_length(self, params=None, grid=None):
        """Compute the length of the curve using specified nodes for quadrature"""

    def translate(self, displacement=[0, 0, 0]):
        """Translate the curve by a rigid displacement in x, y, z"""
        self.shift += jnp.asarray(displacement)

    def rotate(self, axis=[0, 0, 1], angle=0):
        """Rotate the curve by a fixed angle about axis in xyz coordinates"""
        R = rotation_matrix(axis, angle)
        self.rotmat = R @ self.rotmat
        self.shift = self.shift @ R.T

    def flip(self, normal):
        """Flip the curve about the plane with specified normal"""
        F = reflection_matrix(normal)
        self.rotmat = F @ self.rotmat
        self.shift = self.shift @ F.T

class Surface(IOAble, ABC):
    """Abstract base class for 2d surfaces in 3d space,
    such as flux surfaces, plasma boundaries, poincare sections
    """

    _io_attrs_ = ["_name", "_grid", "_sym", "_L", "_M", "_N"]

    @property
    def name(self):
        """Name of the surface"""
        return self._name

    @name.setter
    def name(self, new):
        self._name = new

    @property
    def L(self):
        """maximum radial mode number"""
        return self._L

    @property
    def M(self):
        """maximum poloidal mode number"""
        return self._M

    @property
    def N(self):
        """maximum toroidal mode number"""
        return self._N

    @property
    def sym(self):
        """stellarator symmetry"""
        return self._sym

    @property
    @abstractmethod
    def grid(self):
        """Default grid for computation"""

    @abstractmethod
    def compute_coordinates(self, params=None, grid=None, dt=0, dz=0):
        """Compute coordinate values at specified nodes"""

    @abstractmethod
    def compute_normal(self, params=None, grid=None):
        """Compute normal vectors to the surface on predefined grid"""

    @abstractmethod
    def compute_surface_area(self, params=None, grids=None):
        """Compute surface area via quadrature"""

    @abstractmethod
    def compute_curvature(self, params=None, grid=None):
        """Compute gaussian and mean curvature"""
<commit_msg>Add string methods to curves and surfaces<commit_after>from abc import ABC, abstractmethod
from desc.backend import jnp
from desc.io import IOAble
from .utils import rotation_matrix, reflection_matrix

class Curve(IOAble, ABC):
    """Abstract base class for 1D curves in 3D space"""

    _io_attrs_ = ["_name", "_grid", "shift", "rotmat"]

    def __init__(self, name):
        self.shift = jnp.array([0, 0, 0])
        self.rotmat = jnp.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
        self.name = name

    @property
    def name(self):
        """Name of the curve."""
        return self._name

    @name.setter
    def name(self, new):
        self._name = new

    @property
    @abstractmethod
    def grid(self):
        """Default grid for computation"""

    @abstractmethod
    def compute_coordinates(self, params=None, grid=None, dt=0):
        """Compute real space coordinates on predefined grid"""

    @abstractmethod
    def compute_frenet_frame(self, params=None, grid=None):
        """Compute frenet frame on predefined grid"""

    @abstractmethod
    def compute_curvature(self, params=None, grid=None):
        """Compute curvature on predefined grid"""

    @abstractmethod
    def compute_torsion(self, params=None, grid=None):
        """Compute torsion on predefined grid"""

    @abstractmethod
    def compute_length(self, params=None, grid=None):
        """Compute the length of the curve using specified nodes for quadrature"""

    def translate(self, displacement=[0, 0, 0]):
        """Translate the curve by a rigid displacement in x, y, z"""
        self.shift += jnp.asarray(displacement)

    def rotate(self, axis=[0, 0, 1], angle=0):
        """Rotate the curve by a fixed angle about axis in xyz coordinates"""
        R = rotation_matrix(axis, angle)
        self.rotmat = R @ self.rotmat
        self.shift = self.shift @ R.T

    def flip(self, normal):
        """Flip the curve about the plane with specified normal"""
        F = reflection_matrix(normal)
        self.rotmat = F @ self.rotmat
        self.shift = self.shift @ F.T

    def __repr__(self):
        """string form of the object"""
        return (
            type(self).__name__
            + " at "
            + str(hex(id(self)))
            + " (name={}, grid={})".format(self.name, self.grid)
        )

class Surface(IOAble, ABC):
    """Abstract base class for 2d surfaces in 3d space,
    such as flux surfaces, plasma boundaries, poincare sections
    """

    _io_attrs_ = ["_name", "_grid", "_sym", "_L", "_M", "_N"]

    @property
    def name(self):
        """Name of the surface"""
        return self._name

    @name.setter
    def name(self, new):
        self._name = new

    @property
    def L(self):
        """maximum radial mode number"""
        return self._L

    @property
    def M(self):
        """maximum poloidal mode number"""
        return self._M

    @property
    def N(self):
        """maximum toroidal mode number"""
        return self._N

    @property
    def sym(self):
        """stellarator symmetry"""
        return self._sym

    @property
    @abstractmethod
    def grid(self):
        """Default grid for computation"""

    @abstractmethod
    def compute_coordinates(self, params=None, grid=None, dt=0, dz=0):
        """Compute coordinate values at specified nodes"""

    @abstractmethod
    def compute_normal(self, params=None, grid=None):
        """Compute normal vectors to the surface on predefined grid"""

    @abstractmethod
    def compute_surface_area(self, params=None, grids=None):
        """Compute surface area via quadrature"""

    @abstractmethod
    def compute_curvature(self, params=None, grid=None):
        """Compute gaussian and mean curvature"""

    def __repr__(self):
        """string form of the object"""
        return (
            type(self).__name__
            + " at "
            + str(hex(id(self)))
            + " (name={}, grid={})".format(self.name, self.grid)
        )
<|endoftext|>


<commit_before>#!/usr/bin/python2.7
# Reddit pics downloader
from multiprocessing import Process, Pool, TimeoutError
from requests import get, TooManyRedirects
from json import loads
from os.path import exists
from os import mkdir, utime
import time
import re
import sys

class UsageError(Exception):
    pass

class InvalidURLError(BaseException):
    pass

class ExistsError(Exception):
    pass

def find_url(url):
    if re.search(r"(jpg|png|jpeg)$", url):
        return url
    else:
        mo = re.search(r"http://imgur\.com/([a-zA-Z0-9]+)", url)
        if mo != None:
            return "http://i.imgur.com/%s.jpg" % mo.group(1)
        else:
            raise InvalidURLError

def get_urls(children):
    urls = []
    for sub in children:
        url = sub['data']['url']
        stamp = int(sub['data']['created'])
        try:
            xurl = find_url(url)
            urls.append({'href': xurl, 'time': stamp, 'subreddit': sub['data']['subreddit']})
            print "Added image %s" % xurl
        except InvalidURLError:
            print "No image found at %s" % url
    return urls

def spider(subreddit, pages):
    print "Spidering subreddit %s (%s pages)" % (subreddit, pages)
    after = None
    urls = []
    for i in range(pages):
        print "Loading page", i + 1, 'of /r/%s' % subreddit
        r = get('http://www.reddit.com/r/%s/.json?count=%s&after=%s' %
            (subreddit, 25 * i, after))
        j = loads(r.content)
        after = j['data']['after']

        urls.extend(get_urls(j['data']['children']))

    if subreddit != urls[0]['subreddit']:
        print "Correcting case /r/%s ==> /r/%s" % (subreddit, urls[0]['subreddit'])
        subreddit = urls[0]['subreddit']
    print 'Downloading images for /r/%s' % subreddit
    p = Pool(processes=20)
    result = p.map_async(download_file, [(url, subreddit) for url in urls])
    try:
        result.get()
    except TimeoutError:
        print "Unfortunately, /r/%s took took long." % subreddit
    sys.exit()

def download_file(args):
    url = args[0]
    subreddit = args[1]
    file_name = url['href'].split('/')[-1]
    try:
        mkdir(subreddit)
    except OSError:
        pass
    file_name = "%s/%s" % (subreddit, file_name)

    try:
        if exists(file_name):
            raise ExistsError

        opened = False
        while not opened:
            try:
                f = open(file_name, 'wb')
                opened = True
            except IOError:
                pass

        try:
            r = get(url['href'], timeout=10)

            try:
                print 'Downloading %s, file-size: %2.2fKB' % \
                    (url['href'], float(r.headers['content-length']) \
                        / 1000)
            except TypeError:
                print "Downloading %s, file-size: Unknown" % \
                    (url['href'])
            f.write(r.content)
            message =  "%s Finished!" % url['href']
        except TooManyRedirects:
            message = "Too many redirects for file %s." % url['href']
        except (IndexError, AttributeError):
            message = "Failed %s" % url['href']
        f.close()
    except ExistsError:
            message = "Skipping %s, file exists." % file_name
    nows = int(time.time())
    utime(file_name, (nows, url['time']))
    print message
    return message

def main():
    try:
        subreddits = sys.argv[1].split(',')
        if subreddits[0] == '--help':
            raise UsageError()
    except (IndexError, UsageError):
        print "Usage: subdown.py <subreddit[,subreddit]> [pages]"
        exit()

    try:
        pages = sys.argv[2]
    except IndexError:
        print "Pages not specified, defaulting to one."
        pages = 1

    for subreddit in subreddits:
        Process(target=spider, args=(subreddit, int(pages))).start()

if __name__ == '__main__':
    main()
<commit_msg>deleting tiny files<commit_after>#!/usr/bin/python2.7
# Reddit pics downloader
from multiprocessing import Process, Pool, TimeoutError
from requests import get, TooManyRedirects
from json import loads
from os.path import exists, getsize
from os import mkdir, utime
import time
import re
import sys

class UsageError(Exception):
    pass

class InvalidURLError(BaseException):
    pass

class ExistsError(Exception):
    pass

def find_url(url):
    if re.search(r"(jpg|png|jpeg)$", url):
        return url
    else:
        mo = re.search(r"http://imgur\.com/([a-zA-Z0-9]+)", url)
        if mo != None:
            return "http://i.imgur.com/%s.jpg" % mo.group(1)
        else:
            raise InvalidURLError

def get_urls(children):
    urls = []
    for sub in children:
        url = sub['data']['url']
        stamp = int(sub['data']['created'])
        try:
            xurl = find_url(url)
            urls.append({'href': xurl, 'time': stamp, 'subreddit': sub['data']['subreddit']})
            print "Added image %s" % xurl
        except InvalidURLError:
            print "No image found at %s" % url
    return urls

def spider(subreddit, pages):
    print "Spidering subreddit %s (%s pages)" % (subreddit, pages)
    after = None
    urls = []
    for i in range(pages):
        print "Loading page", i + 1, 'of /r/%s' % subreddit
        r = get('http://www.reddit.com/r/%s/.json?count=%s&after=%s' %
            (subreddit, 25 * i, after))
        j = loads(r.content)
        after = j['data']['after']

        urls.extend(get_urls(j['data']['children']))

    if subreddit != urls[0]['subreddit']:
        print "Correcting case /r/%s ==> /r/%s" % (subreddit, urls[0]['subreddit'])
        subreddit = urls[0]['subreddit']
    print 'Downloading images for /r/%s' % subreddit
    p = Pool(processes=20)
    result = p.map_async(download_file, [(url, subreddit) for url in urls])
    try:
        result.get()
    except TimeoutError:
        print "Unfortunately, /r/%s took took long." % subreddit
    sys.exit()

def download_file(args):
    url = args[0]
    subreddit = args[1]
    file_name = url['href'].split('/')[-1]
    try:
        mkdir(subreddit)
    except OSError:
        pass
    file_name = "%s/%s" % (subreddit, file_name)

    try:
        if exists(file_name):
            raise ExistsError

        opened = False
        while not opened:
            try:
                f = open(file_name, 'wb')
                opened = True
            except IOError:
                pass

        try:
            r = get(url['href'], timeout=10)

            try:
                print 'Downloading %s, file-size: %2.2fKB' % \
                    (url['href'], float(r.headers['content-length']) \
                        / 1000)
            except TypeError:
                print "Downloading %s, file-size: Unknown" % \
                    (url['href'])
            f.write(r.content)
            message =  "%s Finished!" % url['href']
        except TooManyRedirects:
            message = "Too many redirects for file %s." % url['href']
        except (IndexError, AttributeError):
            message = "Failed %s" % url['href']
        f.close()
    except ExistsError:
            message = "Skipping %s, file exists." % file_name
    nows = int(time.time())
    utime(file_name, (nows, url['time']))
    if getsize(file_name) < 50:
        message = """File size of %s is less than 50 bytes and thus unlikely to be a
 valid image - deleting!""" % file_name
    print message
    return message

def main():
    try:
        subreddits = sys.argv[1].split(',')
        if subreddits[0] == '--help':
            raise UsageError()
    except (IndexError, UsageError):
        print "Usage: subdown.py <subreddit[,subreddit]> [pages]"
        exit()

    try:
        pages = sys.argv[2]
    except IndexError:
        print "Pages not specified, defaulting to one."
        pages = 1

    for subreddit in subreddits:
        Process(target=spider, args=(subreddit, int(pages))).start()

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


<commit_before>from math import cos,sin,acos,asin,tan
from math import degrees as deg, radians as rad
from datetime import date,datetime,time,timedelta
import time as tm
import requests
from PIL import Image
from io import StringIO,BytesIO
import os, sys

# this module is not provided here. See text.
#from timezone import LocalTimezone

dst = tm.localtime().tm_isdst

class sun:
 """
 Calculate sunrise and sunset based on equations from NOAA
 http://www.srrb.noaa.gov/highlights/sunrise/calcdetails.html

 typical use, calculating the sunrise at the present day:

 import datetime
 import sunrise
 s = sun(lat=49,long=3)
 print('sunrise at ',s.sunrise(when=datetime.datetime.now())
 """
 def __init__(self,lat=42.728120,long=-73.690108): # default Amsterdam
  self.lat=lat
  self.long=long

  print ("NOW IS: " , datetime.now())
 def sunrise(self,when=datetime.now()):
  """
  return the time of sunrise as a datetime.time object
  when is a datetime.datetime object. If none is given
  a local time zone is assumed (including daylight saving
  if present)
  """
  if when is None : when = datetime.now()
  self.__preptime(when)
  self.__calc()
  return sun.__timefromdecimalday(self.sunrise_t)

 def sunset(self,when=None):
  if when is None : when = datetime.now()
  self.__preptime(when)
  self.__calc()
  return sun.__timefromdecimalday(self.sunset_t)

 def solarnoon(self,when=None):
  if when is None : when = datetime.now()
  self.__preptime(when)
  self.__calc()
  return sun.__timefromdecimalday(self.solarnoon_t)

 @staticmethod
 def __timefromdecimalday(day):
  """
  returns a datetime.time object.

  day is a decimal day between 0.0 and 1.0, e.g. noon = 0.5
  """
  hours  = 24.0*day
  h      = int(hours)
  minutes= (hours-h)*60
  m      = int(minutes)
  seconds= (minutes-m)*60
  s      = int(seconds)
  return time(hour=h,minute=m,second=s)

 def __preptime(self,when):
  """
  Extract information in a suitable format from when,
  a datetime.datetime object.
  """
  # datetime days are numbered in the Gregorian calendar
  # while the calculations from NOAA are distibuted as
  # OpenOffice spreadsheets with days numbered from
  # 1/1/1900. The difference are those numbers taken for
  # 18/12/2010
  self.day = when.toordinal()-(734124-40529)
  t=when.time()
  self.time= (t.hour + t.minute/60.0 + t.second/3600.0)/24.0

  self.timezone=0
  offset=when.utcoffset()
  if not offset is None:
   self.timezone=offset.seconds/3600.0

 def __calc(self):
  """
  Perform the actual calculations for sunrise, sunset and
  a number of related quantities.

  The results are stored in the instance variables
  sunrise_t, sunset_t and solarnoon_t
  """
  timezone = -5 + dst # in hours, east is positive
  longitude= self.long     # in decimal degrees, east is positive
  latitude = self.lat      # in decimal degrees, north is positive

  time  = self.time # percentage past midnight, i.e. noon  is 0.5
  day      = self.day     # daynumber 1=1/1/1900

  Jday     =day+2415018.5+time-timezone/24 # Julian day
  Jcent    =(Jday-2451545)/36525    # Julian century

  Manom    = 357.52911+Jcent*(35999.05029-0.0001537*Jcent)
  Mlong    = 280.46646+Jcent*(36000.76983+Jcent*0.0003032)%360
  Eccent   = 0.016708634-Jcent*(0.000042037+0.0001537*Jcent)
  Mobliq   = 23+(26+((21.448-Jcent*(46.815+Jcent*(0.00059-Jcent*0.001813))))/60)/60
  obliq    = Mobliq+0.00256*cos(rad(125.04-1934.136*Jcent))
  vary     = tan(rad(obliq/2))*tan(rad(obliq/2))
  Seqcent  = sin(rad(Manom))*(1.914602-Jcent*(0.004817+0.000014*Jcent))+sin(rad(2*Manom))*(0.019993-0.000101*Jcent)+sin(rad(3*Manom))*0.000289
  Struelong= Mlong+Seqcent
  Sapplong = Struelong-0.00569-0.00478*sin(rad(125.04-1934.136*Jcent))
  declination = deg(asin(sin(rad(obliq))*sin(rad(Sapplong))))

  eqtime   = 4*deg(vary*sin(2*rad(Mlong))-2*Eccent*sin(rad(Manom))+4*Eccent*vary*sin(rad(Manom))*cos(2*rad(Mlong))-0.5*vary*vary*sin(4*rad(Mlong))-1.25*Eccent*Eccent*sin(2*rad(Manom)))

  hourangle= deg(acos(cos(rad(90.833))/(cos(rad(latitude))*cos(rad(declination)))-tan(rad(latitude))*tan(rad(declination))))

  self.solarnoon_t=(720-4*longitude-eqtime+timezone*60)/1440
  self.sunrise_t  =self.solarnoon_t-hourangle*4/1440
  self.sunset_t   =self.solarnoon_t+hourangle*4/1440

if __name__ == "__main__":
  s=sun(lat=42.727848,long=-73.690065)
  today = datetime.today().date()
  print("Todays Date ", datetime.today().date())
  sunrise = datetime.combine(datetime.now().date(),s.sunrise())
  #d = datetime(2014, 9, 18, 12, 55, 0)
  pictoday = False
  while(True):
    if (today != datetime.today().date()):
      sunrise =  datetime.combine(datetime.now().date(),s.sunrise())
      today = datetime.today().date()
      print(datetime.today().date())
      print(s.sunrise(),s.solarnoon(),s.sunset())
      pictoday=False

    diff = (sunrise - datetime.now())
    if (diff.total_seconds() < 30 and diff.total_seconds() > 0) and not pictoday:
      print("Taking Pic")
      directory = os.getcwd() + "/sunrises/"
      if not os.path.exists(directory):
        os.makedirs(directory)

      r = requests.get('http://192.168.0.24/image.jpg', auth=('admin', ''))
      i = Image.open(BytesIO(r.content))
      img_name = directory + str(datetime.today().date()) + ".jpg"
      i.save(img_name)
      pictoday = True

<commit_msg>dropbox file saving<commit_after>from math import cos,sin,acos,asin,tan
from math import degrees as deg, radians as rad
from datetime import date,datetime,time,timedelta
import time as tm
import requests
from PIL import Image
from io import StringIO,BytesIO
import os, sys

# this module is not provided here. See text.
#from timezone import LocalTimezone

dst = tm.localtime().tm_isdst

class sun:
 """
 Calculate sunrise and sunset based on equations from NOAA
 http://www.srrb.noaa.gov/highlights/sunrise/calcdetails.html

 typical use, calculating the sunrise at the present day:

 import datetime
 import sunrise
 s = sun(lat=49,long=3)
 print('sunrise at ',s.sunrise(when=datetime.datetime.now())
 """
 def __init__(self,lat=42.728120,long=-73.690108): # default Amsterdam
  self.lat=lat
  self.long=long

  print ("NOW IS: " , datetime.now())
 def sunrise(self,when=datetime.now()):
  """
  return the time of sunrise as a datetime.time object
  when is a datetime.datetime object. If none is given
  a local time zone is assumed (including daylight saving
  if present)
  """
  if when is None : when = datetime.now()
  self.__preptime(when)
  self.__calc()
  return sun.__timefromdecimalday(self.sunrise_t)

 def sunset(self,when=None):
  if when is None : when = datetime.now()
  self.__preptime(when)
  self.__calc()
  return sun.__timefromdecimalday(self.sunset_t)

 def solarnoon(self,when=None):
  if when is None : when = datetime.now()
  self.__preptime(when)
  self.__calc()
  return sun.__timefromdecimalday(self.solarnoon_t)

 @staticmethod
 def __timefromdecimalday(day):
  """
  returns a datetime.time object.

  day is a decimal day between 0.0 and 1.0, e.g. noon = 0.5
  """
  hours  = 24.0*day
  h      = int(hours)
  minutes= (hours-h)*60
  m      = int(minutes)
  seconds= (minutes-m)*60
  s      = int(seconds)
  return time(hour=h,minute=m,second=s)

 def __preptime(self,when):
  """
  Extract information in a suitable format from when,
  a datetime.datetime object.
  """
  # datetime days are numbered in the Gregorian calendar
  # while the calculations from NOAA are distibuted as
  # OpenOffice spreadsheets with days numbered from
  # 1/1/1900. The difference are those numbers taken for
  # 18/12/2010
  self.day = when.toordinal()-(734124-40529)
  t=when.time()
  self.time= (t.hour + t.minute/60.0 + t.second/3600.0)/24.0

  self.timezone=0
  offset=when.utcoffset()
  if not offset is None:
   self.timezone=offset.seconds/3600.0

 def __calc(self):
  """
  Perform the actual calculations for sunrise, sunset and
  a number of related quantities.

  The results are stored in the instance variables
  sunrise_t, sunset_t and solarnoon_t
  """
  timezone = -5 + dst # in hours, east is positive
  longitude= self.long     # in decimal degrees, east is positive
  latitude = self.lat      # in decimal degrees, north is positive

  time  = self.time # percentage past midnight, i.e. noon  is 0.5
  day      = self.day     # daynumber 1=1/1/1900

  Jday     =day+2415018.5+time-timezone/24 # Julian day
  Jcent    =(Jday-2451545)/36525    # Julian century

  Manom    = 357.52911+Jcent*(35999.05029-0.0001537*Jcent)
  Mlong    = 280.46646+Jcent*(36000.76983+Jcent*0.0003032)%360
  Eccent   = 0.016708634-Jcent*(0.000042037+0.0001537*Jcent)
  Mobliq   = 23+(26+((21.448-Jcent*(46.815+Jcent*(0.00059-Jcent*0.001813))))/60)/60
  obliq    = Mobliq+0.00256*cos(rad(125.04-1934.136*Jcent))
  vary     = tan(rad(obliq/2))*tan(rad(obliq/2))
  Seqcent  = sin(rad(Manom))*(1.914602-Jcent*(0.004817+0.000014*Jcent))+sin(rad(2*Manom))*(0.019993-0.000101*Jcent)+sin(rad(3*Manom))*0.000289
  Struelong= Mlong+Seqcent
  Sapplong = Struelong-0.00569-0.00478*sin(rad(125.04-1934.136*Jcent))
  declination = deg(asin(sin(rad(obliq))*sin(rad(Sapplong))))

  eqtime   = 4*deg(vary*sin(2*rad(Mlong))-2*Eccent*sin(rad(Manom))+4*Eccent*vary*sin(rad(Manom))*cos(2*rad(Mlong))-0.5*vary*vary*sin(4*rad(Mlong))-1.25*Eccent*Eccent*sin(2*rad(Manom)))

  hourangle= deg(acos(cos(rad(90.833))/(cos(rad(latitude))*cos(rad(declination)))-tan(rad(latitude))*tan(rad(declination))))

  self.solarnoon_t=(720-4*longitude-eqtime+timezone*60)/1440
  self.sunrise_t  =self.solarnoon_t-hourangle*4/1440
  self.sunset_t   =self.solarnoon_t+hourangle*4/1440

if __name__ == "__main__":
  s=sun(lat=42.727848,long=-73.690065)
  today = datetime.today().date()
  print("Todays Date ", datetime.today().date())
  sunrise = datetime.combine(datetime.now().date(),s.sunrise())
  #d = datetime(2014, 9, 18, 12, 55, 0)
  pictoday = False
  while(True):
    if (today != datetime.today().date()):
      sunrise =  datetime.combine(datetime.now().date(),s.sunrise())
      today = datetime.today().date()
      print(datetime.today().date())
      print(s.sunrise(),s.solarnoon(),s.sunset())
      pictoday=False

    dropbox_dir = sys.argv[1]
    diff = (sunrise - datetime.now())
    if (diff.total_seconds() < 30 and diff.total_seconds() > 0) and not pictoday:
      print("Taking Pic")
      directory = dropbox_dir + "/sunrises/"
      if not os.path.exists(directory):
        os.makedirs(directory)

      r = requests.get('http://192.168.0.24/image.jpg', auth=('admin', ''))
      i = Image.open(BytesIO(r.content))
      img_name = directory + str(datetime.today().date()) + ".jpg"
      i.save(img_name)
      pictoday = True

<|endoftext|>


<commit_before>"""Support command."""
import sublime
import sublime_plugin
import textwrap
import webbrowser
import re

__version__ = "3.0.0-beta.05"
__pc_name__ = 'ColorHelper'

CSS = '''
div.color-helper { padding: 10px; margin: 0; }
.color-helper h1, .color-helper h2, .color-helper h3,
.color-helper h4, .color-helper h5, .color-helper h6 {
    {{'.string'|css}}
}
.color-helper blockquote { {{'.comment'|css}} }
.color-helper a { text-decoration: none; }
'''

def list2string(obj):
    """Convert list to string."""

    return '.'.join([str(x) for x in obj])

def format_version(module, attr, call=False):
    """Format the version."""

    try:
        if call:
            version = getattr(module, attr)()
        else:
            version = getattr(module, attr)
    except Exception as e:
        print(e)
        version = 'Version could not be acquired!'

    if not isinstance(version, str):
        version = list2string(version)
    return version

def is_installed_by_package_control():
    """Check if installed by package control."""

    settings = sublime.load_settings('Package Control.sublime-settings')
    return str(__pc_name__ in set(settings.get('installed_packages', [])))

class ColorHelperSupportInfoCommand(sublime_plugin.ApplicationCommand):
    """Support info."""

    def run(self):
        """Run command."""

        info = {}

        info["platform"] = sublime.platform()
        info["version"] = sublime.version()
        info["arch"] = sublime.arch()
        info["plugin_version"] = __version__
        info["pc_install"] = is_installed_by_package_control()
        try:
            import mdpopups
            info["mdpopups_version"] = format_version(mdpopups, 'version', call=True)
        except Exception:
            info["mdpopups_version"] = 'Version could not be acquired!'

        try:
            import coloraide
            info["coloraide_version"] = format_version(coloraide, '__version__')
        except Exception:
            info["coloraide_version"] = 'Version could not be acquired!'

        try:
            import markdown
            info["markdown_version"] = format_version(markdown, 'version')
        except Exception:
            info["markdown_version"] = 'Version could not be acquired!'

        try:
            import jinja2
            info["jinja_version"] = format_version(jinja2, '__version__')
        except Exception:
            info["jinja_version"] = 'Version could not be acquired!'

        try:
            import pygments
            info["pygments_version"] = format_version(pygments, '__version__')
        except Exception:
            info["pygments_version"] = 'Version could not be acquired!'

        msg = textwrap.dedent(
            """\
            - ST ver.: %(version)s
            - Platform: %(platform)s
            - Arch: %(arch)s
            - Plugin ver.: %(plugin_version)s
            - Install via PC: %(pc_install)s
            - coloraide ver: %(coloraide_version)s
            - mdpopups ver.: %(mdpopups_version)s
            - markdown ver.: %(markdown_version)s
            - pygments ver.: %(pygments_version)s
            - jinja2 ver.: %(jinja_version)s
            """ % info
        )

        sublime.message_dialog(msg + '\nInfo has been copied to the clipboard.')
        sublime.set_clipboard(msg)

class ColorHelperOpenSiteCommand(sublime_plugin.ApplicationCommand):
    """Open site links."""

    def run(self, url):
        """Open the URL."""

        webbrowser.open_new_tab(url)

class ColorHelperDocCommand(sublime_plugin.WindowCommand):
    """Open doc page."""

    re_pkgs = re.compile(r'^Packages')

    def on_navigate(self, href):
        """Handle links."""

        if href.startswith('sub://Packages'):
            sublime.run_command('open_file', {"file": self.re_pkgs.sub('${packages}', href[6:])})
        else:
            webbrowser.open_new_tab(href)

    def run(self, page):
        """Open page."""

        try:
            import mdpopups
            has_phantom_support = (mdpopups.version() >= (1, 10, 0)) and (int(sublime.version()) >= 3124)
        except Exception:
            has_phantom_support = False

        if not has_phantom_support:
            sublime.run_command('open_file', {"file": page})
        else:
            text = sublime.load_resource(page.replace('${packages}', 'Packages'))
            view = self.window.new_file()
            view.set_name('ColorHelper - Quick Start')
            view.settings().set('gutter', False)
            view.settings().set('word_wrap', False)
            if has_phantom_support:
                mdpopups.add_phantom(
                    view,
                    'quickstart',
                    sublime.Region(0),
                    text,
                    sublime.LAYOUT_INLINE,
                    css=CSS,
                    wrapper_class="color-helper",
                    on_navigate=self.on_navigate
                )
            else:
                view.run_command('insert', {"characters": text})
            view.set_read_only(True)
            view.set_scratch(True)

class ColorHelperChangesCommand(sublime_plugin.WindowCommand):
    """Changelog command."""

    def run(self):
        """Show the changelog in a new view."""
        try:
            import mdpopups
            has_phantom_support = (mdpopups.version() >= (1, 10, 0)) and (int(sublime.version()) >= 3124)
        except Exception:
            has_phantom_support = False

        text = sublime.load_resource('Packages/ColorHelper/CHANGES.md')
        view = self.window.new_file()
        view.set_name('ColorHelper - Changelog')
        view.settings().set('gutter', False)
        view.settings().set('word_wrap', False)
        if has_phantom_support:
            mdpopups.add_phantom(
                view,
                'changelog',
                sublime.Region(0),
                text,
                sublime.LAYOUT_INLINE,
                wrapper_class="color-helper",
                css=CSS,
                on_navigate=self.on_navigate
            )
        else:
            view.run_command('insert', {"characters": text})
        view.set_read_only(True)
        view.set_scratch(True)

    def on_navigate(self, href):
        """Open links."""
        webbrowser.open_new_tab(href)
<commit_msg>Bump beta version<commit_after>"""Support command."""
import sublime
import sublime_plugin
import textwrap
import webbrowser
import re

__version__ = "3.0.0-beta.06"
__pc_name__ = 'ColorHelper'

CSS = '''
div.color-helper { padding: 10px; margin: 0; }
.color-helper h1, .color-helper h2, .color-helper h3,
.color-helper h4, .color-helper h5, .color-helper h6 {
    {{'.string'|css}}
}
.color-helper blockquote { {{'.comment'|css}} }
.color-helper a { text-decoration: none; }
'''

def list2string(obj):
    """Convert list to string."""

    return '.'.join([str(x) for x in obj])

def format_version(module, attr, call=False):
    """Format the version."""

    try:
        if call:
            version = getattr(module, attr)()
        else:
            version = getattr(module, attr)
    except Exception as e:
        print(e)
        version = 'Version could not be acquired!'

    if not isinstance(version, str):
        version = list2string(version)
    return version

def is_installed_by_package_control():
    """Check if installed by package control."""

    settings = sublime.load_settings('Package Control.sublime-settings')
    return str(__pc_name__ in set(settings.get('installed_packages', [])))

class ColorHelperSupportInfoCommand(sublime_plugin.ApplicationCommand):
    """Support info."""

    def run(self):
        """Run command."""

        info = {}

        info["platform"] = sublime.platform()
        info["version"] = sublime.version()
        info["arch"] = sublime.arch()
        info["plugin_version"] = __version__
        info["pc_install"] = is_installed_by_package_control()
        try:
            import mdpopups
            info["mdpopups_version"] = format_version(mdpopups, 'version', call=True)
        except Exception:
            info["mdpopups_version"] = 'Version could not be acquired!'

        try:
            import coloraide
            info["coloraide_version"] = format_version(coloraide, '__version__')
        except Exception:
            info["coloraide_version"] = 'Version could not be acquired!'

        try:
            import markdown
            info["markdown_version"] = format_version(markdown, 'version')
        except Exception:
            info["markdown_version"] = 'Version could not be acquired!'

        try:
            import jinja2
            info["jinja_version"] = format_version(jinja2, '__version__')
        except Exception:
            info["jinja_version"] = 'Version could not be acquired!'

        try:
            import pygments
            info["pygments_version"] = format_version(pygments, '__version__')
        except Exception:
            info["pygments_version"] = 'Version could not be acquired!'

        msg = textwrap.dedent(
            """\
            - ST ver.: %(version)s
            - Platform: %(platform)s
            - Arch: %(arch)s
            - Plugin ver.: %(plugin_version)s
            - Install via PC: %(pc_install)s
            - coloraide ver: %(coloraide_version)s
            - mdpopups ver.: %(mdpopups_version)s
            - markdown ver.: %(markdown_version)s
            - pygments ver.: %(pygments_version)s
            - jinja2 ver.: %(jinja_version)s
            """ % info
        )

        sublime.message_dialog(msg + '\nInfo has been copied to the clipboard.')
        sublime.set_clipboard(msg)

class ColorHelperOpenSiteCommand(sublime_plugin.ApplicationCommand):
    """Open site links."""

    def run(self, url):
        """Open the URL."""

        webbrowser.open_new_tab(url)

class ColorHelperDocCommand(sublime_plugin.WindowCommand):
    """Open doc page."""

    re_pkgs = re.compile(r'^Packages')

    def on_navigate(self, href):
        """Handle links."""

        if href.startswith('sub://Packages'):
            sublime.run_command('open_file', {"file": self.re_pkgs.sub('${packages}', href[6:])})
        else:
            webbrowser.open_new_tab(href)

    def run(self, page):
        """Open page."""

        try:
            import mdpopups
            has_phantom_support = (mdpopups.version() >= (1, 10, 0)) and (int(sublime.version()) >= 3124)
        except Exception:
            has_phantom_support = False

        if not has_phantom_support:
            sublime.run_command('open_file', {"file": page})
        else:
            text = sublime.load_resource(page.replace('${packages}', 'Packages'))
            view = self.window.new_file()
            view.set_name('ColorHelper - Quick Start')
            view.settings().set('gutter', False)
            view.settings().set('word_wrap', False)
            if has_phantom_support:
                mdpopups.add_phantom(
                    view,
                    'quickstart',
                    sublime.Region(0),
                    text,
                    sublime.LAYOUT_INLINE,
                    css=CSS,
                    wrapper_class="color-helper",
                    on_navigate=self.on_navigate
                )
            else:
                view.run_command('insert', {"characters": text})
            view.set_read_only(True)
            view.set_scratch(True)

class ColorHelperChangesCommand(sublime_plugin.WindowCommand):
    """Changelog command."""

    def run(self):
        """Show the changelog in a new view."""
        try:
            import mdpopups
            has_phantom_support = (mdpopups.version() >= (1, 10, 0)) and (int(sublime.version()) >= 3124)
        except Exception:
            has_phantom_support = False

        text = sublime.load_resource('Packages/ColorHelper/CHANGES.md')
        view = self.window.new_file()
        view.set_name('ColorHelper - Changelog')
        view.settings().set('gutter', False)
        view.settings().set('word_wrap', False)
        if has_phantom_support:
            mdpopups.add_phantom(
                view,
                'changelog',
                sublime.Region(0),
                text,
                sublime.LAYOUT_INLINE,
                wrapper_class="color-helper",
                css=CSS,
                on_navigate=self.on_navigate
            )
        else:
            view.run_command('insert', {"characters": text})
        view.set_read_only(True)
        view.set_scratch(True)

    def on_navigate(self, href):
        """Open links."""
        webbrowser.open_new_tab(href)
<|endoftext|>


<commit_before># Copyright 2018 D-Wave Systems Inc.
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.
#
# ================================================================================================

__version__ = '0.8.3'
__author__ = 'D-Wave Systems Inc.'
__authoremail__ = 'acondello@dwavesys.com'
__description__ = 'A shared API for binary quadratic model samplers.'
<commit_msg>Update version 0.8.3 -> 0.8.4<commit_after># Copyright 2018 D-Wave Systems Inc.
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.
#
# ================================================================================================

__version__ = '0.8.4'
__author__ = 'D-Wave Systems Inc.'
__authoremail__ = 'acondello@dwavesys.com'
__description__ = 'A shared API for binary quadratic model samplers.'
<|endoftext|>


<commit_before>import sys
sys.path.insert(0, 'lib/')

import Adafruit_MCP230xx
from db import *

class SwitchController:

  ON = 1
  OFF = 0

  def __init__(self, id):

    self.switch_db = Switchs()

    self.switch_data = self.switch_db.find_by_id(id)

    self.GPIO_pin = self.switch_data['code']

  def setup_controller(self):
    self.gpio_controller = Adafruit_MCP230xx.Adafruit_MCP230XX(address = 0x20, num_gpios = 16)
    self.set_output()

  def set_output(self):
    self.gpio_controller.config(self.GPIO_pin, self.gpio_controller.OUTPUT)

  def on(self):
    self.switch_db.update_state(self.switch_data['id'], self.ON)
    self.output(self.GPIO_pin, self.ON)

  def off(self):
    self.switch_db.update_state(self.switch_data['id'], self.OFF)
    self.output(self.GPIO_pinl, self.OFF)

class Switchs(Db):

  def find_by_id(self, id):
    return self.query_one("SELECT * FROM switchs where id = '" + str(id) + "'")

  def update_state(self,id,state):
    return self.query_one("UPDATE switchs SET state = '" + state + "' where id = '" + str(id) + "'")

  def get_all(self):
    return self.query("SELECT * FROM switchs")
<commit_msg>int concatenations update<commit_after>import sys
sys.path.insert(0, 'lib/')

import Adafruit_MCP230xx
from db import *

class SwitchController:

  ON = 1
  OFF = 0

  def __init__(self, id):

    self.switch_db = Switchs()

    self.switch_data = self.switch_db.find_by_id(id)

    self.GPIO_pin = self.switch_data['code']

  def setup_controller(self):
    self.gpio_controller = Adafruit_MCP230xx.Adafruit_MCP230XX(address = 0x20, num_gpios = 16)
    self.set_output()

  def set_output(self):
    self.gpio_controller.config(self.GPIO_pin, self.gpio_controller.OUTPUT)

  def on(self):
    self.switch_db.update_state(self.switch_data['id'], self.ON)
    self.output(self.GPIO_pin, self.ON)

  def off(self):
    self.switch_db.update_state(self.switch_data['id'], self.OFF)
    self.output(self.GPIO_pinl, self.OFF)

class Switchs(Db):

  def find_by_id(self, id):
    return self.query_one("SELECT * FROM switchs where id = '" + str(id) + "'")

  def update_state(self,id,state):
    return self.query_one("UPDATE switchs SET state = '" + str(state) + "' where id = '" + str(id) + "'")

  def get_all(self):
    return self.query("SELECT * FROM switchs")
<|endoftext|>