<commit_before>import os
import platform
import textwrap
import unittest

import pytest

from conans.test.assets.sources import gen_function_cpp
from conans.test.utils.tools import TestClient

from conans.util.files import save, load

@pytest.mark.tool_cmake
@pytest.mark.skipif(platform.system() != "Windows", reason="Only for windows")
class CustomConfigurationTest(unittest.TestCase):
    conanfile = textwrap.dedent("""
        from conans import ConanFile
        from conan.tools.cmake import CMakeDeps
        class App(ConanFile):
            settings = "os", "arch", "compiler", "build_type"
            requires = "hello/0.1"

            def generate(self):
                cmake = CMakeDeps(self)
                cmake.configurations.append("ReleaseShared")
                if self.options["hello"].shared:
                    cmake.configuration = "ReleaseShared"
                cmake.generate()

            def imports(self):
                config = str(self.settings.build_type)
                if self.options["hello"].shared:
                    config = "ReleaseShared"
                self.copy("*.dll", src="bin", dst=config, keep_path=False)
        """)

    app = gen_function_cpp(name="main", includes=["hello"], calls=["hello"])

    cmakelist = textwrap.dedent("""
        set(CMAKE_CONFIGURATION_TYPES Debug Release ReleaseShared CACHE STRING
            "Available build-types: Debug, Release and ReleaseShared")

        cmake_minimum_required(VERSION 2.8)
        project(App C CXX)

        set(CMAKE_PREFIX_PATH ${CMAKE_BINARY_DIR} ${CMAKE_PREFIX_PATH})
        set(CMAKE_MODULE_PATH ${CMAKE_BINARY_DIR} ${CMAKE_MODULE_PATH})

        set(CMAKE_CXX_FLAGS_RELEASESHARED ${CMAKE_CXX_FLAGS_RELEASE})
        set(CMAKE_C_FLAGS_RELEASESHARED ${CMAKE_C_FLAGS_RELEASE})
        set(CMAKE_EXE_LINKER_FLAGS_RELEASESHARED ${CMAKE_EXE_LINKER_FLAGS_RELEASE})

        find_package(hello REQUIRED)
        add_executable(app app.cpp)
        target_link_libraries(app PRIVATE hello::hello)
        """)

    def setUp(self):
        self.client = TestClient(path_with_spaces=False)
        self.client.run("new hello/0.1 -s")
        self.client.run("create . hello/0.1@ -s compiler.version=15 "
                        "-s build_type=Release -o hello:shared=True")
        self.client.run("create . hello/0.1@ -s compiler.version=15 "
                        "-s build_type=Release")

        # Prepare the actual consumer package
        self.client.save({"conanfile.py": self.conanfile,
                          "CMakeLists.txt": self.cmakelist,
                          "app.cpp": self.app})

    def test_generator_multi(self):
        settings = {"compiler": "Visual Studio",
                    "compiler.version": "15",
                    "arch": "x86_64",
                    "build_type": "Release",
                    }

        settings = " ".join('-s %s="%s"' % (k, v) for k, v in settings.items() if v)

        # Run the configure corresponding to this test case
        with self.client.chdir('build'):
            self.client.run("install .. %s -o hello:shared=True" % settings)
            self.client.run("install .. %s -o hello:shared=False" % settings)
            self.assertTrue(os.path.isfile(os.path.join(self.client.current_folder,
                                                        "helloTarget-releaseshared.cmake")))
            self.assertTrue(os.path.isfile(os.path.join(self.client.current_folder,
                                                        "helloTarget-release.cmake")))

            self.client.run_command('cmake .. -G "Visual Studio 15 Win64"')
            self.client.run_command('cmake --build . --config Release')
            self.client.run_command(r"Release\\app.exe")
            self.assertIn("hello/0.1: Hello World Release!", self.client.out)
            self.assertIn("main: Release!", self.client.out)
            self.client.run_command('cmake --build . --config ReleaseShared')
            self.client.run_command(r"ReleaseShared\\app.exe")
            self.assertIn("hello/0.1: Hello World Release!", self.client.out)
            self.assertIn("main: Release!", self.client.out)

@pytest.mark.tool_cmake
@pytest.mark.skipif(platform.system() != "Windows", reason="Only for windows")
class CustomSettingsTest(unittest.TestCase):
    conanfile = textwrap.dedent("""
        from conans import ConanFile
        from conan.tools.cmake import CMakeDeps

        class App(ConanFile):
            settings = "os", "arch", "compiler", "build_type"
            requires = "hello/0.1"

            def generate(self):
                cmake = CMakeDeps(self)
                #cmake.configurations.append("MyRelease") # NOT NECESSARY!!!
                cmake.generate()
        """)

    app = gen_function_cpp(name="main", includes=["hello"], calls=["hello"])

    cmakelist = textwrap.dedent("""
        set(CMAKE_CONFIGURATION_TYPES Debug Release MyRelease CACHE STRING
            "Available build-types: Debug, Release and MyRelease")

        cmake_minimum_required(VERSION 2.8)
        project(App C CXX)

        set(CMAKE_PREFIX_PATH ${CMAKE_BINARY_DIR} ${CMAKE_PREFIX_PATH})
        set(CMAKE_MODULE_PATH ${CMAKE_BINARY_DIR} ${CMAKE_MODULE_PATH})

        set(CMAKE_CXX_FLAGS_MYRELEASE ${CMAKE_CXX_FLAGS_RELEASE})
        set(CMAKE_C_FLAGS_MYRELEASE ${CMAKE_C_FLAGS_RELEASE})
        set(CMAKE_EXE_LINKER_FLAGS_MYRELEASE ${CMAKE_EXE_LINKER_FLAGS_RELEASE})

        find_package(hello REQUIRED)
        add_executable(app app.cpp)
        target_link_libraries(app PRIVATE hello::hello)
        """)

    def setUp(self):
        self.client = TestClient(path_with_spaces=False)
        settings = load(self.client.cache.settings_path)
        settings = settings.replace("Release", "MyRelease")
        save(self.client.cache.settings_path, settings)
        self.client.run("new hello/0.1 -s")
        cmake = self.client.load("src/CMakeLists.txt")

        cmake = cmake.replace("cmake_minimum_required", """
            set(CMAKE_CONFIGURATION_TYPES Debug MyRelease Release CACHE STRING "Types")

            cmake_minimum_required""")
        cmake = cmake.replace("conan_basic_setup()", """
            conan_basic_setup()
            set(CMAKE_CXX_FLAGS_MYRELEASE ${CMAKE_CXX_FLAGS_RELEASE})
            set(CMAKE_C_FLAGS_MYRELEASE ${CMAKE_C_FLAGS_RELEASE})
            set(CMAKE_EXE_LINKER_FLAGS_MYRELEASE ${CMAKE_EXE_LINKER_FLAGS_RELEASE})
            """)
        self.client.save({"src/CMakeLists.txt": cmake})
        self.client.run("create . hello/0.1@ -s compiler.version=15 -s build_type=MyRelease")

        # Prepare the actual consumer package
        self.client.save({"conanfile.py": self.conanfile,
                          "CMakeLists.txt": self.cmakelist,
                          "app.cpp": self.app})

    def test_generator_multi(self):
        settings = {"compiler": "Visual Studio",
                    "compiler.version": "15",
                    "arch": "x86_64",
                    "build_type": "MyRelease",
                    }

        settings = " ".join('-s %s="%s"' % (k, v) for k, v in settings.items() if v)

        # Run the configure corresponding to this test case
        build_directory = os.path.join(self.client.current_folder, "build").replace("\\", "/")
        with self.client.chdir(build_directory):
            self.client.run("install .. %s" % settings)
            self.assertTrue(os.path.isfile(os.path.join(self.client.current_folder,
                                                        "helloTarget-myrelease.cmake")))

            self.client.run_command('cmake .. -G "Visual Studio 15 Win64"')
            self.client.run_command('cmake --build . --config MyRelease')
            self.client.run_command(r"MyRelease\\app.exe")
            self.assertIn("hello/0.1: Hello World Release!", self.client.out)
            self.assertIn("main: Release!", self.client.out)
