<commit_before>import scipy as sp
import numpy as np
from numpy.testing import assert_almost_equal, assert_array_equal
from spherecluster import VonMisesFisherMixture
from spherecluster import von_mises_fisher_mixture

class TestVonMisesFisherMixture(object):
    def test_vmf_log_dense(self):
        '''
        Test that approximation approaches whatever scipy has.
        '''
        n_examples = 2
        n_features = 50

        kappas = np.linspace(2, 600, 20)

        mu = np.random.randn(n_features)
        mu /= np.linalg.norm(mu)

        X = np.random.randn(n_examples, n_features)
        for ee in range(n_examples):
            X[ee, :] /= np.linalg.norm(X[ee, :])

        diffs = []
        for kappa in kappas:
            v = von_mises_fisher_mixture._vmf_log(
                    X,
                    kappa,
                    mu)

            v_approx = von_mises_fisher_mixture._vmf_log_asymptotic(
                    X,
                    kappa,
                    mu)

            normalized_approx_diff =\
                    np.linalg.norm(v - v_approx) / np.linalg.norm(v)
            print normalized_approx_diff
            diffs.append(normalized_approx_diff)

        assert diffs[0] > 10 * diffs[-1]

    def test_vmf_log_detect_breakage(self):
        n_examples = 3
        kappas = [5, 30, 100, 1000, 5000]
        n_features = range(2, 500)

        breakage_points = []
        for kappa in kappas:
            first_breakage = None
            for n_f in n_features:
                mu = np.random.randn(n_f)
                mu /= np.linalg.norm(mu)

                X = np.random.randn(n_examples, n_f)
                for ee in range(n_examples):
                    X[ee, :] /= np.linalg.norm(X[ee, :])

                try:
                    von_mises_fisher_mixture._vmf_log(
                            X,
                            kappa,
                            mu)
                except:
                    if first_breakage is None:
                        first_breakage = n_f

            breakage_points.append(first_breakage)
            print 'Scipy vmf_log breaks for kappa={} at n_features={}'.format(
                    kappa,
                    first_breakage
                )

        print breakage_points
        assert_array_equal(breakage_points, [141, 420, 311, 3, 3])

    def test_integration_multiple_jobs(self):
        n_clusters = 5
        n_examples = 20
        n_features = 100
        X = np.random.randn(n_examples, n_features)
        for ee in range(n_examples):
            X[ee, :] /= np.linalg.norm(X[ee, :])

        movmf = VonMisesFisherMixture(
                n_clusters=n_clusters,
                posterior_type='soft',
                n_jobs=2)
        movmf.fit(X)

        assert movmf.cluster_centers_.shape == (n_clusters, n_features)
        assert len(movmf.concentrations_) == n_clusters
        assert len(movmf.weights_) == n_clusters
        assert len(movmf.labels_) == n_examples

        for center in movmf.cluster_centers_:
            assert_almost_equal(np.linalg.norm(center), 1.0)

        for concentration in movmf.concentrations_:
            assert concentration > 0

        for weight in movmf.weights_:
            assert not np.isnan(weight)

        plabels = movmf.predict(X)
        assert_array_equal(plabels, movmf.labels_)

        ll = movmf.log_likelihood(X)
        ll_labels = np.zeros(movmf.labels_.shape)
        for ee in range(n_examples):
            ll_labels[ee] = np.argmax(ll[:, ee])

        assert_array_equal(ll_labels, movmf.labels_)

    def test_integration_dense_soft(self):
        n_clusters = 5
        n_examples = 20
        n_features = 100
        X = np.random.randn(n_examples, n_features)
        for ee in range(n_examples):
            X[ee, :] /= np.linalg.norm(X[ee, :])

        movmf = VonMisesFisherMixture(
                n_clusters=n_clusters,
                posterior_type='soft')
        movmf.fit(X)

        assert movmf.cluster_centers_.shape == (n_clusters, n_features)
        assert len(movmf.concentrations_) == n_clusters
        assert len(movmf.weights_) == n_clusters
        assert len(movmf.labels_) == n_examples

        for center in movmf.cluster_centers_:
            assert_almost_equal(np.linalg.norm(center), 1.0)

        for concentration in movmf.concentrations_:
            assert concentration > 0

        for weight in movmf.weights_:
            assert not np.isnan(weight)

        plabels = movmf.predict(X)
        assert_array_equal(plabels, movmf.labels_)

        ll = movmf.log_likelihood(X)
        ll_labels = np.zeros(movmf.labels_.shape)
        for ee in range(n_examples):
            ll_labels[ee] = np.argmax(ll[:, ee])

        assert_array_equal(ll_labels, movmf.labels_)

    def test_integration_dense_hard(self):
        n_clusters = 5
        n_examples = 20
        n_features = 100
        X = np.random.randn(n_examples, n_features)
        for ee in range(n_examples):
            X[ee, :] /= np.linalg.norm(X[ee, :])

        movmf = VonMisesFisherMixture(
                n_clusters=n_clusters,
                posterior_type='hard')
        movmf.fit(X)

        assert movmf.cluster_centers_.shape == (n_clusters, n_features)
        assert len(movmf.concentrations_) == n_clusters
        assert len(movmf.weights_) == n_clusters
        assert len(movmf.labels_) == n_examples

        for center in movmf.cluster_centers_:
            assert_almost_equal(np.linalg.norm(center), 1.0)

        for concentration in movmf.concentrations_:
            assert concentration > 0

        for weight in movmf.weights_:
            assert not np.isnan(weight)

        plabels = movmf.predict(X)
        assert_array_equal(plabels, movmf.labels_)

        ll = movmf.log_likelihood(X)
        ll_labels = np.zeros(movmf.labels_.shape)
        for ee in range(n_examples):
            ll_labels[ee] = np.argmax(ll[:, ee])

        assert_array_equal(ll_labels, movmf.labels_)

    def test_integration_sparse_soft(self):
        n_clusters = 5
        n_examples = 20
        n_features = 100
        n_nonzero = 10
        X = sp.sparse.csr_matrix((n_examples, n_features))
        for ee in range(n_examples):
            ridx = np.random.randint(n_features, size=(n_nonzero))
            X[ee, ridx] = np.random.randn(n_nonzero)
            X[ee, :] /= sp.sparse.linalg.norm(X[ee, :])

        movmf = VonMisesFisherMixture(
                n_clusters=n_clusters,
                posterior_type='soft')
        movmf.fit(X)

        assert movmf.cluster_centers_.shape == (n_clusters, n_features)
        assert len(movmf.concentrations_) == n_clusters
        assert len(movmf.weights_) == n_clusters
        assert len(movmf.labels_) == n_examples

        for center in movmf.cluster_centers_:
            assert_almost_equal(np.linalg.norm(center), 1.0)

        for concentration in movmf.concentrations_:
            assert concentration > 0

        for weight in movmf.weights_:
            assert not np.isnan(weight)

        plabels = movmf.predict(X)
        assert_array_equal(plabels, movmf.labels_)

        ll = movmf.log_likelihood(X)
        ll_labels = np.zeros(movmf.labels_.shape)
        for ee in range(n_examples):
            ll_labels[ee] = np.argmax(ll[:, ee])

        assert_array_equal(ll_labels, movmf.labels_)

    def test_integration_sparse_hard(self):
        n_clusters = 5
        n_examples = 20
        n_features = 100
        n_nonzero = 10
        X = sp.sparse.csr_matrix((n_examples, n_features))
        for ee in range(n_examples):
            ridx = np.random.randint(n_features, size=(n_nonzero))
            X[ee, ridx] = np.random.randn(n_nonzero)
            X[ee, :] /= sp.sparse.linalg.norm(X[ee, :])

        movmf = VonMisesFisherMixture(
                n_clusters=n_clusters,
                posterior_type='hard')
        movmf.fit(X)

        assert movmf.cluster_centers_.shape == (n_clusters, n_features)
        assert len(movmf.concentrations_) == n_clusters
        assert len(movmf.weights_) == n_clusters
        assert len(movmf.labels_) == n_examples

        for center in movmf.cluster_centers_:
            assert_almost_equal(np.linalg.norm(center), 1.0)

        for concentration in movmf.concentrations_:
            assert concentration > 0

        for weight in movmf.weights_:
            assert not np.isnan(weight)

        plabels = movmf.predict(X)
        assert_array_equal(plabels, movmf.labels_)

        ll = movmf.log_likelihood(X)
        ll_labels = np.zeros(movmf.labels_.shape)
        for ee in range(n_examples):
            ll_labels[ee] = np.argmax(ll[:, ee])

        assert_array_equal(ll_labels, movmf.labels_)

<commit_msg>parameterize some tests for readability<commit_after>import pytest
import scipy as sp
import numpy as np
from numpy.testing import assert_almost_equal, assert_array_equal
from spherecluster import VonMisesFisherMixture
from spherecluster import von_mises_fisher_mixture

