<commit_before>from subprocess import call
import re

from common import *

class _AnyNumber(int):
    def __eq__(self, other):
        return True
ANY = _AnyNumber(1)

class PathTester(object):

    def __init__(self, test, root):
        self.test = test
        self.root = root

        self.paths = []
        self.matched = set()
        self.scan()

    def scan(self):

        paths = []

        for dir_name, dir_names, file_names in os.walk(self.root):
            for name in dir_names:
                path = os.path.join(dir_name, name)[len(self.root):] + '/'
                paths.append(path)
            for name in file_names:
                path = os.path.join(dir_name, name)[len(self.root):]
                paths.append(path)

        for pattern in (r'\._', r'\.DS_Store$', r'.*\.pyc$'):
            paths = [path for path in paths if not re.match(pattern, path)]

        paths = [x for x in paths if x not in self.matched]
        self.paths.extend(paths)

        print 'PathTester found', len(paths), 'new items'
        # if paths:
        #    print '\n'.join('\t' + x for x in sorted(paths))

    def __enter__(self):
        self.scan()

    def __exit__(self, *args):
        self.assertMatchedAll()

    def assertMatches(self, count, pattern, msg=None):

        if not pattern:
            self.fail('no pattern specified')

        full_pattern = pattern + r'$'
        if full_pattern[0] != '/':
            full_pattern = r'(?:/[^/]*)*?/' + full_pattern

        paths = self.paths
        self.paths = []
        for path in paths:
            if re.match(full_pattern, path):
                self.matched.add(path)
            else:
                self.paths.append(path)
        self.test.assertEqual(
            count,
            len(paths) - len(self.paths),
            msg or ('found %d, expected %d via %r; %d remain:\n\t' % (len(paths) - len(self.paths), count, pattern, len(self.paths))) + '\n\t'.join(sorted(self.paths))
        )

    def assertMatchedAll(self, msg=None):
        self.test.assertFalse(self.paths, msg or ('%d paths remain:\n\t' % len(self.paths)) + '\n\t'.join(sorted(self.paths)))

    def assertProject(self):
        self.assertMatches(1, r'/Assets/')
        self.assertMatches(1, r'/SEQ/')
        self.assertMatches(1, r'/\.sgfs-cache\.sqlite')
        self.assertMatches(1, r'/\.sgfs\.yml')

    def assertAssetType(self, count):
        self.assertMatches(count,  r'/Assets/(Character|Vehicle)/')

    def assertAsset(self, count):
        self.assertMatches(count,  r'/Assets/(Character|Vehicle)/(\1_\d+)/')
        self.assertMatches(count,  r'/Assets/(Character|Vehicle)/(\1_\d+)/\.sgfs\.yml')

    def assertAssetTask(self, count, type_, maya=False, nuke=False):
        self._assertTask(count, r'/Assets/(Character|Vehicle)/(\1_\d+)', type_, maya=maya, nuke=nuke)

    def _assertTask(self, count, base, type_, maya, nuke):
        self.assertMatches(count, base + r'/%s/' % type_)
        self.assertMatches(ANY, base + r'/%s/\.sgfs\.yml' % type_)
        self.assertMatches(count if maya else 0, base + r'/%s/scenes/' % type_)
        self.assertMatches(count if maya else 0, base + r'/%s/workspace.mel' % type_)
        self.assertMatches(count if nuke else 0, base + r'/%s/scripts/' % type_)

    def assertSequence(self, count):
        self.assertMatches(count, r'/SEQ/(\w{2})/')
        self.assertMatches(count, r'/SEQ/(\w{2})/\.sgfs\.yml')

    def assertShot(self, count):
        self.assertMatches(count, r'/SEQ/(\w{2})/\1_\d{3}/')
        self.assertMatches(count, r'/SEQ/(\w{2})/\1_\d{3}/\.sgfs\.yml')
        self.assertMatches(count * 3, r'/SEQ/(\w{2})/\1_\d{3}/(Audio|Plates|Ref)/')

    def assertShotTask(self, count, type_, maya=False, nuke=False):
        self._assertTask(count, r'/SEQ/(\w{2})/\1_\d{3}', type_, maya=maya, nuke=nuke)

    def assertFullStructure(self):
        self.assertProject()
        self.assertAssetType(2)
        self.assertAsset(4)
        self.assertAssetTask(4, 'Anm', maya=True, nuke=False)
        self.assertAssetTask(4, 'Comp', maya=False, nuke=True)
        self.assertAssetTask(4, 'Model', maya=True, nuke=False)
        self.assertSequence(2)
        self.assertShot(4)
        self.assertShotTask(4, 'Anm', maya=True, nuke=False)
        self.assertShotTask(4, 'Comp', maya=False, nuke=True)
        self.assertShotTask(4, 'Model', maya=True, nuke=False)
        self.assertMatchedAll()

class Base(TestCase):

    def setUp(self):
        sg = Shotgun()
        self.sg = self.fix = fix = Fixture(sg)

        self.proj_name = 'Test Project ' + mini_uuid()
        proj = fix.Project(self.proj_name)
        seqs = [proj.Sequence(code, project=proj) for code in ('AA', 'BB')]
        shots = [seq.Shot('%s_%03d' % (seq['code'], i), project=proj) for seq in seqs for i in range(1, 3)]
        steps = [fix.find_or_create('Step', code=code, short_name=code) for code in ('Anm', 'Comp', 'Model')]
        assets = [proj.Asset(sg_asset_type=type_, code="%s %d" % (type_, i)) for type_ in ('Character', 'Vehicle') for i in range(1, 3)]
        tasks = [entity.Task(step['code'] + ' something', step=step, entity=entity, project=proj) for step in (steps + steps[-1:]) for entity in (shots + assets)]

        self.proj = minimal(proj)
        self.seqs = map(minimal, seqs)
        self.shots = map(minimal, shots)
        self.steps = map(minimal, steps)
        self.tasks = map(minimal, tasks)
        self.assets = map(minimal, assets)

        self.session = Session(self.sg)
        self.sgfs = SGFS(root=self.sandbox, session=self.session)
        self = None

    def pathTester(self):
        return PathTester(self, os.path.join(self.sandbox, self.proj_name.replace(' ', '_')))

class TestFullStructure(Base):

    def test_full_structure(self):
        self.sgfs.create_structure(self.tasks + self.assets)
        paths = self.pathTester()
        paths.assertFullStructure()

class TestIncrementalStructure(Base):

    def test_incremental_structure(self):

        paths = self.pathTester()

        proj = self.session.merge(self.proj)
        proj.fetch('name')
        self.sgfs.create_structure([proj])
        with paths:
            paths.assertProject()

        for seq in self.seqs:
            self.sgfs.create_structure([seq])
            with paths:
                paths.assertSequence(1)

        for asset in self.assets:
            self.sgfs.create_structure([asset])
            with paths:
                paths.assertAssetType(ANY)
                paths.assertAsset(1)

        for shot in self.shots:
            self.sgfs.create_structure([shot])
            with paths:
                paths.assertShot(1)

        self.sgfs.create_structure(self.tasks)
        with paths:
            paths.assertAssetTask(len(self.assets), 'Anm', maya=True, nuke=False)
            paths.assertAssetTask(len(self.assets), 'Comp', maya=False, nuke=True)
            paths.assertAssetTask(len(self.assets), 'Model', maya=True, nuke=False)
            paths.assertShotTask(len(self.shots), 'Anm', maya=True, nuke=False)
            paths.assertShotTask(len(self.shots), 'Comp', maya=False, nuke=True)
            paths.assertShotTask(len(self.shots), 'Model', maya=True, nuke=False)

        root = os.path.join(self.sandbox, self.proj_name.replace(' ', '_'))
        self.assertEqual(1, len(self.sgfs.get_directory_entity_tags(root)))
        self.assertEqual(1, len(self.sgfs.get_directory_entity_tags(root + '/SEQ/AA/AA_001/Anm')))
        self.assertEqual(2, len(self.sgfs.get_directory_entity_tags(root + '/SEQ/AA/AA_001/Model')))

class TestMutatedStructure(Base):

    def test_mutated_structure(self):

        root = os.path.join(self.sandbox, self.proj_name.replace(' ', '_'))

        paths = self.pathTester()

        proj = self.session.merge(self.proj)
        proj.fetch('name')
        self.sgfs.create_structure([proj])
        with paths:
            paths.assertProject()

        for seq in self.seqs:
            self.sgfs.create_structure([seq])
            with paths:
                paths.assertSequence(1)

        # Mutate the sequences, and rebuild the cache.
        call(['mv', root + '/SEQ/AA', root + '/SEQ/XX'])
        call(['mv', root + '/SEQ/BB', root + '/SEQ_BB'])
        print '==== MUTATION ===='
        self.sgfs.rebuild_cache(root)

        self.sgfs.create_structure(self.shots)
        paths.scan()
        paths.assertMatches(2, r'SEQ/XX/AA_\d+/')
        paths.assertMatches(2, r'SEQ/XX/AA_\d+/\.sgfs\.yml')
        paths.assertMatches(2, r'SEQ_BB/BB_\d+/')
        paths.assertMatches(2, r'SEQ_BB/BB_\d+/\.sgfs\.yml')

        tags = self.sgfs.get_directory_entity_tags(root + '/SEQ/XX/AA_001')
        self.assertEqual(1, len(tags))
        self.assertSameEntity(tags[0]['entity'], self.shots[0])

        tags = self.sgfs.get_directory_entity_tags(root + '/SEQ_BB/BB_001')
        self.assertEqual(1, len(tags))
        self.assertSameEntity(tags[0]['entity'], self.shots[3])

class TestDryRun(Base):

    def test_dry_run(self):
        self.sgfs.create_structure(self.tasks + self.assets, dry_run=True)
        paths = self.pathTester()
        paths.assertMatchedAll()

       <commit_msg>Test new structure<commit_after>from subprocess import call
import re

from common import *

class _AnyNumber(int):
    def __eq__(self, other):
        return True
ANY = _AnyNumber(1)

