<commit_before>#!/usr/bin/env python3
# Music Director using Multicast Ethernet
# January 2016
# Manuel Moreno

import socket
import struct
import json
import argparse
from DirectorMidiFile import *
from logger import *

# 8 music voices
# message = identifier, length of data, 8 notes (one per instrument)
# note = 0 means hold the last note
# note = 255 means silence, stop the last note

dim = 1000
can_frame_fmt = "=IB3x8s"

def build_can_frame(can_id, data):
    can_dlc = len(data)
    data = data.ljust(8, b'\x00')
    return struct.pack(can_frame_fmt, can_id, can_dlc, data)

class Director:
    """ Fist version using multicast ethernet
    """

    def __init__(self, tracks=8):
        # create a raw socket
        print("Init Multicast socket")
        self.multicast_group = ('224.0.0.1', 10000)
        # Create the datagram socket
        self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        # Set a timeout so the socket does not block indefinitely when trying
        # to receive data.
        self.s.settimeout(0.2)
        # Set the time-to-live for messages to 1 so they do not go past the
        # local network segment.
        ttl = struct.pack('b', 1)
        self.s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
        # print(str(self.notes[0]).replace(",", "\n"))

    def __setattr__(self, key, value):
        super().__setattr__(key, value)
        if key == "file_name":
            self.mid = DirectorMidiFile(self.file_name)
            self.tracks = len(self.mid.tracks)

    def play(self):
        t = 0
        logging.info("Playing...")

        for msg, track in self.mid.play_tracks():
            msg_out = {}
            msg_in = {}

            if msg.type == 'note_on':
                msg_in[track] = [msg.note]
            elif msg.type == 'note_off':
                msg_out[track] = [msg.note]
            else:
                continue

            json_string = json.dumps({
                "in": msg_in,
                "out": msg_out,
                "tracks": self.tracks
            })
            logging.debug("data_sent:" + json_string)
            sent = self.s.sendto(json_string.encode(), self.multicast_group)

        json_string = json.dumps({
            "in": {},
            "out": list(range(self.tracks)),
            "tracks": self.tracks
        })
        self.s.sendto(json_string.encode(), self.multicast_group)
        logging.info("Play Over")
        self.s.close()

def main():
    parser = argparse.ArgumentParser(description="Start director to play music with Pi Orchestra")
    parser.add_argument("-d", "--debug", action="store_true", help="Print debug information")
    args = parser.parse_args()

    if args.debug:
        logging.getLogger().setLevel(logging.DEBUG)
        logging.debug("Starting in DEBUG mode")

    dir1 = Director()
    dir1.file_name = "sheets/Mario.mid"
    dir1.play()

if __name__ == '__main__':
    set_default_logger("director.log")

    try:
        main()
    except KeyboardInterrupt:
        logging.info("Shutting down Director, Thanks for the ride!")
<commit_msg>Remove unnecessary variables<commit_after>#!/usr/bin/env python3
# Music Director using Multicast Ethernet
# January 2016
# Manuel Moreno

import socket
import struct
import json
import argparse
from DirectorMidiFile import *
from logger import *

# 8 music voices
# message = identifier, length of data, 8 notes (one per instrument)
# note = 0 means hold the last note
# note = 255 means silence, stop the last note

dim = 1000
can_frame_fmt = "=IB3x8s"

def build_can_frame(can_id, data):
    can_dlc = len(data)
    data = data.ljust(8, b'\x00')
    return struct.pack(can_frame_fmt, can_id, can_dlc, data)

class Director:
    """ Fist version using multicast ethernet
    """

    def __init__(self):
        self.file_name = None

        # create a raw socket
        print("Init Multicast socket")
        self.multicast_group = ('224.0.0.1', 10000)
        # Create the datagram socket
        self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        # Set a timeout so the socket does not block indefinitely when trying
        # to receive data.
        self.s.settimeout(0.2)
        # Set the time-to-live for messages to 1 so they do not go past the
        # local network segment.
        ttl = struct.pack('b', 1)
        self.s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
        # print(str(self.notes[0]).replace(",", "\n"))

    def __setattr__(self, key, value):
        super().__setattr__(key, value)
        if key == "file_name":
            self.mid = DirectorMidiFile(self.file_name)
            self.tracks = len(self.mid.tracks)

    def play(self):
        logging.info("Playing...")

        for msg, track in self.mid.play_tracks():
            msg_out = {}
            msg_in = {}

            if msg.type == 'note_on':
                msg_in[track] = [msg.note]
            elif msg.type == 'note_off':
                msg_out[track] = [msg.note]
            else:
                continue

            json_string = json.dumps({
                "in": msg_in,
                "out": msg_out,
                "tracks": self.tracks
            })
            logging.debug("data_sent:" + json_string)
            sent = self.s.sendto(json_string.encode(), self.multicast_group)

        json_string = json.dumps({
            "in": {},
            "out": list(range(self.tracks)),
            "tracks": self.tracks
        })
        self.s.sendto(json_string.encode(), self.multicast_group)
        logging.info("Play Over")
        self.s.close()

def main():
    parser = argparse.ArgumentParser(description="Start director to play music with Pi Orchestra")
    parser.add_argument("-d", "--debug", action="store_true", help="Print debug information")
    args = parser.parse_args()

    if args.debug:
        logging.getLogger().setLevel(logging.DEBUG)
        logging.debug("Starting in DEBUG mode")

    dir1 = Director()
    dir1.file_name = "sheets/Mario.mid"
    dir1.play()

if __name__ == '__main__':
    set_default_logger("director.log")

    try:
        main()
    except KeyboardInterrupt:
        logging.info("Shutting down Director, Thanks for the ride!")
<|endoftext|>


<commit_before>from urllib2 import urlopen
import urllib
import json

from base import *
from outcomes import Outcomes

class ApplicationTest(BaseTest):

    def test_index(self):
        u = urlopen(URL)
        self.assertEqual(u.getcode(), 200)
        self.assertEqual(URL, u.geturl())
        meta = u.info()
        self.assertEqual(meta.getheaders('content-type'), [MIME_HTML])
        content = [line for line in u][0]
        self.assertRegexpMatches(content, 'Hello world')

    outcome_definition = [
        {'field': 'id', 'type': int},
        {'field': 'category_id', 'type': int},
        {'field': 'created_at', 'type': unicode},
        {'field': 'created_by', 'type': int},
        {'field': 'amount', 'type': float},
        {'field': 'description', 'type': unicode}
    ]

    def assertOutcomeIsCorrect(self, outcome):
        for field in self.outcome_definition:
            self.assertTrue(outcome.has_key(field['field']))
            self.assertTrue(type(outcome[field['field']]) is field['type'])

    def test_list(self):
        u = urlopen(URL + '/outcomes')
        self.assertEqual(u.getcode(), 200)
        meta = u.info()
        self.assertEqual(meta.getheaders('content-type'), [MIME_JSON])
        data = json.loads([line for line in u][0])
        self.assertIsInstance(data['objects'], list)
        self.assertIsInstance(data['meta'], dict)
        for outcome in data['objects']:
            self.assertOutcomeIsCorrect(outcome)

    def test_show(self):
        u = urlopen(URL + '/outcomes/1')
        self.assertEqual(u.getcode(), 200)
        meta = u.info()
        self.assertEqual(meta.getheaders('content-type'), [MIME_JSON])
        content = [line for line in u][0]
        outcome = json.loads(content)
        O = Outcomes()
        self.assertEqual(outcome, O.getOneBy('1'))
        self.assertOutcomeIsCorrect(outcome)

    def test_add(self):
        params = {
            'category_id': 2,
            'amount': 2.0,
            'created_by': 2,
            'created_at': '2013-09-02 00:00:00',
            'description': 'dunno what'
        }
        params = urllib.urlencode(params)
        f = urllib.urlopen(URL + '/outcomes', params)
<commit_msg>simplified test outcome definition<commit_after>from urllib2 import urlopen
import urllib
import json

from base import *
from outcomes import Outcomes

class ApplicationTest(BaseTest):

    def test_index(self):
        u = urlopen(URL)
        self.assertEqual(u.getcode(), 200)
        self.assertEqual(URL, u.geturl())
        meta = u.info()
        self.assertEqual(meta.getheaders('content-type'), [MIME_HTML])
        content = [line for line in u][0]
        self.assertRegexpMatches(content, 'Hello world')

    outcome_definition = {
        'id': int,
        'category_id': int,
        'created_at': unicode,
        'created_by': int,
        'amount': float,
        'description': unicode
    }

    def assertOutcomeIsCorrect(self, outcome):
        for field in self.outcome_definition:
            self.assertTrue(outcome.has_key(field))
            self.assertTrue(type(outcome[field]) is self.outcome_definition[field])

    def test_list(self):
        u = urlopen(URL + '/outcomes')
        self.assertEqual(u.getcode(), 200)
        meta = u.info()
        self.assertEqual(meta.getheaders('content-type'), [MIME_JSON])
        data = json.loads([line for line in u][0])
        self.assertIsInstance(data['objects'], list)
        self.assertIsInstance(data['meta'], dict)
        for outcome in data['objects']:
            self.assertOutcomeIsCorrect(outcome)

    def test_show(self):
        u = urlopen(URL + '/outcomes/1')
        self.assertEqual(u.getcode(), 200)
        meta = u.info()
        self.assertEqual(meta.getheaders('content-type'), [MIME_JSON])
        content = [line for line in u][0]
        outcome = json.loads(content)
        O = Outcomes()
        self.assertEqual(outcome, O.getOneBy('1'))
        self.assertOutcomeIsCorrect(outcome)

    def test_add(self):
        params = {
            'category_id': 2,
            'amount': 2.0,
            'created_by': 2,
            'created_at': '2013-09-02 00:00:00',
            'description': 'dunno what'
        }
        params = urllib.urlencode(params)
        f = urllib.urlopen(URL + '/outcomes', params)