class TestVonMisesFisherMixture(object):
    def test_vmf_log_dense(self):
        '''
        Test that approximation approaches whatever scipy has.
        '''
        n_examples = 2
        n_features = 50

        kappas = np.linspace(2, 600, 20)

        mu = np.random.randn(n_features)
        mu /= np.linalg.norm(mu)

        X = np.random.randn(n_examples, n_features)
        for ee in range(n_examples):
            X[ee, :] /= np.linalg.norm(X[ee, :])

        diffs = []
        for kappa in kappas:
            v = von_mises_fisher_mixture._vmf_log(
                    X,
                    kappa,
                    mu)

            v_approx = von_mises_fisher_mixture._vmf_log_asymptotic(
                    X,
                    kappa,
                    mu)

            normalized_approx_diff =\
                    np.linalg.norm(v - v_approx) / np.linalg.norm(v)
            print normalized_approx_diff
            diffs.append(normalized_approx_diff)

        assert diffs[0] > 10 * diffs[-1]

    def test_vmf_log_detect_breakage(self):
        '''
        Find where scipy approximation breaks down.
        This doesn't really test anything but demonstrates where approximation
        should be applied instead.
        '''
        n_examples = 3
        kappas = [5, 30, 100, 1000, 5000]
        n_features = range(2, 500)

        breakage_points = []
        for kappa in kappas:
            first_breakage = None
            for n_f in n_features:
                mu = np.random.randn(n_f)
                mu /= np.linalg.norm(mu)

                X = np.random.randn(n_examples, n_f)
                for ee in range(n_examples):
                    X[ee, :] /= np.linalg.norm(X[ee, :])

                try:
                    von_mises_fisher_mixture._vmf_log(
                            X,
                            kappa,
                            mu)
                except:
                    if first_breakage is None:
                        first_breakage = n_f

            breakage_points.append(first_breakage)
            print 'Scipy vmf_log breaks for kappa={} at n_features={}'.format(
                    kappa,
                    first_breakage
                )

        print breakage_points
        assert_array_equal(breakage_points, [141, 420, 311, 3, 3])

    def test_integration_multiple_jobs(self):
        n_clusters = 5
        n_examples = 20
        n_features = 100
        X = np.random.randn(n_examples, n_features)
        for ee in range(n_examples):
            X[ee, :] /= np.linalg.norm(X[ee, :])

        movmf = VonMisesFisherMixture(
                n_clusters=n_clusters,
                posterior_type='soft',
                n_jobs=2)
        movmf.fit(X)

        assert movmf.cluster_centers_.shape == (n_clusters, n_features)
        assert len(movmf.concentrations_) == n_clusters
        assert len(movmf.weights_) == n_clusters
        assert len(movmf.labels_) == n_examples

        for center in movmf.cluster_centers_:
            assert_almost_equal(np.linalg.norm(center), 1.0)

        for concentration in movmf.concentrations_:
            assert concentration > 0

        for weight in movmf.weights_:
            assert not np.isnan(weight)

        plabels = movmf.predict(X)
        assert_array_equal(plabels, movmf.labels_)

        ll = movmf.log_likelihood(X)
        ll_labels = np.zeros(movmf.labels_.shape)
        for ee in range(n_examples):
            ll_labels[ee] = np.argmax(ll[:, ee])

        assert_array_equal(ll_labels, movmf.labels_)

    @pytest.mark.parametrize("params_in", [
        {
            'posterior_type': 'soft',
        },
        {
            'posterior_type': 'hard',
        },
        {
            'posterior_type': 'soft',
            'n_jobs': 2,
        },
        {
            'posterior_type': 'hard',
            'n_jobs': 3,
        },
        {
            'posterior_type': 'hard',
            'force_weights': np.ones(5.)/5.,
        },
    ])
    def test_integration_dense(self, params_in):
        n_clusters = 5
        n_examples = 20
        n_features = 100
        X = np.random.randn(n_examples, n_features)
        for ee in range(n_examples):
            X[ee, :] /= np.linalg.norm(X[ee, :])

        params_in.update({'n_clusters': n_clusters})
        movmf = VonMisesFisherMixture(**params_in)
        movmf.fit(X)

        assert movmf.cluster_centers_.shape == (n_clusters, n_features)
        assert len(movmf.concentrations_) == n_clusters
        assert len(movmf.weights_) == n_clusters
        assert len(movmf.labels_) == n_examples

        for center in movmf.cluster_centers_:
            assert_almost_equal(np.linalg.norm(center), 1.0)

        for concentration in movmf.concentrations_:
            assert concentration > 0

        for weight in movmf.weights_:
            assert not np.isnan(weight)

        plabels = movmf.predict(X)
        assert_array_equal(plabels, movmf.labels_)

        ll = movmf.log_likelihood(X)
        ll_labels = np.zeros(movmf.labels_.shape)
        for ee in range(n_examples):
            ll_labels[ee] = np.argmax(ll[:, ee])

        assert_array_equal(ll_labels, movmf.labels_)

    @pytest.mark.parametrize("params_in", [
        {
            'posterior_type': 'soft',
        },
        {
            'posterior_type': 'hard',
        },
        {
            'posterior_type': 'soft',
            'n_jobs': 2,
        },
        {
            'posterior_type': 'hard',
            'n_jobs': 3,
        },
        {
            'posterior_type': 'hard',
            'force_weights': np.ones(5.)/5.,
        },
    ])
    def test_integration_sparse(self, params_in):
        n_clusters = 5
        n_examples = 20
        n_features = 100
        n_nonzero = 10
        X = sp.sparse.csr_matrix((n_examples, n_features))
        for ee in range(n_examples):
            ridx = np.random.randint(n_features, size=(n_nonzero))
            X[ee, ridx] = np.random.randn(n_nonzero)
            X[ee, :] /= sp.sparse.linalg.norm(X[ee, :])

        movmf = VonMisesFisherMixture(
                n_clusters=n_clusters,
                posterior_type='soft')
        movmf.fit(X)

        assert movmf.cluster_centers_.shape == (n_clusters, n_features)
        assert len(movmf.concentrations_) == n_clusters
        assert len(movmf.weights_) == n_clusters
        assert len(movmf.labels_) == n_examples

        for center in movmf.cluster_centers_:
            assert_almost_equal(np.linalg.norm(center), 1.0)

        for concentration in movmf.concentrations_:
            assert concentration > 0

        for weight in movmf.weights_:
            assert not np.isnan(weight)

        plabels = movmf.predict(X)
        assert_array_equal(plabels, movmf.labels_)

        ll = movmf.log_likelihood(X)
        ll_labels = np.zeros(movmf.labels_.shape)
        for ee in range(n_examples):
            ll_labels[ee] = np.argmax(ll[:, ee])

        assert_array_equal(ll_labels, movmf.labels_)
<|endoftext|>


<commit_before>from django.conf.urls.defaults import *
from report_builder import views

urlpatterns = patterns('',
    url('^report/add/$',  views.ReportCreateView.as_view(), name="report_create"),
    url('^report/(?P<pk>\d+)/$', views.ReportUpdateView.as_view(), name="report_update_view"),
    url('^report/(?P<pk>\d+)/download_xlsx$',  views.download_xlsx),
    ('^ajax_get_related/$', views.ajax_get_related),
    ('^ajax_get_fields/$', views.ajax_get_fields),
    url('^ajax_get_choices/$', views.ajax_get_choices, name="ajax_get_choices"),
    url('^ajax_get_formats/$', views.ajax_get_formats, name="ajax_get_formats"),
    ('^ajax_preview/$', views.ajax_preview),
    ('^report/(?P<pk>\d+)/add_star/$', views.ajax_add_star),
    ('^report/(?P<pk>\d+)/create_copy/$', views.create_copy),
    ('^export_to_report/$', views.export_to_report),
)
<commit_msg>urls.defaults are deprecated, removed.<commit_after>from django.conf.urls import patterns, url
from report_builder import views

urlpatterns = patterns('',
    url('^report/add/$',  views.ReportCreateView.as_view(), name="report_create"),
    url('^report/(?P<pk>\d+)/$', views.ReportUpdateView.as_view(), name="report_update_view"),
    url('^report/(?P<pk>\d+)/download_xlsx$',  views.download_xlsx),
    url('^ajax_get_related/$', views.ajax_get_related),
    url('^ajax_get_fields/$', views.ajax_get_fields),
    url('^ajax_get_choices/$', views.ajax_get_choices, name="ajax_get_choices"),
    url('^ajax_get_formats/$', views.ajax_get_formats, name="ajax_get_formats"),
    url('^ajax_preview/$', views.ajax_preview),
    url('^report/(?P<pk>\d+)/add_star/$', views.ajax_add_star),
    url('^report/(?P<pk>\d+)/create_copy/$', views.create_copy),
    url('^export_to_report/$', views.export_to_report),
)
<|endoftext|>


<commit_before>#copyright ReportLab Inc. 2000
#see license.txt for license details
#history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/lib/utils.py?cvsroot=reportlab
#$Header: /tmp/reportlab/reportlab/lib/utils.py,v 1.11 2001/03/26 11:12:21 rgbecker Exp $
__version__=''' $Id: utils.py,v 1.11 2001/03/26 11:12:21 rgbecker Exp $ '''