<commit_msg>testing cmake imported config (#9129)<commit_after>import os
import platform
import textwrap
import unittest

import pytest

from conans.test.assets.genconanfile import GenConanfile
from conans.test.assets.sources import gen_function_cpp
from conans.test.utils.tools import TestClient

from conans.util.files import save, load

@pytest.mark.tool_cmake
@pytest.mark.skipif(platform.system() != "Windows", reason="Only for windows")
class CustomConfigurationTest(unittest.TestCase):
    conanfile = textwrap.dedent("""
        from conans import ConanFile
        from conan.tools.cmake import CMakeDeps
        class App(ConanFile):
            settings = "os", "arch", "compiler", "build_type"
            requires = "hello/0.1"

            def generate(self):
                cmake = CMakeDeps(self)
                cmake.configurations.append("ReleaseShared")
                if self.options["hello"].shared:
                    cmake.configuration = "ReleaseShared"
                cmake.generate()

            def imports(self):
                config = str(self.settings.build_type)
                if self.options["hello"].shared:
                    config = "ReleaseShared"
                self.copy("*.dll", src="bin", dst=config, keep_path=False)
        """)

    app = gen_function_cpp(name="main", includes=["hello"], calls=["hello"])

    cmakelist = textwrap.dedent("""
        set(CMAKE_CONFIGURATION_TYPES Debug Release ReleaseShared CACHE STRING
            "Available build-types: Debug, Release and ReleaseShared")

        cmake_minimum_required(VERSION 2.8)
        project(App C CXX)

        set(CMAKE_PREFIX_PATH ${CMAKE_BINARY_DIR} ${CMAKE_PREFIX_PATH})
        set(CMAKE_MODULE_PATH ${CMAKE_BINARY_DIR} ${CMAKE_MODULE_PATH})

        set(CMAKE_CXX_FLAGS_RELEASESHARED ${CMAKE_CXX_FLAGS_RELEASE})
        set(CMAKE_C_FLAGS_RELEASESHARED ${CMAKE_C_FLAGS_RELEASE})
        set(CMAKE_EXE_LINKER_FLAGS_RELEASESHARED ${CMAKE_EXE_LINKER_FLAGS_RELEASE})

        find_package(hello REQUIRED)
        add_executable(app app.cpp)
        target_link_libraries(app PRIVATE hello::hello)
        """)

    def setUp(self):
        self.client = TestClient(path_with_spaces=False)
        self.client.run("new hello/0.1 -s")
        self.client.run("create . hello/0.1@ -s compiler.version=15 "
                        "-s build_type=Release -o hello:shared=True")
        self.client.run("create . hello/0.1@ -s compiler.version=15 "
                        "-s build_type=Release")

        # Prepare the actual consumer package
        self.client.save({"conanfile.py": self.conanfile,
                          "CMakeLists.txt": self.cmakelist,
                          "app.cpp": self.app})

    def test_generator_multi(self):
        settings = {"compiler": "Visual Studio",
                    "compiler.version": "15",
                    "arch": "x86_64",
                    "build_type": "Release",
                    }

        settings = " ".join('-s %s="%s"' % (k, v) for k, v in settings.items() if v)

        # Run the configure corresponding to this test case
        with self.client.chdir('build'):
            self.client.run("install .. %s -o hello:shared=True" % settings)
            self.client.run("install .. %s -o hello:shared=False" % settings)
            self.assertTrue(os.path.isfile(os.path.join(self.client.current_folder,
                                                        "helloTarget-releaseshared.cmake")))
            self.assertTrue(os.path.isfile(os.path.join(self.client.current_folder,
                                                        "helloTarget-release.cmake")))

            self.client.run_command('cmake .. -G "Visual Studio 15 Win64"')
            self.client.run_command('cmake --build . --config Release')
            self.client.run_command(r"Release\\app.exe")
            self.assertIn("hello/0.1: Hello World Release!", self.client.out)
            self.assertIn("main: Release!", self.client.out)
            self.client.run_command('cmake --build . --config ReleaseShared')
            self.client.run_command(r"ReleaseShared\\app.exe")
            self.assertIn("hello/0.1: Hello World Release!", self.client.out)
            self.assertIn("main: Release!", self.client.out)

@pytest.mark.tool_cmake
@pytest.mark.skipif(platform.system() != "Windows", reason="Only for windows")
class CustomSettingsTest(unittest.TestCase):
    conanfile = textwrap.dedent("""
        from conans import ConanFile
        from conan.tools.cmake import CMakeDeps

        class App(ConanFile):
            settings = "os", "arch", "compiler", "build_type"
            requires = "hello/0.1"

            def generate(self):
                cmake = CMakeDeps(self)
                #cmake.configurations.append("MyRelease") # NOT NECESSARY!!!
                cmake.generate()
        """)

    app = gen_function_cpp(name="main", includes=["hello"], calls=["hello"])

    cmakelist = textwrap.dedent("""
        set(CMAKE_CONFIGURATION_TYPES Debug Release MyRelease CACHE STRING
            "Available build-types: Debug, Release and MyRelease")

        cmake_minimum_required(VERSION 2.8)
        project(App C CXX)

        set(CMAKE_PREFIX_PATH ${CMAKE_BINARY_DIR} ${CMAKE_PREFIX_PATH})
        set(CMAKE_MODULE_PATH ${CMAKE_BINARY_DIR} ${CMAKE_MODULE_PATH})

        set(CMAKE_CXX_FLAGS_MYRELEASE ${CMAKE_CXX_FLAGS_RELEASE})
        set(CMAKE_C_FLAGS_MYRELEASE ${CMAKE_C_FLAGS_RELEASE})
        set(CMAKE_EXE_LINKER_FLAGS_MYRELEASE ${CMAKE_EXE_LINKER_FLAGS_RELEASE})

        find_package(hello REQUIRED)
        add_executable(app app.cpp)
        target_link_libraries(app PRIVATE hello::hello)
        """)

    def setUp(self):
        self.client = TestClient(path_with_spaces=False)
        settings = load(self.client.cache.settings_path)
        settings = settings.replace("Release", "MyRelease")
        save(self.client.cache.settings_path, settings)
        self.client.run("new hello/0.1 -s")
        cmake = self.client.load("src/CMakeLists.txt")

        cmake = cmake.replace("cmake_minimum_required", """
            set(CMAKE_CONFIGURATION_TYPES Debug MyRelease Release CACHE STRING "Types")

            cmake_minimum_required""")
        cmake = cmake.replace("conan_basic_setup()", """
            conan_basic_setup()
            set(CMAKE_CXX_FLAGS_MYRELEASE ${CMAKE_CXX_FLAGS_RELEASE})
            set(CMAKE_C_FLAGS_MYRELEASE ${CMAKE_C_FLAGS_RELEASE})
            set(CMAKE_EXE_LINKER_FLAGS_MYRELEASE ${CMAKE_EXE_LINKER_FLAGS_RELEASE})
            """)
        self.client.save({"src/CMakeLists.txt": cmake})
        self.client.run("create . hello/0.1@ -s compiler.version=15 -s build_type=MyRelease")

        # Prepare the actual consumer package
        self.client.save({"conanfile.py": self.conanfile,
                          "CMakeLists.txt": self.cmakelist,
                          "app.cpp": self.app})

    def test_generator_multi(self):
        settings = {"compiler": "Visual Studio",
                    "compiler.version": "15",
                    "arch": "x86_64",
                    "build_type": "MyRelease",
                    }

        settings = " ".join('-s %s="%s"' % (k, v) for k, v in settings.items() if v)

        # Run the configure corresponding to this test case
        build_directory = os.path.join(self.client.current_folder, "build").replace("\\", "/")
        with self.client.chdir(build_directory):
            self.client.run("install .. %s" % settings)
            self.assertTrue(os.path.isfile(os.path.join(self.client.current_folder,
                                                        "helloTarget-myrelease.cmake")))

            self.client.run_command('cmake .. -G "Visual Studio 15 Win64"')
            self.client.run_command('cmake --build . --config MyRelease')
            self.client.run_command(r"MyRelease\\app.exe")
            self.assertIn("hello/0.1: Hello World Release!", self.client.out)
            self.assertIn("main: Release!", self.client.out)

@pytest.mark.tool_cmake
def test_changing_build_type():
    client = TestClient(path_with_spaces=False)
    dep_conanfile = textwrap.dedent(r"""
       from conans import ConanFile
       from conans.tools import save

       class Dep(ConanFile):
           settings = "build_type"
           def build(self):
               save("hello.h",
               '# include <iostream>\n'
               'void hello(){{std::cout<<"BUILD_TYPE={}!!";}}'.format(self.settings.build_type))
           def package(self):
               self.copy("*.h", dst="include")
           """)
    client.save({"conanfile.py": dep_conanfile})
    client.run("create . dep/0.1@ -s build_type=Release")
    client.run("create . dep/0.1@ -s build_type=Debug")

    cmakelists = textwrap.dedent("""
        set(CMAKE_CXX_COMPILER_WORKS 1)
        set(CMAKE_CXX_ABI_COMPILED 1)
        cmake_minimum_required(VERSION 3.15)
        project(App CXX)

        # NOTE: NO MAP necessary!!!
        find_package(dep REQUIRED)
        add_executable(app app.cpp)
        target_link_libraries(app PRIVATE dep::dep)
        """)
    app = gen_function_cpp(name="main", includes=["hello"], calls=["hello"])
    pkg_conanfile = GenConanfile("pkg", "0.1").with_requires("dep/0.1").\
        with_generator("CMakeDeps").with_generator("CMakeToolchain").\
        with_settings("os", "compiler", "arch", "build_type")
    client.save({"conanfile.py": pkg_conanfile,
                 "CMakeLists.txt": cmakelists,
                 "app.cpp": app}, clean_first=True)

    # in MSVC multi-config -s pkg:build_type=Debug is not really necesary, toolchain do nothing
    # TODO: Challenge how to define consumer build_type for conanfile.txt
    client.run("install . -s pkg:build_type=Debug -s build_type=Release")
    client.run_command("cmake . -DCMAKE_TOOLCHAIN_FILE=conan_toolchain.cmake")
    client.run_command("cmake --build . --config Debug")
    cmd = os.path.join(".", "Debug", "app") if platform.system() == "Windows" else "./app"
    client.run_command(cmd)
    assert "main: Debug!" in client.out
    assert "BUILD_TYPE=Release!!" in client.out

<|endoftext|>


<commit_before>#!/usr/bin/python

'''
This example illustrates how to use cv2.HoughCircles() function.

Usage:
    houghcircles.py [<image_name>]
    image argument defaults to ../data/board.jpg
'''

# Python 2/3 compatibility
from __future__ import print_function

import cv2
import numpy as np
import sys

if __name__ == '__main__':
    print(__doc__)

    try:
        fn = sys.argv[1]
    except IndexError:
        fn = "../data/board.jpg"

    src = cv2.imread(fn, 1)
    img = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    img = cv2.medianBlur(img, 5)
    cimg = src.copy() # numpy function

    circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 10, np.array([]), 100, 30, 1, 30)

    if circles != None: # Check if circles have been found and only then iterate over these and add them to the image
        a, b, c = circles.shape
        for i in range(b):
            cv2.circle(cimg, (circles[0][i][0], circles[0][i][1]), circles[0][i][2], (0, 0, 255), 3, cv2.LINE_AA)
            cv2.circle(cimg, (circles[0][i][0], circles[0][i][1]), 2, (0, 255, 0), 3, cv2.LINE_AA)  # draw center of circle

    cv2.imshow("source", src)
    cv2.imshow("detected circles", cimg)
    cv2.waitKey(0)