<|endoftext|>


<commit_before>import os
import sys
import subprocess
import shlex
import shutil
import sys
import time
import datetime
import pytest

HERE = os.path.abspath(os.path.dirname(__file__))

skip_on_windows = pytest.mark.skipif('sys.platform == "win32"', reason="not working on windows")
skip_on_osx = pytest.mark.skipif('sys.platform == "darwin"', reason="not working on osx")
skip_always = pytest.mark.skipif('1 == 1', reason="tests are broken")

# ------------------------------------------------------------------------------

def exe(command):
    """
    Executes command and returns string representations of stdout and stderr captured from the console.
    When universal_newlines=True stdout and stderr are opened in text mode.
    Otherwise, they are opened in binary mode. In that case captured stdout and stderr
    are not strings and Python 3 throws type error when compared against strings later in tests.
    Note:
    This feature is only available if Python is built with universal newline support (the default).
    Also, the newlines attribute of the file objects stdout, stdin and stderr are not updated by the
    communicate() method.
    See https://docs.python.org/2/library/subprocess.html
    """
    stdout, stderr = subprocess.Popen(shlex.split(command),
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE,
                                      universal_newlines=True).communicate()

    if stderr:
        sys.stderr.write(stderr)

    return stdout, stderr

# ------------------------------------------------------------------------------

def configure_build_and_exe(name, setup_command, launcher=None):

    stamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d-%H-%M-%S')

    os.chdir(os.path.join(HERE, name, 'cmake'))
    shutil.copy(os.path.join('..', '..', '..', 'update.py'), 'update.py')

    dst_dir = 'lib'
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    shutil.copy(os.path.join('..', '..', '..', dst_dir, 'config.py'), dst_dir)

    dst_dir = os.path.join('lib', 'docopt')
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    shutil.copy(os.path.join('..', '..', '..', dst_dir, 'docopt.py'), dst_dir)

    stdout, stderr = exe('python update.py ..')
    os.chdir(os.path.join(HERE, name))

    make_command = 'make'
    binary = './bin/example'
    if sys.platform == 'win32':
        setup_command += ' --generator="MinGW Makefiles"'
        make_command = 'mingw32-make'
        binary = 'bin\\\example.exe'

    if launcher:
        binary = '%s %s' % (launcher, binary)

    setup_command += ' build-%s' % stamp

    stdout, stderr = exe(setup_command)

    os.chdir(os.path.join(HERE, name, 'build-%s' % stamp))

    stdout, stderr = exe(make_command)
    # mi: remove <assert stderr == ''> due to warnings flushed to stderr

    stdout, stderr = exe(binary)
    assert stderr == ''

    assert 'PASSED' in stdout

# ------------------------------------------------------------------------------

def test_cxx_custom():
    configure_build_and_exe('cxx_custom', 'python setup.py --cxx=g++')

# ------------------------------------------------------------------------------

def test_extra_cmake_options():
    configure_build_and_exe('extra_cmake_options', 'python setup.py --cxx=g++ --cmake-options="-DENABLE_SOMETHING=OFF -DENABLE_FOO=ON"')

# ------------------------------------------------------------------------------

def test_cxx():
    configure_build_and_exe('cxx', 'python setup.py --cxx=g++')

@skip_on_osx
def test_cxx_static():
    configure_build_and_exe('cxx', 'python setup.py --cxx=g++ --static')

# ------------------------------------------------------------------------------

def test_fc():
    configure_build_and_exe('fc', 'python setup.py --fc=gfortran')

# ------------------------------------------------------------------------------

def test_fc_git_info():
    configure_build_and_exe('fc_git_info', 'python setup.py --fc=gfortran')

# ------------------------------------------------------------------------------

def test_fc_int64():
    configure_build_and_exe('fc_int64', 'python setup.py --fc=gfortran --int64')

# ------------------------------------------------------------------------------

def test_fc_mpi():
    if sys.platform == 'win32':
        configure_build_and_exe('fc_mpi', 'python setup.py --mpi --fc=gfortran --extra-fc-flags="-D_WIN64 -D INT_PTR_KIND()=8 -fno-range-check" --add-definitions="-D USE_MPI_MODULE"', 'mpiexec -n 2')
    else:
        configure_build_and_exe('fc_mpi', 'python setup.py --mpi --fc=mpif90 --add-definitions="-D USE_MPI_MODULE"', 'mpirun -np 2')

def test_fc_mpi_include():
    if sys.platform == 'win32':
        configure_build_and_exe('fc_mpi', 'python setup.py --mpi --fc=gfortran --extra-fc-flags="-D_WIN64 -D INT_PTR_KIND()=8 -fno-range-check"', 'mpiexec -np 2')
    else:
        configure_build_and_exe('fc_mpi', 'python setup.py --mpi --fc=mpif90', 'mpirun -np 2')

# ------------------------------------------------------------------------------

def test_fc_omp():
    os.environ['OMP_NUM_THREADS'] = '2'
    configure_build_and_exe('fc_omp', 'python setup.py --omp --fc=gfortran')

@skip_on_osx
def test_fc_static():
    configure_build_and_exe('fc', 'python setup.py --fc=gfortran --static')

# ------------------------------------------------------------------------------

def test_fc_blas():
    configure_build_and_exe('fc_blas', 'python setup.py --fc=gfortran --cmake-options="-DMATH_LIB_SEARCH_ORDER=\'OPENBLAS;ATLAS;MKL;SYSTEM_NATIVE\'"')

@skip_on_osx
def test_fc_blas_static():
    configure_build_and_exe('fc_blas', 'python setup.py --fc=gfortran --static --cmake-options="-DMATH_LIB_SEARCH_ORDER=\'OPENBLAS;ATLAS;MKL;SYSTEM_NATIVE\'"')

def test_cc_cblas():
    configure_build_and_exe('cc_cblas', 'python setup.py --cc=gcc --cmake-options="-DMATH_LIB_SEARCH_ORDER=\'OPENBLAS;ATLAS;MKL;SYSTEM_NATIVE\'"')

@skip_on_osx
def test_cc_cblas_static():
    configure_build_and_exe('cc_cblas', 'python setup.py --cc=gcc --static --cmake-options="-DMATH_LIB_SEARCH_ORDER=\'OPENBLAS;ATLAS;MKL;SYSTEM_NATIVE\'"')

# ------------------------------------------------------------------------------

def test_fc_lapack():
    configure_build_and_exe('fc_lapack', 'python setup.py --fc=gfortran --cmake-options="-DMATH_LIB_SEARCH_ORDER=\'OPENBLAS;ATLAS;MKL;SYSTEM_NATIVE\'"')

@skip_on_osx
def test_fc_lapack_static():
    configure_build_and_exe('fc_lapack', 'python setup.py --fc=gfortran --static --cmake-options="-DMATH_LIB_SEARCH_ORDER=\'OPENBLAS;ATLAS;MKL;SYSTEM_NATIVE\'"')

def test_cc_clapack():
    configure_build_and_exe('cc_clapack', 'python setup.py --cc=gcc --cmake-options="-DMATH_LIB_SEARCH_ORDER=\'OPENBLAS;ATLAS;MKL;SYSTEM_NATIVE\'"')

@skip_on_osx
def test_cc_clapack_static():
    configure_build_and_exe('cc_clapack', 'python setup.py --cc=gcc --static --cmake-options="-DMATH_LIB_SEARCH_ORDER=\'OPENBLAS;ATLAS;MKL;SYSTEM_NATIVE\'"')

# ------------------------------------------------------------------------------

def test_python_interpreter():
    configure_build_and_exe('python_interpreter', 'python setup.py --cxx=g++')

def test_python_interpreter_custom():
    setup = 'python setup.py --cxx=g++ --python=%s' % sys.executable
    configure_build_and_exe('python_interpreter_custom', setup)

def test_python_libs():
    configure_build_and_exe('python_libs', 'python setup.py --cxx=g++')

def test_python_libs_custom():
    python_executable = sys.executable
    configure_build_and_exe('python_libs_custom', 'python setup.py --cxx=g++ --python={}'.format(python_executable))

@skip_on_windows
@skip_always
def test_boost_header_only():
    configure_build_and_exe('boost_header_only', 'python setup.py --cxx=g++')

@skip_on_windows
@skip_always
def test_boost_libs():
    configure_build_and_exe('boost_libs', 'python setup.py --cxx=g++')

@skip_on_windows
@skip_always
def test_boost_mpi_libs():
    configure_build_and_exe('boost_mpi_libs', 'python setup.py --cxx=g++ --mpi')

@skip_on_windows
@skip_always
def test_boost_python_libs():
    configure_build_and_exe('boost_python_libs', 'python setup.py --cxx=g++')