class PathTester(object):

    def __init__(self, test, root):
        self.test = test
        self.root = root

        self.paths = []
        self.matched = set()
        self.scan()

    def scan(self):

        paths = []

        for dir_name, dir_names, file_names in os.walk(self.root):
            for name in dir_names:
                path = os.path.join(dir_name, name)[len(self.root):] + '/'
                paths.append(path)
            for name in file_names:
                path = os.path.join(dir_name, name)[len(self.root):]
                paths.append(path)

        for pattern in (r'\._', r'\.DS_Store$', r'.*\.pyc$'):
            paths = [path for path in paths if not re.match(pattern, path)]

        paths = [x for x in paths if x not in self.matched]
        self.paths.extend(paths)

        print 'PathTester found', len(paths), 'new items'
        # if paths:
        #    print '\n'.join('\t' + x for x in sorted(paths))

    def __enter__(self):
        self.scan()

    def __exit__(self, *args):
        self.assertMatchedAll()

    def assertMatches(self, count, pattern, msg=None):

        if not pattern:
            self.fail('no pattern specified')

        full_pattern = pattern + r'$'
        if full_pattern[0] != '/':
            full_pattern = r'(?:/[^/]*)*?/' + full_pattern

        paths = self.paths
        self.paths = []
        for path in paths:
            if re.match(full_pattern, path):
                self.matched.add(path)
            else:
                self.paths.append(path)
        self.test.assertEqual(
            count,
            len(paths) - len(self.paths),
            msg or ('found %d, expected %d via %r; %d remain:\n\t' % (len(paths) - len(self.paths), count, pattern, len(self.paths))) + '\n\t'.join(sorted(self.paths))
        )

    def assertMatchedAll(self, msg=None):
        self.test.assertFalse(self.paths, msg or ('%d paths remain:\n\t' % len(self.paths)) + '\n\t'.join(sorted(self.paths)))

    def assertProject(self):
        self.assertMatches(1, r'/Assets/')
        self.assertMatches(1, r'/SEQ/')
        self.assertMatches(1, r'/\.sgfs-cache\.sqlite')
        self.assertMatches(1, r'/\.sgfs\.yml')

    def assertAssetType(self, count):
        self.assertMatches(count,  r'/Assets/(Character|Vehicle)/')

    def assertAsset(self, count):
        self.assertMatches(count,  r'/Assets/(Character|Vehicle)/(\1_\d+)/')
        self.assertMatches(count,  r'/Assets/(Character|Vehicle)/(\1_\d+)/\.sgfs\.yml')

    def assertAssetTask(self, count, type_, **kwargs):
        self._assertTask(count, r'/Assets/(Character|Vehicle)/(\1_\d+)', type_, **kwargs)

    def _assertTask(self, count, base, type_, maya=False, nuke=False, mudbox=False):
        self.assertMatches(count, base + r'/%s/' % type_)
        self.assertMatches(ANY, base + r'/%s/\.sgfs\.yml' % type_)
        self.assertMatches(ANY, base + r'/%s/dailies/' % type_)
        self.assertMatches(count if maya else 0, base + r'/%s/maya/' % type_)
        self.assertMatches(count if maya else 0, base + r'/%s/maya/published/' % type_)
        self.assertMatches(count if maya else 0, base + r'/%s/maya/scenes/' % type_)
        self.assertMatches(count if maya else 0, base + r'/%s/maya/workspace.mel' % type_)
        self.assertMatches(count if mudbox else 0, base + r'/%s/mudbox/' % type_)
        self.assertMatches(count if mudbox else 0, base + r'/%s/mudbox/published/' % type_)
        self.assertMatches(count if nuke else 0, base + r'/%s/nuke/' % type_)
        self.assertMatches(count if nuke else 0, base + r'/%s/nuke/published/' % type_)
        self.assertMatches(count if nuke else 0, base + r'/%s/nuke/renders/' % type_)
        self.assertMatches(count if nuke else 0, base + r'/%s/nuke/scripts/' % type_)

    def assertSequence(self, count):
        self.assertMatches(count, r'/SEQ/(\w{2})/')
        self.assertMatches(count, r'/SEQ/(\w{2})/\.sgfs\.yml')

    def assertShot(self, count):
        self.assertMatches(count, r'/SEQ/(\w{2})/\1_\d{3}/')
        self.assertMatches(count, r'/SEQ/(\w{2})/\1_\d{3}/\.sgfs\.yml')
        self.assertMatches(count * 3, r'/SEQ/(\w{2})/\1_\d{3}/(Audio|Plates|Ref)/')

    def assertShotTask(self, count, type_, **kwargs):
        self._assertTask(count, r'/SEQ/(\w{2})/\1_\d{3}', type_, **kwargs)

    def assertFullStructure(self):
        self.assertProject()
        self.assertAssetType(2)
        self.assertAsset(4)
        self.assertAssetTask(4, 'Anm', maya=True)
        self.assertAssetTask(4, 'Comp', nuke=True)
        self.assertAssetTask(4, 'Model', maya=True, mudbox=True)
        self.assertSequence(2)
        self.assertShot(4)
        self.assertShotTask(4, 'Anm', maya=True)
        self.assertShotTask(4, 'Comp', nuke=True)
        self.assertShotTask(4, 'Model', maya=True, mudbox=True)
        self.assertMatchedAll()

class Base(TestCase):

    def setUp(self):
        sg = Shotgun()
        self.sg = self.fix = fix = Fixture(sg)

        self.proj_name = 'Test Project ' + mini_uuid()
        proj = fix.Project(self.proj_name)
        seqs = [proj.Sequence(code, project=proj) for code in ('AA', 'BB')]
        shots = [seq.Shot('%s_%03d' % (seq['code'], i), project=proj) for seq in seqs for i in range(1, 3)]
        steps = [fix.find_or_create('Step', code=code, short_name=code) for code in ('Anm', 'Comp', 'Model')]
        assets = [proj.Asset(sg_asset_type=type_, code="%s %d" % (type_, i)) for type_ in ('Character', 'Vehicle') for i in range(1, 3)]
        tasks = [entity.Task(step['code'] + ' something', step=step, entity=entity, project=proj) for step in (steps + steps[-1:]) for entity in (shots + assets)]

        self.proj = minimal(proj)
        self.seqs = map(minimal, seqs)
        self.shots = map(minimal, shots)
        self.steps = map(minimal, steps)
        self.tasks = map(minimal, tasks)
        self.assets = map(minimal, assets)

        self.session = Session(self.sg)
        self.sgfs = SGFS(root=self.sandbox, session=self.session)
        self = None

    def pathTester(self):
        return PathTester(self, os.path.join(self.sandbox, self.proj_name.replace(' ', '_')))

class TestFullStructure(Base):

    def test_full_structure(self):
        self.sgfs.create_structure(self.tasks + self.assets)
        paths = self.pathTester()
        paths.assertFullStructure()

class TestIncrementalStructure(Base):

    def test_incremental_structure(self):

        paths = self.pathTester()

        proj = self.session.merge(self.proj)
        proj.fetch('name')
        self.sgfs.create_structure([proj])
        with paths:
            paths.assertProject()

        for seq in self.seqs:
            self.sgfs.create_structure([seq])
            with paths:
                paths.assertSequence(1)

        for asset in self.assets:
            self.sgfs.create_structure([asset])
            with paths:
                paths.assertAssetType(ANY)
                paths.assertAsset(1)

        for shot in self.shots:
            self.sgfs.create_structure([shot])
            with paths:
                paths.assertShot(1)

        self.sgfs.create_structure(self.tasks)
        with paths:
            paths.assertAssetTask(len(self.assets), 'Anm', maya=True)
            paths.assertAssetTask(len(self.assets), 'Comp', nuke=True)
            paths.assertAssetTask(len(self.assets), 'Model', maya=True, mudbox=True)
            paths.assertShotTask(len(self.shots), 'Anm', maya=True)
            paths.assertShotTask(len(self.shots), 'Comp', nuke=True)
            paths.assertShotTask(len(self.shots), 'Model', maya=True, mudbox=True)

        root = os.path.join(self.sandbox, self.proj_name.replace(' ', '_'))
        self.assertEqual(1, len(self.sgfs.get_directory_entity_tags(root)))
        self.assertEqual(1, len(self.sgfs.get_directory_entity_tags(root + '/SEQ/AA/AA_001/Anm')))
        self.assertEqual(2, len(self.sgfs.get_directory_entity_tags(root + '/SEQ/AA/AA_001/Model')))

class TestMutatedStructure(Base):

    def test_mutated_structure(self):

        root = os.path.join(self.sandbox, self.proj_name.replace(' ', '_'))

        paths = self.pathTester()

        proj = self.session.merge(self.proj)
        proj.fetch('name')
        self.sgfs.create_structure([proj])
        with paths:
            paths.assertProject()

        for seq in self.seqs:
            self.sgfs.create_structure([seq])
            with paths:
                paths.assertSequence(1)

        # Mutate the sequences, and rebuild the cache.
        call(['mv', root + '/SEQ/AA', root + '/SEQ/XX'])
        call(['mv', root + '/SEQ/BB', root + '/SEQ_BB'])
        print '==== MUTATION ===='
        self.sgfs.rebuild_cache(root)

        self.sgfs.create_structure(self.shots)
        paths.scan()
        paths.assertMatches(2, r'SEQ/XX/AA_\d+/')
        paths.assertMatches(2, r'SEQ/XX/AA_\d+/\.sgfs\.yml')
        paths.assertMatches(2, r'SEQ_BB/BB_\d+/')
        paths.assertMatches(2, r'SEQ_BB/BB_\d+/\.sgfs\.yml')

        tags = self.sgfs.get_directory_entity_tags(root + '/SEQ/XX/AA_001')
        self.assertEqual(1, len(tags))
        self.assertSameEntity(tags[0]['entity'], self.shots[0])

        tags = self.sgfs.get_directory_entity_tags(root + '/SEQ_BB/BB_001')
        self.assertEqual(1, len(tags))
        self.assertSameEntity(tags[0]['entity'], self.shots[3])

class TestDryRun(Base):

    def test_dry_run(self):
        self.sgfs.create_structure(self.tasks + self.assets, dry_run=True)
        paths = self.pathTester()
        paths.assertMatchedAll()

       <|endoftext|>


<commit_before>from __future__ import division, absolute_import, print_function
from past.builtins import xrange

import unittest
import numpy.testing as testing
import numpy as np

import redmapper

class SplineTestCase(unittest.TestCase):
    def runTest(self):
        """
        This tests the functionality of the redmapper.utilities
        spline against the spline output values from a spline
        implemented in IDL found in RM 6.3.1 DR8.
        """
        # create test data
        # these numbers are from redMaPPer 6.3.1, DR8
        xx = np.array([0.05,0.15,0.25,0.35,0.45,0.60],dtype=np.float64)
        yy = np.array([15.685568,17.980721,18.934799,19.671671,19.796223,20.117981], dtype=np.float64)

        # will want to add error checking and exceptions to CubicSpline

        spl=redmapper.utilities.CubicSpline(xx, yy)
        vals=spl(np.array([0.01, 0.44, 0.55, 0.665]))

        # these numbers are also from redMaPPer 6.3.1, DR8
        testing.assert_almost_equal(vals,np.array([14.648017,19.792828,19.973761,20.301322],dtype=np.float64),decimal=6)