<commit_msg>Removed trailing spaces at line 32<commit_after>#!/usr/bin/python

'''
This example illustrates how to use cv2.HoughCircles() function.

Usage:
    houghcircles.py [<image_name>]
    image argument defaults to ../data/board.jpg
'''

# Python 2/3 compatibility
from __future__ import print_function

import cv2
import numpy as np
import sys

if __name__ == '__main__':
    print(__doc__)

    try:
        fn = sys.argv[1]
    except IndexError:
        fn = "../data/board.jpg"

    src = cv2.imread(fn, 1)
    img = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    img = cv2.medianBlur(img, 5)
    cimg = src.copy() # numpy function

    circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 10, np.array([]), 100, 30, 1, 30)

    if circles != None: # Check if circles have been found and only then iterate over these and add them to the image
        a, b, c = circles.shape
        for i in range(b):
            cv2.circle(cimg, (circles[0][i][0], circles[0][i][1]), circles[0][i][2], (0, 0, 255), 3, cv2.LINE_AA)
            cv2.circle(cimg, (circles[0][i][0], circles[0][i][1]), 2, (0, 255, 0), 3, cv2.LINE_AA)  # draw center of circle

    cv2.imshow("source", src)
    cv2.imshow("detected circles", cimg)
    cv2.waitKey(0)
<|endoftext|>


<commit_before># coding: utf-8
"""
gae-init
~~~~~~~~

Google App Engine with Bootstrap, Flask and tons of other cool features.

https://github.com/gae-init
http://gae-init.appspot.com

Copyright (c) 2012-2015 by Panayiotis Lipiridis.
License MIT, see LICENSE for more details.

"""

__version__ = '3.3.1'
<commit_msg>Version 3.3.2<commit_after># coding: utf-8
"""
gae-init
~~~~~~~~

Google App Engine with Bootstrap, Flask and tons of other cool features.

https://github.com/gae-init
http://gae-init.appspot.com

Copyright (c) 2012-2015 by Panayiotis Lipiridis.
License MIT, see LICENSE for more details.

"""

__version__ = '3.3.2'
<|endoftext|>


<commit_before>
print("This is metrochrome.py")
print("-- More features coming later")<commit_msg>Removed a line from metrochrome.py<commit_after>

print("This is metrochrome.py")
print("-- More features coming later")
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals

from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.messages.views import SuccessMessageMixin
from django.core.urlresolvers import reverse
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import CreateView, DetailView, ListView, RedirectView, UpdateView
from django.shortcuts import redirect, render, get_object_or_404

from actstream import action
from actstream import actions
from braces.views import LoginRequiredMixin
from notifications.signals import notify

from .models import Group
from .forms import GroupForm, GroupUpdateForm, GroupAddForm , GroupLeaveForm
from django.db.models import Q

class GroupsAbortView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
    model = Group
    form_class = GroupLeaveForm
    query_pk_and_slug = True
    template_name = 'groups/groups_abort.html'
    success_message = "You aborted Group %(name)s successfully"

    def form_valid(self, form):
        # remove request user from the members of group
        form.instance.members.remove(self.request.user)
        form.save()

        return super(GroupsAbortView, self).form_valid(form)

    def get_form_kwargs(self):
        kwargs = super(GroupsAbortView, self).get_form_kwargs()
        kwargs.update({'request_user': self.request.user})
        kwargs.update(self.kwargs)  # self.kwargs contains all url conf params
        return kwargs

    def get_success_url(self):
        action.send(self.request.user, verb='aborted', target=self.object)
        notify.send(self.request.user, recipient=self.object.creator, verb=u'has aborted from your Group', level='success')
        return reverse("groups:groups-detail",
                       kwargs={'pk': self.kwargs['pk']})

class GroupsCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
    model = Group
    form_class = GroupForm
    template_name = "groups/groups_create.html"
    success_message = "%(name)s was created successfully"

    def get_form_kwargs(self):
        kwargs = super(GroupsCreateView, self).get_form_kwargs()
        kwargs.update({'request_user': self.request.user})
        kwargs.update(self.kwargs)  # self.kwargs contains all url conf params
        return kwargs

    def get_success_url(self):
        action.send(self.request.user, verb='created', target=self.object)
        return super(GroupsCreateView, self).get_success_url()

class GroupsDetailView(LoginRequiredMixin, DetailView):
    model = Group
    query_pk_and_slug = True
    template_name = 'groups/groups_detail.html'

class GroupsJoinView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
    model = Group
    form_class = GroupAddForm
    query_pk_and_slug = True
    template_name = 'groups/groups_join.html'
    success_message = "You joined Group %(name)s successfully"

    def form_valid(self, form):
        # add request user to the members of group
        form.instance.members.add(self.request.user)
        form.save()

        return super(GroupsJoinView, self).form_valid(form)

    def get_form_kwargs(self):
        kwargs = super(GroupsJoinView, self).get_form_kwargs()
        kwargs.update({'request_user': self.request.user})
        kwargs.update(self.kwargs)  # self.kwargs contains all url conf params
        return kwargs

    def get_success_url(self):
        action.send(self.request.user, verb='joined', target=self.object)
        notify.send(self.request.user, recipient=self.object.creator, verb=u'has joined to your Group', level='success')
        return reverse("groups:groups-detail",
                       kwargs={'pk': self.kwargs['pk']})

class GroupsListView(LoginRequiredMixin, ListView):
    template_name = 'groups/groups_list.html'
    paginate_by = settings.GROUPS_MAX_ITEMS_PER_PAGE

    def get_queryset(self):
        return Group.objects.all()

class GroupsMyListView(LoginRequiredMixin, ListView):
    template_name = 'groups/groups_my_list.html'
    paginate_by = settings.GROUPS_MAX_ITEMS_PER_PAGE

    def get_queryset(self):
        return Group.objects.filter(creator=self.request.user)

class GroupsUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
    model = Group
    form_class = GroupUpdateForm
    query_pk_and_slug = True
    template_name = 'groups/groups_update.html'
    success_message = "%(name)s was updated successfully"

    def dispatch(self, request, *args, **kwargs):
        group = get_object_or_404(Group, pk=self.kwargs['pk'])

        if not group.creator == request.user and not request.user.is_staff:
            messages.error(request, 'Permission denied.')
            return redirect('groups:groups-alllist')
        else:
            return super(GroupsUpdateView, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
    #    self.object.version += 1
        return super(GroupsUpdateView, self).form_valid(form)

    def get_form_kwargs(self):
        kwargs = super(GroupsUpdateView, self).get_form_kwargs()
        kwargs.update({'request_user': self.request.user})
        kwargs.update(self.kwargs)  # self.kwargs contains all url conf params
        return kwargs

    def get_success_url(self):
        action.send(self.request.user, verb='updated', target=self.object)
        return reverse("groups:groups-detail",
                       kwargs={'pk': self.kwargs['pk']})

@login_required
@csrf_exempt
def follow_group(request, pk):
    """
    Creates the follow relationship between ``request.user`` and the ``Group``
    """
    group = get_object_or_404(Group, id=pk)

    if group.is_public or request.user.is_staff:
        actions.follow(request.user, group, send_action=True)
        notify.send(request.user, recipient=group.creator, verb=u'has followed your Group', level='success')
        request.user.userprofile.follow_groups.add(group)
        messages.success(request, 'Successed, you are following this Group.')
    else:
        messages.error(request, 'Permission denied.')

    return redirect('groups:groups-detail', pk)
<commit_msg>更新 views GroupsJoinView 和 follow_group(), 當使用者加入群組時，自動幫使用者 follow group。而 follow_group() 是給非 member 使用的<commit_after># -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals

from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.messages.views import SuccessMessageMixin
from django.core.urlresolvers import reverse
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import CreateView, DetailView, ListView, RedirectView, UpdateView
from django.shortcuts import redirect, render, get_object_or_404

from actstream import action
from actstream import actions
from braces.views import LoginRequiredMixin
from notifications.signals import notify

from .models import Group
from .forms import GroupForm, GroupUpdateForm, GroupAddForm , GroupLeaveForm
from django.db.models import Q

class GroupsAbortView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
    model = Group
    form_class = GroupLeaveForm
    query_pk_and_slug = True
    template_name = 'groups/groups_abort.html'
    success_message = "You aborted Group %(name)s successfully"

    def form_valid(self, form):
        # remove request user from the members of group
        form.instance.members.remove(self.request.user)
        form.save()

        return super(GroupsAbortView, self).form_valid(form)

    def get_form_kwargs(self):
        kwargs = super(GroupsAbortView, self).get_form_kwargs()
        kwargs.update({'request_user': self.request.user})
        kwargs.update(self.kwargs)  # self.kwargs contains all url conf params
        return kwargs

    def get_success_url(self):
        action.send(self.request.user, verb='aborted', target=self.object)
        notify.send(self.request.user, recipient=self.object.creator, verb=u'has aborted from your Group', level='success')
        return reverse("groups:groups-detail",
                       kwargs={'pk': self.kwargs['pk']})

class GroupsCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
    model = Group
    form_class = GroupForm
    template_name = "groups/groups_create.html"
    success_message = "%(name)s was created successfully"

    def get_form_kwargs(self):
        kwargs = super(GroupsCreateView, self).get_form_kwargs()
        kwargs.update({'request_user': self.request.user})
        kwargs.update(self.kwargs)  # self.kwargs contains all url conf params
        return kwargs

    def get_success_url(self):
        action.send(self.request.user, verb='created', target=self.object)
        return super(GroupsCreateView, self).get_success_url()

class GroupsDetailView(LoginRequiredMixin, DetailView):
    model = Group
    query_pk_and_slug = True
    template_name = 'groups/groups_detail.html'

class GroupsJoinView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
    model = Group
    form_class = GroupAddForm
    query_pk_and_slug = True
    template_name = 'groups/groups_join.html'
    success_message = "You joined Group %(name)s successfully"

    def form_valid(self, form):
        # add request user to the members of group
        form.instance.members.add(self.request.user)
        form.save()

        return super(GroupsJoinView, self).form_valid(form)

    def get_form_kwargs(self):
        kwargs = super(GroupsJoinView, self).get_form_kwargs()
        kwargs.update({'request_user': self.request.user})
        kwargs.update(self.kwargs)  # self.kwargs contains all url conf params
        return kwargs

    def get_success_url(self):
        action.send(self.request.user, verb='joined', target=self.object)
        actions.follow(self.request.user, self.object, send_action=True)
        notify.send(self.request.user, recipient=self.object.creator, verb=u'has joined to your Group', level='success')
        return reverse("groups:groups-detail",
                       kwargs={'pk': self.kwargs['pk']})

class GroupsListView(LoginRequiredMixin, ListView):
    template_name = 'groups/groups_list.html'
    paginate_by = settings.GROUPS_MAX_ITEMS_PER_PAGE

    def get_queryset(self):
        return Group.objects.all()

class GroupsMyListView(LoginRequiredMixin, ListView):
    template_name = 'groups/groups_my_list.html'
    paginate_by = settings.GROUPS_MAX_ITEMS_PER_PAGE

    def get_queryset(self):
        return Group.objects.filter(creator=self.request.user)

class GroupsUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
    model = Group
    form_class = GroupUpdateForm
    query_pk_and_slug = True
    template_name = 'groups/groups_update.html'
    success_message = "%(name)s was updated successfully"

    def dispatch(self, request, *args, **kwargs):
        group = get_object_or_404(Group, pk=self.kwargs['pk'])

        if not group.creator == request.user and not request.user.is_staff:
            messages.error(request, 'Permission denied.')
            return redirect('groups:groups-alllist')
        else:
            return super(GroupsUpdateView, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
    #    self.object.version += 1
        return super(GroupsUpdateView, self).form_valid(form)

    def get_form_kwargs(self):
        kwargs = super(GroupsUpdateView, self).get_form_kwargs()
        kwargs.update({'request_user': self.request.user})
        kwargs.update(self.kwargs)  # self.kwargs contains all url conf params
        return kwargs

    def get_success_url(self):
        action.send(self.request.user, verb='updated', target=self.object)
        return reverse("groups:groups-detail",
                       kwargs={'pk': self.kwargs['pk']})

@login_required
@csrf_exempt
def follow_group(request, pk):
    """
    Creates the follow relationship between ``request.user`` and the ``Group``
    """
    group = get_object_or_404(Group, id=pk)

    # Check user is not member of the group
    if not group.members.filter(id=request.user.id).exists():
        actions.follow(request.user, group, send_action=True)
        notify.send(request.user, recipient=group.creator, verb=u'has followed your Group', level='success')
        request.user.userprofile.follow_groups.add(group)
        messages.success(request, 'Successed, you are following this Group.')

    return redirect('groups:groups-detail', pk)
<|endoftext|>


<commit_before># Copyright 2018 Google LLC
#
# 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.

import setuptools

with open("README.rst", "r") as fh:
    long_description = fh.read()

namespaces = ['compatibility_lib']

setuptools.setup(
    name="compatibility_lib",
    version="0.0.6",
    author="Cloud Python",
    description="A library to get and store the dependency compatibility status"
                "data to BigQuery.",
    long_description=long_description,
    license="Apache-2.0",
    include_package_data=True,
    url="https://github.com/GoogleCloudPlatform/cloud-opensource-python/tree/master/compatibility_lib",
    packages=setuptools.find_packages(),
    namespace_packages=namespaces,
    classifiers=(
        "Intended Audience :: Developers",
        "Development Status :: 3 - Alpha",
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: Apache Software License",
    ),
)
<commit_msg>0.0.7 (#121)<commit_after># Copyright 2018 Google LLC
#
# 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.

import setuptools

with open("README.rst", "r") as fh:
    long_description = fh.read()

namespaces = ['compatibility_lib']

setuptools.setup(
    name="compatibility_lib",
    version="0.0.7",
    author="Cloud Python",
    description="A library to get and store the dependency compatibility status"
                "data to BigQuery.",
    long_description=long_description,
    license="Apache-2.0",
    include_package_data=True,
    url="https://github.com/GoogleCloudPlatform/cloud-opensource-python/tree/master/compatibility_lib",
    packages=setuptools.find_packages(),
    namespace_packages=namespaces,
    classifiers=(
        "Intended Audience :: Developers",
        "Development Status :: 3 - Alpha",
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: Apache Software License",
    ),
)
<|endoftext|>


<commit_before>import feedparser, json
from bottle import Request, route, run, view, template, install, redirect, hook, request, response, abort, static_file, JSONPlugin

from models import *

class CustomJsonEncoder(json.JSONEncoder):
	def default(self, obj):
		if isinstance(obj, datetime):
			return str(obj.strftime("%Y-%m-%d %H:%M:%S"))
		if isinstance(obj, Model):
			return obj.__dict__['_data']
		return json.JSONEncoder.default(self, obj)

install(JSONPlugin(json_dumps=lambda s: json.dumps(s, cls=CustomJsonEncoder)))

def accept_json(self):
	return True if (self.get_header('Accept') == 'application/json') else False

Request.accept_json = accept_json

def is_active(url):
	fullpath = request.path + ('?' + request.query_string if request.query_string else '')
	return 'active' if fullpath == url else ''

@hook('before_request')
def connect():
	db.connect()

@hook('after_request')
def disconnect():
	db.close()

@route('/')
def index():
	redirect('/items')

@route('/channels/<id:int>/items', method = 'GET')
@route('/items', method = 'GET')
def items(id = None):
	valid_params = {'1' : True, '0' : False}
	starred = valid_params.get(request.query.getone('starred'))
	read = valid_params.get(request.query.getone('read'))

	channel = request.query.channel or id
	since_id  = request.query.since_id
	max_id = request.query.max_id
	count = int(request.query.count) if request.query.count else None
	page = int(request.query.page) if request.query.page else None

	query = Item.select()
	if channel: query = query.where(Item.channel == channel)
	if starred: query = query.where(Item.starred == starred)
	if read: query = query.where(Item.read == read)
	if since_id: query = query.where(Item.id >= since_id)
	if max_id: query = query.where(Item.id <= max_id)
	if page: query = query.paginate(page, count)

	items = list(query.order_by(Item.updated.desc()).limit(count))
	if (request.accept_json()):
		return { 'items' : items }
	else:
		return template('index', items = items, channels = Channel.select(), is_active = is_active)

@route('/items/<id:int>', method = 'GET')
def item(id):
	try:
		item = Item.get(Item.id == id)
	except Item.DoesNotExist:
		abort(404, 'Item does not exist')
	return {'item' : item}

@route('/items/<id:int>', method = 'PATCH')
def patch_item(id):
	try:
		item = Item.get(Item.id == id)
	except Item.DoesNotExist:
		abort(404)

	valid_keys = ['read', 'starred']
	for key in set(valid_keys).intersection(set(request.json.keys())):
		setattr(item, key, request.json[key])

	item.save()
	return response.status

@route("/channels", method = 'GET')
def channels():
	return { 'channels' : Channel.select() }

@route("/channels/<id:int>", method = 'GET')
def channel(id):
	try:
		channel = Channel.get(Channel.id == id)
	except:
		abort(404, 'Channel does not exist')
	return { 'channel' : channel }

@route('/channels/<id:int>/delete', method = 'GET')
def delete_channel_confirm(id):
	try:
		channel = Channel.get(Channel.id == id)
	except Channel.DoesNotExist:
		abort(404)
	tpl = """Delete channel {{channel.title}}?
	<form action="/channels/{{channel.id}}/delete" method="post">
	<input type ="submit" value="Ok"></form>"""
	return template(tpl, channel = channel)

@route('/channels/<id:int>', method = 'DELETE')
@route('/channels/<id:int>/delete', method = 'POST')
def delete_channel(id):
	try:
		c = Channel.get(Channel.id == id)
		Item.delete().where(Item.channel == c).execute()
		Channel.delete().where(Channel.id == id).execute()
	except Channel.DoesNotExist:
		abort(404, 'Channel does not exist')
	redirect('/')

@route('/channels/create', method = 'GET')
def create_channel():
	return """<form action="/channels" method="POST">
		Url: <input type="text" name = "url" class="url"/>
		<input type="submit" value = "Add">"""

@route('/channels', method = 'POST')
def post_channel():
	url = request.forms.get('url')
	try:
		Channel.create_from_url(url)
	except:
		abort(404, "Feed does not exist")
	channel = Channel.get(Channel.url == url)
	channel.update_feed()
	redirect('/channels/' + str(channel.id) + "/items")

@route('/channels/update', method = 'GET')
def update_channels():
	for c in Channel.select():
		c.update_feed()
	return redirect('/items')

@route('/channels/<id:int>/update', method='GET')
def update_channel(id):
	try:
		c = Channel.get(Channel.id == id)
		c.update_feed()
	except Channel.DoesNotExist:
		abort(404)
	return redirect('/channels/' + str(c.id) + '/items')

@route('/static/<filename>')
def server_static(filename):
	return static_file(filename, root='static/')

@route('/favicon.ico')
def get_favicon():
    return server_static('favicon.ico')

try:
	from mod_wsgi import version
except:
	run(host='0.0.0.0', port=3000, reloader = True, debug = True)
<commit_msg>Working mimerender.<commit_after>import feedparser, json
from bottle import Request, route, run, view, template, install, redirect, hook, request, response, abort, static_file, JSONPlugin
import mimerender
from models import *

class CustomJsonEncoder(json.JSONEncoder):
	def default(self, obj):
		if isinstance(obj, datetime):
			return str(obj.strftime("%Y-%m-%d %H:%M:%S"))
		if isinstance(obj, Model):
			return obj.__dict__['_data']
		return json.JSONEncoder.default(self, obj)

install(JSONPlugin(json_dumps=lambda s: json.dumps(s, cls=CustomJsonEncoder)))

def accept_json(self):
	return True if (self.get_header('Accept') == 'application/json') else False

Request.accept_json = accept_json

mimerender = mimerender.BottleMimeRender()

render_json = lambda **args: json.dumps(args, cls = CustomJsonEncoder)
render_html = lambda name = 'index', **kwargs: template(name, kwargs, is_active = is_active, channels = Channel.select())

def is_active(url):
	fullpath = request.path + ('?' + request.query_string if request.query_string else '')
	return 'active' if fullpath == url else ''

@hook('before_request')
def connect():
	db.connect()

@hook('after_request')
def disconnect():
	db.close()

@route('/')
def index():
	redirect('/items')

@route('/channels/<id:int>/items', method = 'GET')
@route('/items', method = 'GET')
@mimerender(default = 'html', html = render_html, json = render_json)
def items(id = None):
	valid_params = {'1' : True, '0' : False}
	starred = valid_params.get(request.query.getone('starred'))
	read = valid_params.get(request.query.getone('read'))

	channel = request.query.channel or id
	since_id  = request.query.since_id
	max_id = request.query.max_id
	count = int(request.query.count) if request.query.count else None
	page = int(request.query.page) if request.query.page else None

	query = Item.select()
	if channel: query = query.where(Item.channel == channel)
	if starred: query = query.where(Item.starred == starred)
	if read: query = query.where(Item.read == read)
	if since_id: query = query.where(Item.id >= since_id)
	if max_id: query = query.where(Item.id <= max_id)
	if page: query = query.paginate(page, count)

	items = list(query.order_by(Item.updated.desc()).limit(count))
	return { 'items' : items }

@route('/items/<id:int>', method = 'GET')
def item(id):
	try:
		item = Item.get(Item.id == id)
	except Item.DoesNotExist:
		abort(404, 'Item does not exist')
	return {'item' : item}

@route('/items/<id:int>', method = 'PATCH')
def patch_item(id):
	try:
		item = Item.get(Item.id == id)
	except Item.DoesNotExist:
		abort(404)

	valid_keys = ['read', 'starred']
	for key in set(valid_keys).intersection(set(request.json.keys())):
		setattr(item, key, request.json[key])

	item.save()
	return response.status

@route("/channels", method = 'GET')
def channels():
	return { 'channels' : Channel.select() }

@route("/channels/<id:int>", method = 'GET')
def channel(id):
	try:
		channel = Channel.get(Channel.id == id)
	except:
		abort(404, 'Channel does not exist')
	return { 'channel' : channel }

@route('/channels/<id:int>/delete', method = 'GET')
def delete_channel_confirm(id):
	try:
		channel = Channel.get(Channel.id == id)
	except Channel.DoesNotExist:
		abort(404)
	tpl = """Delete channel {{channel.title}}?
	<form action="/channels/{{channel.id}}/delete" method="post">
	<input type ="submit" value="Ok"></form>"""
	return template(tpl, channel = channel)

@route('/channels/<id:int>', method = 'DELETE')
@route('/channels/<id:int>/delete', method = 'POST')
def delete_channel(id):
	try:
		c = Channel.get(Channel.id == id)
		Item.delete().where(Item.channel == c).execute()
		Channel.delete().where(Channel.id == id).execute()
	except Channel.DoesNotExist:
		abort(404, 'Channel does not exist')
	redirect('/')

@route('/channels/create', method = 'GET')
def create_channel():
	return """<form action="/channels" method="POST">
		Url: <input type="text" name = "url" class="url"/>
		<input type="submit" value = "Add">"""

@route('/channels', method = 'POST')
def post_channel():
	url = request.forms.get('url')
	try:
		Channel.create_from_url(url)
	except:
		abort(404, "Feed does not exist")
	channel = Channel.get(Channel.url == url)
	channel.update_feed()
	redirect('/channels/' + str(channel.id) + "/items")

@route('/channels/update', method = 'GET')
def update_channels():
	for c in Channel.select():
		c.update_feed()
	return redirect('/items')

@route('/channels/<id:int>/update', method='GET')
def update_channel(id):
	try:
		c = Channel.get(Channel.id == id)
		c.update_feed()
	except Channel.DoesNotExist:
		abort(404)
	return redirect('/channels/' + str(c.id) + '/items')

@route('/static/<filename>')
def server_static(filename):
	return static_file(filename, root='static/')

@route('/favicon.ico')
def get_favicon():
    return server_static('favicon.ico')

try:
	from mod_wsgi import version
except:
	run(host='0.0.0.0', port=3000, reloader = True, debug = True)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
""" This module provides common functions which are usually needed in
all other submodules or interactively.
"""

import collections
import datetime
import functools
import itertools
import operator
import os
import os.path
import subprocess

from midas.compat import GzipFile
from midas.compat import ifilter
from midas.compat import imap
from midas.compat import urlparse
import midas.compat as vt_comp

import midas as md

### Functions that work on MapReduce-style 'key\tvalue' lines ###

def split_key_value(line, sep='\t'):
    return line.strip().split(sep, 1)

def get_key(line, sep='\t'):
    return split_key_value(line, sep)[0]

### Functions that are often needed in interactive use ###

def count_by_key(iterable, keyfunc=lambda o: o):
    counter = collections.defaultdict(int)
    for item in iterable:
        counter[keyfunc(item)] += 1
    return counter

def collect_by_key(iterable, keyfunc):
    collected = collections.defaultdict(list)
    for item in iterable:
        collected[keyfunc(item)].append(item)
    return collected

def relation_stats(iterable):
    counter = count_by_key(iterable)
    return (sum(vt_comp.d_itervalues(counter)),
            len(counter),
            sum(v for v in vt_comp.d_itervalues(counter) if v > 1),
            sum(1 for v in vt_comp.d_itervalues(counter) if v > 1))

### Functions to query sites and companies ###

SiteCount = collections.namedtuple('SiteCount', ['site', 'count'])

def make_p_empty_attr(attr_name):
    def p_empty_attr(o):
        attr = getattr(o, attr_name)
        return attr is None or attr == ''
    return p_empty_attr

### Useful miscelanious stuff ###

def takewhile_common(list1, list2):
    for a, b in zip(list1, list2):
        if a != b:
            break
        yield a

def iter_ts_until_gap(ts, all_dates):
    first_common = all_dates.index(ts[-1])
    return takewhile_common(ts[::-1], all_dates[first_common::-1])
<commit_msg>cleaning up<commit_after># -*- coding: utf-8 -*-
""" This module provides common functions which are usually needed in
all other submodules or interactively.
"""

import collections

from midas.compat import d_itervalues

### Functions that work on MapReduce-style 'key\tvalue' lines ###

def split_key_value(line, sep='\t'):
    return line.strip().split(sep, 1)

def get_key(line, sep='\t'):
    return split_key_value(line, sep)[0]

### Functions that are often needed in interactive use ###

def count_by_key(iterable, keyfunc=lambda o: o):
    counter = collections.defaultdict(int)
    for item in iterable:
        counter[keyfunc(item)] += 1
    return counter

def collect_by_key(iterable, keyfunc):
    collected = collections.defaultdict(list)
    for item in iterable:
        collected[keyfunc(item)].append(item)
    return collected

def relation_stats(iterable):
    counter = count_by_key(iterable)
    return (sum(d_itervalues(counter)),
            len(counter),
            sum(v for v in d_itervalues(counter) if v > 1),
            sum(1 for v in d_itervalues(counter) if v > 1))

### Functions to query sites and companies ###

def make_p_empty_attr(attr_name):
    def p_empty_attr(o):
        attr = getattr(o, attr_name)
        return attr is None or attr == ''
    return p_empty_attr

### Useful miscelanious stuff ###

def takewhile_common(list1, list2):
    for a, b in zip(list1, list2):
        if a != b:
            break
        yield a

def iter_ts_until_gap(ts, all_dates):
    first_common = all_dates.index(ts[-1])
    return takewhile_common(ts[::-1], all_dates[first_common::-1])
<|endoftext|>


<commit_before>"""
Django settings for {{ cookiecutter.repo_name }} project.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import os
from os.path import abspath, dirname, join, normpath
from sys import path

from django.core.exceptions import ImproperlyConfigured

def get_env_variable(var_name):
    """ Get the environment variable or return exception """
    try:
        return os.environ[var_name]
    except KeyError:
        error_msg = "Set the %s environment variable" % var_name
        raise ImproperlyConfigured(error_msg)

# Absolute filesystem path to the Django project directory:
DJANGO_ROOT = dirname(dirname(abspath(__file__)))

# Absolute filesystem path to the top-level project folder:
PROJECT_ROOT = dirname(DJANGO_ROOT)

# Add our project to our pythonpath, this way we don't need to type our project
# name in our dotted import paths:
path.append(DJANGO_ROOT)

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# Do not set SECRET_KEY or LDAP password or any other sensitive data here.
# Instead, create a local.py file on the server.

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'compressor',
    'taggit',
    'modelcluster',

    'wagtail.contrib.wagtailsitemaps',
    'wagtail.contrib.wagtailsearchpromotions',
    'wagtail.contrib.settings',
    'wagtail.wagtailforms',
    'wagtail.wagtailredirects',
    'wagtail.wagtailembeds',
    'wagtail.wagtailsites',
    'wagtail.wagtailusers',
    'wagtail.wagtailsnippets',
    'wagtail.wagtaildocs',
    'wagtail.wagtailimages',
    'wagtail.wagtailsearch',
    'wagtail.wagtailadmin',
    'wagtail.wagtailcore',

    'wagalytics',
    'wagtailfontawesome',

    {% if cookiecutter.use_django_cachalot == "y" %}
    'cachalot',
    {% endif %}

    'utils',
    'pages',
    'blog',
    'events',
    'contact',
    'people',
    'photo_gallery',
    'products',
    'documents_gallery',
    'feeds',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',

    'wagtail.wagtailcore.middleware.SiteMiddleware',
    'wagtail.wagtailredirects.middleware.RedirectMiddleware',
)

ROOT_URLCONF = '{{ cookiecutter.repo_name }}.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'debug' : DEBUG,
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'wagtail.contrib.settings.context_processors.settings',
            ],
        },
    },
]

WSGI_APPLICATION = '{{ cookiecutter.repo_name }}.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': '{{ cookiecutter.repo_name }}',
        'USER': '',
        'HOST': '',  # Set to empty string for localhost.
        'PORT': '',  # Set to empty string for default.
        'CONN_MAX_AGE': 600,
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_ROOT = join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'compressor.finders.CompressorFinder',
)

# 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.
)

MEDIA_ROOT = join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'

# Django compressor settings
# http://django-compressor.readthedocs.org/en/latest/settings/

COMPRESS_PRECOMPILERS = (
    ('text/x-scss', 'django_libsass.SassCompiler'),
)

COMPRESS_OFFLINE = True

# Settings for wagalytics
GA_KEY_FILEPATH = ''
GA_VIEW_ID = ''

# Google Maps Key

GOOGLE_MAPS_KEY = ''
DYNAMIC_MAP_URL = ''
STATIC_MAP_URL = ''

# Facebook Open Tags
FB_SITE_NAME = ''
FB_URL = ''
FB_DESCRIPTION = ''
FB_APP_ID = ''

# Twitter Cards

TWITTER_URL = ''
TWITTER_CREATOR = ''
TWITTER_DESCRIPTION = ''

# Use Redis as the cache backend for extra performance

{% if cookiecutter.use_django_cachalot == "y" %}

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

{% endif %}

# Wagtail settings

LOGIN_URL = 'wagtailadmin_login'
LOGIN_REDIRECT_URL = 'wagtailadmin_home'

WAGTAIL_SITE_NAME = "{{ cookiecutter.project_name }}"

WAGTAILSEARCH_RESULTS_TEMPLATE = 'utils/tags/search/search_results.html'

# Use Elasticsearch as the search backend for extra performance and better search results
# WAGTAILSEARCH_BACKENDS = {
#     'default': {
#         'BACKEND': 'wagtail.wagtailsearch.backends.elasticsearch.ElasticSearch',
#         'INDEX': '{{ cookiecutter.repo_name }}',
#     },
# }

# Celery settings
# When you have multiple sites using the same Redis server,
# specify a different Redis DB. e.g. redis://localhost/5

BROKER_URL = 'redis://'

CELERY_SEND_TASK_ERROR_EMAILS = True
CELERYD_LOG_COLOR = False
<commit_msg>Address issue #301 and #314<commit_after>"""
Django settings for {{ cookiecutter.repo_name }} project.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import os
from os.path import abspath, dirname, join, normpath
from sys import path

from django.core.exceptions import ImproperlyConfigured

def get_env_variable(var_name):
    """ Get the environment variable or return exception """
    try:
        return os.environ[var_name]
    except KeyError:
        error_msg = "Set the %s environment variable" % var_name
        raise ImproperlyConfigured(error_msg)

# Absolute filesystem path to the Django project directory:
DJANGO_ROOT = dirname(dirname(abspath(__file__)))

# Absolute filesystem path to the top-level project folder:
PROJECT_ROOT = dirname(DJANGO_ROOT)

# Add our project to our pythonpath, this way we don't need to type our project
# name in our dotted import paths:
path.append(DJANGO_ROOT)

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# Do not set SECRET_KEY or LDAP password or any other sensitive data here.
# Instead, create a local.py file on the server.

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'compressor',
    'taggit',
    'modelcluster',

    'wagtail.contrib.wagtailsitemaps',
    'wagtail.contrib.wagtailsearchpromotions',
    'wagtail.contrib.settings',
    'wagtail.wagtailforms',
    'wagtail.wagtailredirects',
    'wagtail.wagtailembeds',
    'wagtail.wagtailsites',
    'wagtail.wagtailusers',
    'wagtail.wagtailsnippets',
    'wagtail.wagtaildocs',
    'wagtail.wagtailimages',
    'wagtail.wagtailsearch',
    'wagtail.wagtailadmin',
    'wagtail.wagtailcore',

    'wagalytics',
    'wagtailfontawesome',

    {% if cookiecutter.use_django_cachalot == "y" %}
    'cachalot',
    {% endif %}

    'utils',
    'pages',
    'blog',
    'events',
    'contact',
    'people',
    'photo_gallery',
    'products',
    'documents_gallery',
    'feeds',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',

    'wagtail.wagtailcore.middleware.SiteMiddleware',
    'wagtail.wagtailredirects.middleware.RedirectMiddleware',
)

ROOT_URLCONF = '{{ cookiecutter.repo_name }}.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'debug' : DEBUG,
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'wagtail.contrib.settings.context_processors.settings',
            ],
        },
    },
]