import string, os
from types import *
from reportlab.lib.logger import warnOnce
SeqTypes = (ListType,TupleType)

try:
	#raise ImportError
	### NOTE!  FP_STR SHOULD PROBABLY ALWAYS DO A PYTHON STR() CONVERSION ON ARGS
	### IN CASE THEY ARE "LAZY OBJECTS".  ACCELLERATOR DOESN'T DO THIS (YET)
	try:
		from reportlab.lib._rl_accel import fp_str	# specific
	except ImportError, errMsg:
		if str(errMsg)!='No module named _rl_accel': raise
		from _rl_accel import fp_str				# in case of builtin version
except ImportError, errMsg:
	if str(errMsg)!='No module named _rl_accel': raise
	def fp_str(*a):
		if len(a)==1 and type(a[0]) in SeqTypes: a = a[0]
		s = []
		for i in a:
			s.append('%0.2f' % i)
		return string.join(s)

def import_zlib():
	try:
		import zlib
	except ImportError, errMsg:
		if str(errMsg)!='No module named zlib': raise
		zlib = None
		warnOnce('zlib not available')
	return zlib

try:
	from PIL import Image
except ImportError, errMsg:
	if str(errMsg)!='No module named PIL': raise
	try:
		import Image
		warnOnce('Python Imaging Library not available as package; upgrade your installation!')
	except ImportError, errMsg:
		if str(errMsg)!='No module named Image': raise
		Image = None
		warnOnce('Python Imaging Library not available')
PIL_Image = Image
del Image

def getHyphenater(hDict=None):
	try:
		from reportlab.lib.pyHnj import Hyphen
		if hDict is None: hDict=os.path.join(os.path.dirname(__file__),'hyphen.mashed')
		return Hyphen(hDict)
	except ImportError, errMsg:
		if str(errMsg)!='No module named pyHnj': raise
		return None

def _className(self):
	'''Return a shortened class name'''
	try:
		name = self.__class__.__name__
		i=string.rfind(name,'.')
		if i>=0: return name[i+1:]
		return name
	except AttributeError:
		return str(self)
<commit_msg>Added dict _updater func<commit_after>#copyright ReportLab Inc. 2000
#see license.txt for license details
#history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/lib/utils.py?cvsroot=reportlab
#$Header: /tmp/reportlab/reportlab/lib/utils.py,v 1.12 2001/04/06 10:02:44 rgbecker Exp $
__version__=''' $Id: utils.py,v 1.12 2001/04/06 10:02:44 rgbecker Exp $ '''

import string, os
from types import *
from reportlab.lib.logger import warnOnce
SeqTypes = (ListType,TupleType)

try:
	#raise ImportError
	### NOTE!  FP_STR SHOULD PROBABLY ALWAYS DO A PYTHON STR() CONVERSION ON ARGS
	### IN CASE THEY ARE "LAZY OBJECTS".  ACCELLERATOR DOESN'T DO THIS (YET)
	try:
		from reportlab.lib._rl_accel import fp_str	# specific
	except ImportError, errMsg:
		if str(errMsg)!='No module named _rl_accel': raise
		from _rl_accel import fp_str				# in case of builtin version
except ImportError, errMsg:
	if str(errMsg)!='No module named _rl_accel': raise
	def fp_str(*a):
		if len(a)==1 and type(a[0]) in SeqTypes: a = a[0]
		s = []
		for i in a:
			s.append('%0.2f' % i)
		return string.join(s)

def import_zlib():
	try:
		import zlib
	except ImportError, errMsg:
		if str(errMsg)!='No module named zlib': raise
		zlib = None
		warnOnce('zlib not available')
	return zlib

try:
	from PIL import Image
except ImportError, errMsg:
	if str(errMsg)!='No module named PIL': raise
	try:
		import Image
		warnOnce('Python Imaging Library not available as package; upgrade your installation!')
	except ImportError, errMsg:
		if str(errMsg)!='No module named Image': raise
		Image = None
		warnOnce('Python Imaging Library not available')
PIL_Image = Image
del Image

def getHyphenater(hDict=None):
	try:
		from reportlab.lib.pyHnj import Hyphen
		if hDict is None: hDict=os.path.join(os.path.dirname(__file__),'hyphen.mashed')
		return Hyphen(hDict)
	except ImportError, errMsg:
		if str(errMsg)!='No module named pyHnj': raise
		return None

def _className(self):
	'''Return a shortened class name'''
	try:
		name = self.__class__.__name__
		i=string.rfind(name,'.')
		if i>=0: return name[i+1:]
		return name
	except AttributeError:
		return str(self)

def _updater(D,X):
	'''copy and update a dictionary'''
	D=D.copy()
	D.update(X)
	return D
<|endoftext|>


<commit_before>#copyright ReportLab Inc. 2000-2001
#see license.txt for license details
#history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/rl_config.py?cvsroot=reportlab
#$Header: /tmp/reportlab/reportlab/rl_config.py,v 1.27 2001/10/05 01:00:34 andy_robinson Exp $

allowTableBoundsErrors = 1 # set to 0 to die on too large elements in tables in debug (recommend 1 for production use)
shapeChecking =				1
defaultEncoding =			'WinAnsiEncoding'		# 'WinAnsi' or 'MacRoman'
pageCompression =			1						# default page compression mode
defaultPageSize =			'A4'					#default page size
defaultImageCaching =		0						#set to zero to remove those annoying cached images
PIL_WARNINGS =				1						#set to zero to remove those annoying warnings
ZLIB_WARNINGS =				1
warnOnMissingFontGlyphs =	0						#if 1, warns of each missing glyph
_verbose =					0
showBoundary =				0						# turns on and off boundary behaviour in Drawing

# places to look for T1Font information
T1SearchPath =	('c:/Program Files/Adobe/Acrobat 4.0/Resource/Font', #Win32
				'c:/Program Files/Adobe/Acrobat 5.0/Resource/Font', #Win32, Acrobat 5
				'%(disk)s/Applications/Python %(sys_version)s/reportlab/fonts', #Mac?
				'/usr/lib/Acrobat4/Resource/Font', #Linux
				'/usr/lib/Acrobat5/Resource/Font', #Linux, Acrobat 5?
				'%(REPORTLAB_DIR)s/fonts' #special
				)

# places to look for CMap files - should ideally merge with above
CMapSearchPath = ('/usr/local/Acrobat4/Resource/CMap',
				'C:\\Program Files\\Adobe\\Acrobat\\Resource\\CMap',
				'C:\\Program Files\\Adobe\\Acrobat 5.0\\Resource\\CMap',
				'C:\\Program Files\\Adobe\\Acrobat 4.0\\Resource\\CMap'
				)

#### Normally don't need to edit below here ####
import os, sys, string
from reportlab.lib import pagesizes

def _setOpt(name, value, conv=None):
	'''set a module level value from environ/default'''
	from os import environ
	ename = 'RL_'+name
	if environ.has_key(ename):
		value = environ[ename]
	if conv: value = conv(value)
	globals()[name] = value

sys_version = string.split(sys.version)[0]		#strip off the other garbage
_SAVED = {}

def	_startUp():
	'''This function allows easy resetting to the global defaults
	If the environment contains 'RL_xxx' then we use the value
	else we use the given default'''
	V = ('T1SearchPath','CMapSearchPath','shapeChecking', 'defaultEncoding', 'pageCompression',
				'defaultPageSize', 'defaultImageCaching', 'PIL_WARNINGS',
				'ZLIB_WARNINGS', 'warnOnMissingFontGlyphs', '_verbose',
				)

	if _SAVED=={}:
		for k in V:
			_SAVED[k] = globals()[k]

	#places to search for Type 1 Font files
	import reportlab
	D = {'REPORTLAB_DIR': os.path.dirname(reportlab.__file__),
		'disk': string.split(os.getcwd(), ':')[0],
		'sys_version': sys_version,
		}

	P=[]
	for p in _SAVED['T1SearchPath']:
		d = string.replace(p % D,'/',os.sep)
		if os.path.isdir(d): P.append(d)
	_setOpt('T1SearchPath',P)

	P=[]
	for p in _SAVED['CMapSearchPath']:
		d = string.replace(p % D,'/',os.sep)
		if os.path.isdir(d): P.append(d)
	_setOpt('CMapSearchPath',P)

	for k in V[1:]:
		v = _SAVED[k]
		if type(v)==type(1): conv = int
		elif k=='defaultPageSize': conv = lambda v,M=pagesizes: getattr(M,v)
		else: conv = None
		_setOpt(k,v,conv)

_startUp()
<commit_msg>Now looks for acrobat 5 _before_ acrobat 4.<commit_after>#copyright ReportLab Inc. 2000-2001
#see license.txt for license details
#history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/rl_config.py?cvsroot=reportlab
#$Header: /tmp/reportlab/reportlab/rl_config.py,v 1.28 2001/11/01 20:53:27 johnprecedo Exp $