class MStarTestCase(unittest.TestCase):
    def runTest(self):
        """
        This tests the MStar function found in the utilities
        class at two different decimal levels.
        """
        # make sure invalid raises proper exception
        self.assertRaises(IOError,redmapper.utilities.MStar,'blah','junk')

        # make an SDSS test...
        ms = redmapper.utilities.MStar('sdss','i03')

        mstar = ms([0.1,0.2,0.3,0.4,0.5])
        # test against IDL...
        testing.assert_almost_equal(mstar,np.array([16.2375,17.8500,18.8281,19.5878,20.1751]),decimal=4)
        # and against regressions...
        testing.assert_almost_equal(mstar,np.array([ 16.23748776,  17.85000035,  18.82812871,  19.58783337,  20.17514801]))

class FunctionsTestCase(unittest.TestCase):
    def runTest(self):
        """
        This tests the conversion between astronomical coordintates
        (RA,DEC) to spherical coordinates (theta,phi). This is
        implemented in the utilities.astro_to_sphere() function.
        """
        ra,dec = 40.1234, 55.9876
        testing.assert_almost_equal(redmapper.utilities.astro_to_sphere(ra,dec),np.array([ 0.5936,  0.7003]),decimal=4)
        #Need a test for chisq_pdf
        #TO DO

# copy this for a new utility test
class UtilityTemplateTestCase(unittest.TestCase):
    def runTest(self):
        pass

if __name__=='__main__':
    unittest.main()
<commit_msg>Test CIC<commit_after>from __future__ import division, absolute_import, print_function
from past.builtins import xrange

import unittest
import numpy.testing as testing
import numpy as np
import fitsio

import redmapper

class SplineTestCase(unittest.TestCase):
    def runTest(self):
        """
        This tests the functionality of the redmapper.utilities
        spline against the spline output values from a spline
        implemented in IDL found in RM 6.3.1 DR8.
        """
        # create test data
        # these numbers are from redMaPPer 6.3.1, DR8
        xx = np.array([0.05,0.15,0.25,0.35,0.45,0.60],dtype=np.float64)
        yy = np.array([15.685568,17.980721,18.934799,19.671671,19.796223,20.117981], dtype=np.float64)

        # will want to add error checking and exceptions to CubicSpline

        spl=redmapper.utilities.CubicSpline(xx, yy)
        vals=spl(np.array([0.01, 0.44, 0.55, 0.665]))

        # these numbers are also from redMaPPer 6.3.1, DR8
        testing.assert_almost_equal(vals,np.array([14.648017,19.792828,19.973761,20.301322],dtype=np.float64),decimal=6)

class MStarTestCase(unittest.TestCase):
    def runTest(self):
        """
        This tests the MStar function found in the utilities
        class at two different decimal levels.
        """
        # make sure invalid raises proper exception
        self.assertRaises(IOError,redmapper.utilities.MStar,'blah','junk')

        # make an SDSS test...
        ms = redmapper.utilities.MStar('sdss','i03')

        mstar = ms([0.1,0.2,0.3,0.4,0.5])
        # test against IDL...
        testing.assert_almost_equal(mstar,np.array([16.2375,17.8500,18.8281,19.5878,20.1751]),decimal=4)
        # and against regressions...
        testing.assert_almost_equal(mstar,np.array([ 16.23748776,  17.85000035,  18.82812871,  19.58783337,  20.17514801]))

class FunctionsTestCase(unittest.TestCase):
    def runTest(self):
        """
        This tests the conversion between astronomical coordintates
        (RA,DEC) to spherical coordinates (theta,phi). This is
        implemented in the utilities.astro_to_sphere() function.
        """
        ra,dec = 40.1234, 55.9876
        testing.assert_almost_equal(redmapper.utilities.astro_to_sphere(ra,dec),np.array([ 0.5936,  0.7003]),decimal=4)
        #Need a test for chisq_pdf
        #TO DO

class CicTestCase(unittest.TestCase):
    def runTest(self):
        incat = fitsio.read('data_for_tests/test_cic_small.fits', ext=1)

        posx = incat[0]['POSX']
        nx = incat[0]['NX']
        posy = incat[0]['POSY']
        ny = incat[0]['NY']
        posz = incat[0]['POSZ']
        nz = incat[0]['NZ']
        value = np.ones(posx.size)

        field = redmapper.utilities.cic(value, posx, nx, posy, ny, posz, nz)
        avfield = redmapper.utilities.cic(value, posx, nx, posy, ny, posz, nz, average=True)
        testing.assert_almost_equal(field, incat[0]['FIELD'], decimal=6)
        testing.assert_almost_equal(avfield, incat[0]['AVFIELD'], decimal=6)

# copy this for a new utility test
class UtilityTemplateTestCase(unittest.TestCase):
    def runTest(self):
        pass

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


<commit_before>MAX_MINIONS = 7

class Board(object):
    """Board class which holds minions on it (4 per side) and Heros."""

    def __init__(self, topHero=None, bottomHero=None):
        self.heroes = {'top':topHero, 'bottom':bottomHero}
        self.decks = {'top':None, 'bottom':None}
        self.hands = {'top':None, 'bottom':None}
        self.manaBase = {'top':0, 'bottom':1}
        self.manaCurrent = {'top':0, 'bottom':1}
        self.minions = {'top':[None, None, None, None, None, None, None], 'bottom':[None, None, None, None, None, None, None]}
        self.playerTurn = 'bottom'
        self.turnCount = 1
        self.log = ["",]

    def set_hand(self, hand, side):
        self.hands[side] = hand
        hand.side = side
        hand.board = self

    def set_deck(self, deck, side):
        self.decks[side] = deck
        deck.side = side

    def set_hero(self, character, side):
        """Set a hero with a given character object."""
        if self.heroes[side] is not None:
            raise Exception
        self.heroes[side] = character
        character.side = side
        character.board = self

    def set_text(self, text):
        """Set the text to be displayed in the output field."""
        self.log.append(text)

    def get_log(self):
        """Return the current text to be displayed."""
        return self.log

    def get_hero(self, side=None):
        """Return one of the heroes (default is the active one)."""
        if side is None:
            side = self.playerTurn
        return self.heroes[side]

    def get_enemy_hero(self):
        """Return the hero from the opposite side."""
        return self.heroes[self.get_enemy_side()]

    def get_minions(self, side=None):
        """Return list of minions (default is the active one)."""
        if side is None:
            side = self.playerTurn
        return self.minions[side]

    def get_enemy_minions(self):
        """Return the minions from the opposite side."""
        return self.minions[self.get_enemy_side()]

    def get_hand(self, side=None):
        if side is None:
            side = self.get_side()
        return self.hands[side]

    def get_side(self):
        """Return the current playerTurn."""
        return self.playerTurn

    def get_enemy_side(self):
        """Return the side opposite of the given side."""
        if self.playerTurn == 'top':
            return 'bottom'
        elif self.playerTurn == 'bottom':
            return 'top'
        else:
            raise Exception('Invalid side: %s' % side)

    def get_empty_minion_positions(self, *args):
        """Return a list of positions (idx+1) where this side has empty minion slots."""
        if 'enemy' in args:
            side = self.get_enemy_side()
        else:
            side = self.get_side()
        emptyPositions = []
        for i, minion in enumerate(self.minions[side]):
            if minion is None:
                emptyPositions.append(i+1)
        return emptyPositions

    def get_canAttack_characters(self):
        """Return a list of characters that can attack right now."""
        side = self.playerTurn
        canAttackChars = []
        for minion in self.minions[side]:
            if minion is None:
                continue
            if minion.can_attack():
                canAttackChars.append(minion)
        if self.heroes[side].can_attack():
            canAttackChars.append(self.heroes[side])
        return canAttackChars

    def get_canAttack_char_positions(self):
        """Return a list of positions of characters that can attack right now."""
        side = self.playerTurn
        canAttackPos = []
        for i, minion in enumerate(self.minions[side]):
            if minion is None:
                continue
            if minion.can_attack():
                canAttackPos.append(i+1)
        if self.heroes[side].can_attack():
            canAttackPos.append(8)
        return canAttackPos

    def get_character(self, pos, side=None):
        """Return the character at the position specified. Default is current side."""
        if side is None:
            side = self.playerTurn
        if pos < 0 or pos > 8:
            raise Exception("Invalid character position.")
        if pos == 8:
            return self.heroes[side]
        else:
            return self.minions[side][pos-1]

    def get_all_characters(self):
        """Return a list of all characters on the board that aren't None."""
        allChars = []
        for minion in self.minions['top']:
            if minion is None:
                continue
            allChars.append(minion)
        for minion in self.minions['bottom']:
            if minion is None:
                continue
            allChars.append(minion)
        allChars.append(self.heroes['top'])
        allChars.append(self.heroes['bottom'])
        return allChars

    def get_character_by_position(self, pos):
        """Return the character from a position. 1-7 enemy minions, 8 enemy hero,
        11-17 friendly minions, 18 friendly hero."""
        if pos not in [1,2,3,4,5,6,7,8,11,12,13,14,15,16,17,18]:
            raise Exception("Invalid target position.")
        if pos == 8:
            return self.get_enemy_hero()
        elif pos == 18:
            return self.get_hero()
        elif 1 <= pos <= 7:
            return self.get_enemy_minions()[pos-1]
        elif 11 <= pos <= 17:
            return self.get_minions()[pos-11]

    def get_targetable_characters(self, attacker):
        """Return a list of characters that can be attacked by the attacker.  Check that
        the attacker can target opponent, and that the opponent can be targeted by attacker."""
        targetableChars = []
        for potentialTarget in self.get_all_characters():
            if attacker.can_target(potentialTarget) and potentialTarget.targetable_by(attacker):
                targetableChars.append(potentialTarget)
        return targetableChars

    def get_target_pos(self, targetChar):
        """Determine where the targetChar is on the board and return a position number
        based on that.  1-7 enemy minions, 8 enemy hero, 11-17 friendly minions, 18 friendly hero.
        Return None if not found."""
        # Check if hero
        if targetChar is self.get_hero():
            return 18
        elif targetChar is self.get_enemy_hero():
            return 8
        elif targetChar in self.get_minions():
            pos = self.get_minions().index(targetChar) + 11
            return pos
        elif targetChar in self.get_enemy_minions():
            pos = self.get_enemy_minions().index(targetChar) + 1
            return pos
        return None

    def update_mana(self):
        """Increate the mana base by 1 if less than 10, then refresh
        the mana to full (overload not implemented)."""
        side = self.get_side()
        if self.manaBase[side] < 10:
            self.manaBase[side] += 1
        self.manaCurrent[side] = self.manaBase[side]

    def increment_turn(self):
        """Increment the turn counter."""
        self.turnCount += 1

    def subtract_mana(self, amount, side=None):
        """Subtract mana from current side, unless side is specified."""
        if side is None:
            side = self.get_side()
        self.manaCurrent[side] -= amount
        if self.manaCurrent[side] < 0:
            raise Exception("Mana less than 0.")

    def add_mana(self, amount, side=None):
        """Subtract mana from current side, unless side is specified."""
        if side is None:
            side = self.get_side()
        if self.manaCurrent[side] >= 10:
            return
        else:
            self.manaCurrent[side] += amount

    def change_side(self):
        """Change the current playerTurn to the opposite side."""
        self.playerTurn = self.get_enemy_side()

    def reset_attacksRemaining(self):
        """Reset the remaining attacks for all characters on the current side."""
        side = self.get_side()
        for minion in self.minions[side]:
            if minion is None:
                continue
            minion.attacksRemaining = 1
            if 'windfury' in minion.status:
                minion.attacksRemaining += 1
        hero = self.heroes[side]
        hero.attacksRemaining = 1
        if 'windfury' in hero.status:
            hero.attacksRemaining += 1

    def summon_minion(self, minion, side=None, pos=None):
        """Place a minion on the board given the side and (optional) position. If position
        is not specified, place the minion in lowest available spot (not implemented yet).
        Positions range from 1-7.  Set attacksRemaining to 0, unless charge."""
        if side is None:
            side = self.get_side()
        minion.side = side
        minion.board = self
        idx = pos - 1
        if self.minions[side][idx] is not None:
            raise Exception("Not a free spot.")
        self.minions[side][idx] = minion
        if "charge" in minion.status:
            minion.attacksRemaining = 1
            if "windfury" in minion.status:
                minion.attacksRemaining += 1

    def destroy_minion(self, deadMinion):
        """Destroy the character specified from the field."""
        for side in ['top', 'bottom']:
            for i, minion in enumerate(self.minions[side]):
                if minion is deadMinion:
                    self.minions[side][i] = None
                    deadMinion.deathrattle()
                    del deadMinion
                    return