WSGI_APPLICATION = '{{ cookiecutter.repo_name }}.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': '{{ cookiecutter.repo_name }}',
        'USER': '',
        'HOST': '',  # Set to empty string for localhost.
        'PORT': '',  # Set to empty string for default.
        'CONN_MAX_AGE': 600,
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_ROOT = join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'compressor.finders.CompressorFinder',
)

# 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.
)

MEDIA_ROOT = join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'

# Django compressor settings
# http://django-compressor.readthedocs.org/en/latest/settings/

COMPRESS_PRECOMPILERS = (
    ('text/x-scss', 'django_libsass.SassCompiler'),
)

COMPRESS_OFFLINE = True

# Settings for wagalytics
GA_KEY_FILEPATH = ''
GA_VIEW_ID = ''

# Google Maps Key

GOOGLE_MAPS_KEY = ''
DYNAMIC_MAP_URL = ''
STATIC_MAP_URL = ''

# Use Redis as the cache backend for extra performance

{% if cookiecutter.use_django_cachalot == "y" %}

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

{% endif %}

# Wagtail settings

LOGIN_URL = 'wagtailadmin_login'
LOGIN_REDIRECT_URL = 'wagtailadmin_home'

WAGTAIL_SITE_NAME = "{{ cookiecutter.project_name }}"