allowTableBoundsErrors = 1 # set to 0 to die on too large elements in tables in debug (recommend 1 for production use)
shapeChecking =				1
defaultEncoding =			'WinAnsiEncoding'		# 'WinAnsi' or 'MacRoman'
pageCompression =			1						# default page compression mode
defaultPageSize =			'A4'					#default page size
defaultImageCaching =		0						#set to zero to remove those annoying cached images
PIL_WARNINGS =				1						#set to zero to remove those annoying warnings
ZLIB_WARNINGS =				1
warnOnMissingFontGlyphs =	0						#if 1, warns of each missing glyph
_verbose =					0
showBoundary =				0						# turns on and off boundary behaviour in Drawing

# places to look for T1Font information
T1SearchPath =	('c:/Program Files/Adobe/Acrobat 5.0/Resource/Font', #Win32, Acrobat 5
				 'c:/Program Files/Adobe/Acrobat 4.0/Resource/Font', #Win32, Acrobat 4
				 '%(disk)s/Applications/Python %(sys_version)s/reportlab/fonts', #Mac?
				 '/usr/lib/Acrobat5/Resource/Font', #Linux, Acrobat 5?
				 '/usr/lib/Acrobat4/Resource/Font', #Linux, Acrobat 4
				 '%(REPORTLAB_DIR)s/fonts' #special
				 )

# places to look for CMap files - should ideally merge with above
CMapSearchPath = ('/usr/local/Acrobat5/Resource/CMap',
				  '/usr/local/Acrobat4/Resource/CMap',
				  'C:\\Program Files\\Adobe\\Acrobat\\Resource\\CMap',
				  'C:\\Program Files\\Adobe\\Acrobat 5.0\\Resource\\CMap',
				  'C:\\Program Files\\Adobe\\Acrobat 4.0\\Resource\\CMap'
				  )

#### Normally don't need to edit below here ####
import os, sys, string
from reportlab.lib import pagesizes

def _setOpt(name, value, conv=None):
	'''set a module level value from environ/default'''
	from os import environ
	ename = 'RL_'+name
	if environ.has_key(ename):
		value = environ[ename]
	if conv: value = conv(value)
	globals()[name] = value

sys_version = string.split(sys.version)[0]		#strip off the other garbage
_SAVED = {}

def	_startUp():
	'''This function allows easy resetting to the global defaults
	If the environment contains 'RL_xxx' then we use the value
	else we use the given default'''
	V = ('T1SearchPath','CMapSearchPath','shapeChecking', 'defaultEncoding', 'pageCompression',
				'defaultPageSize', 'defaultImageCaching', 'PIL_WARNINGS',
				'ZLIB_WARNINGS', 'warnOnMissingFontGlyphs', '_verbose',
				)

	if _SAVED=={}:
		for k in V:
			_SAVED[k] = globals()[k]

	#places to search for Type 1 Font files
	import reportlab
	D = {'REPORTLAB_DIR': os.path.dirname(reportlab.__file__),
		'disk': string.split(os.getcwd(), ':')[0],
		'sys_version': sys_version,
		}

	P=[]
	for p in _SAVED['T1SearchPath']:
		d = string.replace(p % D,'/',os.sep)
		if os.path.isdir(d): P.append(d)
	_setOpt('T1SearchPath',P)

	P=[]
	for p in _SAVED['CMapSearchPath']:
		d = string.replace(p % D,'/',os.sep)
		if os.path.isdir(d): P.append(d)
	_setOpt('CMapSearchPath',P)

	for k in V[1:]:
		v = _SAVED[k]
		if type(v)==type(1): conv = int
		elif k=='defaultPageSize': conv = lambda v,M=pagesizes: getattr(M,v)
		else: conv = None
		_setOpt(k,v,conv)

_startUp()
<|endoftext|>


<commit_before>#
# Copyright (c) 2004 Specifix, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/cpl.php.
#
# This program is distributed in the hope that it will be useful, but
# without any waranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
<commit_msg>import changeset first, to get the import order right<commit_after>#
# Copyright (c) 2004 Specifix, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/cpl.php.
#
# This program is distributed in the hope that it will be useful, but
# without any waranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#

import changeset
<|endoftext|>


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

from .base import BufferedDBWriter
from odps import ODPS, tunnel

class MaxComputeDBWriter(BufferedDBWriter):
    def __init__(self, conn, table_name, table_schema, buff_size):
        return super().__init__(conn, table_name, table_schema, buff_size)

    def flush(self):
        compress = tunnel.CompressOption.CompressAlgorithm.ODPS_ZLIB
        self.conn.write_table(self.table, self.rows, compress_option=compress)
        self.rows = []