<commit_msg>implemented taunt<commit_after>MAX_MINIONS = 7

class Board(object):
    """Board class which holds minions on it (4 per side) and Heros."""

    def __init__(self, topHero=None, bottomHero=None):
        self.heroes = {'top':topHero, 'bottom':bottomHero}
        self.decks = {'top':None, 'bottom':None}
        self.hands = {'top':None, 'bottom':None}
        self.manaBase = {'top':0, 'bottom':1}
        self.manaCurrent = {'top':0, 'bottom':1}
        self.minions = {'top':[None, None, None, None, None, None, None], 'bottom':[None, None, None, None, None, None, None]}
        self.playerTurn = 'bottom'
        self.turnCount = 1
        self.log = ["",]

    def set_hand(self, hand, side):
        self.hands[side] = hand
        hand.side = side
        hand.board = self

    def set_deck(self, deck, side):
        self.decks[side] = deck
        deck.side = side

    def set_hero(self, character, side):
        """Set a hero with a given character object."""
        if self.heroes[side] is not None:
            raise Exception
        self.heroes[side] = character
        character.side = side
        character.board = self

    def set_text(self, text):
        """Set the text to be displayed in the output field."""
        self.log.append(text)

    def get_log(self):
        """Return the current text to be displayed."""
        return self.log

    def get_hero(self, side=None):
        """Return one of the heroes (default is the active one)."""
        if side is None:
            side = self.playerTurn
        return self.heroes[side]

    def get_enemy_hero(self):
        """Return the hero from the opposite side."""
        return self.heroes[self.get_enemy_side()]

    def get_minions(self, side=None, valid=False):
        """Return list of minions (default is the active one). Includes None values."""
        if side is None:
            side = self.playerTurn
        minions = self.minions[side]
        if valid:
            return [minion for minion in minions if minion is not None]
        else:
            return minions

    def get_enemy_minions(self, valid=False):
        """Return the minions from the opposite side.  Includes None values."""
        minions = self.minions[self.get_enemy_side()]
        if valid:
            return [minion for minion in minions if minion is not None]
        else:
            return minions

    def get_hand(self, side=None):
        if side is None:
            side = self.get_side()
        return self.hands[side]

    def get_side(self):
        """Return the current playerTurn."""
        return self.playerTurn

    def get_enemy_side(self):
        """Return the side opposite of the given side."""
        if self.playerTurn == 'top':
            return 'bottom'
        elif self.playerTurn == 'bottom':
            return 'top'
        else:
            raise Exception('Invalid side: %s' % side)

    def get_empty_minion_positions(self, *args):
        """Return a list of positions (idx+1) where this side has empty minion slots."""
        if 'enemy' in args:
            side = self.get_enemy_side()
        else:
            side = self.get_side()
        emptyPositions = []
        for i, minion in enumerate(self.minions[side]):
            if minion is None:
                emptyPositions.append(i+1)
        return emptyPositions

    def get_canAttack_characters(self):
        """Return a list of characters that can attack right now."""
        side = self.playerTurn
        canAttackChars = []
        for minion in self.minions[side]:
            if minion is None:
                continue
            if minion.can_attack():
                canAttackChars.append(minion)
        if self.heroes[side].can_attack():
            canAttackChars.append(self.heroes[side])
        return canAttackChars

    def get_canAttack_char_positions(self):
        """Return a list of positions of characters that can attack right now."""
        side = self.playerTurn
        canAttackPos = []
        for i, minion in enumerate(self.minions[side]):
            if minion is None:
                continue
            if minion.can_attack():
                canAttackPos.append(i+1)
        if self.heroes[side].can_attack():
            canAttackPos.append(8)
        return canAttackPos

    def get_character(self, pos, side=None):
        """Return the character at the position specified. Default is current side."""
        if side is None:
            side = self.playerTurn
        if pos < 0 or pos > 8:
            raise Exception("Invalid character position.")
        if pos == 8:
            return self.heroes[side]
        else:
            return self.minions[side][pos-1]

    def get_all_characters(self):
        """Return a list of all characters on the board that aren't None."""
        allChars = []
        for minion in self.minions['top']:
            if minion is None:
                continue
            allChars.append(minion)
        for minion in self.minions['bottom']:
            if minion is None:
                continue
            allChars.append(minion)
        allChars.append(self.heroes['top'])
        allChars.append(self.heroes['bottom'])
        return allChars

    def get_character_by_position(self, pos):
        """Return the character from a position. 1-7 enemy minions, 8 enemy hero,
        11-17 friendly minions, 18 friendly hero."""
        if pos not in [1,2,3,4,5,6,7,8,11,12,13,14,15,16,17,18]:
            raise Exception("Invalid target position.")
        if pos == 8:
            return self.get_enemy_hero()
        elif pos == 18:
            return self.get_hero()
        elif 1 <= pos <= 7:
            return self.get_enemy_minions()[pos-1]
        elif 11 <= pos <= 17:
            return self.get_minions()[pos-11]

    def get_targetable_characters(self, attacker):
        """Return a list of characters that can be ATTACKED by the attacker.  Check that
        the attacker can target opponent, and that the opponent can be targeted by attacker."""
        enemy_taunts = [minion for minion in self.get_enemy_minions(valid=True) if 'taunt' in minion.status]

        targetableChars = []
        for potentialTarget in self.get_all_characters():
            if attacker.can_target(potentialTarget) and potentialTarget.targetable_by(attacker):
                if len(enemy_taunts) and potentialTarget not in enemy_taunts:
                    continue
                targetableChars.append(potentialTarget)
        return targetableChars

    def get_target_pos(self, targetChar):
        """Determine where the targetChar is on the board and return a position number
        based on that.  1-7 enemy minions, 8 enemy hero, 11-17 friendly minions, 18 friendly hero.
        Return None if not found."""
        # Check if hero
        if targetChar is self.get_hero():
            return 18
        elif targetChar is self.get_enemy_hero():
            return 8
        elif targetChar in self.get_minions():
            pos = self.get_minions().index(targetChar) + 11
            return pos
        elif targetChar in self.get_enemy_minions():
            pos = self.get_enemy_minions().index(targetChar) + 1
            return pos
        return None

    def update_mana(self):
        """Increate the mana base by 1 if less than 10, then refresh
        the mana to full (overload not implemented)."""
        side = self.get_side()
        if self.manaBase[side] < 10:
            self.manaBase[side] += 1
        self.manaCurrent[side] = self.manaBase[side]

    def increment_turn(self):
        """Increment the turn counter."""
        self.turnCount += 1

    def subtract_mana(self, amount, side=None):
        """Subtract mana from current side, unless side is specified."""
        if side is None:
            side = self.get_side()
        self.manaCurrent[side] -= amount
        if self.manaCurrent[side] < 0:
            raise Exception("Mana less than 0.")

    def add_mana(self, amount, side=None):
        """Subtract mana from current side, unless side is specified."""
        if side is None:
            side = self.get_side()
        if self.manaCurrent[side] >= 10:
            return
        else:
            self.manaCurrent[side] += amount

    def change_side(self):
        """Change the current playerTurn to the opposite side."""
        self.playerTurn = self.get_enemy_side()

    def reset_attacksRemaining(self):
        """Reset the remaining attacks for all characters on the current side."""
        side = self.get_side()
        for minion in self.minions[side]:
            if minion is None:
                continue
            minion.attacksRemaining = 1
            if 'windfury' in minion.status:
                minion.attacksRemaining += 1
        hero = self.heroes[side]
        hero.attacksRemaining = 1
        if 'windfury' in hero.status:
            hero.attacksRemaining += 1

    def summon_minion(self, minion, side=None, pos=None):
        """Place a minion on the board given the side and (optional) position. If position
        is not specified, place the minion in lowest available spot (not implemented yet).
        Positions range from 1-7.  Set attacksRemaining to 0, unless charge."""
        if side is None:
            side = self.get_side()
        minion.side = side
        minion.board = self
        idx = pos - 1
        if self.minions[side][idx] is not None:
            raise Exception("Not a free spot.")
        self.minions[side][idx] = minion
        if "charge" in minion.status:
            minion.attacksRemaining = 1
            if "windfury" in minion.status:
                minion.attacksRemaining += 1

    def destroy_minion(self, deadMinion):
        """Destroy the character specified from the field."""
        for side in ['top', 'bottom']:
            for i, minion in enumerate(self.minions[side]):
                if minion is deadMinion:
                    self.minions[side][i] = None
                    deadMinion.deathrattle()
                    del deadMinion
                    return