WAGTAILSEARCH_RESULTS_TEMPLATE = 'utils/tags/search/search_results.html'

# Use Elasticsearch as the search backend for extra performance and better search results
# WAGTAILSEARCH_BACKENDS = {
#     'default': {
#         'BACKEND': 'wagtail.wagtailsearch.backends.elasticsearch.ElasticSearch',
#         'INDEX': '{{ cookiecutter.repo_name }}',
#     },
# }

# Celery settings
# When you have multiple sites using the same Redis server,
# specify a different Redis DB. e.g. redis://localhost/5

BROKER_URL = 'redis://'

CELERY_SEND_TASK_ERROR_EMAILS = True
CELERYD_LOG_COLOR = False
<|endoftext|>


<commit_before># coding: utf-8
import logging
import sqlparse
from pygments import highlight
from pygments.lexers import SqlLexer
from pygments.formatters import TerminalFormatter

LEXER = SqlLexer()
FORMATTER = TerminalFormatter()

class SqlFormatter(logging.Formatter):
    def __init__(self, *args, **kwargs):
        super(SqlFormatter, self).__init__(*args, **kwargs)

    def format(self, record):
        msg = super(SqlFormatter, self).format(record)
        msg = sqlparse.format(record.msg, reindent=True, keyword_case='upper')
        return highlight(msg, LEXER, FORMATTER)