<commit_msg>clang does not have omp, skip this test on osx<commit_after>import os
import sys
import subprocess
import shlex
import shutil
import sys
import time
import datetime
import pytest

HERE = os.path.abspath(os.path.dirname(__file__))

skip_on_windows = pytest.mark.skipif('sys.platform == "win32"', reason="not working on windows")
skip_on_osx = pytest.mark.skipif('sys.platform == "darwin"', reason="not working on osx")
skip_always = pytest.mark.skipif('1 == 1', reason="tests are broken")

# ------------------------------------------------------------------------------

def exe(command):
    """
    Executes command and returns string representations of stdout and stderr captured from the console.
    When universal_newlines=True stdout and stderr are opened in text mode.
    Otherwise, they are opened in binary mode. In that case captured stdout and stderr
    are not strings and Python 3 throws type error when compared against strings later in tests.
    Note:
    This feature is only available if Python is built with universal newline support (the default).
    Also, the newlines attribute of the file objects stdout, stdin and stderr are not updated by the
    communicate() method.
    See https://docs.python.org/2/library/subprocess.html
    """
    stdout, stderr = subprocess.Popen(shlex.split(command),
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE,
                                      universal_newlines=True).communicate()

    if stderr:
        sys.stderr.write(stderr)

    return stdout, stderr

# ------------------------------------------------------------------------------

def configure_build_and_exe(name, setup_command, launcher=None):

    stamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d-%H-%M-%S')

    os.chdir(os.path.join(HERE, name, 'cmake'))
    shutil.copy(os.path.join('..', '..', '..', 'update.py'), 'update.py')

    dst_dir = 'lib'
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    shutil.copy(os.path.join('..', '..', '..', dst_dir, 'config.py'), dst_dir)

    dst_dir = os.path.join('lib', 'docopt')
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    shutil.copy(os.path.join('..', '..', '..', dst_dir, 'docopt.py'), dst_dir)

    stdout, stderr = exe('python update.py ..')
    os.chdir(os.path.join(HERE, name))

    make_command = 'make'
    binary = './bin/example'
    if sys.platform == 'win32':
        setup_command += ' --generator="MinGW Makefiles"'
        make_command = 'mingw32-make'
        binary = 'bin\\\example.exe'

    if launcher:
        binary = '%s %s' % (launcher, binary)

    setup_command += ' build-%s' % stamp

    stdout, stderr = exe(setup_command)

    os.chdir(os.path.join(HERE, name, 'build-%s' % stamp))

    stdout, stderr = exe(make_command)
    # mi: remove <assert stderr == ''> due to warnings flushed to stderr

    stdout, stderr = exe(binary)
    assert stderr == ''

    assert 'PASSED' in stdout

# ------------------------------------------------------------------------------

def test_cxx_custom():
    configure_build_and_exe('cxx_custom', 'python setup.py --cxx=g++')

# ------------------------------------------------------------------------------

def test_extra_cmake_options():
    configure_build_and_exe('extra_cmake_options', 'python setup.py --cxx=g++ --cmake-options="-DENABLE_SOMETHING=OFF -DENABLE_FOO=ON"')

# ------------------------------------------------------------------------------

def test_cxx():
    configure_build_and_exe('cxx', 'python setup.py --cxx=g++')

@skip_on_osx
def test_cxx_static():
    configure_build_and_exe('cxx', 'python setup.py --cxx=g++ --static')

# ------------------------------------------------------------------------------

def test_fc():
    configure_build_and_exe('fc', 'python setup.py --fc=gfortran')

# ------------------------------------------------------------------------------

def test_fc_git_info():
    configure_build_and_exe('fc_git_info', 'python setup.py --fc=gfortran')

# ------------------------------------------------------------------------------

def test_fc_int64():
    configure_build_and_exe('fc_int64', 'python setup.py --fc=gfortran --int64')

# ------------------------------------------------------------------------------

def test_fc_mpi():
    if sys.platform == 'win32':
        configure_build_and_exe('fc_mpi', 'python setup.py --mpi --fc=gfortran --extra-fc-flags="-D_WIN64 -D INT_PTR_KIND()=8 -fno-range-check" --add-definitions="-D USE_MPI_MODULE"', 'mpiexec -n 2')
    else:
        configure_build_and_exe('fc_mpi', 'python setup.py --mpi --fc=mpif90 --add-definitions="-D USE_MPI_MODULE"', 'mpirun -np 2')

def test_fc_mpi_include():
    if sys.platform == 'win32':
        configure_build_and_exe('fc_mpi', 'python setup.py --mpi --fc=gfortran --extra-fc-flags="-D_WIN64 -D INT_PTR_KIND()=8 -fno-range-check"', 'mpiexec -np 2')
    else:
        configure_build_and_exe('fc_mpi', 'python setup.py --mpi --fc=mpif90', 'mpirun -np 2')

# ------------------------------------------------------------------------------

@skip_on_osx
def test_fc_omp():
    os.environ['OMP_NUM_THREADS'] = '2'
    configure_build_and_exe('fc_omp', 'python setup.py --omp --fc=gfortran')

@skip_on_osx
def test_fc_static():
    configure_build_and_exe('fc', 'python setup.py --fc=gfortran --static')

# ------------------------------------------------------------------------------

def test_fc_blas():
    configure_build_and_exe('fc_blas', 'python setup.py --fc=gfortran --cmake-options="-DMATH_LIB_SEARCH_ORDER=\'OPENBLAS;ATLAS;MKL;SYSTEM_NATIVE\'"')

@skip_on_osx
def test_fc_blas_static():
    configure_build_and_exe('fc_blas', 'python setup.py --fc=gfortran --static --cmake-options="-DMATH_LIB_SEARCH_ORDER=\'OPENBLAS;ATLAS;MKL;SYSTEM_NATIVE\'"')

def test_cc_cblas():
    configure_build_and_exe('cc_cblas', 'python setup.py --cc=gcc --cmake-options="-DMATH_LIB_SEARCH_ORDER=\'OPENBLAS;ATLAS;MKL;SYSTEM_NATIVE\'"')

@skip_on_osx
def test_cc_cblas_static():
    configure_build_and_exe('cc_cblas', 'python setup.py --cc=gcc --static --cmake-options="-DMATH_LIB_SEARCH_ORDER=\'OPENBLAS;ATLAS;MKL;SYSTEM_NATIVE\'"')

# ------------------------------------------------------------------------------

def test_fc_lapack():
    configure_build_and_exe('fc_lapack', 'python setup.py --fc=gfortran --cmake-options="-DMATH_LIB_SEARCH_ORDER=\'OPENBLAS;ATLAS;MKL;SYSTEM_NATIVE\'"')

@skip_on_osx
def test_fc_lapack_static():
    configure_build_and_exe('fc_lapack', 'python setup.py --fc=gfortran --static --cmake-options="-DMATH_LIB_SEARCH_ORDER=\'OPENBLAS;ATLAS;MKL;SYSTEM_NATIVE\'"')

def test_cc_clapack():
    configure_build_and_exe('cc_clapack', 'python setup.py --cc=gcc --cmake-options="-DMATH_LIB_SEARCH_ORDER=\'OPENBLAS;ATLAS;MKL;SYSTEM_NATIVE\'"')

@skip_on_osx
def test_cc_clapack_static():
    configure_build_and_exe('cc_clapack', 'python setup.py --cc=gcc --static --cmake-options="-DMATH_LIB_SEARCH_ORDER=\'OPENBLAS;ATLAS;MKL;SYSTEM_NATIVE\'"')

# ------------------------------------------------------------------------------

def test_python_interpreter():
    configure_build_and_exe('python_interpreter', 'python setup.py --cxx=g++')

def test_python_interpreter_custom():
    setup = 'python setup.py --cxx=g++ --python=%s' % sys.executable
    configure_build_and_exe('python_interpreter_custom', setup)

def test_python_libs():
    configure_build_and_exe('python_libs', 'python setup.py --cxx=g++')

def test_python_libs_custom():
    python_executable = sys.executable
    configure_build_and_exe('python_libs_custom', 'python setup.py --cxx=g++ --python={}'.format(python_executable))

@skip_on_windows
@skip_always
def test_boost_header_only():
    configure_build_and_exe('boost_header_only', 'python setup.py --cxx=g++')

@skip_on_windows
@skip_always
def test_boost_libs():
    configure_build_and_exe('boost_libs', 'python setup.py --cxx=g++')

@skip_on_windows
@skip_always
def test_boost_mpi_libs():
    configure_build_and_exe('boost_mpi_libs', 'python setup.py --cxx=g++ --mpi')

@skip_on_windows
@skip_always
def test_boost_python_libs():
    configure_build_and_exe('boost_python_libs', 'python setup.py --cxx=g++')
<|endoftext|>


<commit_before># -*- coding: utf8 -*-
# Copyright (C) 2013 Daniel Lombraña González
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import pbclient
import json
from mock import patch
from collections import namedtuple

FakeRequest = namedtuple('FakeRequest', ['text', 'status_code', 'headers'])