<|endoftext|>


<commit_before>from gaphas.matrix import Matrix
from gaphas.solver import NORMAL, Constraint, Variable

class Position:
    """A point constructed of two `Variable`'s.

    >>> vp = Position(3, 5)
    >>> vp.x, vp.y
    (Variable(3, 20), Variable(5, 20))
    >>> vp.pos
    (Variable(3, 20), Variable(5, 20))
    >>> vp[0], vp[1]
    (Variable(3, 20), Variable(5, 20))
    """

    def __init__(self, x, y, strength=NORMAL):
        self._x = Variable(x, strength)
        self._y = Variable(y, strength)

    def _set_x(self, v):
        self._x.value = v

    x = property(lambda s: s._x, _set_x)

    def _set_y(self, v):
        self._y.value = v

    y = property(lambda s: s._y, _set_y)

    strength = property(lambda s: s._x.strength)

    def _set_pos(self, pos):
        """Set handle position (Item coordinates)."""
        self._x.value, self._y.value = pos

    pos = property(lambda s: (s._x, s._y), _set_pos)

    def __str__(self):
        return f"<{self.__class__.__name__} object on ({self._x}, {self._y})>"

    __repr__ = __str__

    def __getitem__(self, index):
        """Shorthand for returning the x(0) or y(1) component of the point.

        >>> h = Position(3, 5)
        >>> h[0]
        Variable(3, 20)
        >>> h[1]
        Variable(5, 20)
        """
        return (self._x, self._y)[index]

    def __iter__(self):
        return iter((self._x, self._y))

    def __eq__(self, other):
        return isinstance(other, Position) and self.x == other.x and self.y == other.y

class MatrixProjection(Constraint):
    def __init__(self, pos: Position, matrix: Matrix):
        proj_pos = Position(0, 0, pos.strength)
        super().__init__(proj_pos.x, proj_pos.y, pos.x, pos.y)

        self._orig_pos = pos
        self._proj_pos = proj_pos
        self.matrix = matrix
        self.solve_for(self._proj_pos.x)

    def add_handler(self, handler):
        if not self._handlers:
            self.matrix.add_handler(self._on_matrix_changed)
        super().add_handler(handler)

    def remove_handler(self, handler):
        super().remove_handler(handler)
        if not self._handlers:
            self.matrix.remove_handler(self._on_matrix_changed)

    def _set_x(self, x):
        self._proj_pos.x = x

    def _set_y(self, y):
        self._proj_pos.y = y

    pos = property(lambda s: s._proj_pos)
    x = property(lambda s: s._proj_pos.x, _set_x)
    y = property(lambda s: s._proj_pos.y, _set_y)

    def mark_dirty(self, var):
        if var is self._orig_pos.x or var is self._orig_pos.y:
            super().mark_dirty(self._orig_pos.x)
            super().mark_dirty(self._orig_pos.y)
        else:
            super().mark_dirty(self._proj_pos.x)
            super().mark_dirty(self._proj_pos.y)

    def solve_for(self, var):
        if var is self._orig_pos.x or var is self._orig_pos.y:
            self._orig_pos.x, self._orig_pos.y = self.matrix.inverse().transform_point(*self._proj_pos)  # type: ignore[misc]
        else:
            self._proj_pos.x, self._proj_pos.y = self.matrix.transform_point(*self._orig_pos)  # type: ignore[misc]

    def _on_matrix_changed(self, matrix):
        self.mark_dirty(self._orig_pos.x)
        self.notify()

    def __getitem__(self, index):
        return self._proj_pos[index]
<commit_msg>Remove type ignore comments for MatrixProjection<commit_after>from gaphas.matrix import Matrix
from gaphas.solver import NORMAL, Constraint, Variable

class Position:
    """A point constructed of two `Variable`'s.

    >>> vp = Position(3, 5)
    >>> vp.x, vp.y
    (Variable(3, 20), Variable(5, 20))
    >>> vp.pos
    (Variable(3, 20), Variable(5, 20))
    >>> vp[0], vp[1]
    (Variable(3, 20), Variable(5, 20))
    """

    def __init__(self, x, y, strength=NORMAL):
        self._x = Variable(x, strength)
        self._y = Variable(y, strength)

    def _set_x(self, v):
        self._x.value = v

    x = property(lambda s: s._x, _set_x)

    def _set_y(self, v):
        self._y.value = v

    y = property(lambda s: s._y, _set_y)

    strength = property(lambda s: s._x.strength)

    def _set_pos(self, pos):
        """Set handle position (Item coordinates)."""
        self._x.value, self._y.value = pos

    pos = property(lambda s: (s._x, s._y), _set_pos)

    def __str__(self):
        return f"<{self.__class__.__name__} object on ({self._x}, {self._y})>"

    __repr__ = __str__

    def __getitem__(self, index):
        """Shorthand for returning the x(0) or y(1) component of the point.

        >>> h = Position(3, 5)
        >>> h[0]
        Variable(3, 20)
        >>> h[1]
        Variable(5, 20)
        """
        return (self._x, self._y)[index]

    def __iter__(self):
        return iter((self._x, self._y))

    def __eq__(self, other):
        return isinstance(other, Position) and self.x == other.x and self.y == other.y

class MatrixProjection(Constraint):
    def __init__(self, pos: Position, matrix: Matrix):
        proj_pos = Position(0, 0, pos.strength)
        super().__init__(proj_pos.x, proj_pos.y, pos.x, pos.y)

        self._orig_pos = pos
        self._proj_pos = proj_pos
        self.matrix = matrix
        self.solve_for(self._proj_pos.x)

    def add_handler(self, handler):
        if not self._handlers:
            self.matrix.add_handler(self._on_matrix_changed)
        super().add_handler(handler)

    def remove_handler(self, handler):
        super().remove_handler(handler)
        if not self._handlers:
            self.matrix.remove_handler(self._on_matrix_changed)

    def _set_x(self, x):
        self._proj_pos.x = x

    def _set_y(self, y):
        self._proj_pos.y = y

    pos = property(lambda s: s._proj_pos)
    x = property(lambda s: s._proj_pos.x, _set_x)
    y = property(lambda s: s._proj_pos.y, _set_y)

    def mark_dirty(self, var):
        if var is self._orig_pos.x or var is self._orig_pos.y:
            super().mark_dirty(self._orig_pos.x)
            super().mark_dirty(self._orig_pos.y)
        else:
            super().mark_dirty(self._proj_pos.x)
            super().mark_dirty(self._proj_pos.y)

    def solve_for(self, var):
        if var is self._orig_pos.x or var is self._orig_pos.y:
            self._orig_pos.x, self._orig_pos.y = self.matrix.inverse().transform_point(
                *self._proj_pos
            )
        else:
            self._proj_pos.x, self._proj_pos.y = self.matrix.transform_point(
                *self._orig_pos
            )

    def _on_matrix_changed(self, matrix):
        self.mark_dirty(self._orig_pos.x)
        self.notify()

    def __getitem__(self, index):
        return self._proj_pos[index]
<|endoftext|>


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

"""This is Gaphor, a Python+GTK based UML modelling tool.

This module allows Gaphor to be launched from the command line.
The main() function sets up the command-line options and arguments and
passes them to the main Application instance."""

__all__ = [ 'main' ]

from optparse import OptionParser
import pygtk

from gaphor.misc.logger import Logger
from gaphor.application import Application

pygtk.require('2.0')

def launch(model=None):
    """Start the main application by initiating and running Application.

    The file_manager service is used here to load a Gaphor model if one was
    specified on the command line.  Otherwise, a new model is created and
    the Gaphor GUI is started."""

    # Make sure gui is loaded ASAP.
    # This prevents menu items from appearing at unwanted places.
    Application.essential_services.append('main_window')

    Application.init()

    main_window = Application.get_service('main_window')

    main_window.open()

    file_manager = Application.get_service('file_manager')

    if model:
        file_manager.load(model)
    else:
        file_manager.action_new()

    Application.run()

def main():
    """Start Gaphor from the command line.  This function creates an option
    parser for retrieving arguments and options from the command line.  This
    includes a Gaphor model to load.

    The application is then initialized, passing along the option parser.  This
    provides and plugins and services with access to the command line options
    and may add their own."""

    parser = OptionParser()

    parser.add_option('-p',\
                      '--profile',\
                      action='store_true',\
                      help='Run in profile')

    parser.add_option('-l',\
                      '--logging',\
                      default='INFO',\
                      help='Logging level')

    options, args = parser.parse_args()

    Logger.log_level = Logger.level_map[options.logging]

    try:
        model = args[0]
    except IndexError:
        model = None

    if options.profile:

        import cProfile
        import pstats

        cProfile.run('import gaphor; gaphor.launch()',\
                     'gaphor.prof')

        profile_stats = pstats.Stats('gaphor.prof')
        profile_stats.strip_dirs().sort_stats('time').print_stats(50)

    else:

        launch(model)

# TODO: Remove this.
import __builtin__

__builtin__.__dict__['log'] = Logger()

# vim:sw=4:et:ai
<commit_msg>Fixed model arg<commit_after>#!/usr/bin/env python

"""This is Gaphor, a Python+GTK based UML modelling tool.

This module allows Gaphor to be launched from the command line.
The main() function sets up the command-line options and arguments and
passes them to the main Application instance."""

__all__ = [ 'main' ]

from optparse import OptionParser
import pygtk

from gaphor.misc.logger import Logger
from gaphor.application import Application

pygtk.require('2.0')

def launch(model=None):
    """Start the main application by initiating and running Application.

    The file_manager service is used here to load a Gaphor model if one was
    specified on the command line.  Otherwise, a new model is created and
    the Gaphor GUI is started."""

    # Make sure gui is loaded ASAP.
    # This prevents menu items from appearing at unwanted places.
    Application.essential_services.append('main_window')

    Application.init()

    main_window = Application.get_service('main_window')

    main_window.open()

    file_manager = Application.get_service('file_manager')

    if model:
        file_manager.load(model)
    else:
        file_manager.action_new()

    Application.run()