<commit_msg>Make SqlFormatter more flexible<commit_after># coding: utf-8
import sys
import logging
import sqlparse
from pygments import highlight
from pygments.lexers import SqlLexer
from pygments.formatters import Terminal256Formatter

class SqlFormatter(logging.Formatter):
    def __init__(self, *args, **kwargs):
        self.highlight = kwargs.pop('highlight', True)
        self.style = kwargs.pop('style', 'default')

        self.parse = kwargs.pop('parse', True)
        self.reindent = kwargs.pop('reindent', True)
        self.keyword_case = kwargs.pop('keyword_case', 'upper')

        self._lexer = SqlLexer()
        self._formatter = Terminal256Formatter(style=self.style)

        super(SqlFormatter, self).__init__(*args, **kwargs)

    def format(self, record):
        super(SqlFormatter, self).format(record)

        msg = record.msg

        if self.parse:
            msg = sqlparse.format(record.msg, reindent=self.reindent, keyword_case=self.keyword_case)

        if self.highlight:
            msg = highlight(msg, self._lexer, self._formatter)

        return msg

class LogDb:
    def __init__(self):
        self.handler = None
        self.propagate = None

    def __call__(self, **options):
        logger = logging.getLogger('django.db.backends')

        if self.handler is None:
            # Enable
            self.handler = logging.StreamHandler(sys.stdout)
            self.handler.setFormatter(SqlFormatter(**options))
            logger.addHandler(self.handler)
            logger.setLevel(logging.DEBUG)

            self.propagate = logger.propagate
            logger.propagate = False
        else:
            # Disable
            logger.removeHandler(self.handler)
            self.handler = None
            logger.setLevel(logging.NOTSET)

            logger.propagate = self.propagate
            self.propagate = None

        return self.handler

logdb = LogDb()
<|endoftext|>


<commit_before>from __future__ import print_function

import numpy as np
import matplotlib.pyplot as plt

import compressible.BC as BC
from compressible.problems import *
import compressible.eos as eos
import mesh.patch as patch
from simulation_null import NullSimulation, grid_setup, bc_setup
from compressible.unsplitFluxes import *
from util import profile

class Variables(object):
    """
    a container class for easy access to the different compressible
    variable by an integer key
    """
    def __init__(self, idens=-1, ixmom=-1, iymom=-1, iener=-1):
        self.nvar = 4

        # conserved variables -- we set these when we initialize for
        # they match the CellCenterData2d object
        self.idens = idens
        self.ixmom = ixmom
        self.iymom = iymom
        self.iener = iener

        # primitive variables
        self.irho = 0
        self.iu = 1
        self.iv = 2
        self.ip = 3

class Simulation(NullSimulation):

    def initialize(self):
        """
        Initialize the grid and variables for compressible flow and set
        the initial conditions for the chosen problem.
        """

        my_grid = grid_setup(self.rp, ng=4)
        my_data = patch.CellCenterData2d(my_grid)

        # define solver specific boundary condition routines
        patch.define_bc("hse", BC.user)

        bc, bc_xodd, bc_yodd = bc_setup(self.rp)

        # density and energy
        my_data.register_var("density", bc)
        my_data.register_var("energy", bc)
        my_data.register_var("x-momentum", bc_xodd)
        my_data.register_var("y-momentum", bc_yodd)

        # store the EOS gamma as an auxillary quantity so we can have a
        # self-contained object stored in output files to make plots.
        # store grav because we'll need that in some BCs
        my_data.set_aux("gamma", self.rp.get_param("eos.gamma"))
        my_data.set_aux("grav", self.rp.get_param("compressible.grav"))

        my_data.create()

        self.cc_data = my_data

        self.vars = Variables(idens = my_data.vars.index("density"),
                              ixmom = my_data.vars.index("x-momentum"),
                              iymom = my_data.vars.index("y-momentum"),
                              iener = my_data.vars.index("energy"))

        # initial conditions for the problem
        exec(self.problem_name + '.init_data(self.cc_data, self.rp)')

        if self.verbose > 0: print(my_data)

    def timestep(self):
        """
        The timestep function computes the advective timestep (CFL)
        constraint.  The CFL constraint says that information cannot
        propagate further than one zone per timestep.

        We use the driver.cfl parameter to control what fraction of the
        CFL step we actually take.
        """

        cfl = self.rp.get_param("driver.cfl")

        # get the variables we need
        dens = self.cc_data.get_var("density")
        xmom = self.cc_data.get_var("x-momentum")
        ymom = self.cc_data.get_var("y-momentum")
        ener = self.cc_data.get_var("energy")

        # we need to compute the pressure
        u = xmom/dens
        v = ymom/dens

        e = (ener - 0.5*dens*(u*u + v*v))/dens

        gamma = self.rp.get_param("eos.gamma")

        p = eos.pres(gamma, dens, e)

        # compute the sounds speed
        cs = np.sqrt(gamma*p/dens)

        # the timestep is min(dx/(|u| + cs), dy/(|v| + cs))
        xtmp = self.cc_data.grid.dx/(abs(u) + cs)
        ytmp = self.cc_data.grid.dy/(abs(v) + cs)

        dt = cfl*min(xtmp.min(), ytmp.min())

        return dt

    def evolve(self, dt):
        """
        Evolve the equations of compressible hydrodynamics through a
        timestep dt.
        """

        tm_evolve = self.tc.timer("evolve")
        tm_evolve.begin()

        dens = self.cc_data.get_var("density")
        ymom = self.cc_data.get_var("y-momentum")
        ener = self.cc_data.get_var("energy")

        grav = self.rp.get_param("compressible.grav")

        myg = self.cc_data.grid

        Flux_x, Flux_y = unsplitFluxes(self.cc_data, self.rp, self.vars, self.tc, dt)

        old_dens = dens.copy()
        old_ymom = ymom.copy()

        # conservative update
        dtdx = dt/myg.dx
        dtdy = dt/myg.dy

        for n in range(self.vars.nvar):
            var = self.cc_data.get_var_by_index(n)

            var.v()[:,:] += \
                dtdx*(Flux_x.v(n=n) - Flux_x.ip(1, n=n)) + \
                dtdy*(Flux_y.v(n=n) - Flux_y.jp(1, n=n))

        # gravitational source terms
        ymom += 0.5*dt*(dens + old_dens)*grav
        ener += 0.5*dt*(ymom + old_ymom)*grav

        tm_evolve.end()

    def dovis(self):
        """
        Do runtime visualization.
        """

        plt.clf()

        plt.rc("font", size=10)

        dens = self.cc_data.get_var("density")
        xmom = self.cc_data.get_var("x-momentum")
        ymom = self.cc_data.get_var("y-momentum")
        ener = self.cc_data.get_var("energy")

        # get the velocities
        u = xmom/dens
        v = ymom/dens

        # get the pressure
        magvel = u**2 + v**2   # temporarily |U|^2
        rhoe = (ener - 0.5*dens*magvel)

        magvel = np.sqrt(magvel)

        e = rhoe/dens

        # access gamma from the cc_data object so we can use dovis
        # outside of a running simulation.
        gamma = self.cc_data.get_aux("gamma")

        p = eos.pres(gamma, dens, e)

        myg = self.cc_data.grid

        # figure out the geometry
        L_x = self.cc_data.grid.xmax - self.cc_data.grid.xmin
        L_y = self.cc_data.grid.ymax - self.cc_data.grid.ymin

        orientation = "vertical"
        shrink = 1.0

        sparseX = 0
        allYlabel = 1

        if L_x > 2*L_y:

            # we want 4 rows:
            #  rho
            #  |U|
            #   p
            #   e
            fig, axes = plt.subplots(nrows=4, ncols=1, num=1)
            orientation = "horizontal"
            if (L_x > 4*L_y):
                shrink = 0.75

            onLeft = list(range(self.vars.nvar))

        elif L_y > 2*L_x:

            # we want 4 columns:  rho  |U|  p  e
            fig, axes = plt.subplots(nrows=1, ncols=4, num=1)
            if (L_y >= 3*L_x):
                shrink = 0.5
                sparseX = 1
                allYlabel = 0

            onLeft = [0]

        else:
            # 2x2 grid of plots with
            #
            #   rho   |u|
            #    p     e
            fig, axes = plt.subplots(nrows=2, ncols=2, num=1)
            plt.subplots_adjust(hspace=0.25)

            onLeft = [0,2]

        fields = [dens, magvel, p, e]
        field_names = [r"$\rho$", r"U", "p", "e"]

        for n in range(4):
            ax = axes.flat[n]

            v = fields[n]
            img = ax.imshow(np.transpose(v.v()),
                        interpolation="nearest", origin="lower",
                        extent=[myg.xmin, myg.xmax, myg.ymin, myg.ymax])

            ax.set_xlabel("x")
            if n == 0:
                ax.set_ylabel("y")
            elif allYlabel:
                ax.set_ylabel("y")

            ax.set_title(field_names[n])

            if not n in onLeft:
                ax.yaxis.offsetText.set_visible(False)
                if n > 0: ax.get_yaxis().set_visible(False)

            if sparseX:
                ax.xaxis.set_major_locator(plt.MaxNLocator(3))

            plt.colorbar(img, ax=ax, orientation=orientation, shrink=shrink)

        plt.figtext(0.05,0.0125, "t = %10.5f" % self.cc_data.t)

        plt.draw()