class TestPybossaClient(object):
    app = dict(info='info',
               time_limit=0,
               description="description",
               short_name="slug",
               owner_id=1,
               id=1,
               link="<link rel='self' title='app' href='http://localhost:5000/api/app/1'/>",
               allow_anonymous_contributors=True,
               hidden=0,
               long_description="long_description",
               name="test")

    task = dict(info="info",
                n_answers=30,
                quorum=0,
                links=["<link rel='parent' title='app' href='http://localhost:5000/api/app/1'/>"],
                calibration=0,
                app_id=1,
                state="completed",
                link="<link rel='self' title='task' href='http://localhost:5000/api/task/1'/>",
                id=1)

    taskrun = dict(info="info",
                   user_id=None,
                   links=[
                       "<link rel='parent' title='app' href='http://localhost:5000/api/app/1'/>"
                       "<link rel='parent' title='task' href='http://localhost:5000/api/taskrun/1'/>"],
                   task_id=1,
                   calibration=None,
                   app_id=1,
                   user_ip="127.0.0.1",
                   link="<link rel='self' title='taskrun' href='http://localhost:5000/api/taskrun/1'/>",
                   id=1)

    def setUp(self):
        self.client = pbclient
        self.client.set('endpoint', 'http://localhost:5000')
        self.client.set('api-key', 'tester')

    def create_fake_request(self, data, status=None, mimetype={'content-type': 'application/json'}):
        if status is None and data['status_code']:
            return FakeRequest(json.dumps(data), data['status_code'], mimetype)
        else:
            return FakeRequest(json.dumps(data), status, mimetype)

    def create_error_output(self, action, status_code, target,
                            exception_cls, exception_msg=None):
        error = dict(action=action,
                     status="failed",
                     status_code=status_code,
                     target=target,
                     exception_cls=exception_cls,
                     exception_msg=exception_msg)
        return error

    def check_error_output(self, res, err):
        for k in err.keys():
            assert err[k] == res[k], err

    @patch('pbclient.requests.get')
    def test_00_get_app_not_found(self, Mock):
        """Test get_app not found works"""
        # App does not exist should return 404 error object
        not_found = self.create_error_output(action='GET', status_code=404,
                                             target='app', exception_cls='NotFound')
        Mock.return_value = self.create_fake_request(not_found)
        err = self.client.get_app(1)
        self.check_error_output(err, not_found)

    @patch('pbclient.requests.get')
    def test_01_get_app_found(self, Mock):
        """Test get_app found works"""
        Mock.return_value = self.create_fake_request(self.app, 200)
        app = self.client.get_app(1)
        assert app.id == self.app['id'], app
        assert app.short_name == self.app['short_name'], app

    @patch('pbclient.requests.get')
    def test_01_get_apps(self, Mock):
        """Test get_apps works"""
        Mock.return_value = self.create_fake_request([self.app], 200)
        apps = self.client.get_apps()
        assert len(apps) == 1, apps
        app = apps[0]
        assert app.id == self.app['id'], app
        assert app.short_name == self.app['short_name'], app

        # Without apps
        Mock.return_value = self.create_fake_request([], 200)
        apps = self.client.get_apps()
        assert len(apps) == 0, apps

    @patch('pbclient.requests.get')
    def test_02_find_app(self, Mock):
        """Test find_app works"""
        Mock.return_value = self.create_fake_request([self.app], 200)
        apps = self.client.find_app(short_name=self.app['short_name'])
        # Only one app is found
        assert len(apps) == 1, apps
        app = apps[0]
        assert app.id == self.app['id'], app
        assert app.short_name == self.app['short_name'], app

    @patch('pbclient.requests.get')
    def test_03_find_app_not_found(self, Mock):
        """Test find_app not found works"""
        Mock.return_value = self.create_fake_request([], 200)
        apps = self.client.find_app(short_name="foobar")
        assert len(apps) == 0, apps

    @patch('pbclient.requests.post')
    def test_04_create_app(self, Mock):
        """Test create_app works"""
        Mock.return_value = self.create_fake_request(self.app, 200)
        app = self.client.create_app(name=self.app['name'],
                                     short_name=self.app['short_name'],
                                     description=self.app['description'])
        assert app.id == self.app['id']
        assert app.short_name == self.app['short_name']

    @patch('pbclient.requests.post')
    def test_05_create_app_exists(self, Mock):
        """Test create_app exists works"""
        already_exists = self.create_error_output(action='POST', status_code=415,
                                                  target='app', exception_cls='IntegrityError')

        Mock.return_value = self.create_fake_request(already_exists, 415)
        app = self.client.create_app(name=self.app['name'],
                                     short_name=self.app['short_name'],
                                     description=self.app['description'])
        self.check_error_output(app, already_exists)
<commit_msg>Unit Tests create_app forbidden<commit_after># -*- coding: utf8 -*-
# Copyright (C) 2013 Daniel Lombraña González
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import pbclient
import json
from mock import patch
from collections import namedtuple

FakeRequest = namedtuple('FakeRequest', ['text', 'status_code', 'headers'])

class TestPybossaClient(object):
    app = dict(info='info',
               time_limit=0,
               description="description",
               short_name="slug",
               owner_id=1,
               id=1,
               link="<link rel='self' title='app' href='http://localhost:5000/api/app/1'/>",
               allow_anonymous_contributors=True,
               hidden=0,
               long_description="long_description",
               name="test")

    task = dict(info="info",
                n_answers=30,
                quorum=0,
                links=["<link rel='parent' title='app' href='http://localhost:5000/api/app/1'/>"],
                calibration=0,
                app_id=1,
                state="completed",
                link="<link rel='self' title='task' href='http://localhost:5000/api/task/1'/>",
                id=1)

    taskrun = dict(info="info",
                   user_id=None,
                   links=[
                       "<link rel='parent' title='app' href='http://localhost:5000/api/app/1'/>"
                       "<link rel='parent' title='task' href='http://localhost:5000/api/taskrun/1'/>"],
                   task_id=1,
                   calibration=None,
                   app_id=1,
                   user_ip="127.0.0.1",
                   link="<link rel='self' title='taskrun' href='http://localhost:5000/api/taskrun/1'/>",
                   id=1)

    def setUp(self):
        self.client = pbclient
        self.client.set('endpoint', 'http://localhost:5000')
        self.client.set('api-key', 'tester')

    def create_fake_request(self, data, status=None, mimetype={'content-type': 'application/json'}):
        if status is None and data['status_code']:
            return FakeRequest(json.dumps(data), data['status_code'], mimetype)
        else:
            return FakeRequest(json.dumps(data), status, mimetype)

    def create_error_output(self, action, status_code, target,
                            exception_cls, exception_msg=None):
        error = dict(action=action,
                     status="failed",
                     status_code=status_code,
                     target=target,
                     exception_cls=exception_cls,
                     exception_msg=exception_msg)
        return error

    def check_error_output(self, res, err):
        for k in err.keys():
            assert err[k] == res[k], err

    @patch('pbclient.requests.get')
    def test_00_get_app_not_found(self, Mock):
        """Test get_app not found works"""
        # App does not exist should return 404 error object
        not_found = self.create_error_output(action='GET', status_code=404,
                                             target='app', exception_cls='NotFound')
        Mock.return_value = self.create_fake_request(not_found)
        err = self.client.get_app(1)
        self.check_error_output(err, not_found)

    @patch('pbclient.requests.get')
    def test_01_get_app_found(self, Mock):
        """Test get_app found works"""
        Mock.return_value = self.create_fake_request(self.app, 200)
        app = self.client.get_app(1)
        assert app.id == self.app['id'], app
        assert app.short_name == self.app['short_name'], app

    @patch('pbclient.requests.get')
    def test_01_get_apps(self, Mock):
        """Test get_apps works"""
        Mock.return_value = self.create_fake_request([self.app], 200)
        apps = self.client.get_apps()
        assert len(apps) == 1, apps
        app = apps[0]
        assert app.id == self.app['id'], app
        assert app.short_name == self.app['short_name'], app

        # Without apps
        Mock.return_value = self.create_fake_request([], 200)
        apps = self.client.get_apps()
        assert len(apps) == 0, apps

    @patch('pbclient.requests.get')
    def test_02_find_app(self, Mock):
        """Test find_app works"""
        Mock.return_value = self.create_fake_request([self.app], 200)
        apps = self.client.find_app(short_name=self.app['short_name'])
        # Only one app is found
        assert len(apps) == 1, apps
        app = apps[0]
        assert app.id == self.app['id'], app
        assert app.short_name == self.app['short_name'], app

    @patch('pbclient.requests.get')
    def test_03_find_app_not_found(self, Mock):
        """Test find_app not found works"""
        Mock.return_value = self.create_fake_request([], 200)
        apps = self.client.find_app(short_name="foobar")
        assert len(apps) == 0, apps

    @patch('pbclient.requests.post')
    def test_04_create_app(self, Mock):
        """Test create_app works"""
        Mock.return_value = self.create_fake_request(self.app, 200)
        app = self.client.create_app(name=self.app['name'],
                                     short_name=self.app['short_name'],
                                     description=self.app['description'])
        assert app.id == self.app['id']
        assert app.short_name == self.app['short_name']

    @patch('pbclient.requests.post')
    def test_05_create_app_exists(self, Mock):
        """Test create_app duplicate entry works"""
        already_exists = self.create_error_output(action='POST', status_code=415,
                                                  target='app', exception_cls='IntegrityError')

        Mock.return_value = self.create_fake_request(already_exists, 415)
        app = self.client.create_app(name=self.app['name'],
                                     short_name=self.app['short_name'],
                                     description=self.app['description'])
        self.check_error_output(app, already_exists)

    @patch('pbclient.requests.post')
    def test_06_create_app_not_allowed(self, Mock):
        """Test create_app not authorized works"""
        not_authorized = self.create_error_output(action='POST', status_code=401,
                                                  target='app', exception_cls='Unauthorized')

        Mock.return_value = self.create_fake_request(not_authorized, 401)
        app = self.client.create_app(name=self.app['name'],
                                     short_name=self.app['short_name'],
                                     description=self.app['description'])
        self.check_error_output(app, not_authorized)

    @patch('pbclient.requests.post')
    def test_07_create_app_forbidden(self, Mock):
        """Test create_app not authorized works"""
        forbidden = self.create_error_output(action='POST', status_code=403,
                                             target='app', exception_cls='Forbidden')

        Mock.return_value = self.create_fake_request(forbidden, 403)
        app = self.client.create_app(name=self.app['name'],
                                     short_name=self.app['short_name'],
                                     description=self.app['description'])
        self.check_error_output(app, forbidden)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import os