def main():
    """Start Gaphor from the command line.  This function creates an option
    parser for retrieving arguments and options from the command line.  This
    includes a Gaphor model to load.

    The application is then initialized, passing along the option parser.  This
    provides and plugins and services with access to the command line options
    and may add their own."""

    parser = OptionParser()

    parser.add_option('-p',\
                      '--profile',\
                      action='store_true',\
                      help='Run in profile')

    parser.add_option('-l',\
                      '--logging',\
                      default='INFO',\
                      help='Logging level')

    options, args = parser.parse_args()

    Logger.log_level = Logger.level_map[options.logging]

    try:
        model = args[1]
    except IndexError:
        model = None

    if options.profile:

        import cProfile
        import pstats

        cProfile.run('import gaphor; gaphor.launch()',\
                     'gaphor.prof')

        profile_stats = pstats.Stats('gaphor.prof')
        profile_stats.strip_dirs().sort_stats('time').print_stats(50)

    else:

        launch(model)

# TODO: Remove this.
import __builtin__

__builtin__.__dict__['log'] = Logger()

# vim:sw=4:et:ai
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
'''
    :codeauthor: :email:`Mike Place <mp@saltstack.com`

    Tests to ensure that the file permissions are set correctly when
    importing from the git repo.
'''

# Import python libs
import os
import stat

# Import salt testing libs
from salttesting import TestCase
from salttesting.helpers import ensure_in_syspath

ensure_in_syspath('..')

from integration import CODE_DIR

EXEMPT_FILES = ['setup.py',
                'runtests.py',
                'saltsh.py',
                'PKGBUILD-git',
                'Makefile',
                'PKGBUILD',
                'salt-minion',
                'build.py',
                'salt-syncic',
                'salt-master',
                'install.sh',
                'salt-minion',
                'salt-call',
                'salt-cp',
                'salt-ssh',
                'salt-key',
                'salt-cloud',
                'salt-run',
                'salt-syndic',
                'salt',
                'rules',
                'pre-applypatch.sample',
                'pre-commit.sample',
                'commit-msg.sample',
                'pre-push.sample',
                'update.sample',
                'pre-rebase.sample',
                'post-update.sample',
                'prepare-commit-msg.sample',
                'applypatch-msg.sample',
                'master.py',
                'ssh-id-wrapper',
                'build_shar.sh']

EXEMPT_DIRS = ['tests', '.git', 'doc']

class GitPermTestCase(TestCase):
    def test_perms(self):
        suspect_files = []
        for root, dirs, files in os.walk(CODE_DIR, topdown=True):
            dirs[:] = [dir for dir in dirs if dir not in EXEMPT_DIRS]
            for fn_ in files:
                fn_path = os.path.join(root, fn_)
                fn_mode = stat.S_IMODE(os.stat(fn_path).st_mode)  # In octal! 420 == 0644
                if fn_mode != 420 and fn_ not in EXEMPT_FILES:
                    suspect_files.append(fn_)

        self.assertEqual(suspect_files, [], 'Found file(s) with incorrect permissions: {0}'.format(suspect_files))

if __name__ == '__main__':
    from integration import run_tests
    run_tests(GitPermTestCase, needs_daemon=False)
<commit_msg>Improve permissions check testcase.<commit_after># -*- coding: utf-8 -*-
'''
    :codeauthor: :email:`Mike Place <mp@saltstack.com`

    Tests to ensure that the file permissions are set correctly when
    importing from the git repo.
'''

# Import python libs
import os
import stat
import pprint

# Import salt testing libs
from salttesting import TestCase
from salttesting.helpers import ensure_in_syspath

ensure_in_syspath('..')

from integration import CODE_DIR

EXEMPT_DIRS = []
EXEMPT_FILES = [
    'debian/rules',
    'doc/.scripts/compile-translation-catalogs',
    'doc/.scripts/download-translation-catalog',
    'doc/.scripts/setup-transifex-config',
    'doc/.scripts/update-transifex-source-translations',
    'pkg/arch/Makefile',
    'pkg/arch/PKGBUILD',
    'pkg/arch/PKGBUILD-git',
    'pkg/arch/PKGBUILD-local',
    'pkg/arch/git/PKGBUILD',
    'pkg/rpm/salt-master',
    'pkg/rpm/salt-minion',
    'pkg/rpm/salt-syndic',
    'pkg/smartos/esky/install.sh',
    'salt/templates/git/ssh-id-wrapper',
    'scripts/salt',
    'scripts/salt-call',
    'scripts/salt-cloud',
    'scripts/salt-cp',
    'scripts/salt-key',
    'scripts/salt-master',
    'scripts/salt-minion',
    'scripts/salt-run',
    'scripts/salt-ssh',
    'scripts/salt-syndic',
    'setup.py',
    'tests/integration/mockbin/su',
    'tests/runtests.py',
    'tests/saltsh.py'
]

IGNORE_PATHS = [
    '.git',
    '.wti',
    'build',
    'dist',
    'salt.egg-info',
    '.ropeproject',
]

class GitPermTestCase(TestCase):
    def test_perms(self):
        suspect_entries = []
        for root, dirnames, filenames in os.walk(CODE_DIR, topdown=True):
            for dirname in dirnames:
                entry = os.path.relpath(
                    os.path.join(root, dirname), CODE_DIR
                )
                if entry in IGNORE_PATHS:
                    continue

                skip_entry = False
                for ignore_path in IGNORE_PATHS:
                    if entry.startswith(ignore_path):
                        skip_entry = True
                        break

                if skip_entry:
                    continue

                fn_mode = stat.S_IMODE(os.stat(entry).st_mode)
                if fn_mode != 493 and entry not in EXEMPT_DIRS:  # In octal! 493 == 0755
                    suspect_entries.append(entry)

            for filename in filenames:
                entry = os.path.relpath(
                    os.path.join(root, filename), CODE_DIR
                )
                if entry in IGNORE_PATHS:
                    continue

                skip_entry = False
                for ignore_path in IGNORE_PATHS:
                    if entry.startswith(ignore_path):
                        skip_entry = True
                        break

                if skip_entry:
                    continue

                fn_mode = stat.S_IMODE(os.stat(entry).st_mode)
                if fn_mode != 420 and entry not in EXEMPT_FILES:  # In octal! 420 == 0644
                    suspect_entries.append(entry)

        try:
            self.assertEqual(suspect_entries, [])
        except AssertionError:
            self.fail(
                'Found file(s) with incorrect permissions:\n{0}'.format(
                    pprint.pformat(sorted(suspect_entries))
                )
            )

if __name__ == '__main__':
    from integration import run_tests
    run_tests(GitPermTestCase, needs_daemon=False)
<|endoftext|>


<commit_before># -*- encoding: utf-8 -*-

from __future__ import unicode_literals

import sys
import io
import time
import json

import socket
import smtplib

from email.utils import formatdate
from email.header import Header
from email.mime.text import MIMEText

import logging
logger = logging.getLogger("isso")

try:
    import uwsgi
except ImportError:
    uwsgi = None

from isso.compat import PY2K
from isso import local

if PY2K:
    from thread import start_new_thread
else:
    from _thread import start_new_thread

class SMTP(object):

    def __init__(self, isso):

        self.isso = isso
        self.conf = isso.conf.section("smtp")

        # test SMTP connectivity
        try:
            with self:
                logger.info("connected to SMTP server")
        except (socket.error, smtplib.SMTPException):
            logger.exception("unable to connect to SMTP server")

        if uwsgi:
            def spooler(args):
                try:
                    self._sendmail(args[b"subject"].decode("utf-8"),
                                   args["body"].decode("utf-8"))
                except smtplib.SMTPConnectError:
                    return uwsgi.SPOOL_RETRY
                else:
                    return uwsgi.SPOOL_OK

            uwsgi.spooler = spooler

    def __enter__(self):
        klass = (smtplib.SMTP_SSL if self.conf.get('security') == 'ssl' else smtplib.SMTP)
        self.client = klass(host=self.conf.get('host'),
                            port=self.conf.getint('port'),
                            timeout=self.conf.getint('timeout'))

        if self.conf.get('security') == 'starttls':
            if sys.version_info >= (3, 4):
                import ssl
                self.client.starttls(context=ssl.create_default_context())
            else:
                self.client.starttls()

        if self.conf.get('username') and self.conf.get('password'):
            self.client.login(self.conf.get('username').encode('ascii', errors='ignore'),
                              self.conf.get('password').encode('ascii', errors='ignore'))

        return self.client

    def __exit__(self, exc_type, exc_value, traceback):
        self.client.quit()

    def __iter__(self):
        yield "comments.new:after-save", self.notify

    def format(self, thread, comment):

        rv = io.StringIO()

        author = comment["author"] or "Anonymous"
        if comment["email"]:
            author += " <%s>" % comment["email"]

        rv.write(author + " wrote:\n")
        rv.write("\n")
        rv.write(comment["text"] + "\n")
        rv.write("\n")

        if comment["website"]:
            rv.write("User's URL: %s\n" % comment["website"])

        rv.write("IP address: %s\n" % comment["remote_addr"])
        rv.write("Link to comment: %s\n" % (local("origin") + thread["uri"] + "#isso-%i" % comment["id"]))
        rv.write("\n")

        uri = local("host") + "/id/%i" % comment["id"]
        key = self.isso.sign(comment["id"])

        rv.write("---\n")
        rv.write("Delete comment: %s\n" % (uri + "/delete/" + key))

        if comment["mode"] == 2:
            rv.write("Activate comment: %s\n" % (uri + "/activate/" + key))

        rv.seek(0)
        return rv.read()

    def notify(self, thread, comment):

        body = self.format(thread, comment)

        if uwsgi:
            uwsgi.spool({b"subject": thread["title"].encode("utf-8"),
                         b"body": body.encode("utf-8")})
        else:
            start_new_thread(self._retry, (thread["title"], body))

    def _sendmail(self, subject, body):

        from_addr = self.conf.get("from")
        to_addr = self.conf.get("to")

        msg = MIMEText(body, 'plain', 'utf-8')
        msg['From'] = from_addr
        msg['To'] = to_addr
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = Header(subject, 'utf-8')

        with self as con:
            con.sendmail(from_addr, to_addr, msg.as_string())

    def _retry(self, subject, body):
        for x in range(5):
            try:
                self._sendmail(subject, body)
            except smtplib.SMTPConnectError:
                time.sleep(60)
            else:
                break