<commit_msg>we were not seeing the update to ymom and ener from gravity<commit_after>from __future__ import print_function

import numpy as np
import matplotlib.pyplot as plt

import compressible.BC as BC
from compressible.problems import *
import compressible.eos as eos
import mesh.patch as patch
from simulation_null import NullSimulation, grid_setup, bc_setup
from compressible.unsplitFluxes import *
from util import profile

class Variables(object):
    """
    a container class for easy access to the different compressible
    variable by an integer key
    """
    def __init__(self, idens=-1, ixmom=-1, iymom=-1, iener=-1):
        self.nvar = 4

        # conserved variables -- we set these when we initialize for
        # they match the CellCenterData2d object
        self.idens = idens
        self.ixmom = ixmom
        self.iymom = iymom
        self.iener = iener

        # primitive variables
        self.irho = 0
        self.iu = 1
        self.iv = 2
        self.ip = 3

class Simulation(NullSimulation):

    def initialize(self):
        """
        Initialize the grid and variables for compressible flow and set
        the initial conditions for the chosen problem.
        """

        my_grid = grid_setup(self.rp, ng=4)
        my_data = patch.CellCenterData2d(my_grid)

        # define solver specific boundary condition routines
        patch.define_bc("hse", BC.user)

        bc, bc_xodd, bc_yodd = bc_setup(self.rp)

        # density and energy
        my_data.register_var("density", bc)
        my_data.register_var("energy", bc)
        my_data.register_var("x-momentum", bc_xodd)
        my_data.register_var("y-momentum", bc_yodd)

        # store the EOS gamma as an auxillary quantity so we can have a
        # self-contained object stored in output files to make plots.
        # store grav because we'll need that in some BCs
        my_data.set_aux("gamma", self.rp.get_param("eos.gamma"))
        my_data.set_aux("grav", self.rp.get_param("compressible.grav"))

        my_data.create()

        self.cc_data = my_data

        self.vars = Variables(idens = my_data.vars.index("density"),
                              ixmom = my_data.vars.index("x-momentum"),
                              iymom = my_data.vars.index("y-momentum"),
                              iener = my_data.vars.index("energy"))

        # initial conditions for the problem
        exec(self.problem_name + '.init_data(self.cc_data, self.rp)')

        if self.verbose > 0: print(my_data)

    def timestep(self):
        """
        The timestep function computes the advective timestep (CFL)
        constraint.  The CFL constraint says that information cannot
        propagate further than one zone per timestep.

        We use the driver.cfl parameter to control what fraction of the
        CFL step we actually take.
        """

        cfl = self.rp.get_param("driver.cfl")

        # get the variables we need
        dens = self.cc_data.get_var("density")
        xmom = self.cc_data.get_var("x-momentum")
        ymom = self.cc_data.get_var("y-momentum")
        ener = self.cc_data.get_var("energy")

        # we need to compute the pressure
        u = xmom/dens
        v = ymom/dens

        e = (ener - 0.5*dens*(u*u + v*v))/dens

        gamma = self.rp.get_param("eos.gamma")

        p = eos.pres(gamma, dens, e)

        # compute the sounds speed
        cs = np.sqrt(gamma*p/dens)

        # the timestep is min(dx/(|u| + cs), dy/(|v| + cs))
        xtmp = self.cc_data.grid.dx/(abs(u) + cs)
        ytmp = self.cc_data.grid.dy/(abs(v) + cs)

        dt = cfl*min(xtmp.min(), ytmp.min())

        return dt

    def evolve(self, dt):
        """
        Evolve the equations of compressible hydrodynamics through a
        timestep dt.
        """

        tm_evolve = self.tc.timer("evolve")
        tm_evolve.begin()

        dens = self.cc_data.get_var("density")
        ymom = self.cc_data.get_var("y-momentum")
        ener = self.cc_data.get_var("energy")

        grav = self.rp.get_param("compressible.grav")

        myg = self.cc_data.grid

        Flux_x, Flux_y = unsplitFluxes(self.cc_data, self.rp, self.vars, self.tc, dt)

        old_dens = dens.copy()
        old_ymom = ymom.copy()

        # conservative update
        dtdx = dt/myg.dx
        dtdy = dt/myg.dy

        for n in range(self.vars.nvar):
            var = self.cc_data.get_var_by_index(n)

            var.v()[:,:] += \
                dtdx*(Flux_x.v(n=n) - Flux_x.ip(1, n=n)) + \
                dtdy*(Flux_y.v(n=n) - Flux_y.jp(1, n=n))

        # gravitational source terms
        ymom.d[:,:] += 0.5*dt*(dens.d[:,:] + old_dens.d[:,:])*grav
        ener.d[:,:] += 0.5*dt*(ymom.d[:,:] + old_ymom.d[:,:])*grav

        tm_evolve.end()

    def dovis(self):
        """
        Do runtime visualization.
        """

        plt.clf()

        plt.rc("font", size=10)

        dens = self.cc_data.get_var("density")
        xmom = self.cc_data.get_var("x-momentum")
        ymom = self.cc_data.get_var("y-momentum")
        ener = self.cc_data.get_var("energy")

        # get the velocities
        u = xmom/dens
        v = ymom/dens

        # get the pressure
        magvel = u**2 + v**2   # temporarily |U|^2
        rhoe = (ener - 0.5*dens*magvel)

        magvel = np.sqrt(magvel)

        e = rhoe/dens

        # access gamma from the cc_data object so we can use dovis
        # outside of a running simulation.
        gamma = self.cc_data.get_aux("gamma")

        p = eos.pres(gamma, dens, e)

        myg = self.cc_data.grid

        # figure out the geometry
        L_x = self.cc_data.grid.xmax - self.cc_data.grid.xmin
        L_y = self.cc_data.grid.ymax - self.cc_data.grid.ymin

        orientation = "vertical"
        shrink = 1.0

        sparseX = 0
        allYlabel = 1

        if L_x > 2*L_y:

            # we want 4 rows:
            #  rho
            #  |U|
            #   p
            #   e
            fig, axes = plt.subplots(nrows=4, ncols=1, num=1)
            orientation = "horizontal"
            if (L_x > 4*L_y):
                shrink = 0.75

            onLeft = list(range(self.vars.nvar))

        elif L_y > 2*L_x:

            # we want 4 columns:  rho  |U|  p  e
            fig, axes = plt.subplots(nrows=1, ncols=4, num=1)
            if (L_y >= 3*L_x):
                shrink = 0.5
                sparseX = 1
                allYlabel = 0

            onLeft = [0]

        else:
            # 2x2 grid of plots with
            #
            #   rho   |u|
            #    p     e
            fig, axes = plt.subplots(nrows=2, ncols=2, num=1)
            plt.subplots_adjust(hspace=0.25)

            onLeft = [0,2]

        fields = [dens, magvel, p, e]
        field_names = [r"$\rho$", r"U", "p", "e"]

        for n in range(4):
            ax = axes.flat[n]

            v = fields[n]
            img = ax.imshow(np.transpose(v.v()),
                        interpolation="nearest", origin="lower",
                        extent=[myg.xmin, myg.xmax, myg.ymin, myg.ymax])

            ax.set_xlabel("x")
            if n == 0:
                ax.set_ylabel("y")
            elif allYlabel:
                ax.set_ylabel("y")

            ax.set_title(field_names[n])

            if not n in onLeft:
                ax.yaxis.offsetText.set_visible(False)
                if n > 0: ax.get_yaxis().set_visible(False)

            if sparseX:
                ax.xaxis.set_major_locator(plt.MaxNLocator(3))

            plt.colorbar(img, ax=ax, orientation=orientation, shrink=shrink)

        plt.figtext(0.05,0.0125, "t = %10.5f" % self.cc_data.t)

        plt.draw()
<|endoftext|>