import chgender

male = 0
female = 0
i = 0

with open(os.getcwd() + '/female.txt', 'r') as f:
    for name in f:
    	name = name.strip('\n')
    	i = i + 1
        if chgender.guess(name) == 0:
        	female = female + 1

with open(os.getcwd() + '/male.txt', 'r') as f:
    for name in f:
    	name = name.strip('\n')
    	i = i + 1
        if chgender.guess(name) == 1:
        	male = male + 1

result = 1. * (female + male)/i
print("accuracy: ")
print(result)<commit_msg>test file modify<commit_after># -*- coding: utf-8 -*-
import os
import chgender

mcount = 0
fcount = 0
correct = 0

with open(os.getcwd() + '/female.txt', 'r') as f:
    for name in f:
    	name = name.strip('\n')
        fcount = fcount + 1
        if chgender.guess(name)[0] == 'female':
        	correct = correct + 1

with open(os.getcwd() + '/male.txt', 'r') as f:
    for name in f:
    	name = name.strip('\n')
        mcount = mcount + 1
        if chgender.guess(name)[0] == 'male':
        	correct = correct + 1

accuracy = 1. * correct/(fcount + mcount)
print('total male input: {} \ntotal female input: {} \naverage accuracy: {}' ''.format(mcount, fcount, accuracy))<|endoftext|>


<commit_before>__author__ = 'Yunxi Lin'
import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException

class CommonMethods():

    def __init__(self):
        self.driver = webdriver
        self.ie_path = 'C:\\selenium\\driver\\IEDriverServer.exe'
        self.chrome_path = 'C:\\selenium\\driver\\chromedriver.exe'

    def set_url(self, base_url):
        try:
            app_url = base_url
        except:
            app_url = 'www.google.com'
            print('URL not found, opening '+ app_url)
        return app_url

    def set_page(self, url):
        self.driver.get(url)

    def navigate(self, base_url):
        get_url = self.set_url(base_url)
        try:
            self.set_page(get_url)
            self.driver.implicitly_wait(10)
        except:
            print('No browser opened')
            self.open_browser()
            self.set_page(get_url)
            self.driver.implicitly_wait(10)
            print('URL navigation')

    def open_browser(self, remote_browser_type = 'firefox', local_browser_name = 'firefox', platform = 'window', hub_url = 'http://localhost:5555/wd/hub'):
        os.environ["webdriver.chrome.driver"]=self.chrome_path
        os.environ["webdriver.ie.driver"]=self.ie_path
        capabilities = DesiredCapabilities
        if(platform!='mac'):
            if(local_browser_name=='firefox'):
                self.driver = webdriver.Firefox()
            elif(local_browser_name=='chrome'):
                self.driver = webdriver.Chrome()
            elif(local_browser_name=='safari'):
                self.driver = webdriver.Safari()
            elif(local_browser_name=='ie'):
                capabilities = DesiredCapabilities.INTERNETEXPLORER.copy()
                capabilities['ignoreProtectedModeSettings'] = True
                self.driver = webdriver.Ie(capabilities)
            elif(local_browser_name=='remote'):
                print('Using remote browser')
                if(remote_browser_type=='firefox'):
                    capabilities = DesiredCapabilities.FIREFOX.copy()
                    capabilities['platform'] = platform
                    capabilities['browserName'] = remote_browser_type
                    #capabilities['version'] = ''
                    self.driver = webdriver.Remote(command_executor=hub_url,desired_capabilities=capabilities)
                elif(remote_browser_type=='ie'):
                    capabilities = DesiredCapabilities.INTERNETEXPLORER.copy()
                    capabilities['ignoreProtectedModeSettings'] = True
                    capabilities['platform'] = platform
                    capabilities['browserName'] = remote_browser_type
                    #capabilities['version'] = ''
                    self.driver = webdriver.Remote(command_executor=hub_url,desired_capabilities=capabilities)
                elif(remote_browser_type=='chrome'):
                    capabilities = DesiredCapabilities.CHROME.copy()
                    capabilities['ignoreProtectedModeSettings'] = True
                    capabilities['platform'] = platform
                    capabilities['browserName'] = remote_browser_type
                    #capabilities['version']
                    self.driver = webdriver.Remote(command_executor=hub_url,desired_capabilities=capabilities)
                elif(remote_browser_type=='safari'):
                    capabilities = DesiredCapabilities.SAFARI.copy()
                    capabilities['ignoreProtectedModeSettings'] = True
                    capabilities['platform'] = platform
                    capabilities['browserName'] = remote_browser_type
                    #capabilities['version']
                    self.driver = webdriver.Remote(command_executor=hub_url,desired_capabilities=capabilities)
        elif(platform=='mac'):
            if(local_browser_name=='remote'):
                self.driver = webdriver.Remote(command_executor=hub_url,desired_capabilities=DesiredCapabilities.SAFARI.copy())
                #self.driver =
            else:
                capabilities = DesiredCapabilities.SAFARI.copy()
                self.driver = webdriver.Safari(capabilities)
        self.driver.delete_all_cookies()
        self.driver.implicitly_wait(10)
        self.driver.maximize_window()

    def close_browser(self, driver):
        try:
            print('Closing browser')
            driver.close()
            print('Browser closed')
        except:
            print('Browser is already closed')

    def teardown(self, driver):
        print('Closing browser')
        driver.delete_all_cookies()
        driver.quit()
        print('Browser closed')

    def reject_popup(self, driver):
        try:
            alert = driver.switch_to.alert
            print('Attempting to dismiss alert')
            alert.dismiss()
            driver.switch_to.default_content()
            print('Alert rejected')
        except:
            print('Alert not found')

    def accept_popup(self, driver):
        try:
            alert = self.driver.switch_to.alert
            print('Attempting to accept alert')
            alert.accept()
            self.driver.switch_to.default_content()
            print('Alert accepted')
        except:
            print('Alert not found')

    def send_keys_to_alert(self, driver, enter_text):
        try:
            alert = self.driver.switch_to.alert
            print('Attempting to send keys to alert')
            alert.send_keys(enter_text)
            print('Successfully entered ' + enter_text + ' into alert')
        except:
            print('Alert not found')

    def set_value_to_element(self, driver, by, by_value, string_value):
        try:
            string_locator = self.driver.find_element(by, by_value)
            elementName = self.driver.find_element(by, by_value).get_attribute('name')
            string_locator.send_keys(string_value)
            print(string_value + ' entered')
        except NoSuchElementException:
            print('Element not found')

<commit_msg>update naming<commit_after>__author__ = 'Yunxi Lin'
import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException

class CommonMethods():

    def __init__(self):
        self.driver = webdriver
        self.ie_path = 'C:\\selenium\\driver\\IEDriverServer.exe'
        self.chrome_path = 'C:\\selenium\\driver\\chromedriver.exe'

    def set_url(self, base_url):
        try:
            app_url = base_url
        except:
            app_url = 'www.google.com'
            print('URL not found, opening '+ app_url)
        return app_url

    def set_page(self, url):
        self.driver.get(url)

    def navigate(self, base_url):
        get_url = self.set_url(base_url)
        try:
            self.set_page(get_url)
            self.driver.implicitly_wait(10)
        except:
            print('No browser opened')
            self.open_browser()
            self.set_page(get_url)
            self.driver.implicitly_wait(10)
            print('URL navigation')

    def open_browser(self, remote_browser_type = 'firefox', local_browser_name = 'firefox', platform = 'window', hub_url = 'http://localhost:5555/wd/hub'):
        os.environ["webdriver.chrome.driver"]=self.chrome_path
        os.environ["webdriver.ie.driver"]=self.ie_path
        capabilities = DesiredCapabilities
        if(platform!='mac'):
            if(local_browser_name=='firefox'):
                self.driver = webdriver.Firefox()
            elif(local_browser_name=='chrome'):
                self.driver = webdriver.Chrome()
            elif(local_browser_name=='safari'):
                self.driver = webdriver.Safari()
            elif(local_browser_name=='ie'):
                capabilities = DesiredCapabilities.INTERNETEXPLORER.copy()
                capabilities['ignoreProtectedModeSettings'] = True
                self.driver = webdriver.Ie(capabilities)
            elif(local_browser_name=='remote'):
                print('Using remote browser')
                if(remote_browser_type=='firefox'):
                    capabilities = DesiredCapabilities.FIREFOX.copy()
                    capabilities['platform'] = platform
                    capabilities['browserName'] = remote_browser_type
                    #capabilities['version'] = ''
                    self.driver = webdriver.Remote(command_executor=hub_url,desired_capabilities=capabilities)
                elif(remote_browser_type=='ie'):
                    capabilities = DesiredCapabilities.INTERNETEXPLORER.copy()
                    capabilities['ignoreProtectedModeSettings'] = True
                    capabilities['platform'] = platform
                    capabilities['browserName'] = remote_browser_type
                    #capabilities['version'] = ''
                    self.driver = webdriver.Remote(command_executor=hub_url,desired_capabilities=capabilities)
                elif(remote_browser_type=='chrome'):
                    capabilities = DesiredCapabilities.CHROME.copy()
                    capabilities['ignoreProtectedModeSettings'] = True
                    capabilities['platform'] = platform
                    capabilities['browserName'] = remote_browser_type
                    #capabilities['version']
                    self.driver = webdriver.Remote(command_executor=hub_url,desired_capabilities=capabilities)
                elif(remote_browser_type=='safari'):
                    capabilities = DesiredCapabilities.SAFARI.copy()
                    capabilities['ignoreProtectedModeSettings'] = True
                    capabilities['platform'] = platform
                    capabilities['browserName'] = remote_browser_type
                    #capabilities['version']
                    self.driver = webdriver.Remote(command_executor=hub_url,desired_capabilities=capabilities)
        elif(platform=='mac'):
            if(local_browser_name=='remote'):
                self.driver = webdriver.Remote(command_executor=hub_url,desired_capabilities=DesiredCapabilities.SAFARI.copy())
                #self.driver =
            else:
                capabilities = DesiredCapabilities.SAFARI.copy()
                self.driver = webdriver.Safari(capabilities)
        self.driver.delete_all_cookies()
        self.driver.implicitly_wait(10)
        self.driver.maximize_window()

    def close_browser(self, driver):
        try:
            print('Closing browser')
            driver.close()
            print('Browser closed')
        except:
            print('Browser is already closed')

    def teardown(self, driver):
        print('Closing browser')
        driver.delete_all_cookies()
        driver.quit()
        print('Browser closed')

    def reject_popup(self, driver):
        try:
            alert = driver.switch_to.alert
            print('Attempting to dismiss alert')
            alert.dismiss()
            driver.switch_to.default_content()
            print('Alert rejected')
        except:
            print('Alert not found')

    def accept_popup(self, driver):
        try:
            alert = self.driver.switch_to.alert
            print('Attempting to accept alert')
            alert.accept()
            self.driver.switch_to.default_content()
            print('Alert accepted')
        except:
            print('Alert not found')

    def send_keys_to_alert(self, driver, enter_text):
        try:
            alert = self.driver.switch_to.alert
            print('Attempting to send keys to alert')
            alert.send_keys(enter_text)
            print('Successfully entered ' + enter_text + ' into alert')
        except:
            print('Alert not found')

    def set_value_to_element(self, driver, by, by_value, string_value):
        try:
            string_locator = self.driver.find_element(by, by_value)
            element_name = self.driver.find_element(by, by_value).get_attribute('name')
            string_locator.send_keys(string_value)
            print(string_value + ' entered')
        except NoSuchElementException:
            print('Element ' +  element_name + ' not found')

<|endoftext|>


<commit_before># Software License Agreement (BSD License)
#
# Copyright (c) 20092011, Eucalyptus Systems, Inc.
# All rights reserved.
#
# Redistribution and use of this software in source and binary forms, with or
# without modification, are permitted provided that the following conditions
# are met:
#
#   Redistributions of source code must retain the above
#   copyright notice, this list of conditions and the
#   following disclaimer.
#
#   Redistributions in binary form must reproduce the above
#   copyright notice, this list of conditions and the
#   following disclaimer in the documentation and/or other
#   materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Author: Neil Soman neil@eucalyptus.com
#         Mitch Garnaat mgarnaat@eucalyptus.com

import euca2ools.commands.eucacommand
from boto.roboto.param import Param
import euca2ools.utils
import os.path

class RunInstances(euca2ools.commands.eucacommand.EucaCommand):

    Description = 'Starts instances.'
    Options = [Param(name='count', short_name='n', long_name='instance-count',
                     optional=True, ptype='string', default='1',
                     doc='Number of instances to run.'),
               Param(name='group_name', short_name='g', long_name='group',
                     optional=True, ptype='string', cardinality='*',
                     doc='Security group to run the instance in.'),
               Param(name='keyname', short_name='k', long_name='key',
                     optional=True, ptype='string',
                     doc='Name of a keypair.'),
               Param(name='user_data', short_name='d', long_name='user-data',
                     optional=True, doc='User data to pass to the instance.'),
               Param(name='user_data_file',
                     short_name='f', long_name='user-data-file',
                     optional=True, ptype='file',
                     doc='File containing user data to pass to the instance.'),
               Param(name='addressing', long_name='addressing',
                     optional=True, ptype='string',
                     doc='Deprecated.'),
               Param(name='instance_type',
                     short_name='t', long_name='instance-type',
                     optional=True, ptype='string', default='m1.small',
                     doc='VM Image type to run the instance as.'),
               Param(name='kernel', long_name='kernel',
                     optional=True, ptype='string',
                     doc='ID of the kernel to be used.'),
               Param(name='ramdisk', long_name='ramdisk',
                     optional=True, ptype='string',
                     doc='ID of the ramdisk to be used.'),
               Param(name='block_device_mapping',
                     short_name='b', long_name='block-device-mapping',
                     optional=True, ptype='string', cardinality='*',
                     doc="""Block device mapping for the instance(s).
                     Option may be used multiple times"""),
               Param(name='monitor', long_name='monitor',
                     optional=True, ptype='boolean', default=False,
                     doc='Enable monitoring for the instance.'),
               Param(name='subnet', short_name='s', long_name='subnet',
                     optional=True, ptype='string',
                     doc='Amazon VPC subnet ID for the instance.'),
               Param(name='zone', short_name='z', long_name='availability-zone',
                     optional=True, ptype='string',
                     doc='availability zone to run the instance in')]
    Args = [Param(name='image_id', ptype='string',
                  optional=False,
                  doc='ID of the image to run.')]

    def display_reservations(self, reservation):
        reservation_string = '%s\t%s' % (reservation.id,
                reservation.owner_id)
        group_delim = '\t'
        for group in reservation.groups:
            reservation_string += '%s%s' % (group_delim, group.id)
            group_delim = ', '
        print 'RESERVATION\t%s' % reservation_string
        euca2ools.utils.print_instances(reservation.instances)

    def read_user_data(self, user_data_filename):
        fp = open(user_data_filename)
        user_data = fp.read()
        fp.close()
        return user_data

    def main(self):
        t = self.count.split('-')
        try:
            if len(t) > 1:
                min_count = int(t[0])
                max_count = int(t[1])
            else:
                min_count = max_count = int(t[0])
        except ValueError:
            msg = 'Invalid value for --instance-count: %s' % count
            self.display_error_and_exit(msg)

        if self.user_data and os.path.isfile(self.user_data):
            msg = 'string provided by user_data (%s) is a file. try %s' % (
                (self.user_data, '--user-data-file'))
            self.display_error_and_exit(msg)

        if not self.user_data:
            if self.user_data_file:
                self.user_data = self.read_user_data(self.user_data_file)

        if self.block_device_mapping:
            self.block_device_mapping = self.parse_block_device_args(self.block_device_mapping)
        conn = self.make_connection_cli()
        return self.make_request_cli(conn, 'run_instances',
                                     image_id=self.image_id,
                                     min_count=min_count,
                                     max_count=max_count,
                                     key_name=self.keyname,
                                     security_groups=self.group_name,
                                     user_data=self.user_data,
                                     addressing_type=self.addressing,
                                     instance_type=self.instance_type,
                                     placement=self.zone,
                                     kernel_id=self.kernel,
                                     ramdisk_id=self.ramdisk,
                                     block_device_map=self.block_device_mapping,
                                     monitoring_enabled=self.monitor,
                                     subnet_id=self.subnet)

    def main_cli(self):
        reservation = self.main()
        self.display_reservations(reservation)

<commit_msg>add --user-data-force flag to ignore the file check of --user-data<commit_after># Software License Agreement (BSD License)
#
# Copyright (c) 20092011, Eucalyptus Systems, Inc.
# All rights reserved.
#
# Redistribution and use of this software in source and binary forms, with or
# without modification, are permitted provided that the following conditions
# are met:
#
#   Redistributions of source code must retain the above
#   copyright notice, this list of conditions and the
#   following disclaimer.
#
#   Redistributions in binary form must reproduce the above
#   copyright notice, this list of conditions and the
#   following disclaimer in the documentation and/or other
#   materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Author: Neil Soman neil@eucalyptus.com
#         Mitch Garnaat mgarnaat@eucalyptus.com