class Stdout(object):

    def __init__(self, conf):
        pass

    def __iter__(self):

        yield "comments.new:new-thread", self._new_thread
        yield "comments.new:finish", self._new_comment
        yield "comments.edit", self._edit_comment
        yield "comments.delete", self._delete_comment
        yield "comments.activate", self._activate_comment

    def _new_thread(self, thread):
        logger.info("new thread %(id)s: %(title)s" % thread)

    def _new_comment(self, thread, comment):
        logger.info("comment created: %s", json.dumps(comment))

    def _edit_comment(self, comment):
        logger.info('comment %i edited: %s', comment["id"], json.dumps(comment))

    def _delete_comment(self, id):
        logger.info('comment %i deleted', id)

    def _activate_comment(self, id):
        logger.info("comment %s activated" % id)
<commit_msg>use system's CA certificates for Python 2.7.9 or higher to verify TLS connection<commit_after># -*- encoding: utf-8 -*-

from __future__ import unicode_literals

import sys
import io
import time
import json

import socket
import smtplib

from email.utils import formatdate
from email.header import Header
from email.mime.text import MIMEText

import logging
logger = logging.getLogger("isso")

try:
    import uwsgi
except ImportError:
    uwsgi = None

from isso.compat import PY2K
from isso import local

if PY2K:
    from thread import start_new_thread
else:
    from _thread import start_new_thread

class SMTP(object):

    def __init__(self, isso):

        self.isso = isso
        self.conf = isso.conf.section("smtp")

        # test SMTP connectivity
        try:
            with self:
                logger.info("connected to SMTP server")
        except (socket.error, smtplib.SMTPException):
            logger.exception("unable to connect to SMTP server")

        if uwsgi:
            def spooler(args):
                try:
                    self._sendmail(args[b"subject"].decode("utf-8"),
                                   args["body"].decode("utf-8"))
                except smtplib.SMTPConnectError:
                    return uwsgi.SPOOL_RETRY
                else:
                    return uwsgi.SPOOL_OK

            uwsgi.spooler = spooler

    def __enter__(self):
        klass = (smtplib.SMTP_SSL if self.conf.get('security') == 'ssl' else smtplib.SMTP)
        self.client = klass(host=self.conf.get('host'),
                            port=self.conf.getint('port'),
                            timeout=self.conf.getint('timeout'))

        if self.conf.get('security') == 'starttls':
            if sys.version_info >= (3, 4) or (2, 7, 9) <= sys.version_info <= (3, 0):
                import ssl
                self.client.starttls(context=ssl.create_default_context())
            else:
                self.client.starttls()

        if self.conf.get('username') and self.conf.get('password'):
            self.client.login(self.conf.get('username').encode('ascii', errors='ignore'),
                              self.conf.get('password').encode('ascii', errors='ignore'))

        return self.client

    def __exit__(self, exc_type, exc_value, traceback):
        self.client.quit()

    def __iter__(self):
        yield "comments.new:after-save", self.notify

    def format(self, thread, comment):

        rv = io.StringIO()

        author = comment["author"] or "Anonymous"
        if comment["email"]:
            author += " <%s>" % comment["email"]

        rv.write(author + " wrote:\n")
        rv.write("\n")
        rv.write(comment["text"] + "\n")
        rv.write("\n")

        if comment["website"]:
            rv.write("User's URL: %s\n" % comment["website"])

        rv.write("IP address: %s\n" % comment["remote_addr"])
        rv.write("Link to comment: %s\n" % (local("origin") + thread["uri"] + "#isso-%i" % comment["id"]))
        rv.write("\n")

        uri = local("host") + "/id/%i" % comment["id"]
        key = self.isso.sign(comment["id"])

        rv.write("---\n")
        rv.write("Delete comment: %s\n" % (uri + "/delete/" + key))

        if comment["mode"] == 2:
            rv.write("Activate comment: %s\n" % (uri + "/activate/" + key))

        rv.seek(0)
        return rv.read()

    def notify(self, thread, comment):

        body = self.format(thread, comment)

        if uwsgi:
            uwsgi.spool({b"subject": thread["title"].encode("utf-8"),
                         b"body": body.encode("utf-8")})
        else:
            start_new_thread(self._retry, (thread["title"], body))

    def _sendmail(self, subject, body):

        from_addr = self.conf.get("from")
        to_addr = self.conf.get("to")

        msg = MIMEText(body, 'plain', 'utf-8')
        msg['From'] = from_addr
        msg['To'] = to_addr
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = Header(subject, 'utf-8')

        with self as con:
            con.sendmail(from_addr, to_addr, msg.as_string())

    def _retry(self, subject, body):
        for x in range(5):
            try:
                self._sendmail(subject, body)
            except smtplib.SMTPConnectError:
                time.sleep(60)
            else:
                break

class Stdout(object):

    def __init__(self, conf):
        pass

    def __iter__(self):

        yield "comments.new:new-thread", self._new_thread
        yield "comments.new:finish", self._new_comment
        yield "comments.edit", self._edit_comment
        yield "comments.delete", self._delete_comment
        yield "comments.activate", self._activate_comment

    def _new_thread(self, thread):
        logger.info("new thread %(id)s: %(title)s" % thread)

    def _new_comment(self, thread, comment):
        logger.info("comment created: %s", json.dumps(comment))

    def _edit_comment(self, comment):
        logger.info('comment %i edited: %s', comment["id"], json.dumps(comment))

    def _delete_comment(self, id):
        logger.info('comment %i deleted', id)

    def _activate_comment(self, id):
        logger.info("comment %s activated" % id)
<|endoftext|>


<commit_before>"""
Tests for the game class
"""

import unittest
import nash
import numpy as np

class TestGame(unittest.TestCase):
    """
    Tests for the game class
    """
    def test_bi_matrix_init(self):
        """Test that can create a bi matrix game"""
        A = np.array([[1, 2], [2, 1]])
        B = np.array([[2, 1], [1, 2]])
        g = nash.Game(A, B)
        self.assertEqual(g.payoff_matrices, (A, B))
        self.assertFalse(g.zero_sum)

    def test_zero_sum_game_init(self):
        """Test that can create a zero sum game"""
        A = np.array([[1, 2], [2, 1]])
        g = nash.Game(A)
        self.assertTrue(np.array_equal(g.payoff_matrices[0], A))
        self.assertTrue(np.array_equal(g.payoff_matrices[0],
                                       -g.payoff_matrices[1]))
        self.assertTrue(g.zero_sum)

    def test_zero_sum_property_from_bi_matrix(self):
        """Test that can create a zero sum game"""
        A = np.array([[1, 2], [2, 1]])
        B = -A
        g = nash.Game(A, B)
        self.assertTrue(g.zero_sum)

    def test_obtain_equilibria_for_bi_matrix(self):
        """Test for the equilibria calculation"""
        A = np.array([[160, 205, 44],
                      [175, 180, 45],
                      [201, 204, 50],
                      [120, 207, 49]])
        B = np.array([[2, 2, 2],
                      [1, 0, 0],
                      [3, 4, 1],
                      [4, 1, 2]])
        g = nash.Game(A, B)
        self.assertTrue(g.obtain_equilibria(),
                        [[(0, 0, 3/4, 1/4), (1/28, 27/28, 0)]])

        A = np.array([[1, 0], [-2, 3]])
        B = np.array([[3, 2], [-1, 0]])
        g = nash.Game(A, B)
        self.assertTrue(g.obtain_equilibria(), [[(0, 1), (0, 1)],
                                                [(1/2, 1/2), (1/2, 1/2)],
                                                [(1, 0), (1, 0)]])
<commit_msg>Add test for potential supports<commit_after>"""
Tests for the game class
"""

import unittest
import nash
import numpy as np

class TestGame(unittest.TestCase):
    """
    Tests for the game class
    """
    def test_bi_matrix_init(self):
        """Test that can create a bi matrix game"""
        A = np.array([[1, 2], [2, 1]])
        B = np.array([[2, 1], [1, 2]])
        g = nash.Game(A, B)
        self.assertEqual(g.payoff_matrices, (A, B))
        self.assertFalse(g.zero_sum)

    def test_zero_sum_game_init(self):
        """Test that can create a zero sum game"""
        A = np.array([[1, 2], [2, 1]])
        g = nash.Game(A)
        self.assertTrue(np.array_equal(g.payoff_matrices[0], A))
        self.assertTrue(np.array_equal(g.payoff_matrices[0],
                                       -g.payoff_matrices[1]))
        self.assertTrue(g.zero_sum)

    def test_zero_sum_property_from_bi_matrix(self):
        """Test that can create a zero sum game"""
        A = np.array([[1, 2], [2, 1]])
        B = -A
        g = nash.Game(A, B)
        self.assertTrue(g.zero_sum)

    def test_obtain_equilibria_for_bi_matrix(self):
        """Test for the equilibria calculation"""
        A = np.array([[160, 205, 44],
                      [175, 180, 45],
                      [201, 204, 50],
                      [120, 207, 49]])
        B = np.array([[2, 2, 2],
                      [1, 0, 0],
                      [3, 4, 1],
                      [4, 1, 2]])
        g = nash.Game(A, B)
        self.assertTrue(g.obtain_equilibria(),
                        [[(0, 0, 3/4, 1/4), (1/28, 27/28, 0)]])

        A = np.array([[1, 0], [-2, 3]])
        B = np.array([[3, 2], [-1, 0]])
        g = nash.Game(A, B)
        self.assertTrue(g.obtain_equilibria(), [[(0, 1), (0, 1)],
                                                [(1/2, 1/2), (1/2, 1/2)],
                                                [(1, 0), (1, 0)]])

    def test_potential_supports(self):
        """Test for the enumeration of potential supports"""
        A = np.array([[1, 0], [-2, 3]])
        B = np.array([[3, 2], [-1, 0]])
        g = nash.Game(A, B)
        self.assertTrue(g.potential_support_pairs(), [[(0,), (0,)],
                                                      [(0,), (1,)],
                                                      [(1,), (0,)],
                                                      [(1,), (1,)],
                                                      [(0, 1), (0, 1)]])
<|endoftext|>


<commit_before># Django settings for issue_tracker project.
import os

DEBUG = True
TEMPLATE_DEBUG = DEBUG

SITE_ROOT = os.path.realpath(os.path.dirname(__file__))

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

MANAGERS = ADMINS

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

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

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