<commit_msg>Fix maxcompute e2e test (#700)<commit_after># Copyright 2019 The SQLFlow Authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from .base import BufferedDBWriter
from odps import ODPS, tunnel

class MaxComputeDBWriter(BufferedDBWriter):
    def __init__(self, conn, table_name, table_schema, buff_size):
        return super().__init__(conn, table_name, table_schema, buff_size)

    def flush(self):
        compress = tunnel.CompressOption.CompressAlgorithm.ODPS_ZLIB
        self.conn.write_table(self.table_name, self.rows, compress_option=compress)
        self.rows = []
<|endoftext|>


<commit_before>"""Sheets to assign workflows to resources and change states."""
from colander import MappingSchema
from colander import deferred
from colander import null
from colander import OneOf
from colander import drop
from pyramid.testing import DummyRequest
from pyramid.threadlocal import get_current_request
from substanced.workflow import IWorkflow
from zope.interface import implementer

from adhocracy_core.exceptions import RuntimeConfigurationError
from adhocracy_core.interfaces import ISheet
from adhocracy_core.schema import AdhocracySchemaNode
from adhocracy_core.schema import DateTime
from adhocracy_core.schema import Text
from adhocracy_core.schema import SingleLine
from adhocracy_core.schema import AdhocracySequenceNode
from adhocracy_core.sheets import add_sheet_to_registry
from adhocracy_core.sheets import sheet_meta
from adhocracy_core.sheets import AnnotationRessourceSheet
from adhocracy_core.interfaces import IResourceSheet

class Workflow(AdhocracySchemaNode):
    """Workflow :class:`adhocracy_core.interfaces.IWorkflow`.

    This schema node is readonly. The value is given by the node binding
    `workflow`.
    """

    schema_type = SingleLine.schema_type
    readonly = True

    @deferred
    def default(self, kw: dict) -> IWorkflow:
        return kw.get('workflow', None)

    def serialize(self, appstruct=null):
        """Serialize the :term:`appstruct` to a :term:`cstruct`."""
        workflow = self.bindings['workflow']
        if workflow is None:
            return ''
        return workflow.type

class State(SingleLine):
    """Workflow state of `context` of the given `workflow` binding."""

    missing = drop

    @deferred
    def default(self, kw: dict) -> str:
        """Return default value."""
        workflow = kw.get('workflow', None)
        if workflow is None:
            return ''
        context = kw['context']
        state = workflow.state_of(context)
        if state is None:
            state = ''
        return state

    @deferred
    def validator(self, kw: dict):
        """Validator."""
        request = kw.get('request', None)
        if request is None:
            return
        workflow = kw.get('workflow', None)
        if workflow is None:
            next_states = []
        else:
            context = kw['context']
            next_states = workflow.get_next_states(context, request)

        def validate_next_states(node, value):
            return OneOf(next_states)(node, value)
        return validate_next_states

class StateName(SingleLine):
    """Workflow state name.

    Possible values are set by the given `workflow` binding.
    """

    @deferred
    def validator(self, kw: dict):
        """Validator."""
        workflow = kw.get('workflow', None)
        if workflow is None:
            states = []
        else:
            states = workflow._states.keys()  # TODO don't use private attr

        def validate_state_name(node, value):
            return OneOf(states)(node, value)
        return validate_state_name

class StateData(MappingSchema):
    """Resource specific data for a workflow state."""

    missing = drop
    default = None

    name = StateName()
    description = Text(missing='',
                       default='')
    start_date = DateTime(missing=None,
                          default=None)

class StateDataList(AdhocracySequenceNode):
    """List of StateData."""

    data = StateData()

class WorkflowAssignmentSchema(MappingSchema):
    """Workflow assignment sheet data structure."""

    workflow = Workflow(missing=drop)
    """Workflow assigned to the sheet context resource.

    This is readonly, the workflow is set by the `workflow` binding.
    Available workflows are defined in :mod:`adhocracy_core.workflows`.
    """

    workflow_state = State(missing=drop)
    """Workflow state of the sheet context resource.

    Setting this executes a transition to the new state value.
    """

    state_data = StateDataList(missing=drop)
    """Optional List of :class:`StateData`.

    example:

        {'name': 'state1', 'description': 'text', 'start_date': <DateTime>}
    """

class IWorkflowAssignment(ISheet):
    """Market interface for the workflow assignment sheet."""

@implementer(IResourceSheet)
class WorkflowAssignmentSheet(AnnotationRessourceSheet):
    """Sheet class for workflow assignment sheets.

    It allows to view and modifiy the workflow state of `context`.
    If the you set a new workflow state a transition to this state is executed.

    The workflow of `context` is only found, if the :term:`resource_type`
    metadata of `context` has a valid 'workflow` entry.

    The sheet schema has to be a sup type of
    :class:`adhocracy_core.sheets.workflow.WorkflowAssignmentSchema`,
    the isheet a subclass of
    :class:`adhocracy_core.sheets.workflow.IWorkflowAssignment`.
    """

    def __init__(self, meta, context, registry=None):
        """Initialize self."""
        super().__init__(meta, context, registry)
        error_msg = '{0} is not a sub type of {1}.'
        if not meta.isheet.isOrExtends(IWorkflowAssignment):
            msg = error_msg.format(str(meta.isheet), str(IWorkflowAssignment))
            raise RuntimeConfigurationError(msg)
        if not isinstance(self.schema, WorkflowAssignmentSchema):
            msg = error_msg.format(str(meta.schema_class),
                                   str(WorkflowAssignmentSchema))
            raise RuntimeConfigurationError(msg)

    def _get_default_appstruct(self) -> dict:
        workflow = self.registry.content.get_workflow(self.context)
        schema = self.schema.bind(context=self.context,
                                  registry=self.registry,
                                  workflow=workflow)
        items = [(n.name, n.default) for n in schema]
        return dict(items)

    def _get_schema_for_cstruct(self, request, params: dict):
        workflow = self.registry.content.get_workflow(self.context)
        schema = self.schema.bind(context=self.context,
                                  registry=self.registry,
                                  workflow=workflow,
                                  request=request)
        return schema

    def _store_data(self, appstruct: dict):
        if 'workflow_state' in appstruct:
            self._set_state(appstruct['workflow_state'])
            del appstruct['workflow_state']
        super()._store_data(appstruct)

    def _set_state(self, name: str):
        """Do transition to state `name`, don`t check user permissions."""
        workflow = self.get()['workflow']
        request = get_current_request() or DummyRequest()  # ease testing
        workflow.transition_to_state(self.context, request, to_state=name)

workflow_meta = sheet_meta._replace(
    isheet=IWorkflowAssignment,
    schema_class=WorkflowAssignmentSchema,
    sheet_class=WorkflowAssignmentSheet,
    permission_edit='do_transition'
)

def includeme(config):
    """Add sheet."""
    add_sheet_to_registry(workflow_meta, config.registry)
<commit_msg>Fix: migration fails due to missing interface sheets.workflow.ISample<commit_after>"""Sheets to assign workflows to resources and change states."""
from colander import MappingSchema
from colander import deferred
from colander import null
from colander import OneOf
from colander import drop
from pyramid.testing import DummyRequest
from pyramid.threadlocal import get_current_request
from substanced.workflow import IWorkflow
from zope.deprecation import deprecated
from zope.interface import implementer

from adhocracy_core.exceptions import RuntimeConfigurationError
from adhocracy_core.interfaces import ISheet
from adhocracy_core.schema import AdhocracySchemaNode
from adhocracy_core.schema import DateTime
from adhocracy_core.schema import Text
from adhocracy_core.schema import SingleLine
from adhocracy_core.schema import AdhocracySequenceNode
from adhocracy_core.sheets import add_sheet_to_registry
from adhocracy_core.sheets import sheet_meta
from adhocracy_core.sheets import AnnotationRessourceSheet
from adhocracy_core.interfaces import IResourceSheet

class ISample(ISheet):
    """Sheet with the sample workflow."""

deprecated('ISample', 'Backward compatible code, dont use')

class Workflow(AdhocracySchemaNode):
    """Workflow :class:`adhocracy_core.interfaces.IWorkflow`.

    This schema node is readonly. The value is given by the node binding
    `workflow`.
    """

    schema_type = SingleLine.schema_type
    readonly = True

    @deferred
    def default(self, kw: dict) -> IWorkflow:
        return kw.get('workflow', None)

    def serialize(self, appstruct=null):
        """Serialize the :term:`appstruct` to a :term:`cstruct`."""
        workflow = self.bindings['workflow']
        if workflow is None:
            return ''
        return workflow.type

class State(SingleLine):
    """Workflow state of `context` of the given `workflow` binding."""

    missing = drop

    @deferred
    def default(self, kw: dict) -> str:
        """Return default value."""
        workflow = kw.get('workflow', None)
        if workflow is None:
            return ''
        context = kw['context']
        state = workflow.state_of(context)
        if state is None:
            state = ''
        return state

    @deferred
    def validator(self, kw: dict):
        """Validator."""
        request = kw.get('request', None)
        if request is None:
            return
        workflow = kw.get('workflow', None)
        if workflow is None:
            next_states = []
        else:
            context = kw['context']
            next_states = workflow.get_next_states(context, request)

        def validate_next_states(node, value):
            return OneOf(next_states)(node, value)
        return validate_next_states

class StateName(SingleLine):
    """Workflow state name.

    Possible values are set by the given `workflow` binding.
    """

    @deferred
    def validator(self, kw: dict):
        """Validator."""
        workflow = kw.get('workflow', None)
        if workflow is None:
            states = []
        else:
            states = workflow._states.keys()  # TODO don't use private attr

        def validate_state_name(node, value):
            return OneOf(states)(node, value)
        return validate_state_name

class StateData(MappingSchema):
    """Resource specific data for a workflow state."""

    missing = drop
    default = None

    name = StateName()
    description = Text(missing='',
                       default='')
    start_date = DateTime(missing=None,
                          default=None)

class StateDataList(AdhocracySequenceNode):
    """List of StateData."""

    data = StateData()

class WorkflowAssignmentSchema(MappingSchema):
    """Workflow assignment sheet data structure."""

    workflow = Workflow(missing=drop)
    """Workflow assigned to the sheet context resource.

    This is readonly, the workflow is set by the `workflow` binding.
    Available workflows are defined in :mod:`adhocracy_core.workflows`.
    """

    workflow_state = State(missing=drop)
    """Workflow state of the sheet context resource.

    Setting this executes a transition to the new state value.
    """

    state_data = StateDataList(missing=drop)
    """Optional List of :class:`StateData`.

    example:

        {'name': 'state1', 'description': 'text', 'start_date': <DateTime>}
    """

class IWorkflowAssignment(ISheet):
    """Market interface for the workflow assignment sheet."""

@implementer(IResourceSheet)
class WorkflowAssignmentSheet(AnnotationRessourceSheet):
    """Sheet class for workflow assignment sheets.

    It allows to view and modifiy the workflow state of `context`.
    If the you set a new workflow state a transition to this state is executed.

    The workflow of `context` is only found, if the :term:`resource_type`
    metadata of `context` has a valid 'workflow` entry.

    The sheet schema has to be a sup type of
    :class:`adhocracy_core.sheets.workflow.WorkflowAssignmentSchema`,
    the isheet a subclass of
    :class:`adhocracy_core.sheets.workflow.IWorkflowAssignment`.
    """

    def __init__(self, meta, context, registry=None):
        """Initialize self."""
        super().__init__(meta, context, registry)
        error_msg = '{0} is not a sub type of {1}.'
        if not meta.isheet.isOrExtends(IWorkflowAssignment):
            msg = error_msg.format(str(meta.isheet), str(IWorkflowAssignment))
            raise RuntimeConfigurationError(msg)
        if not isinstance(self.schema, WorkflowAssignmentSchema):
            msg = error_msg.format(str(meta.schema_class),
                                   str(WorkflowAssignmentSchema))
            raise RuntimeConfigurationError(msg)

    def _get_default_appstruct(self) -> dict:
        workflow = self.registry.content.get_workflow(self.context)
        schema = self.schema.bind(context=self.context,
                                  registry=self.registry,
                                  workflow=workflow)
        items = [(n.name, n.default) for n in schema]
        return dict(items)

    def _get_schema_for_cstruct(self, request, params: dict):
        workflow = self.registry.content.get_workflow(self.context)
        schema = self.schema.bind(context=self.context,
                                  registry=self.registry,
                                  workflow=workflow,
                                  request=request)
        return schema

    def _store_data(self, appstruct: dict):
        if 'workflow_state' in appstruct:
            self._set_state(appstruct['workflow_state'])
            del appstruct['workflow_state']
        super()._store_data(appstruct)

    def _set_state(self, name: str):
        """Do transition to state `name`, don`t check user permissions."""
        workflow = self.get()['workflow']
        request = get_current_request() or DummyRequest()  # ease testing
        workflow.transition_to_state(self.context, request, to_state=name)

workflow_meta = sheet_meta._replace(
    isheet=IWorkflowAssignment,
    schema_class=WorkflowAssignmentSchema,
    sheet_class=WorkflowAssignmentSheet,
    permission_edit='do_transition'
)

def includeme(config):
    """Add sheet."""
    add_sheet_to_registry(workflow_meta, config.registry)
<|endoftext|>


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

import sys
from java.awt import *
from java.lang import *
from javax.swing import *
from edu.mines.jtk.awt import *
from edu.mines.jtk.dsp import *
from edu.mines.jtk.mosaic import *
from edu.mines.jtk.util import *
from edu.mines.jtk.util.ArrayMath import *

# 2014 Average Rainfall in inches
# Data provided by Weather Underground (www.wunderground.com)
#        Houston  Denver Seattle
data = [  0.04,   0.02,   0.12,  # Jan
          0.10,   0.01,   0.21,  # Feb
          0.08,   0.02,   0.25,  # Mar
          0.07,   0.05,   0.12,  # Apr
          0.42,   0.13,   0.08,  # May
          0.09,   0.06,   0.01,  # Jun
          0.20,   0.16,   0.00,  # Jul
          0.05,   0.07,   0.00,  # Aug
          0.16,   0.07,   0.03,  # Sep
          0.11,   0.05,   0.18,  # Oct
          0.12,   0.02,   0.14,  # Nov
          0.24,   0.01,   0.15   # Dec
       ]

# Yearly US Budget Surplus and GDP  (Millions)
#         Surplus       GDP
gdp = [ -484602.0,	17700000.0,
        -679544.0,	17080000.0,
        -1086963.0,	16330000.0,
        -1299593.0,	15790000.0,
        -1294373.0,	15230000.0,
        -1412688.0,	14570000.0,
        -458553.0,	14550000.0,
        -160701.0,	14690000.0,
        -248181.0,	14070000.0,
        -318346.0,	13380000.0,
        -412727.0,	12560000.0,
        -377585.0,	11820000.0,
        -157758.0,	11100000.0,
        128236.0,	10700000.0,
        236241.0,	10470000.0,
        125610.0,	9930000.0,
        69270.0,	9330000.0,
        -21884.0,	8790000.0,
        -107431.0,	8290000.0,
        -163952.0,	7800000.0,
        -203186.0,	7480000.0,
        -255051.0,	7030000.0,
        -290321.0,	6700000.0,
        -269238.0,	6280000.0,
        -221036.0,	6020000.0,
        -152639.0,	5760000.0,
        -155178.0,	5410000.0,
        -149730.0,	5020000.0,
        -221227.0,	4670000.0,
        -212308.0,	4450000.0,
        -185367.0,	4150000.0,
        -207802.0,	3800000.0,
        -127977.0,	3410000.0,
        -78968.0,	3280000.0,
        -73830.0,	2990000.0,
        -40726.0,	2730000.0,
        -59185.0,	2480000.0,
        -53659.0,	2170000.0,
        -73732.0,	1940000.0,
        -53242.0,	1770000.0,
        -6135.0,	1600000.0,
        -14908.0,	1480000.0,
        -23373.0,	1330000.0,
        -23033.0,	1190000.0,
        -2842.0,	1090000.0,
        3242.0,	1040000.0,
        -25161.0,	970000.0,
        -8643.0,	880000.0,
        -3698.0,	830000.0,
        -1411.0,	770000.0,
        -5915.0,	700000.0,
        -4756.0,	650000.0,
        -7146.0,	610000.0,
        -3335.0,	580000.0,
        301.0,	540000.0,
        -12849.0,	530000.0,
        -2769.0,	500000.0,
        3412.0,	480000.0,
        3947.0,	460000.0,
        -2993.0,	440000.0,
        -1154.0,	400000.0,
        -6493.0,	390000.0,
        -1519.0,	380000.0,
        6102.0,	360000.0,
        -3119.0,	320000.0,
        580.0,	270000.0,
        11796.0,	280000.0,
        4018.0,	260000.0,
        -15936.0,	230000.0,
        -47553.0,	230000.0,
        -47557.0,	220000.0,
        -54554.0,	200000.0,
        -20503.0,	170000.0,
        -4941.0,	130000.0,
        -2920.0,	100000.0,
        -2846.0,	90000.0,
        -89.0,	90000.0,
        -2193.0,	90000.0,
        -4304.0,	80000.0,
        -2803.0,	70000.0,
        -3586.0,	70000.0,
        -2602.0,	60000.0,
        -2735.0,	60000.0,
        -462.0,	80000.0,
        738.0,	90000.0
      ]

KHOU = 0
KBKF = 1
KBFI = 2
n2 = 12
d2 = 1.0
f2 = 1.0

n3 = 85
d3 = 1.0
f3 = 1930

s3 = Sampling(n3,d3,f3)
s2 = Sampling(n2,d2,f2)

BLUE_500  = Color(0x2196F3,False)
AMBER_500 = Color(0xFFC107,False)
PINK_500  = Color(0xE91E63,False)

# For testing below.
def makePlotPanel1(f):
  pp = PlotPanel()
  bv = pp.addBars(s2,f)
  bv.setFillColor(0,BLUE_500)
  bv.setFillColor(1,AMBER_500)
  bv.setFillColor(2,PINK_500)
  bv.setLineColor(Color.BLACK)
  bv.setBarWidth(0.98)
  bv.setAlignment(BarsView.Alignment.ALIGN_CENTER)
  bv.setOrientation(BarsView.Orientation.X1RIGHT_X2UP)
  bv.setStackBars(True)
  return pp

def makePlotPanel2(f):
  pp = PlotPanel()
  gv = pp.addGrid()
  gv.setVertical(GridView.Vertical.ZERO)
  gv.setColor(Color.GRAY)
  bv = pp.addBars(s3,f)
  c0 = Color(133,125,125)
  c1 = Color(250,8,8)
  bv.setColorMap(ColorMap(0,5,prettyColors(c0,c1)))
  bv.setLineColor(Color.WHITE)
  bv.setBarWidth(1.00)
  bv.setAlignment(BarsView.Alignment.ALIGN_CENTER)
  bv.setOrientation(BarsView.Orientation.X1DOWN_X2RIGHT)
  return pp

def makePlotPanel3(f):
  pp = PlotPanel()
  gv = pp.addGrid()
  gv.setVertical(GridView.Vertical.ZERO)
  gv.setColor(Color.GRAY)
  bv = pp.addBars(f)
  bv.setFillColor(BLUE_500)
  bv.setBarWidth(1.00)
  bv.setAlignment(BarsView.Alignment.ALIGN_CENTER)
  bv.setOrientation(BarsView.Orientation.X1DOWN_X2RIGHT)
  return pp

def prettyColors(c0,c1):
  r0 = c0.red/255.0
  g0 = c0.green/255.0
  b0 = c0.blue/255.0

  r1 = c1.red/255.0
  g1 = c1.green/255.0
  b1 = c1.blue/255.0

  color = []
  dr = (r1-r0) / 256.0
  dg = (g1-g0) / 256.0
  db = (b1-b0) / 256.0
  for i in range(256):
    color.append(Color(r0+i*dr,g0+i*dg,b0+i*db))
  return ColorMap.makeIndexColorModel(color)

def compileWeather():
  f = [[0 for i in xrange(12)] for i in xrange(3)]
  for i in range(12):
    f[KHOU][i] = data[KHOU+3*i]
    f[KBKF][i] = data[KBKF+3*i]
    f[KBFI][i] = data[KBFI+3*i]
  return f

def compileDeficit():
  l = len(gdp)/2
  f = [0 for i in xrange(l)]
  for i in range(l):
    f[n3-i-1] = -1*(gdp[2*i]/gdp[2*i+1])*100
  return f

def fakeData():
  f = [0 for i in xrange(10)]
  for i in range(10):
    f[i] = i-5
  return f

def test1():
  f = compileWeather()
  pp = makePlotPanel1(f)
  pp.setVLabel("Average Rainfall (inches)")
  pp.setHLabel("Month")
  pp.setTitle("2014 Average Rainfall (in)")
  pf = PlotFrame(pp)
  pf.pack();
  pf.setDefaultCloseOperation(PlotFrame.EXIT_ON_CLOSE)
  pf.setVisible(True)

def test2():
  f = compileDeficit()
  pp = makePlotPanel2(f)
  pp.setTitle("US Deficit as Percent of GDP (1930-2014)")
  pp.setHLabel("Deficit (% of GDP)")
  pp.setVLabel("Fiscal Year")
  pf = PlotFrame(pp)
  pf.pack();
  pf.setDefaultCloseOperation(PlotFrame.EXIT_ON_CLOSE)
  pf.setVisible(True)

def test3():
  f = fakeData()
  pp = makePlotPanel3(f)
  pf = PlotFrame(pp)
  pf.pack();
  pf.setDefaultCloseOperation(PlotFrame.EXIT_ON_CLOSE)
  pf.setVisible(True)

def main(args):
  test1()
  test2()
  test3()

#############################################################################
class RunMain(Runnable):
  def run(self):
    main(sys.argv)
SwingUtilities.invokeLater(RunMain())
<commit_msg>BarsView Demo<commit_after># Copyright 2015, Colorado School of Mines and others.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Author: Chris Engelsma
# Version: 2015.10.27

import sys
from java.awt import *
from java.lang import *
from javax.swing import *
from edu.mines.jtk.awt import *
from edu.mines.jtk.dsp import *
from edu.mines.jtk.mosaic import *
from edu.mines.jtk.util import *
from edu.mines.jtk.util.ArrayMath import *

# 2014 Average Rainfall in inches
# Data provided by Weather Underground (www.wunderground.com)
#        Houston  Denver Seattle
data = [  0.04,   0.02,   0.12,  # Jan
          0.10,   0.01,   0.21,  # Feb
          0.08,   0.02,   0.25,  # Mar
          0.07,   0.05,   0.12,  # Apr
          0.42,   0.13,   0.08,  # May
          0.09,   0.06,   0.01,  # Jun
          0.20,   0.16,   0.00,  # Jul
          0.05,   0.07,   0.00,  # Aug
          0.16,   0.07,   0.03,  # Sep
          0.11,   0.05,   0.18,  # Oct
          0.12,   0.02,   0.14,  # Nov
          0.24,   0.01,   0.15   # Dec
       ]

# Yearly US Budget Surplus and GDP  (Millions)
#         Surplus       GDP
gdp = [ -484602.0,	17700000.0,
        -679544.0,	17080000.0,
        -1086963.0,	16330000.0,
        -1299593.0,	15790000.0,
        -1294373.0,	15230000.0,
        -1412688.0,	14570000.0,
        -458553.0,	14550000.0,
        -160701.0,	14690000.0,
        -248181.0,	14070000.0,
        -318346.0,	13380000.0,
        -412727.0,	12560000.0,
        -377585.0,	11820000.0,
        -157758.0,	11100000.0,
        128236.0,	10700000.0,
        236241.0,	10470000.0,
        125610.0,	9930000.0,
        69270.0,	9330000.0,
        -21884.0,	8790000.0,
        -107431.0,	8290000.0,
        -163952.0,	7800000.0,
        -203186.0,	7480000.0,
        -255051.0,	7030000.0,
        -290321.0,	6700000.0,
        -269238.0,	6280000.0,
        -221036.0,	6020000.0,
        -152639.0,	5760000.0,
        -155178.0,	5410000.0,
        -149730.0,	5020000.0,
        -221227.0,	4670000.0,
        -212308.0,	4450000.0,
        -185367.0,	4150000.0,
        -207802.0,	3800000.0,
        -127977.0,	3410000.0,
        -78968.0,	3280000.0,
        -73830.0,	2990000.0,
        -40726.0,	2730000.0,
        -59185.0,	2480000.0,
        -53659.0,	2170000.0,
        -73732.0,	1940000.0,
        -53242.0,	1770000.0,
        -6135.0,	1600000.0,
        -14908.0,	1480000.0,
        -23373.0,	1330000.0,
        -23033.0,	1190000.0,
        -2842.0,	1090000.0,
        3242.0,	1040000.0,
        -25161.0,	970000.0,
        -8643.0,	880000.0,
        -3698.0,	830000.0,
        -1411.0,	770000.0,
        -5915.0,	700000.0,
        -4756.0,	650000.0,
        -7146.0,	610000.0,
        -3335.0,	580000.0,
        301.0,	540000.0,
        -12849.0,	530000.0,
        -2769.0,	500000.0,
        3412.0,	480000.0,
        3947.0,	460000.0,
        -2993.0,	440000.0,
        -1154.0,	400000.0,
        -6493.0,	390000.0,
        -1519.0,	380000.0,
        6102.0,	360000.0,
        -3119.0,	320000.0,
        580.0,	270000.0,
        11796.0,	280000.0,
        4018.0,	260000.0,
        -15936.0,	230000.0,
        -47553.0,	230000.0,
        -47557.0,	220000.0,
        -54554.0,	200000.0,
        -20503.0,	170000.0,
        -4941.0,	130000.0,
        -2920.0,	100000.0,
        -2846.0,	90000.0,
        -89.0,	90000.0,
        -2193.0,	90000.0,
        -4304.0,	80000.0,
        -2803.0,	70000.0,
        -3586.0,	70000.0,
        -2602.0,	60000.0,
        -2735.0,	60000.0,
        -462.0,	80000.0,
        738.0,	90000.0
      ]

KHOU = 0
KBKF = 1
KBFI = 2
n2 = 12
d2 = 1.0
f2 = 1.0

n3 = 85
d3 = 1.0
f3 = 1930

s3 = Sampling(n3,d3,f3)
s2 = Sampling(n2,d2,f2)

BLUE_500  = Color(0x2196F3,False)
AMBER_500 = Color(0xFFC107,False)
PINK_500  = Color(0xE91E63,False)

# For testing below.
def makePlotPanel1(f):
  pp = PlotPanel()
  bv = pp.addBars(s2,f)
  bv.setFillColor(0,BLUE_500)
  bv.setFillColor(1,AMBER_500)
  bv.setFillColor(2,PINK_500)
  bv.setLineColor(Color.BLACK)
  bv.setBarWidth(0.98)
  bv.setAlignment(BarsView.Alignment.ALIGN_CENTER)
  bv.setOrientation(BarsView.Orientation.X1RIGHT_X2UP)
  bv.setStackBars(True)
  return pp

def makePlotPanel2(f):
  pp = PlotPanel()
  gv = pp.addGrid()
  gv.setVertical(GridView.Vertical.ZERO)
  gv.setColor(Color.GRAY)
  bv = pp.addBars(s3,f)
  c0 = Color(133,125,125)
  c1 = Color(250,8,8)
  bv.setColorMap(ColorMap(0,5,prettyColors(c0,c1)))
  bv.setLineColor(Color.WHITE)
  bv.setBarWidth(1.00)
  bv.setAlignment(BarsView.Alignment.ALIGN_CENTER)
  bv.setOrientation(BarsView.Orientation.X1DOWN_X2RIGHT)
  return pp

def makePlotPanel3(f):
  pp = PlotPanel()
  gv = pp.addGrid()
  gv.setVertical(GridView.Vertical.ZERO)
  gv.setColor(Color.GRAY)
  bv = pp.addBars(f)
  bv.setFillColor(BLUE_500)
  bv.setBarWidth(1.00)
  bv.setAlignment(BarsView.Alignment.ALIGN_CENTER)
  bv.setOrientation(BarsView.Orientation.X1DOWN_X2RIGHT)
  return pp

def prettyColors(c0,c1):
  r0 = c0.red/255.0
  g0 = c0.green/255.0
  b0 = c0.blue/255.0

  r1 = c1.red/255.0
  g1 = c1.green/255.0
  b1 = c1.blue/255.0

  color = []
  dr = (r1-r0) / 256.0
  dg = (g1-g0) / 256.0
  db = (b1-b0) / 256.0
  for i in range(256):
    color.append(Color(r0+i*dr,g0+i*dg,b0+i*db))
  return ColorMap.makeIndexColorModel(color)

def compileWeather():
  f = [[0 for i in xrange(12)] for i in xrange(3)]
  for i in range(12):
    f[KHOU][i] = data[KHOU+3*i]
    f[KBKF][i] = data[KBKF+3*i]
    f[KBFI][i] = data[KBFI+3*i]
  return f

def compileDeficit():
  l = len(gdp)/2
  f = [0 for i in xrange(l)]
  for i in range(l):
    f[n3-i-1] = -1*(gdp[2*i]/gdp[2*i+1])*100
  return f

def fakeData():
  f = [0 for i in xrange(10)]
  for i in range(10):
    f[i] = i-5
  return f

def test1():
  f = compileWeather()
  pp = makePlotPanel1(f)
  pp.setVLabel("Average Rainfall (inches)")
  pp.setHLabel("Month")
  pp.setTitle("2014 Average Rainfall (in)")
  pf = PlotFrame(pp)
  pf.pack();
  pf.setDefaultCloseOperation(PlotFrame.EXIT_ON_CLOSE)
  pf.setVisible(True)

def test2():
  f = compileDeficit()
  pp = makePlotPanel2(f)
  pp.setTitle("US Deficit as Percent of GDP (1930-2014)")
  pp.setHLabel("Deficit (% of GDP)")
  pp.setVLabel("Fiscal Year")
  pf = PlotFrame(pp)
  pf.pack();
  pf.setDefaultCloseOperation(PlotFrame.EXIT_ON_CLOSE)
  pf.setVisible(True)

def test3():
  f = fakeData()
  pp = makePlotPanel3(f)
  pf = PlotFrame(pp)
  pf.pack();
  pf.setDefaultCloseOperation(PlotFrame.EXIT_ON_CLOSE)
  pf.setVisible(True)

def main(args):
  test1()
<<<<<<< HEAD
  test2()
  test3()
=======
#  test2()
#  test3()
>>>>>>> origin/master

#############################################################################
class RunMain(Runnable):
  def run(self):
    main(sys.argv)
SwingUtilities.invokeLater(RunMain())
<|endoftext|>


<commit_before>import functools

from django.conf import settings
from django.utils import six
from jira import JIRA, JIRAError

from . import models

def get_active_backend():
    return globals()[settings.WALDUR_SUPPORT['ACTIVE_BACKEND']]()

class SupportBackendError(Exception):
    pass

class SupportBackend(object):
    """ Interface for support backend """
    def create_issue(self, issue):
        pass

    def update_issue(self, issue):
        pass

    def delete_issue(self, issue):
        pass

    def create_comment(self, comment):
        pass

    def update_comment(self, comment):
        pass

    def delete_comment(self, comment):
        pass

    def get_users(self):
        """
        This method should return all users that are related to support project on backend.

        Each user should be represented as not saved SupportUser instance.
        """
        pass

class JiraBackendError(SupportBackendError):
    pass

class JiraBackend(SupportBackend):
    credentials = settings.WALDUR_SUPPORT.get('CREDENTIALS', {})
    project_details = settings.WALDUR_SUPPORT.get('PROJECT', {})

    def reraise_exceptions(func):
        @functools.wraps(func)
        def wrapped(self, *args, **kwargs):
            try:
                return func(self, *args, **kwargs)
            except JIRAError as e:
                six.reraise(JiraBackendError, e)
        return wrapped

    @property
    @reraise_exceptions
    def manager(self):
        # manager will be the same for all issues - we can cache it on the class level.
        if not hasattr(self.__class__, '_manager'):
            self.__class__._manager = JIRA(
                server=self.credentials['server'],
                options={'verify': self.credentials['verify_ssl']},
                basic_auth=(self.credentials['username'], self.credentials['password']),
                validate=False)
        return self.__class__._manager

    @reraise_exceptions
    def _get_field_id_by_name(self, field_name):
        if not hasattr(self.__class__, '_fields'):
            self.__class__._fields = self.manager.fields()
        try:
            return next(f['id'] for f in self.__class__._fields if field_name in f['clauseNames'])
        except StopIteration:
            return JiraBackendError('Field "%s" does not exist in JIRA.' % field_name)

    def _issue_to_dict(self, issue):
        """ Convert issue to dict that can be accepted by JIRA as input parameters """
        args = {
            'project': self.project_details['key'],
            'summary': issue.summary,
            'description': issue.description,
            'issuetype': {'name': issue.type},
        }
        if issue.reporter:
            args[self._get_field_id_by_name(self.project_details['reporter_field'])] = issue.reporter.name
            # args['reporter'] = {'name': issue.reporter.name}
        if issue.caller:
            name = issue.caller.full_name or issue.caller.username
            args[self._get_field_id_by_name(self.project_details['caller_field'])] = name
        if issue.impact:
            args[self._get_field_id_by_name(self.project_details['impact_field'])] = issue.impact
        if issue.priority:
            args['priority'] = {'name': issue.priority}
        return args

    @reraise_exceptions
    def create_issue(self, issue):
        backend_issue = self.manager.create_issue(**self._issue_to_dict(issue))
        if issue.assignee:
            self.manager.assign_issue(backend_issue.key, issue.assignee.backend_id)
        issue.key = backend_issue.key
        issue.backend_id = backend_issue.key
        issue.resolution = backend_issue.fields.resolution or ''
        issue.status = backend_issue.fields.status.name or ''
        issue.link = backend_issue.permalink()
        issue.priority = backend_issue.fields.priority.name
        issue.save()

    @reraise_exceptions
    def update_issue(self, issue):
        backend_issue = self.manager.issue(issue.backend_id)
        backend_issue.update(summary=issue.summary, description=issue.description)

    @reraise_exceptions
    def delete_issue(self, issue):
        backend_issue = self.manager.issue(issue.backend_id)
        backend_issue.delete()

    def _prepare_comment_message(self, comment):
        return comment.description

    @reraise_exceptions
    def create_comment(self, comment):
        backend_comment = self.manager.add_comment(comment.issue.backend_id, self._prepare_comment_message(comment))
        comment.backend_id = backend_comment.id
        comment.save(update_fields=['backend_id'])

    @reraise_exceptions
    def update_comment(self, comment):
        backend_comment = self.manager.comment(comment.issue.backend_id, comment.backend_id)
        backend_comment.update(body=self._prepare_comment_message(comment))

    @reraise_exceptions
    def delete_comment(self, comment):
        backend_comment = self.manager.comment(comment.issue.backend_id, comment.backend_id)
        backend_comment.delete()

    @reraise_exceptions
    def get_users(self):
        users = self.manager.search_assignable_users_for_projects('', self.project_details['key'])
        return [models.SupportUser(name=user.displayName, backend_id=user.key) for user in users]
<commit_msg>Make sure that backend will return all users<commit_after>import functools

from django.conf import settings
from django.utils import six
from jira import JIRA, JIRAError

from . import models

def get_active_backend():
    return globals()[settings.WALDUR_SUPPORT['ACTIVE_BACKEND']]()

class SupportBackendError(Exception):
    pass

class SupportBackend(object):
    """ Interface for support backend """
    def create_issue(self, issue):
        pass

    def update_issue(self, issue):
        pass

    def delete_issue(self, issue):
        pass

    def create_comment(self, comment):
        pass

    def update_comment(self, comment):
        pass

    def delete_comment(self, comment):
        pass

    def get_users(self):
        """
        This method should return all users that are related to support project on backend.

        Each user should be represented as not saved SupportUser instance.
        """
        pass

class JiraBackendError(SupportBackendError):
    pass

class JiraBackend(SupportBackend):
    credentials = settings.WALDUR_SUPPORT.get('CREDENTIALS', {})
    project_details = settings.WALDUR_SUPPORT.get('PROJECT', {})

    def reraise_exceptions(func):
        @functools.wraps(func)
        def wrapped(self, *args, **kwargs):
            try:
                return func(self, *args, **kwargs)
            except JIRAError as e:
                six.reraise(JiraBackendError, e)
        return wrapped

    @property
    @reraise_exceptions
    def manager(self):
        # manager will be the same for all issues - we can cache it on the class level.
        if not hasattr(self.__class__, '_manager'):
            self.__class__._manager = JIRA(
                server=self.credentials['server'],
                options={'verify': self.credentials['verify_ssl']},
                basic_auth=(self.credentials['username'], self.credentials['password']),
                validate=False)
        return self.__class__._manager

    @reraise_exceptions
    def _get_field_id_by_name(self, field_name):
        if not hasattr(self.__class__, '_fields'):
            self.__class__._fields = self.manager.fields()
        try:
            return next(f['id'] for f in self.__class__._fields if field_name in f['clauseNames'])
        except StopIteration:
            return JiraBackendError('Field "%s" does not exist in JIRA.' % field_name)

    def _issue_to_dict(self, issue):
        """ Convert issue to dict that can be accepted by JIRA as input parameters """
        args = {
            'project': self.project_details['key'],
            'summary': issue.summary,
            'description': issue.description,
            'issuetype': {'name': issue.type},
        }
        if issue.reporter:
            args[self._get_field_id_by_name(self.project_details['reporter_field'])] = issue.reporter.name
            # args['reporter'] = {'name': issue.reporter.name}
        if issue.caller:
            name = issue.caller.full_name or issue.caller.username
            args[self._get_field_id_by_name(self.project_details['caller_field'])] = name
        if issue.impact:
            args[self._get_field_id_by_name(self.project_details['impact_field'])] = issue.impact
        if issue.priority:
            args['priority'] = {'name': issue.priority}
        return args

    @reraise_exceptions
    def create_issue(self, issue):
        backend_issue = self.manager.create_issue(**self._issue_to_dict(issue))
        if issue.assignee:
            self.manager.assign_issue(backend_issue.key, issue.assignee.backend_id)
        issue.key = backend_issue.key
        issue.backend_id = backend_issue.key
        issue.resolution = backend_issue.fields.resolution or ''
        issue.status = backend_issue.fields.status.name or ''
        issue.link = backend_issue.permalink()
        issue.priority = backend_issue.fields.priority.name
        issue.save()

    @reraise_exceptions
    def update_issue(self, issue):
        backend_issue = self.manager.issue(issue.backend_id)
        backend_issue.update(summary=issue.summary, description=issue.description)

    @reraise_exceptions
    def delete_issue(self, issue):
        backend_issue = self.manager.issue(issue.backend_id)
        backend_issue.delete()

    def _prepare_comment_message(self, comment):
        return comment.description

    @reraise_exceptions
    def create_comment(self, comment):
        backend_comment = self.manager.add_comment(comment.issue.backend_id, self._prepare_comment_message(comment))
        comment.backend_id = backend_comment.id
        comment.save(update_fields=['backend_id'])

    @reraise_exceptions
    def update_comment(self, comment):
        backend_comment = self.manager.comment(comment.issue.backend_id, comment.backend_id)
        backend_comment.update(body=self._prepare_comment_message(comment))

    @reraise_exceptions
    def delete_comment(self, comment):
        backend_comment = self.manager.comment(comment.issue.backend_id, comment.backend_id)
        backend_comment.delete()

    @reraise_exceptions
    def get_users(self):
        users = self.manager.search_assignable_users_for_projects('', self.project_details['key'], maxResults=False)
        return [models.SupportUser(name=user.displayName, backend_id=user.key) for user in users]
<|endoftext|>