import euca2ools.commands.eucacommand
from boto.roboto.param import Param
import euca2ools.utils
import os.path

class RunInstances(euca2ools.commands.eucacommand.EucaCommand):

    Description = 'Starts instances.'
    Options = [Param(name='count', short_name='n', long_name='instance-count',
                     optional=True, ptype='string', default='1',
                     doc='Number of instances to run.'),
               Param(name='group_name', short_name='g', long_name='group',
                     optional=True, ptype='string', cardinality='*',
                     doc='Security group to run the instance in.'),
               Param(name='keyname', short_name='k', long_name='key',
                     optional=True, ptype='string',
                     doc='Name of a keypair.'),
               Param(name='user_data', short_name='d', long_name='user-data',
                     optional=True, doc='User data to pass to the instance.'),
               Param(name='user_data_force', long_name='user-data-force',
                     optional=True,
                     doc='Just like --user-data, but ignore any checks.'),
               Param(name='user_data_file',
                     short_name='f', long_name='user-data-file',
                     optional=True, ptype='file',
                     doc='File containing user data to pass to the instance.'),
               Param(name='addressing', long_name='addressing',
                     optional=True, ptype='string',
                     doc='Deprecated.'),
               Param(name='instance_type',
                     short_name='t', long_name='instance-type',
                     optional=True, ptype='string', default='m1.small',
                     doc='VM Image type to run the instance as.'),
               Param(name='kernel', long_name='kernel',
                     optional=True, ptype='string',
                     doc='ID of the kernel to be used.'),
               Param(name='ramdisk', long_name='ramdisk',
                     optional=True, ptype='string',
                     doc='ID of the ramdisk to be used.'),
               Param(name='block_device_mapping',
                     short_name='b', long_name='block-device-mapping',
                     optional=True, ptype='string', cardinality='*',
                     doc="""Block device mapping for the instance(s).
                     Option may be used multiple times"""),
               Param(name='monitor', long_name='monitor',
                     optional=True, ptype='boolean', default=False,
                     doc='Enable monitoring for the instance.'),
               Param(name='subnet', short_name='s', long_name='subnet',
                     optional=True, ptype='string',
                     doc='Amazon VPC subnet ID for the instance.'),
               Param(name='zone', short_name='z', long_name='availability-zone',
                     optional=True, ptype='string',
                     doc='availability zone to run the instance in')]
    Args = [Param(name='image_id', ptype='string',
                  optional=False,
                  doc='ID of the image to run.')]

    def display_reservations(self, reservation):
        reservation_string = '%s\t%s' % (reservation.id,
                reservation.owner_id)
        group_delim = '\t'
        for group in reservation.groups:
            reservation_string += '%s%s' % (group_delim, group.id)
            group_delim = ', '
        print 'RESERVATION\t%s' % reservation_string
        euca2ools.utils.print_instances(reservation.instances)

    def read_user_data(self, user_data_filename):
        fp = open(user_data_filename)
        user_data = fp.read()
        fp.close()
        return user_data

    def main(self):
        t = self.count.split('-')
        try:
            if len(t) > 1:
                min_count = int(t[0])
                max_count = int(t[1])
            else:
                min_count = max_count = int(t[0])
        except ValueError:
            msg = 'Invalid value for --instance-count: %s' % count
            self.display_error_and_exit(msg)

        if self.user_data and os.path.isfile(self.user_data):
            msg = ('string provided as user-data [%s] is a file.\nTry %s or %s'
                    % (self.user_data, '--user-data-file', '--user-data-force'))
            self.display_error_and_exit(msg)

        if self.user_data_force:
            self.user_data = self.user_data_force

        if not self.user_data:
            if self.user_data_file:
                self.user_data = self.read_user_data(self.user_data_file)

        if self.block_device_mapping:
            self.block_device_mapping = self.parse_block_device_args(self.block_device_mapping)
        conn = self.make_connection_cli()
        return self.make_request_cli(conn, 'run_instances',
                                     image_id=self.image_id,
                                     min_count=min_count,
                                     max_count=max_count,
                                     key_name=self.keyname,
                                     security_groups=self.group_name,
                                     user_data=self.user_data,
                                     addressing_type=self.addressing,
                                     instance_type=self.instance_type,
                                     placement=self.zone,
                                     kernel_id=self.kernel,
                                     ramdisk_id=self.ramdisk,
                                     block_device_map=self.block_device_mapping,
                                     monitoring_enabled=self.monitor,
                                     subnet_id=self.subnet)

    def main_cli(self):
        reservation = self.main()
        self.display_reservations(reservation)

<|endoftext|>


<commit_before>from collections import Counter
import csv
import logging
import progressbar

from eva_cttv_pipeline.trait_mapping.output import output_trait
from eva_cttv_pipeline.trait_mapping.oxo import get_oxo_results
from eva_cttv_pipeline.trait_mapping.oxo import uris_to_oxo_format
from eva_cttv_pipeline.trait_mapping.trait import Trait
from eva_cttv_pipeline.trait_mapping.trait_names_parsing import parse_trait_names
from eva_cttv_pipeline.trait_mapping.zooma import get_zooma_results

logger = logging.getLogger(__package__)

def get_uris_for_oxo(zooma_result_list: list) -> set:
    """
    For a list of Zooma mappings return a list of uris for the mappings in that list with a high
    confidence.

    :param zooma_result_list: List with elements of class ZoomaResult
    :return: set of uris from high confidence Zooma mappings, for which to query OxO
    """
    uri_set = set()
    for mapping in zooma_result_list:
        # Only use high confidence Zooma mappings for querying OxO
        if mapping.confidence.lower() == "high":
            uri_set.update([entry.uri for entry in mapping.mapping_list])
    return uri_set

def process_trait(trait: Trait, filters: dict, zooma_host: str, oxo_target_list: list,
                  oxo_distance: int) -> Trait:
    """
    Process a single trait. Find any mappings in Zooma. If there are no high confidence Zooma
    mappings that are in EFO then query OxO with any high confidence mappings not in EFO.

    :param trait: The trait to be processed.
    :param filters: A dictionary of filters to use for querying Zooma.
    :param zooma_host: A string with the hostname to use for querying Zooma
    :param oxo_target_list: A list of strings, each being an OxO ID for an ontology. Used to specify
                            which ontologies should be queried using OxO.
    :param oxo_distance: int specifying the maximum number of steps to use to query OxO. i.e. OxO's
                         "distance" parameter.
    :return: The original trait after querying Zooma and possibly OxO, with any results found.
    """

    logger.debug('Processing trait {}'.format(trait.name))
    trait.zooma_result_list = get_zooma_results(trait.name, filters, zooma_host)
    trait.process_zooma_results()
    if (trait.is_finished
            or len(trait.zooma_result_list) == 0
            or any([entry.is_current
                    for mapping in trait.zooma_result_list
                    for entry in mapping.mapping_list])):
        return trait
    uris_for_oxo_set = get_uris_for_oxo(trait.zooma_result_list)
    if len(uris_for_oxo_set) == 0:
        return trait
    oxo_input_id_list = uris_to_oxo_format(uris_for_oxo_set)
    trait.oxo_result_list = get_oxo_results(oxo_input_id_list, oxo_target_list, oxo_distance)

    if not trait.oxo_result_list:
        logger.warning('No OxO mapping for trait {}'.format(trait.name))

    trait.process_oxo_mappings()

    return trait

def main(input_filepath, output_mappings_filepath, output_curation_filepath, filters, zooma_host,
         oxo_target_list, oxo_distance, unattended):
    trait_names_list = parse_trait_names(input_filepath)
    trait_names_counter = Counter(trait_names_list)

    with open(output_mappings_filepath, "w", newline='') as mapping_file, \
            open(output_curation_filepath, "wt") as curation_file:
        mapping_writer = csv.writer(mapping_file, delimiter="\t")
        mapping_writer.writerow(["#clinvar_trait_name", "uri", "label"])
        curation_writer = csv.writer(curation_file, delimiter="\t")

        trait_names_iterator = trait_names_counter.items()
        if not unattended:
            progress = progressbar.ProgressBar(max_value=len(trait_names_counter),
                                               widgets=[progressbar.AdaptiveETA(samples=1000)])
            trait_names_iterator = progress(trait_names_iterator)

        logger.info("Loaded {} trait names".format(len(trait_names_counter)))
        for i, (trait_name, freq) in enumerate(trait_names_iterator):
            trait = Trait(trait_name, freq)
            trait = process_trait(trait, filters, zooma_host, oxo_target_list,
                                  oxo_distance)
            output_trait(trait, mapping_writer, curation_writer)
            if unattended and i % 100 == 0:
                logger.info("Processed {} records".format(i))
<commit_msg>Log start and end of work<commit_after>from collections import Counter
import csv
import logging
import progressbar

from eva_cttv_pipeline.trait_mapping.output import output_trait
from eva_cttv_pipeline.trait_mapping.oxo import get_oxo_results
from eva_cttv_pipeline.trait_mapping.oxo import uris_to_oxo_format
from eva_cttv_pipeline.trait_mapping.trait import Trait
from eva_cttv_pipeline.trait_mapping.trait_names_parsing import parse_trait_names
from eva_cttv_pipeline.trait_mapping.zooma import get_zooma_results

logger = logging.getLogger(__package__)