SITE_ID = 1

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

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

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

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

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

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

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

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

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

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'g-4*2@39a&4rf-r%a8ma77-k(=&hz7l0*%2!43ics15$11bcgi'

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

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'issue_tracker.urls'

TEMPLATE_DIRS = (
    os.path.join(SITE_ROOT, 'templates'),
)

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

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}
<commit_msg>Added settings for the database.<commit_after># Django settings for issue_tracker project.
import os

DEBUG = True
TEMPLATE_DEBUG = DEBUG

SITE_ROOT = os.path.realpath(os.path.dirname(__file__))

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

MANAGERS = ADMINS

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

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

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

SITE_ID = 1

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

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

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

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

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

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

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

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

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

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'g-4*2@39a&4rf-r%a8ma77-k(=&hz7l0*%2!43ics15$11bcgi'

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

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'issue_tracker.urls'

TEMPLATE_DIRS = (
    os.path.join(SITE_ROOT, 'templates'),
)

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

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


<commit_before># -*- coding: utf-8 -*-

"""CLI scripts."""

#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------

import argparse
import os
import os.path as op
import glob
import json

from ..ext.six import string_types
from .format_manager import convert, format_manager

#------------------------------------------------------------------------------
# Utility functions
#------------------------------------------------------------------------------

def _flatten(l):
    return [item for sublist in l for item in sublist]

def _ensure_list(l):
    if isinstance(l, string_types):
        return [l]
    elif isinstance(l, list):
        return l
    else:
        raise RuntimeError("This should be a string or a list: "
                           "{0:s}.".format(str(l)))

def _to_skip(dirname):
    out = op.basename(dirname).startswith(('.', '_', '/'))
    return out

def _expand_dirs_to_files(files_or_dirs, recursive=False):
    files = []
    files_or_dirs = _ensure_list(files_or_dirs)
    for file_or_dir in files_or_dirs:
        file_or_dir = op.realpath(file_or_dir)
        if op.isdir(file_or_dir):
            # Skip dirnames starting with '.'
            if _to_skip(file_or_dir):
                continue
            # Recursively visit the directories and add the files.
            if recursive:
                files.extend(_expand_dirs_to_files([op.join(file_or_dir, file)
                             for file in os.listdir(file_or_dir)],
                             recursive=recursive))
            else:
                files.extend([op.join(file_or_dir, file)
                              for file in os.listdir(file_or_dir)])
        elif '*' in file_or_dir:
            files.extend(glob.glob(file_or_dir))
        else:
            files.append(file_or_dir)
    return files

def _common_root(files):
    files = [op.realpath(file) for file in files]
    root = op.commonprefix(files)
    if not op.exists(root):
        root = op.dirname(root)
    if root:
        assert op.exists(root)
        assert op.isdir(root), root
    return root

def _construct_tree(path):
    if not op.exists(path):
        try:
            os.makedirs(op.dirname(path))
        except FileExistsError:
            pass

def _file_has_extension(file, extensions):
    if not isinstance(extensions, list):
        extensions = [extensions]
    return any(file.endswith(extension) for extension in extensions)

def _filter_files_by_extension(files, extensions):
    return [file for file in files if _file_has_extension(file, extensions)]

def _load_file(file, from_):
    return format_manager().load(file, name=from_)

def _save_file(file, to, contents, overwrite=False):
    format_manager().save(file, contents, name=to, overwrite=overwrite)

#------------------------------------------------------------------------------
# Conversion functions
#------------------------------------------------------------------------------

def _converted_filename(file, from_, to):
    base, from_extension = op.splitext(file)
    to_extension = format_manager().file_extension(to)
    return ''.join((base, to_extension))

def convert_files(files_or_dirs,
                  overwrite=None,
                  from_=None,
                  to=None,
                  from_kwargs=None,
                  to_kwargs=None,
                  output_folder=None,
                  recursive=False,
                  simulate=False,
                  ):
    # Find all files.
    files = _expand_dirs_to_files(files_or_dirs, recursive=recursive)

    # Filter by from extension.
    from_extension = format_manager().file_extension(from_)
    files = _filter_files_by_extension(files, from_extension)

    # Get the common root of all files.
    if output_folder:
        output_folder = op.realpath(output_folder)
        root = _common_root(files)

    # Convert all files.
    for file in files:
        print("Converting {0:s}...".format(file))
        converted = convert(file, from_, to,
                            from_kwargs=from_kwargs, to_kwargs=to_kwargs)
        file_to = _converted_filename(file, from_, to)

        # Compute the output path.
        if output_folder:
            # Path relative to the common root.
            rel_file = op.relpath(file_to, root)
            # Reconstruct the internal folder structure within the output
            # folder.
            file_to = op.join(output_folder, rel_file)
            # Create the subfolders if necessary.
            _construct_tree(file_to)

        if not simulate:
            _save_file(file_to, to, converted, overwrite=overwrite)

def main():
    desc = 'Convert files across formats supported by ipymd.'
    parser = argparse.ArgumentParser(description=desc)

    parser.add_argument('files_or_dirs', nargs='+',
                        help=('list of files or directories to convert'))

    formats = ', '.join(format_manager().formats)
    parser.add_argument('--from', dest='from_', required=True,
                        help='one of {0:s}'.format(formats))

    parser.add_argument('--to', dest='to', required=True,
                        help='one of {0:s}'.format(formats))

    parser.add_argument('--overwrite', dest='overwrite', action='store_true',
                        help=('overwrite target file if it exists '
                              '(false by default)'))

    # Parse the CLI arguments.
    args = parser.parse_args()
    convert_files(args.files_or_dirs,
                  overwrite=args.overwrite,
                  from_=args.from_,
                  to=args.to,
                  )

if __name__ == '__main__':
    main()
<commit_msg>Improved conversion script.<commit_after># -*- coding: utf-8 -*-
from __future__ import print_function

"""CLI scripts."""

#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------

import argparse
import os
import os.path as op
import glob
import json

from ..ext.six import string_types
from .format_manager import convert, format_manager

#------------------------------------------------------------------------------
# Utility functions
#------------------------------------------------------------------------------

def _flatten(l):
    return [item for sublist in l for item in sublist]

def _ensure_list(l):
    if isinstance(l, string_types):
        return [l]
    elif isinstance(l, list):
        return l
    else:
        raise RuntimeError("This should be a string or a list: "
                           "{0:s}.".format(str(l)))

def _to_skip(dirname):
    out = op.basename(dirname).startswith(('.', '_', '/'))
    return out

def _expand_dirs_to_files(files_or_dirs, recursive=False):
    files = []
    files_or_dirs = _ensure_list(files_or_dirs)
    for file_or_dir in files_or_dirs:
        file_or_dir = op.realpath(file_or_dir)
        if op.isdir(file_or_dir):
            # Skip dirnames starting with '.'
            if _to_skip(file_or_dir):
                continue
            # Recursively visit the directories and add the files.
            if recursive:
                files.extend(_expand_dirs_to_files([op.join(file_or_dir, file)
                             for file in os.listdir(file_or_dir)],
                             recursive=recursive))
            else:
                files.extend([op.join(file_or_dir, file)
                              for file in os.listdir(file_or_dir)])
        elif '*' in file_or_dir:
            files.extend(glob.glob(file_or_dir))
        else:
            files.append(file_or_dir)
    return files

def _common_root(files):
    files = [op.realpath(file) for file in files]
    root = op.commonprefix(files)
    if not op.exists(root):
        root = op.dirname(root)
    if root:
        assert op.exists(root)
        assert op.isdir(root), root
    return root

def _construct_tree(path):
    if not op.exists(path):
        try:
            os.makedirs(op.dirname(path))
        except FileExistsError:
            pass

def _file_has_extension(file, extensions):
    if not isinstance(extensions, list):
        extensions = [extensions]
    return any(file.endswith(extension) for extension in extensions)

def _filter_files_by_extension(files, extensions):
    return [file for file in files if _file_has_extension(file, extensions)]

def _load_file(file, from_):
    return format_manager().load(file, name=from_)

def _save_file(file, to, contents, overwrite=False):
    format_manager().save(file, contents, name=to, overwrite=overwrite)

#------------------------------------------------------------------------------
# Conversion functions
#------------------------------------------------------------------------------

def _converted_filename(file, from_, to):
    base, from_extension = op.splitext(file)
    to_extension = format_manager().file_extension(to)
    return ''.join((base, to_extension))

def convert_files(files_or_dirs,
                  overwrite=None,
                  from_=None,
                  to=None,
                  from_kwargs=None,
                  to_kwargs=None,
                  output_folder=None,
                  recursive=False,
                  simulate=False,
                  ):
    # Find all files.
    files = _expand_dirs_to_files(files_or_dirs, recursive=recursive)

    # Filter by from extension.
    from_extension = format_manager().file_extension(from_)
    files = _filter_files_by_extension(files, from_extension)

    # Get the common root of all files.
    if output_folder:
        output_folder = op.realpath(output_folder)
        root = _common_root(files)

    # Convert all files.
    for file in files:
        print("Converting {0:s}...".format(file), end=' ')
        converted = convert(file, from_, to,
                            from_kwargs=from_kwargs, to_kwargs=to_kwargs)
        file_to = _converted_filename(file, from_, to)
        print("done.")

        # Compute the output path.
        if output_folder:
            # Path relative to the common root.
            rel_file = op.relpath(file_to, root)
            # Reconstruct the internal folder structure within the output
            # folder.
            file_to = op.join(output_folder, rel_file)
            # Create the subfolders if necessary.
            _construct_tree(file_to)

        print(" Saving to {0:s}...".format(file_to), end=' ')
        if simulate:
            print("skipped (simulation).")
        else:
            _save_file(file_to, to, converted, overwrite=overwrite)
            print('done.')

def main():
    desc = 'Convert files across formats supported by ipymd.'
    parser = argparse.ArgumentParser(description=desc)

    parser.add_argument('files_or_dirs', nargs='+',
                        help=('list of files or directories to convert'))

    formats = ', '.join(format_manager().formats)
    parser.add_argument('--from', dest='from_', required=True,
                        help='one of {0:s}'.format(formats))

    parser.add_argument('--to', dest='to', required=True,
                        help='one of {0:s}'.format(formats))

    parser.add_argument('--overwrite', dest='overwrite', action='store_true',
                        help=('overwrite target file if it exists '
                              '(false by default)'))

    # Parse the CLI arguments.
    args = parser.parse_args()
    convert_files(args.files_or_dirs,
                  overwrite=args.overwrite,
                  from_=args.from_,
                  to=args.to,
                  )

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