def get_uris_for_oxo(zooma_result_list: list) -> set:
    """
    For a list of Zooma mappings return a list of uris for the mappings in that list with a high
    confidence.

    :param zooma_result_list: List with elements of class ZoomaResult
    :return: set of uris from high confidence Zooma mappings, for which to query OxO
    """
    uri_set = set()
    for mapping in zooma_result_list:
        # Only use high confidence Zooma mappings for querying OxO
        if mapping.confidence.lower() == "high":
            uri_set.update([entry.uri for entry in mapping.mapping_list])
    return uri_set

def process_trait(trait: Trait, filters: dict, zooma_host: str, oxo_target_list: list,
                  oxo_distance: int) -> Trait:
    """
    Process a single trait. Find any mappings in Zooma. If there are no high confidence Zooma
    mappings that are in EFO then query OxO with any high confidence mappings not in EFO.

    :param trait: The trait to be processed.
    :param filters: A dictionary of filters to use for querying Zooma.
    :param zooma_host: A string with the hostname to use for querying Zooma
    :param oxo_target_list: A list of strings, each being an OxO ID for an ontology. Used to specify
                            which ontologies should be queried using OxO.
    :param oxo_distance: int specifying the maximum number of steps to use to query OxO. i.e. OxO's
                         "distance" parameter.
    :return: The original trait after querying Zooma and possibly OxO, with any results found.
    """

    logger.debug('Processing trait {}'.format(trait.name))
    trait.zooma_result_list = get_zooma_results(trait.name, filters, zooma_host)
    trait.process_zooma_results()
    if (trait.is_finished
            or len(trait.zooma_result_list) == 0
            or any([entry.is_current
                    for mapping in trait.zooma_result_list
                    for entry in mapping.mapping_list])):
        return trait
    uris_for_oxo_set = get_uris_for_oxo(trait.zooma_result_list)
    if len(uris_for_oxo_set) == 0:
        return trait
    oxo_input_id_list = uris_to_oxo_format(uris_for_oxo_set)
    trait.oxo_result_list = get_oxo_results(oxo_input_id_list, oxo_target_list, oxo_distance)

    if not trait.oxo_result_list:
        logger.warning('No OxO mapping for trait {}'.format(trait.name))

    trait.process_oxo_mappings()

    return trait

def main(input_filepath, output_mappings_filepath, output_curation_filepath, filters, zooma_host,
         oxo_target_list, oxo_distance, unattended):
    logger.info('Started parsing trait names')
    trait_names_list = parse_trait_names(input_filepath)
    trait_names_counter = Counter(trait_names_list)

    with open(output_mappings_filepath, "w", newline='') as mapping_file, \
            open(output_curation_filepath, "wt") as curation_file:
        mapping_writer = csv.writer(mapping_file, delimiter="\t")
        mapping_writer.writerow(["#clinvar_trait_name", "uri", "label"])
        curation_writer = csv.writer(curation_file, delimiter="\t")

        trait_names_iterator = trait_names_counter.items()
        if not unattended:
            progress = progressbar.ProgressBar(max_value=len(trait_names_counter),
                                               widgets=[progressbar.AdaptiveETA(samples=1000)])
            trait_names_iterator = progress(trait_names_iterator)

        logger.info("Loaded {} trait names".format(len(trait_names_counter)))
        for i, (trait_name, freq) in enumerate(trait_names_iterator):
            trait = Trait(trait_name, freq)
            trait = process_trait(trait, filters, zooma_host, oxo_target_list,
                                  oxo_distance)
            output_trait(trait, mapping_writer, curation_writer)
            if unattended and i % 100 == 0:
                logger.info("Processed {} records".format(i))

    logger.info('Finished processing trait names')
<|endoftext|>


<commit_before>from functools import singledispatch, wraps
from inspect import isfunction
from typing import Callable, no_type_check

def applicationpolicy(arg: Callable) -> Callable:
    """
    Decorator for application policy method.

    Allows policy to be built up from methods
    registered for different event classes.
    """

    assert isfunction(arg), arg

    @no_type_check
    def _mutator(func):
        wrapped = singledispatch(func)

        @wraps(wrapped)
        def wrapper(*args, **kwargs):
            event = kwargs.get("event") or args[-1]
            return wrapped.dispatch(type(event))(*args, **kwargs)

        wrapper.register = wrapped.register

        return wrapper

    return _mutator(arg)
<commit_msg>Added applicationpolicy2 decorator, which doesn't use singledispatch (and so doesn't involve weakrefs, it's also much simpler).<commit_after>from functools import singledispatch, wraps
from inspect import isfunction
from typing import Callable, no_type_check

def applicationpolicy(arg: Callable) -> Callable:
    """
    Decorator for application policy method.

    Allows policy to be built up from methods
    registered for different event classes.
    """

    assert isfunction(arg), arg

    @no_type_check
    def _mutator(func):
        wrapped = singledispatch(func)

        @wraps(wrapped)
        def wrapper(*args, **kwargs):
            event = kwargs.get("event") or args[-1]
            return wrapped.dispatch(type(event))(*args, **kwargs)

        wrapper.register = wrapped.register

        return wrapper

    return _mutator(arg)

def applicationpolicy2(arg: Callable) -> Callable:
    """
    This one doesn't use weakrefs.
    """
    handlers = {}
    cache = {}

    def _mutator(func):

        def dispatch(event_type):
            try:
                return handlers[event_type]
            except KeyError:
                try:
                    return cache[event_type]
                except KeyError:
                    for key, value in handlers:
                        if issubclass(event_type, key):
                            cache[event_type] = value
                            return value
                    else:
                        cache[event_type] = func
                        return func

        def register(event_type):
            def registered(func):
                handlers[event_type] = func
            return registered

        @wraps(func)
        def wrapper(*args, **kwargs):
            event = kwargs.get("event") or args[-1]
            return dispatch(type(event))(*args, **kwargs)

        wrapper.register = register

        return wrapper

    return _mutator(arg)
<|endoftext|>


<commit_before>"""
Demonstration of Tube
"""

import sys
from vispy import scene
from vispy.color import get_colormap

import numpy as np
from scipy.special import sph_harm

canvas = scene.SceneCanvas(keys='interactive')
canvas.view = canvas.central_widget.add_view()

thetas, phis = np.meshgrid(np.linspace(0, np.pi, 100),
                           np.linspace(0, 2*np.pi, 150))
shape = thetas.shape
linear_shape = thetas.shape[0] * thetas.shape[1]

for l in range(5):
    for m in range(l+1):
        harmonic_values = sph_harm(m, l, phis, thetas).real
        rs = 1. + 0.4*harmonic_values

        xs = rs * np.sin(thetas) * np.cos(phis)
        ys = rs * np.sin(thetas) * np.sin(phis)
        zs = rs * np.cos(thetas)

        xs -= 4.25
        zs -= 4.25
        xs += 2.5 * l
        zs += 2.5 * m

        v_min = np.min(harmonic_values)
        v_max = np.max(harmonic_values)
        scale = 1. / np.max(np.abs([v_min, v_max]))

        cm = get_colormap('hot')
        harmonic_values *= 0.5*scale
        harmonic_values += 0.5
        colors = cm[harmonic_values.reshape(linear_shape)].rgb.reshape(
            (shape[0], shape[1], 3))

        mesh = scene.visuals.ImplicitMesh(xs, ys, zs, color=colors)

        canvas.view.add(mesh)

canvas.view.set_camera('turntable', mode='perspective',
                       up='z', distance=12)
canvas.show()

if __name__ == '__main__':
    if sys.flags.interactive != 1:
        canvas.app.run()
<commit_msg>Tweaked implicit mesh example defaults<commit_after>"""
Demonstration of Tube
"""

import sys
from vispy import scene
from vispy.color import get_colormap

import numpy as np
from scipy.special import sph_harm

canvas = scene.SceneCanvas(keys='interactive')
canvas.view = canvas.central_widget.add_view()

thetas, phis = np.meshgrid(np.linspace(0, np.pi, 100),
                           np.linspace(0, 2*np.pi, 150))
shape = thetas.shape
linear_shape = thetas.shape[0] * thetas.shape[1]
cm = get_colormap('hot')

for l in range(5):
    for m in range(l+1):
        harmonic_values = sph_harm(m, l, phis, thetas).real
        rs = 1. + 0.4*harmonic_values

        xs = rs * np.sin(thetas) * np.cos(phis)
        ys = rs * np.sin(thetas) * np.sin(phis)
        zs = rs * np.cos(thetas)

        xs -= 4.5
        zs -= 4.5
        xs += 2.5 * l
        zs += 2.5 * m

        v_min = np.min(harmonic_values)
        v_max = np.max(harmonic_values)
        scale = 1. / np.max(np.abs([v_min, v_max]))

        harmonic_values *= 0.5*scale
        harmonic_values += 0.5
        colors = cm[harmonic_values.reshape(linear_shape)].rgb.reshape(
            (shape[0], shape[1], 3))

        mesh = scene.visuals.ImplicitMesh(xs, ys, zs, color=colors)

        canvas.view.add(mesh)

canvas.view.set_camera('turntable', mode='perspective',
                       up='z', distance=12)
canvas.show()

if __name__ == '__main__':
    if sys.flags.interactive != 1:
        canvas.app.run()
<|endoftext|>