<commit_before>__author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>"
__date__ = "$Aug 05, 2014 17:38:58 EDT$"

import ctypes
import multiprocessing

import numpy

import spams_sandbox
import spams_sandbox.spams_sandbox

import synthetic_data

class TestSpamsSandbox(object):
    def setup(self):
        self.p = numpy.array([[27, 51],
                              [66, 85],
                              [77, 45]])

        self.p3 = numpy.array([[27, 51, 37],
                               [66, 85, 25],
                               [77, 45, 73]])

        self.space = numpy.array((100, 100))
        self.space3 = numpy.array((100, 100, 100))
        self.radii = numpy.array((5, 6, 7))

        self.g = synthetic_data.generate_hypersphere_masks(self.space, self.p, self.radii)

        self.g = self.g.reshape((self.g.shape[0], -1))
        self.g = self.g.transpose()
        self.g = numpy.asmatrix(self.g)
        self.g = numpy.asfortranarray(self.g)

        self.g3 = synthetic_data.generate_hypersphere_masks(self.space3, self.p3, self.radii)

        self.g3 = self.g3.reshape((self.g3.shape[0], -1))
        self.g3 = self.g3.transpose()
        self.g3 = numpy.asmatrix(self.g3)
        self.g3 = numpy.asfortranarray(self.g3)

    def test_run_multiprocessing_queue_spams_trainDL_1(self):
        out_queue = multiprocessing.Queue()

        spams_sandbox.spams_sandbox.run_multiprocessing_queue_spams_trainDL(out_queue,
                                                                            self.g.astype(float),
                                                                            **{
                                                                                "gamma2" : 0,
                                                                                "gamma1" : 0,
                                                                                "numThreads" : -1,
                                                                                "K" : self.g.shape[1],
                                                                                "iter" : 10,
                                                                                "modeD" : 0,
                                                                                "posAlpha" : True,
                                                                                "clean" : True,
                                                                                "posD" : True,
                                                                                "batchsize" : 256,
                                                                                "lambda1" : 0.2,
                                                                                "lambda2" : 0,
                                                                                "mode" : 2
                                                                               }
        )
        d = out_queue.get()

        d = (d != 0)

        self.g = self.g.transpose()
        d = d.transpose()

        assert(self.g.shape == d.shape)

        assert((self.g.astype(bool).max(axis = 0) == d.astype(bool).max(axis = 0)).all())

        unmatched_g = range(len(self.g))
        matched = dict()

        for i in xrange(len(d)):
            new_unmatched_g = []
            for j in unmatched_g:
                if not (d[i] == self.g[j]).all():
                    new_unmatched_g.append(j)
                else:
                    matched[i] = j

            unmatched_g = new_unmatched_g

        print unmatched_g

        assert(len(unmatched_g) == 0)

    def test_run_multiprocessing_queue_spams_trainDL_2(self):
        out_queue = multiprocessing.Queue()

        spams_sandbox.spams_sandbox.run_multiprocessing_queue_spams_trainDL(out_queue,
                                                                            self.g3.astype(float),
                                                                            **{
                                                                                "gamma2" : 0,
                                                                                "gamma1" : 0,
                                                                                "numThreads" : -1,
                                                                                "K" : self.g3.shape[1],
                                                                                "iter" : 10,
                                                                                "modeD" : 0,
                                                                                "posAlpha" : True,
                                                                                "clean" : True,
                                                                                "posD" : True,
                                                                                "batchsize" : 256,
                                                                                "lambda1" : 0.2,
                                                                                "lambda2" : 0,
                                                                                "mode" : 2
                                                                               }
        )
        d3 = out_queue.get()

        d3 = (d3 != 0)

        self.g3 = self.g3.transpose()
        d3 = d3.transpose()

        assert(self.g3.shape == d3.shape)

        assert((self.g3.astype(bool).max(axis = 0) == d3.astype(bool).max(axis = 0)).all())

        unmatched_g3 = range(len(self.g3))
        matched = dict()

        for i in xrange(len(d3)):
            new_unmatched_g3 = []
            for j in unmatched_g3:
                if not (d3[i] == self.g3[j]).all():
                    new_unmatched_g3.append(j)
                else:
                    matched[i] = j

            unmatched_g3 = new_unmatched_g3

        print unmatched_g3

        assert(len(unmatched_g3) == 0)

    def test_call_multiprocessing_queue_spams_trainDL_1(self):
        d = spams_sandbox.spams_sandbox.call_multiprocessing_queue_spams_trainDL(self.g.astype(float),
                                                                                **{
                                                                                "gamma2" : 0,
                                                                                "gamma1" : 0,
                                                                                "numThreads" : -1,
                                                                                "K" : self.g.shape[1],
                                                                                "iter" : 10,
                                                                                "modeD" : 0,
                                                                                "posAlpha" : True,
                                                                                "clean" : True,
                                                                                "posD" : True,
                                                                                "batchsize" : 256,
                                                                                "lambda1" : 0.2,
                                                                                "lambda2" : 0,
                                                                                "mode" : 2
                                                                                }
        )
        d = (d != 0)

        self.g = self.g.transpose()
        d = d.transpose()

        assert(self.g.shape == d.shape)

        assert((self.g.astype(bool).max(axis = 0) == d.astype(bool).max(axis = 0)).all())

        unmatched_g = range(len(self.g))
        matched = dict()

        for i in xrange(len(d)):
            new_unmatched_g = []
            for j in unmatched_g:
                if not (d[i] == self.g[j]).all():
                    new_unmatched_g.append(j)
                else:
                    matched[i] = j

            unmatched_g = new_unmatched_g

        print unmatched_g

        assert(len(unmatched_g) == 0)

    def test_call_multiprocessing_queue_spams_trainDL_2(self):
        d3 = spams_sandbox.spams_sandbox.call_multiprocessing_queue_spams_trainDL(self.g3.astype(float),
                                                                                **{
                                                                                "gamma2" : 0,
                                                                                "gamma1" : 0,
                                                                                "numThreads" : -1,
                                                                                "K" : self.g3.shape[1],
                                                                                "iter" : 10,
                                                                                "modeD" : 0,
                                                                                "posAlpha" : True,
                                                                                "clean" : True,
                                                                                "posD" : True,
                                                                                "batchsize" : 256,
                                                                                "lambda1" : 0.2,
                                                                                "lambda2" : 0,
                                                                                "mode" : 2
                                                                                }
        )
        d3 = (d3 != 0)

        self.g3 = self.g3.transpose()
        d3 = d3.transpose()

        assert(self.g3.shape == d3.shape)

        assert((self.g3.astype(bool).max(axis = 0) == d3.astype(bool).max(axis = 0)).all())

        unmatched_g3 = range(len(self.g3))
        matched = dict()

        for i in xrange(len(d3)):
            new_unmatched_g3 = []
            for j in unmatched_g3:
                if not (d3[i] == self.g3[j]).all():
                    new_unmatched_g3.append(j)
                else:
                    matched[i] = j

            unmatched_g3 = new_unmatched_g3

        print unmatched_g3

        assert(len(unmatched_g3) == 0)

    def test_run_multiprocessing_array_spams_trainDL(self):
        output_array_size = self.g.shape[0] * self.g.shape[1]
        output_array = multiprocessing.Array(ctypes.c_double, output_array_size)

        spams_sandbox.spams_sandbox.run_multiprocessing_array_spams_trainDL(output_array,
                                                                            self.g.astype(float),
                                                                            **{
                                                                                "gamma2" : 0,
                                                                                "gamma1" : 0,
                                                                                "numThreads" : -1,
                                                                                "K" : self.g.shape[1],
                                                                                "iter" : 10,
                                                                                "modeD" : 0,
                                                                                "posAlpha" : True,
                                                                                "clean" : True,
                                                                                "posD" : True,
                                                                                "batchsize" : 256,
                                                                                "lambda1" : 0.2,
                                                                                "lambda2" : 0,
                                                                                "mode" : 2
                                                                               }
        )
        d = numpy.frombuffer(output_array.get_obj(), dtype = ctypes.c_double).reshape((-1, self.g.shape[1])).copy()
        d = (d != 0)

        self.g = self.g.transpose()
        d = d.transpose()

        assert(self.g.shape == d.shape)

        assert((self.g.astype(bool).max(axis = 0) == d.astype(bool).max(axis = 0)).all())

        unmatched_g = range(len(self.g))
        matched = dict()

        for i in xrange(len(d)):
            new_unmatched_g = []
            for j in unmatched_g:
                if not (d[i] == self.g[j]).all():
                    new_unmatched_g.append(j)
                else:
                    matched[i] = j

            unmatched_g = new_unmatched_g

        print unmatched_g

        assert(len(unmatched_g) == 0)

    def test_call_multiprocessing_array_spams_trainDL(self):
        d = spams_sandbox.spams_sandbox.call_multiprocessing_array_spams_trainDL(self.g.astype(float),
                                                                                **{
                                                                                "gamma2" : 0,
                                                                                "gamma1" : 0,
                                                                                "numThreads" : -1,
                                                                                "K" : self.g.shape[1],
                                                                                "iter" : 10,
                                                                                "modeD" : 0,
                                                                                "posAlpha" : True,
                                                                                "clean" : True,
                                                                                "posD" : True,
                                                                                "batchsize" : 256,
                                                                                "lambda1" : 0.2,
                                                                                "lambda2" : 0,
                                                                                "mode" : 2
                                                                                }
        )
        d = (d != 0)

        self.g = self.g.transpose()
        d = d.transpose()

        assert(self.g.shape == d.shape)

        assert((self.g.astype(bool).max(axis = 0) == d.astype(bool).max(axis = 0)).all())

        unmatched_g = range(len(self.g))
        matched = dict()

        for i in xrange(len(d)):
            new_unmatched_g = []
            for j in unmatched_g:
                if not (d[i] == self.g[j]).all():
                    new_unmatched_g.append(j)
                else:
                    matched[i] = j

            unmatched_g = new_unmatched_g

        print unmatched_g

        assert(len(unmatched_g) == 0)

    def test_call_spams_trainDL(self):
        d = spams_sandbox.spams_sandbox.call_spams_trainDL(self.g.astype(float),
                                                           **{
                                                                "gamma2" : 0,
                                                                "gamma1" : 0,
                                                                "numThreads" : -1,
                                                                "K" : self.g.shape[1],
                                                                "iter" : 10,
                                                                "modeD" : 0,
                                                                "posAlpha" : True,
                                                                "clean" : True,
                                                                "posD" : True,
                                                                "batchsize" : 256,
                                                                "lambda1" : 0.2,
                                                                "lambda2" : 0,
                                                                "mode" : 2
                                                              }
        )
        d = (d != 0)

        self.g = self.g.transpose()
        d = d.transpose()

        assert(self.g.shape == d.shape)

        assert((self.g.astype(bool).max(axis = 0) == d.astype(bool).max(axis = 0)).all())

        unmatched_g = range(len(self.g))
        matched = dict()

        for i in xrange(len(d)):
            new_unmatched_g = []
            for j in unmatched_g:
                if not (d[i] == self.g[j]).all():
                    new_unmatched_g.append(j)
                else:
                    matched[i] = j

            unmatched_g = new_unmatched_g

        print unmatched_g

        assert(len(unmatched_g) == 0)

    def teardown(self):
        self.p = None
        self.space = None
        self.radii = None
        self.g = None

        self.p3 = None
        self.g3 = None
<commit_msg>tests/test_spams_sandbox.py: Added a test for spams_sandbox.spams_sandbox.run_multiprocessing_array_spams_trainDL using 3D data.<commit_after>__author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>"
__date__ = "$Aug 05, 2014 17:38:58 EDT$"

import ctypes
import multiprocessing

import numpy

import spams_sandbox
import spams_sandbox.spams_sandbox

import synthetic_data

class TestSpamsSandbox(object):
    def setup(self):
        self.p = numpy.array([[27, 51],
                              [66, 85],
                              [77, 45]])

        self.p3 = numpy.array([[27, 51, 37],
                               [66, 85, 25],
                               [77, 45, 73]])

        self.space = numpy.array((100, 100))
        self.space3 = numpy.array((100, 100, 100))
        self.radii = numpy.array((5, 6, 7))

        self.g = synthetic_data.generate_hypersphere_masks(self.space, self.p, self.radii)

        self.g = self.g.reshape((self.g.shape[0], -1))
        self.g = self.g.transpose()
        self.g = numpy.asmatrix(self.g)
        self.g = numpy.asfortranarray(self.g)

        self.g3 = synthetic_data.generate_hypersphere_masks(self.space3, self.p3, self.radii)

        self.g3 = self.g3.reshape((self.g3.shape[0], -1))
        self.g3 = self.g3.transpose()
        self.g3 = numpy.asmatrix(self.g3)
        self.g3 = numpy.asfortranarray(self.g3)

    def test_run_multiprocessing_queue_spams_trainDL_1(self):
        out_queue = multiprocessing.Queue()

        spams_sandbox.spams_sandbox.run_multiprocessing_queue_spams_trainDL(out_queue,
                                                                            self.g.astype(float),
                                                                            **{
                                                                                "gamma2" : 0,
                                                                                "gamma1" : 0,
                                                                                "numThreads" : -1,
                                                                                "K" : self.g.shape[1],
                                                                                "iter" : 10,
                                                                                "modeD" : 0,
                                                                                "posAlpha" : True,
                                                                                "clean" : True,
                                                                                "posD" : True,
                                                                                "batchsize" : 256,
                                                                                "lambda1" : 0.2,
                                                                                "lambda2" : 0,
                                                                                "mode" : 2
                                                                               }
        )
        d = out_queue.get()

        d = (d != 0)

        self.g = self.g.transpose()
        d = d.transpose()

        assert(self.g.shape == d.shape)

        assert((self.g.astype(bool).max(axis = 0) == d.astype(bool).max(axis = 0)).all())

        unmatched_g = range(len(self.g))
        matched = dict()

        for i in xrange(len(d)):
            new_unmatched_g = []
            for j in unmatched_g:
                if not (d[i] == self.g[j]).all():
                    new_unmatched_g.append(j)
                else:
                    matched[i] = j

            unmatched_g = new_unmatched_g

        print unmatched_g

        assert(len(unmatched_g) == 0)

    def test_run_multiprocessing_queue_spams_trainDL_2(self):
        out_queue = multiprocessing.Queue()

        spams_sandbox.spams_sandbox.run_multiprocessing_queue_spams_trainDL(out_queue,
                                                                            self.g3.astype(float),
                                                                            **{
                                                                                "gamma2" : 0,
                                                                                "gamma1" : 0,
                                                                                "numThreads" : -1,
                                                                                "K" : self.g3.shape[1],
                                                                                "iter" : 10,
                                                                                "modeD" : 0,
                                                                                "posAlpha" : True,
                                                                                "clean" : True,
                                                                                "posD" : True,
                                                                                "batchsize" : 256,
                                                                                "lambda1" : 0.2,
                                                                                "lambda2" : 0,
                                                                                "mode" : 2
                                                                               }
        )
        d3 = out_queue.get()

        d3 = (d3 != 0)

        self.g3 = self.g3.transpose()
        d3 = d3.transpose()

        assert(self.g3.shape == d3.shape)

        assert((self.g3.astype(bool).max(axis = 0) == d3.astype(bool).max(axis = 0)).all())

        unmatched_g3 = range(len(self.g3))
        matched = dict()

        for i in xrange(len(d3)):
            new_unmatched_g3 = []
            for j in unmatched_g3:
                if not (d3[i] == self.g3[j]).all():
                    new_unmatched_g3.append(j)
                else:
                    matched[i] = j

            unmatched_g3 = new_unmatched_g3

        print unmatched_g3

        assert(len(unmatched_g3) == 0)

    def test_call_multiprocessing_queue_spams_trainDL_1(self):
        d = spams_sandbox.spams_sandbox.call_multiprocessing_queue_spams_trainDL(self.g.astype(float),
                                                                                **{
                                                                                "gamma2" : 0,
                                                                                "gamma1" : 0,
                                                                                "numThreads" : -1,
                                                                                "K" : self.g.shape[1],
                                                                                "iter" : 10,
                                                                                "modeD" : 0,
                                                                                "posAlpha" : True,
                                                                                "clean" : True,
                                                                                "posD" : True,
                                                                                "batchsize" : 256,
                                                                                "lambda1" : 0.2,
                                                                                "lambda2" : 0,
                                                                                "mode" : 2
                                                                                }
        )
        d = (d != 0)

        self.g = self.g.transpose()
        d = d.transpose()

        assert(self.g.shape == d.shape)

        assert((self.g.astype(bool).max(axis = 0) == d.astype(bool).max(axis = 0)).all())

        unmatched_g = range(len(self.g))
        matched = dict()

        for i in xrange(len(d)):
            new_unmatched_g = []
            for j in unmatched_g:
                if not (d[i] == self.g[j]).all():
                    new_unmatched_g.append(j)
                else:
                    matched[i] = j

            unmatched_g = new_unmatched_g

        print unmatched_g

        assert(len(unmatched_g) == 0)

    def test_call_multiprocessing_queue_spams_trainDL_2(self):
        d3 = spams_sandbox.spams_sandbox.call_multiprocessing_queue_spams_trainDL(self.g3.astype(float),
                                                                                **{
                                                                                "gamma2" : 0,
                                                                                "gamma1" : 0,
                                                                                "numThreads" : -1,
                                                                                "K" : self.g3.shape[1],
                                                                                "iter" : 10,
                                                                                "modeD" : 0,
                                                                                "posAlpha" : True,
                                                                                "clean" : True,
                                                                                "posD" : True,
                                                                                "batchsize" : 256,
                                                                                "lambda1" : 0.2,
                                                                                "lambda2" : 0,
                                                                                "mode" : 2
                                                                                }
        )
        d3 = (d3 != 0)

        self.g3 = self.g3.transpose()
        d3 = d3.transpose()

        assert(self.g3.shape == d3.shape)

        assert((self.g3.astype(bool).max(axis = 0) == d3.astype(bool).max(axis = 0)).all())

        unmatched_g3 = range(len(self.g3))
        matched = dict()

        for i in xrange(len(d3)):
            new_unmatched_g3 = []
            for j in unmatched_g3:
                if not (d3[i] == self.g3[j]).all():
                    new_unmatched_g3.append(j)
                else:
                    matched[i] = j

            unmatched_g3 = new_unmatched_g3

        print unmatched_g3

        assert(len(unmatched_g3) == 0)

    def test_run_multiprocessing_array_spams_trainDL_1(self):
        output_array_size = self.g.shape[0] * self.g.shape[1]
        output_array = multiprocessing.Array(ctypes.c_double, output_array_size)

        spams_sandbox.spams_sandbox.run_multiprocessing_array_spams_trainDL(output_array,
                                                                            self.g.astype(float),
                                                                            **{
                                                                                "gamma2" : 0,
                                                                                "gamma1" : 0,
                                                                                "numThreads" : -1,
                                                                                "K" : self.g.shape[1],
                                                                                "iter" : 10,
                                                                                "modeD" : 0,
                                                                                "posAlpha" : True,
                                                                                "clean" : True,
                                                                                "posD" : True,
                                                                                "batchsize" : 256,
                                                                                "lambda1" : 0.2,
                                                                                "lambda2" : 0,
                                                                                "mode" : 2
                                                                               }
        )
        d = numpy.frombuffer(output_array.get_obj(), dtype = ctypes.c_double).reshape((-1, self.g.shape[1])).copy()
        d = (d != 0)

        self.g = self.g.transpose()
        d = d.transpose()

        assert(self.g.shape == d.shape)

        assert((self.g.astype(bool).max(axis = 0) == d.astype(bool).max(axis = 0)).all())

        unmatched_g = range(len(self.g))
        matched = dict()

        for i in xrange(len(d)):
            new_unmatched_g = []
            for j in unmatched_g:
                if not (d[i] == self.g[j]).all():
                    new_unmatched_g.append(j)
                else:
                    matched[i] = j

            unmatched_g = new_unmatched_g

        print unmatched_g

        assert(len(unmatched_g) == 0)

    def test_run_multiprocessing_array_spams_trainDL_2(self):
        output_array_size = self.g3.shape[0] * self.g3.shape[1]
        output_array = multiprocessing.Array(ctypes.c_double, output_array_size)

        spams_sandbox.spams_sandbox.run_multiprocessing_array_spams_trainDL(output_array,
                                                                            self.g3.astype(float),
                                                                            **{
                                                                                "gamma2" : 0,
                                                                                "gamma1" : 0,
                                                                                "numThreads" : -1,
                                                                                "K" : self.g3.shape[1],
                                                                                "iter" : 10,
                                                                                "modeD" : 0,
                                                                                "posAlpha" : True,
                                                                                "clean" : True,
                                                                                "posD" : True,
                                                                                "batchsize" : 256,
                                                                                "lambda1" : 0.2,
                                                                                "lambda2" : 0,
                                                                                "mode" : 2
                                                                               }
        )
        d3 = numpy.frombuffer(output_array.get_obj(), dtype = ctypes.c_double).reshape((-1, self.g3.shape[1])).copy()
        d3 = (d3 != 0)

        self.g3 = self.g3.transpose()
        d3 = d3.transpose()

        assert(self.g3.shape == d3.shape)

        assert((self.g3.astype(bool).max(axis = 0) == d3.astype(bool).max(axis = 0)).all())

        unmatched_g3 = range(len(self.g3))
        matched = dict()

        for i in xrange(len(d3)):
            new_unmatched_g3 = []
            for j in unmatched_g3:
                if not (d3[i] == self.g3[j]).all():
                    new_unmatched_g3.append(j)
                else:
                    matched[i] = j

            unmatched_g3 = new_unmatched_g3

        print unmatched_g3

        assert(len(unmatched_g3) == 0)

    def test_call_multiprocessing_array_spams_trainDL(self):
        d = spams_sandbox.spams_sandbox.call_multiprocessing_array_spams_trainDL(self.g.astype(float),
                                                                                **{
                                                                                "gamma2" : 0,
                                                                                "gamma1" : 0,
                                                                                "numThreads" : -1,
                                                                                "K" : self.g.shape[1],
                                                                                "iter" : 10,
                                                                                "modeD" : 0,
                                                                                "posAlpha" : True,
                                                                                "clean" : True,
                                                                                "posD" : True,
                                                                                "batchsize" : 256,
                                                                                "lambda1" : 0.2,
                                                                                "lambda2" : 0,
                                                                                "mode" : 2
                                                                                }
        )
        d = (d != 0)

        self.g = self.g.transpose()
        d = d.transpose()

        assert(self.g.shape == d.shape)

        assert((self.g.astype(bool).max(axis = 0) == d.astype(bool).max(axis = 0)).all())

        unmatched_g = range(len(self.g))
        matched = dict()

        for i in xrange(len(d)):
            new_unmatched_g = []
            for j in unmatched_g:
                if not (d[i] == self.g[j]).all():
                    new_unmatched_g.append(j)
                else:
                    matched[i] = j

            unmatched_g = new_unmatched_g

        print unmatched_g

        assert(len(unmatched_g) == 0)

    def test_call_spams_trainDL(self):
        d = spams_sandbox.spams_sandbox.call_spams_trainDL(self.g.astype(float),
                                                           **{
                                                                "gamma2" : 0,
                                                                "gamma1" : 0,
                                                                "numThreads" : -1,
                                                                "K" : self.g.shape[1],
                                                                "iter" : 10,
                                                                "modeD" : 0,
                                                                "posAlpha" : True,
                                                                "clean" : True,
                                                                "posD" : True,
                                                                "batchsize" : 256,
                                                                "lambda1" : 0.2,
                                                                "lambda2" : 0,
                                                                "mode" : 2
                                                              }
        )
        d = (d != 0)

        self.g = self.g.transpose()
        d = d.transpose()

        assert(self.g.shape == d.shape)

        assert((self.g.astype(bool).max(axis = 0) == d.astype(bool).max(axis = 0)).all())

        unmatched_g = range(len(self.g))
        matched = dict()

        for i in xrange(len(d)):
            new_unmatched_g = []
            for j in unmatched_g:
                if not (d[i] == self.g[j]).all():
                    new_unmatched_g.append(j)
                else:
                    matched[i] = j

            unmatched_g = new_unmatched_g

        print unmatched_g

        assert(len(unmatched_g) == 0)

    def teardown(self):
        self.p = None
        self.space = None
        self.radii = None
        self.g = None

        self.p3 = None
        self.g3 = None
<|endoftext|>


<commit_before>import xlrd
import math
def angstronIndex (airTemperature, relactiveHumidity):
    ###This function calculates the Angstron Index for a given air temperature and relactive humidity, , measured at 12h.
    result = 0.05 * relactiveHumidity - 0.1 * (airTemperature - 27)
    print('O indice de Angstron do dia eh: ', round(result, 2))

def telicynIndex(airTemperature, dewPoint, N):
    ###This function calculates the Angstron Index for a set of air temperature and dew point, measured at 13h.
    i = 0
    result = 0.0
    while i < N:
        result = math.log(airTemperature - dewPoint, 10) + result
        i = i + 1
    print('O indice de Telicyn do dia e: ', round(result, 2))

def nesterofIndex(airTemperature, airDeficit, N):
    ###This function calculates the Angstron Index for a set of air temperature and air deficit, measured at 13h.
    i = 0
    result = 0.0
    while i < N:
        result = airDeficit - airTemperature + result

    print('O indice de Nesterof e: ', result)

def monteAlegre(relactiveHumidity, N):
    i = 0
    result = 0.0
    while i < N:
        result = (100 / relactiveHumidity) + result
        i = i + 1
    print('Monte Alegre Formula is: ', round(result,2))

workbook = xlrd.open_workbook('/home/thiago/Desktop/Meteorologia/Documents/__RJ_A601_ECOLOGIA_AGRICOLA.xls')
worksheet = workbook.sheet_by_index(0)

airTemp12 = worksheet.cell(12, 13).value
umiRel = worksheet.cell(12, 37).value

airTemp13 = worksheet.cell(12, 14).value
dewPt = worksheet.cell(12, 62).value

umiRel13 = worksheet.cell(12, 38).value

angstronIndex(airTemp12, umiRel)
telicynIndex(airTemp13, dewPt, 1)
#nesterofIndex(airTemp13, )
monteAlegre(umiRel13, 1)
<commit_msg>Correcting typos<commit_after>import xlrd
import math
def angstronIndex (airTemperature, relactiveHumidity):
    ###This function calculates the Angstron Index for a given air temperature and relactive humidity, , measured at 12h.
    result = 0.05 * relactiveHumidity - 0.1 * (airTemperature - 27)
    print('Angstron Index is:', round(result, 2))

def telicynIndex(airTemperature, dewPoint, N):
    ###This function calculates the Telicyn Index for a set of air temperature and dew point, measured at 13h.
    i = 0
    result = 0.0
    while i < N:
        result = math.log(airTemperature - dewPoint, 10) + result
        i = i + 1
    print('Telicyn index is:', round(result, 2))

def nesterovIndex(airTemperature, airDeficit, N):
    ###This function calculates the Nesterov Index for a set of air temperature and air deficit, measured at 13h.
    i = 0
    result = 0.0
    while i < N:
        #falta calcular o airDeficit
        result = airDeficit - airTemperature + result

    print('Nesterov Index is:', result)

def monteAlegre(relactiveHumidity, N):
        ###This function calculates the Monte Alegre's Formula for a set of relactive humidity, measured at 13h.
    i = 0
    result = 0.0
    while i < N:
        result = (100 / relactiveHumidity) + result
        i = i + 1
    print('Monte Alegre Formula is:', round(result,2))

print("""\t\tHi! This is the Index Incendies Calculator - IIC.
Please follow the below instructions in order to calculate one of the available indexes.
Tell us where the .XLS (Excel File) is located in your computer.
Remeber to use /home/user/Documents/<archieve_name>.xls for Linux or C:/Documents/<archieve_name>.xls for Windows""")

workbook = xlrd.open_workbook('/home/thiago/Desktop/Meteorologia/Documents/__RJ_A601_ECOLOGIA_AGRICOLA.xls')
worksheet = workbook.sheet_by_index(0)

airTemp12 = worksheet.cell(12, 13).value
umiRel = worksheet.cell(12, 37).value

airTemp13 = worksheet.cell(12, 14).value
dewPt = worksheet.cell(12, 62).value

umiRel13 = worksheet.cell(12, 38).value

angstronIndex(airTemp12, umiRel)
telicynIndex(airTemp13, dewPt, 1)
#nesterofIndex(airTemp13, )
monteAlegre(umiRel13, 1)
<|endoftext|>


<commit_before>#!/usr/bin/python3

from functools import wraps
from flask import Flask, render_template, request, redirect, send_file, Response, jsonify
import variables as var
import util
from datetime import datetime
import os
import os.path
import shutil
import random
from werkzeug.utils import secure_filename
import errno
import media
import logging
import time

class ReverseProxied(object):
    '''Wrap the application in this middleware and configure the
    front-end server to add these headers, to let you quietly bind
    this to a URL other than / and to an HTTP scheme that is
    different than what is used locally.

    In nginx:
    location /myprefix {
        proxy_pass http://192.168.0.1:5001;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Scheme $scheme;
        proxy_set_header X-Script-Name /myprefix;
        }

    :param app: the WSGI application
    '''

    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
        if script_name:
            environ['SCRIPT_NAME'] = script_name
            path_info = environ['PATH_INFO']
            if path_info.startswith(script_name):
                environ['PATH_INFO'] = path_info[len(script_name):]

        scheme = environ.get('HTTP_X_SCHEME', '')
        if scheme:
            environ['wsgi.url_scheme'] = scheme
        real_ip = environ.get('HTTP_X_REAL_IP', '')
        if real_ip:
            environ['REMOTE_ADDR'] = real_ip
        return self.app(environ, start_response)

web = Flask(__name__)

def init_proxy():
    global web
    if var.is_proxified:
        web.wsgi_app = ReverseProxied(web.wsgi_app)

# https://stackoverflow.com/questions/29725217/password-protect-one-webpage-in-flask-app

def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    return username == var.config.get("webinterface", "user") and password == var.config.get("webinterface", "password")

def authenticate():
    """Sends a 401 response that enables basic auth"""
    logging.info("Web Interface login failed.")
    return Response(
    'Could not verify your access level for that URL.\n'
    'You have to login with proper credentials', 401,
    {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if var.config.getboolean("webinterface", "require_auth") and (not auth or not check_auth(auth.username, auth.password)):
            if auth:
                logging.info("Web Interface login attempt, user: %s" % auth.username)
            return authenticate()
        return f(*args, **kwargs)
    return decorated

@web.route("/", methods=['GET'])
@requires_auth
def index():
    folder_path = var.music_folder
    files = util.get_recursive_filelist_sorted(var.music_folder)
    music_library = util.Dir(folder_path)
    for file in files:
        music_library.add_file(file)

    return render_template('index.html',
                           all_files=files,
                           music_library=music_library,
                           os=os,
                           playlist=var.playlist,
                           user=var.user
                           )

@web.route("/playlist", methods=['GET'])
@requires_auth
def playlist():
    if var.playlist.length() == 0:
        return jsonify([render_template('playlist.html',
                               m=False,
                               index=-1
                               )]
                       )

    data = []

    for index, item in enumerate(var.playlist.playlist):
         data.append(render_template('playlist.html',
                                     index=index,
                                     m=item,
                                     playlist=var.playlist
                                     )
                     )

    return jsonify(data)

@web.route("/post", methods=['POST'])
@requires_auth
def post():
    folder_path = var.music_folder
    files = util.get_recursive_filelist_sorted(var.music_folder)
    music_library = util.Dir(folder_path)
    for file in files:
        music_library.add_file(file)
    if request.method == 'POST':
        logging.debug("Post request: "+ str(request.form))
        if 'add_file_bottom' in request.form and ".." not in request.form['add_file_bottom']:
            path = var.config.get('bot', 'music_folder') + request.form['add_file_bottom']
            if os.path.isfile(path):
                item = {'type': 'file',
                        'path' : request.form['add_file_bottom'],
                        'title' : '',
                        'user' : 'Web'}
                var.playlist.append(var.botamusique.get_music_tag_info(item, path))
                logging.info('web: add to playlist(bottom): ' + item['path'])

        elif 'add_file_next' in request.form and ".." not in request.form['add_file_next']:
            path = var.config.get('bot', 'music_folder') + request.form['add_file_next']
            if os.path.isfile(path):
                item = {'type': 'file',
                        'path' : request.form['add_file_next'],
                        'title' : '',
                        'user' : 'Web'}
                var.playlist.insert(
                    var.playlist.current_index + 1,
                    var.botamusique.get_music_tag_info(item, var.config.get('bot', 'music_folder') + item['path'])
                )
                logging.info('web: add to playlist(next): ' + item['path'])

        elif ('add_folder' in request.form and ".." not in request.form['add_folder']) or ('add_folder_recursively' in request.form and ".." not in request.form['add_folder_recursively']):
            try:
                folder = request.form['add_folder']
            except:
                folder = request.form['add_folder_recursively']

            if not folder.endswith('/'):
                folder += '/'

            print('folder:', folder)

            if os.path.isdir(var.config.get('bot', 'music_folder') + folder):
                if 'add_folder_recursively' in request.form:
                    files = music_library.get_files_recursively(folder)
                else:
                    files = music_library.get_files(folder)

                files = list(map(lambda file: var.botamusique.get_music_tag_info({'type':'file','path': os.path.join(folder, file), 'user':'Web'}, \
                                                                                var.config.get('bot', 'music_folder') + os.path.join(folder, file)), files))

                logging.info("web: add to playlist: " + " ,".join([file['path'] for file in files]))
                var.playlist.extend(files)

        elif 'add_url' in request.form:
            var.playlist.append({'type':'url',
                                 'url': request.form['add_url'],
                                 'user': 'Web',
                                 'ready': 'validation'})
            logging.info("web: add to playlist: " + request.form['add_url'])
            media.url.get_url_info()
            var.playlist.playlist[-1]['ready'] = "no"

        elif 'add_radio' in request.form:
            var.playlist.append({'type': 'radio',
                                 'path': request.form['add_radio'],
                                 'user': "Web"})
            logging.info("web: add to playlist: " + request.form['add_radio'])

        elif 'delete_music' in request.form:
            logging.info("web: delete from playlist: " + var.playlist.playlist[int(request.form['delete_music'])]['path'])
            if len(var.playlist.playlist) >= int(request.form['delete_music']):
                if var.playlist.current_index == int(request.form['delete_music']):
                    var.botamusique.pause()
                    var.playlist.remove(int(request.form['delete_music']))
                    var.botamusique.launch_music()
                else:
                    var.playlist.remove(int(request.form['delete_music']))

        elif 'play_music' in request.form:
            logging.info("web: jump to: " + var.playlist.playlist[int(request.form['play_music'])]['path'])
            if len(var.playlist.playlist) >= int(request.form['play_music']):
                var.botamusique.pause()
                var.botamusique.launch_music(int(request.form['play_music']))

        elif 'delete_music_file' in request.form and ".." not in request.form['delete_music_file']:
            path = var.config.get('bot', 'music_folder') + request.form['delete_music_file']
            if os.path.isfile(path):
                logging.info("web: delete file " + path)
                os.remove(path)

        elif 'delete_folder' in request.form and ".." not in request.form['delete_folder']:
            path = var.config.get('bot', 'music_folder') + request.form['delete_folder']
            if os.path.isdir(path):
                logging.info("web: delete folder " + path)
                shutil.rmtree(path)
                time.sleep(0.1)

        elif 'action' in request.form:
            action = request.form['action']
            if action == "randomize":
                var.playlist.randomize()
            elif action == "stop":
                var.botamusique.pause()
            elif action == "clear":
                var.botamusique.stop()
            elif action == "volume_up":
                if var.botamusique.volume + 0.03 < 1.0:
                    var.botamusique.volume = var.botamusique.volume + 0.03
                else:
                    var.botamusique.volume = 1.0
                logging.info("web: volume up to %d" % (var.botamusique.volume * 100))
            elif action == "volume_down":
                if var.botamusique.volume - 0.03 > 0:
                    var.botamusique.volume = var.botamusique.volume - 0.03
                else:
                    var.botamusique.volume = 0
                logging.info("web: volume down to %d" % (var.botamusique.volume * 100))

        return jsonify({'ver': var.playlist.version})

@web.route('/upload', methods=["POST"])
def upload():
    files = request.files.getlist("file[]")
    if not files:
        return redirect("./", code=406)

    #filename = secure_filename(file.filename).strip()
    for file in files:
        filename = file.filename
        if filename == '':
            return redirect("./", code=406)

        targetdir = request.form['targetdir'].strip()
        if targetdir == '':
            targetdir = 'uploads/'
        elif '../' in targetdir:
            return redirect("./", code=406)

        logging.info('Uploading file:')
        logging.info(' - filename: ' + filename)
        logging.info(' - targetdir: ' + targetdir)
        logging.info(' - mimetype: ' + file.mimetype)

        if "audio" in file.mimetype:
            storagepath = os.path.abspath(os.path.join(var.music_folder, targetdir))
            print('storagepath:',storagepath)
            if not storagepath.startswith(os.path.abspath(var.music_folder)):
                return redirect("./", code=406)

            try:
                os.makedirs(storagepath)
            except OSError as ee:
                if ee.errno != errno.EEXIST:
                    return redirect("./", code=500)

            filepath = os.path.join(storagepath, filename)
            logging.info(' - filepath: ' + filepath)
            if os.path.exists(filepath):
                return redirect("./", code=406)

            file.save(filepath)
        else:
            return redirect("./", code=409)

    return redirect("./", code=302)

@web.route('/download', methods=["GET"])
def download():
    if 'file' in request.args:
        requested_file = request.args['file']
        if '../' not in requested_file:
            folder_path = var.music_folder
            files = util.get_recursive_filelist_sorted(var.music_folder)

            if requested_file in files:
                filepath = os.path.join(folder_path, requested_file)
                try:
                    return send_file(filepath, as_attachment=True)
                except Exception as e:
                    self.log.exception(e)
                    self.Error(400)
    elif 'directory' in request.args:
        requested_dir = request.args['directory']
        folder_path = var.music_folder
        requested_dir_fullpath = os.path.abspath(os.path.join(folder_path, requested_dir)) + '/'
        if requested_dir_fullpath.startswith(folder_path):
            if os.path.samefile(requested_dir_fullpath, folder_path):
                prefix = 'all'
            else:
                prefix = secure_filename(os.path.relpath(requested_dir_fullpath, folder_path))
            zipfile = util.zipdir(requested_dir_fullpath, prefix)
            try:
                return send_file(zipfile, as_attachment=True)
            except Exception as e:
                self.log.exception(e)
                self.Error(400)

    return redirect("./", code=400)

if __name__ == '__main__':
    web.run(port=8181, host="127.0.0.1")
<commit_msg>fixed logging problem for radio<commit_after>#!/usr/bin/python3

from functools import wraps
from flask import Flask, render_template, request, redirect, send_file, Response, jsonify
import variables as var
import util
from datetime import datetime
import os
import os.path
import shutil
import random
from werkzeug.utils import secure_filename
import errno
import media
import logging
import time

class ReverseProxied(object):
    '''Wrap the application in this middleware and configure the
    front-end server to add these headers, to let you quietly bind
    this to a URL other than / and to an HTTP scheme that is
    different than what is used locally.

    In nginx:
    location /myprefix {
        proxy_pass http://192.168.0.1:5001;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Scheme $scheme;
        proxy_set_header X-Script-Name /myprefix;
        }

    :param app: the WSGI application
    '''

    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
        if script_name:
            environ['SCRIPT_NAME'] = script_name
            path_info = environ['PATH_INFO']
            if path_info.startswith(script_name):
                environ['PATH_INFO'] = path_info[len(script_name):]

        scheme = environ.get('HTTP_X_SCHEME', '')
        if scheme:
            environ['wsgi.url_scheme'] = scheme
        real_ip = environ.get('HTTP_X_REAL_IP', '')
        if real_ip:
            environ['REMOTE_ADDR'] = real_ip
        return self.app(environ, start_response)

web = Flask(__name__)

def init_proxy():
    global web
    if var.is_proxified:
        web.wsgi_app = ReverseProxied(web.wsgi_app)

# https://stackoverflow.com/questions/29725217/password-protect-one-webpage-in-flask-app

def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    return username == var.config.get("webinterface", "user") and password == var.config.get("webinterface", "password")

def authenticate():
    """Sends a 401 response that enables basic auth"""
    logging.info("Web Interface login failed.")
    return Response(
    'Could not verify your access level for that URL.\n'
    'You have to login with proper credentials', 401,
    {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if var.config.getboolean("webinterface", "require_auth") and (not auth or not check_auth(auth.username, auth.password)):
            if auth:
                logging.info("Web Interface login attempt, user: %s" % auth.username)
            return authenticate()
        return f(*args, **kwargs)
    return decorated

@web.route("/", methods=['GET'])
@requires_auth
def index():
    folder_path = var.music_folder
    files = util.get_recursive_filelist_sorted(var.music_folder)
    music_library = util.Dir(folder_path)
    for file in files:
        music_library.add_file(file)

    return render_template('index.html',
                           all_files=files,
                           music_library=music_library,
                           os=os,
                           playlist=var.playlist,
                           user=var.user
                           )

@web.route("/playlist", methods=['GET'])
@requires_auth
def playlist():
    if var.playlist.length() == 0:
        return jsonify([render_template('playlist.html',
                               m=False,
                               index=-1
                               )]
                       )

    data = []

    for index, item in enumerate(var.playlist.playlist):
         data.append(render_template('playlist.html',
                                     index=index,
                                     m=item,
                                     playlist=var.playlist
                                     )
                     )

    return jsonify(data)

@web.route("/post", methods=['POST'])
@requires_auth
def post():
    folder_path = var.music_folder
    files = util.get_recursive_filelist_sorted(var.music_folder)
    music_library = util.Dir(folder_path)
    for file in files:
        music_library.add_file(file)
    if request.method == 'POST':
        logging.debug("Post request: "+ str(request.form))
        if 'add_file_bottom' in request.form and ".." not in request.form['add_file_bottom']:
            path = var.config.get('bot', 'music_folder') + request.form['add_file_bottom']
            if os.path.isfile(path):
                item = {'type': 'file',
                        'path' : request.form['add_file_bottom'],
                        'title' : '',
                        'user' : 'Web'}
                var.playlist.append(var.botamusique.get_music_tag_info(item, path))
                logging.info('web: add to playlist(bottom): ' + item['path'])

        elif 'add_file_next' in request.form and ".." not in request.form['add_file_next']:
            path = var.config.get('bot', 'music_folder') + request.form['add_file_next']
            if os.path.isfile(path):
                item = {'type': 'file',
                        'path' : request.form['add_file_next'],
                        'title' : '',
                        'user' : 'Web'}
                var.playlist.insert(
                    var.playlist.current_index + 1,
                    var.botamusique.get_music_tag_info(item, var.config.get('bot', 'music_folder') + item['path'])
                )
                logging.info('web: add to playlist(next): ' + item['path'])

        elif ('add_folder' in request.form and ".." not in request.form['add_folder']) or ('add_folder_recursively' in request.form and ".." not in request.form['add_folder_recursively']):
            try:
                folder = request.form['add_folder']
            except:
                folder = request.form['add_folder_recursively']

            if not folder.endswith('/'):
                folder += '/'

            print('folder:', folder)

            if os.path.isdir(var.config.get('bot', 'music_folder') + folder):
                if 'add_folder_recursively' in request.form:
                    files = music_library.get_files_recursively(folder)
                else:
                    files = music_library.get_files(folder)

                files = list(map(lambda file: var.botamusique.get_music_tag_info({'type':'file','path': os.path.join(folder, file), 'user':'Web'}, \
                                                                                var.config.get('bot', 'music_folder') + os.path.join(folder, file)), files))

                logging.info("web: add to playlist: " + " ,".join([file['path'] for file in files]))
                var.playlist.extend(files)

        elif 'add_url' in request.form:
            var.playlist.append({'type':'url',
                                 'url': request.form['add_url'],
                                 'user': 'Web',
                                 'ready': 'validation'})
            logging.info("web: add to playlist: " + request.form['add_url'])
            media.url.get_url_info()
            var.playlist.playlist[-1]['ready'] = "no"

        elif 'add_radio' in request.form:
            var.playlist.append({'type': 'radio',
                                 'path': request.form['add_radio'],
                                 'user': "Web"})
            logging.info("web: add to playlist: " + request.form['add_radio'])

        elif 'delete_music' in request.form:
            music = var.playlist.playlist[int(request.form['delete_music'])]
            logging.info("web: delete from playlist: " + str(music['path'] if 'path' in music else music['url']))

            if len(var.playlist.playlist) >= int(request.form['delete_music']):
                if var.playlist.current_index == int(request.form['delete_music']):
                    var.botamusique.pause()
                    var.playlist.remove(int(request.form['delete_music']))
                    var.botamusique.launch_music()
                else:
                    var.playlist.remove(int(request.form['delete_music']))

        elif 'play_music' in request.form:
            music = var.playlist.playlist[int(request.form['play_music'])]
            logging.info("web: jump to: " + str(music['path'] if 'path' in music else music['url']))

            if len(var.playlist.playlist) >= int(request.form['play_music']):
                var.botamusique.pause()
                var.botamusique.launch_music(int(request.form['play_music']))

        elif 'delete_music_file' in request.form and ".." not in request.form['delete_music_file']:
            path = var.config.get('bot', 'music_folder') + request.form['delete_music_file']
            if os.path.isfile(path):
                logging.info("web: delete file " + path)
                os.remove(path)

        elif 'delete_folder' in request.form and ".." not in request.form['delete_folder']:
            path = var.config.get('bot', 'music_folder') + request.form['delete_folder']
            if os.path.isdir(path):
                logging.info("web: delete folder " + path)
                shutil.rmtree(path)
                time.sleep(0.1)

        elif 'action' in request.form:
            action = request.form['action']
            if action == "randomize":
                var.playlist.randomize()
            elif action == "stop":
                var.botamusique.pause()
            elif action == "clear":
                var.botamusique.stop()
            elif action == "volume_up":
                if var.botamusique.volume + 0.03 < 1.0:
                    var.botamusique.volume = var.botamusique.volume + 0.03
                else:
                    var.botamusique.volume = 1.0
                logging.info("web: volume up to %d" % (var.botamusique.volume * 100))
            elif action == "volume_down":
                if var.botamusique.volume - 0.03 > 0:
                    var.botamusique.volume = var.botamusique.volume - 0.03
                else:
                    var.botamusique.volume = 0
                logging.info("web: volume down to %d" % (var.botamusique.volume * 100))

        return jsonify({'ver': var.playlist.version})

@web.route('/upload', methods=["POST"])
def upload():
    files = request.files.getlist("file[]")
    if not files:
        return redirect("./", code=406)

    #filename = secure_filename(file.filename).strip()
    for file in files:
        filename = file.filename
        if filename == '':
            return redirect("./", code=406)

        targetdir = request.form['targetdir'].strip()
        if targetdir == '':
            targetdir = 'uploads/'
        elif '../' in targetdir:
            return redirect("./", code=406)

        logging.info('Uploading file:')
        logging.info(' - filename: ' + filename)
        logging.info(' - targetdir: ' + targetdir)
        logging.info(' - mimetype: ' + file.mimetype)

        if "audio" in file.mimetype:
            storagepath = os.path.abspath(os.path.join(var.music_folder, targetdir))
            print('storagepath:',storagepath)
            if not storagepath.startswith(os.path.abspath(var.music_folder)):
                return redirect("./", code=406)

            try:
                os.makedirs(storagepath)
            except OSError as ee:
                if ee.errno != errno.EEXIST:
                    return redirect("./", code=500)

            filepath = os.path.join(storagepath, filename)
            logging.info(' - filepath: ' + filepath)
            if os.path.exists(filepath):
                return redirect("./", code=406)

            file.save(filepath)
        else:
            return redirect("./", code=409)

    return redirect("./", code=302)

@web.route('/download', methods=["GET"])
def download():
    if 'file' in request.args:
        requested_file = request.args['file']
        if '../' not in requested_file:
            folder_path = var.music_folder
            files = util.get_recursive_filelist_sorted(var.music_folder)

            if requested_file in files:
                filepath = os.path.join(folder_path, requested_file)
                try:
                    return send_file(filepath, as_attachment=True)
                except Exception as e:
                    self.log.exception(e)
                    self.Error(400)
    elif 'directory' in request.args:
        requested_dir = request.args['directory']
        folder_path = var.music_folder
        requested_dir_fullpath = os.path.abspath(os.path.join(folder_path, requested_dir)) + '/'
        if requested_dir_fullpath.startswith(folder_path):
            if os.path.samefile(requested_dir_fullpath, folder_path):
                prefix = 'all'
            else:
                prefix = secure_filename(os.path.relpath(requested_dir_fullpath, folder_path))
            zipfile = util.zipdir(requested_dir_fullpath, prefix)
            try:
                return send_file(zipfile, as_attachment=True)
            except Exception as e:
                self.log.exception(e)
                self.Error(400)

    return redirect("./", code=400)

if __name__ == '__main__':
    web.run(port=8181, host="127.0.0.1")
<|endoftext|>


<commit_before>"""
Django settings for siftsite project.

Generated by 'django-admin startproject' using Django 1.11.4.

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ncy+5ie@kezm(=jd6ugld=o^bw_ahc6-2)^!c(4tuvoyhp&_km'

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

ALLOWED_HOSTS = []

# Application definition

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_URL = '/static/'

INSTALLED_APPS = [
    'labeller',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'siftsite.urls'

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

WSGI_APPLICATION = 'siftsite.wsgi.application'

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True
<commit_msg>added static root to settings.py<commit_after>"""
Django settings for siftsite project.

Generated by 'django-admin startproject' using Django 1.11.4.

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ncy+5ie@kezm(=jd6ugld=o^bw_ahc6-2)^!c(4tuvoyhp&_km'

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

ALLOWED_HOSTS = []

# Application definition

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static')

INSTALLED_APPS = [
    'labeller',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'siftsite.urls'

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

WSGI_APPLICATION = 'siftsite.wsgi.application'

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""Module containing the GistFile object."""
from __future__ import unicode_literals

from ..models import GitHubCore

class _GistFile(GitHubCore):
    """Base for GistFile classes."""

    def _update_attributes(self, gistfile):
        self.raw_url = gistfile['raw_url']
        self.filename = gistfile['filename']
        self.language = gistfile['language']
        self.size = gistfile['size']
        self.type = gistfile['type']

    def _repr(self):
        return '<{s.class_name} [{s.name}]>'.format(s=self)

    def content(self):
        """Retrieve contents of file from key 'raw_url'.

        :returns: unaltered, untruncated contents of file.
        :rtype: bytes
        """
        resp = self._get(self.raw_url)
        if self._boolean(resp, 200, 404):
            return resp.content
        return None

class ShortGistFile(_GistFile):
    """This represents the file object returned by interacting with gists.

    The object has the following attributes as returned by the API for a Gist:

    .. attribute:: raw_url

        This URL provides access to the complete, untruncated content of the
        file represented by this object.

    .. attribute:: filename

        The string for the filename.

    .. attribute:: language

        The GitHub detected language for the file, e.g., Erlang, Python, text.

    .. attribute:: type

        The mime-type of the file. Related to :attr:`language`.

    .. attribute:: size

        The file size in bytes.
    """

    class_name = 'ShortGistFile'

class GistFile(_GistFile):
    """This represents the full file object returned by interacting with gists.

    The object has all of the attributes as returned by the API for a
    ShortGistFile as well as:

    .. attribute:: truncated

        A boolean attribute that indicates whether :attr:`original_content`
        contains all of the file's contents.

    .. attribute:: original_content

        The contents of the file (potentially truncated) returned by the API.
        If the file was truncated use :meth:`content` to retrieve it in its
        entirety.

    """

    class_name = 'GistFile'

    def _update_attributes(self, gistfile):
        super(GistFile, self)._update_attributes(gistfile)
        self.original_content = gistfile['content']
        self.truncated = gistfile['truncated']
<commit_msg>Use filename in *GistFile reprs<commit_after># -*- coding: utf-8 -*-
"""Module containing the GistFile object."""
from __future__ import unicode_literals

from ..models import GitHubCore

class _GistFile(GitHubCore):
    """Base for GistFile classes."""

    def _update_attributes(self, gistfile):
        self.raw_url = gistfile['raw_url']
        self.filename = gistfile['filename']
        self.language = gistfile['language']
        self.size = gistfile['size']
        self.type = gistfile['type']

    def _repr(self):
        return '<{s.class_name} [{s.filename}]>'.format(s=self)

    def content(self):
        """Retrieve contents of file from key 'raw_url'.

        :returns: unaltered, untruncated contents of file.
        :rtype: bytes
        """
        resp = self._get(self.raw_url)
        if self._boolean(resp, 200, 404):
            return resp.content
        return None

class ShortGistFile(_GistFile):
    """This represents the file object returned by interacting with gists.

    The object has the following attributes as returned by the API for a Gist:

    .. attribute:: raw_url

        This URL provides access to the complete, untruncated content of the
        file represented by this object.

    .. attribute:: filename

        The string for the filename.

    .. attribute:: language

        The GitHub detected language for the file, e.g., Erlang, Python, text.

    .. attribute:: type

        The mime-type of the file. Related to :attr:`language`.

    .. attribute:: size

        The file size in bytes.
    """

    class_name = 'ShortGistFile'

class GistFile(_GistFile):
    """This represents the full file object returned by interacting with gists.

    The object has all of the attributes as returned by the API for a
    ShortGistFile as well as:

    .. attribute:: truncated

        A boolean attribute that indicates whether :attr:`original_content`
        contains all of the file's contents.

    .. attribute:: original_content

        The contents of the file (potentially truncated) returned by the API.
        If the file was truncated use :meth:`content` to retrieve it in its
        entirety.

    """

    class_name = 'GistFile'

    def _update_attributes(self, gistfile):
        super(GistFile, self)._update_attributes(gistfile)
        self.original_content = gistfile['content']
        self.truncated = gistfile['truncated']
<|endoftext|>


<commit_before>#!/usr/bin/python

#import matplotlib
#matplotlib.use('Agg') # Force matplotlib to not use any Xwindows backend.

import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import elements
import GridUtils as GU
#import XSFutils
import basUtils
import ProbeParticle as PP

from optparse import OptionParser

parser = OptionParser()
parser.add_option(      "--dfrange", action="store", type="float", help="Range of plotted frequency shift (df)", nargs=2)
(options, args) = parser.parse_args()

print " >> WARNING!!! OVEWRITING SETTINGS by params.ini  "

PP.loadParams( 'params.ini' )

Fx,lvec,nDim,head=GU.loadXSF('FFel_x.xsf')
Fy,lvec,nDim,head=GU.loadXSF('FFel_y.xsf')
Fz,lvec,nDim,head=GU.loadXSF('FFel_z.xsf')

PP.params['gridA'] = lvec[ 1,:  ].copy()
PP.params['gridB'] = lvec[ 2,:  ].copy()
PP.params['gridC'] = lvec[ 3,:  ].copy()
PP.params['gridN'] = nDim.copy()

FF   = np.zeros( (nDim[0],nDim[1],nDim[2],3) )
FFLJ = np.zeros( np.shape( FF ) )
FFel = np.zeros( np.shape( FF ) )

FFel[:,:,:,0]=Fx
FFel[:,:,:,1]=Fy
FFel[:,:,:,2]=Fz

cell =np.array([
PP.params['gridA'],
PP.params['gridB'],
PP.params['gridC'],
]).copy()
gridN = PP.params['gridN']

PP.setFF( FF, cell  )

print " # ============ define atoms "

atoms    = basUtils.loadAtoms('input.xyz', elements.ELEMENT_DICT )
Rs       = np.array([atoms[1],atoms[2],atoms[3]]);
iZs      = np.array( atoms[0])

if not PP.params['PBC' ]:
	print " NO PBC => autoGeom "
	PP.autoGeom( Rs, shiftXY=True,  fitCell=True,  border=3.0 )
	print " NO PBC => params[ 'gridA'   ] ", PP.params[ 'gridA' ]
	print " NO PBC => params[ 'gridB'   ] ", PP.params[ 'gridB'   ]
	print " NO PBC => params[ 'gridC'   ] ", PP.params[ 'gridC'   ]
	print " NO PBC => params[ 'scanMin' ] ", PP.params[ 'scanMin' ]
	print " NO PBC => params[ 'scanMax' ] ", PP.params[ 'scanMax' ]

Rs = np.transpose( Rs, (1,0) ).copy()
Qs = np.array( atoms[4] )

if PP.params['PBC' ]:
	iZs,Rs,Qs = PP.PBCAtoms( iZs, Rs, Qs, avec=PP.params['gridA'], bvec=PP.params['gridB'] )

print "shape( Rs )", np.shape( Rs );
#print "Rs : ",Rs

print " # ============ define Scan and allocate arrays   - do this before simulation, in case it will crash "

dz    = PP.params['scanStep'][2]
zTips = np.arange( PP.params['scanMin'][2], PP.params['scanMax'][2]+0.00001, dz )[::-1];
ntips = len(zTips);
print " zTips : ",zTips
rTips = np.zeros((ntips,3))
rs    = np.zeros((ntips,3))
fs    = np.zeros((ntips,3))

rTips[:,0] = 1.0
rTips[:,1] = 1.0
rTips[:,2] = zTips

PP.setTip()

xTips  = np.arange( PP.params['scanMin'][0], PP.params['scanMax'][0]+0.00001, 0.1 )
yTips  = np.arange( PP.params['scanMin'][1], PP.params['scanMax'][1]+0.00001, 0.1 )
extent=( xTips[0], xTips[-1], yTips[0], yTips[-1] )
fzs    = np.zeros(( len(zTips), len(yTips ), len(xTips ) ));

nslice = 10;

atomTypesFile = os.path.dirname(sys.argv[0]) + '/defaults/atomtypes.ini'
FFparams      = PP.loadSpecies(atomTypesFile)
C6,C12        = PP.getAtomsLJ( PP.params['probeType'], iZs, FFparams )

print " # ============ define Grid "

cell =np.array([
PP.params['gridA'],
PP.params['gridB'],
PP.params['gridC'],
]).copy()

gridN = PP.params['gridN']

# ==============================================
#   The costly part of simulation starts here
# ==============================================

print " # =========== Sample LenardJones "

PP.setFF( FF, cell  )
PP.setFF_Pointer( FF )
PP.getLenardJonesFF( Rs, C6, C12 )

#plt.figure(figsize=( 5*nslice,5 )); plt.title( ' FF LJ ' )
#for i in range(nslice):
#	plt.subplot( 1, nslice, i+1 )
#	plt.imshow( FF[i,:,:,2], origin='image', interpolation='nearest' )

withElectrostatics = ( abs( PP.params['charge'] )>0.001 )
if withElectrostatics:
	print " # =========== Sample Coulomb "
	FF += FFel*PP.params['charge']
	PP.setFF_Pointer( FF )

del FFel

#plt.figure(figsize=( 5*nslice,5 )); plt.title( ' FF total ' )
#for i in range(nslice):
#	plt.subplot( 1, nslice, i+1 )
#	plt.imshow( FF[i,:,:,2], origin='image', interpolation='nearest' )

print " # ============  Relaxed Scan 3D "

for ix,x in enumerate( xTips  ):
	print "relax ix:", ix
	rTips[:,0] = x
	for iy,y in enumerate( yTips  ):
		rTips[:,1] = y
		itrav = PP.relaxTipStroke( rTips, rs, fs ) / float( len(zTips) )
		fzs[:,iy,ix] = fs[:,2].copy()

print " # ============  convert Fz -> df "

dfs = PP.Fz2df( fzs, dz = dz, k0 = PP.params['kCantilever'], f0=PP.params['f0Cantilever'], n=int(PP.params['Amplitude']/dz) )

print " # ============  Plot Relaxed Scan 3D "
slices = range( 0, len(dfs) )
for ii,i in enumerate(slices):
	print " plotting ", i
	plt.figure( figsize=( 10,10 ) )
	if(options.dfrange != None):
		fmin = options.dfrange[0]
		fmax = options.dfrange[1]
		plt.imshow( dfs[i], origin='image', interpolation=PP.params['imageInterpolation'], vmin=fmin, vmax=fmax, cmap=PP.params['colorscale'], extent=extent )
	else:
		plt.imshow( dfs[i], origin='image', interpolation=PP.params['imageInterpolation'], cmap=PP.params['colorscale'], extent=extent )
	z = zTips[i] - PP.params['moleculeShift' ][2]
	plt.colorbar();
	plt.xlabel(r' Tip_x $\AA$')
	plt.ylabel(r' Tip_y $\AA$')
	plt.title( r"df Tip_z = %2.2f $\AA$" %z  )
	plt.savefig( 'df_%04i.png' %i, bbox_inches='tight' )

print " ***** ALL DONE ***** "
<commit_msg>cleanign up code/ppr.py<commit_after>#!/usr/bin/python

import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import elements
import GridUtils as GU
import basUtils
import ProbeParticle as PP

from optparse import OptionParser

parser = OptionParser()
parser.add_option(      "--dfrange", action="store", type="float", help="Range of plotted frequency shift (df)", nargs=2)
(options, args) = parser.parse_args()

print " >> WARNING!!! OVEWRITING SETTINGS by params.ini  "

PP.loadParams( 'params.ini' )

Fx,lvec,nDim,head=GU.loadXSF('FFel_x.xsf')
Fy,lvec,nDim,head=GU.loadXSF('FFel_y.xsf')
Fz,lvec,nDim,head=GU.loadXSF('FFel_z.xsf')

PP.params['gridA'] = lvec[ 1,:  ].copy()
PP.params['gridB'] = lvec[ 2,:  ].copy()
PP.params['gridC'] = lvec[ 3,:  ].copy()
PP.params['gridN'] = nDim.copy()

FF   = np.zeros( (nDim[0],nDim[1],nDim[2],3) )
FFLJ = np.zeros( np.shape( FF ) )
FFel = np.zeros( np.shape( FF ) )

FFel[:,:,:,0]=Fx
FFel[:,:,:,1]=Fy
FFel[:,:,:,2]=Fz

cell =np.array([
PP.params['gridA'],
PP.params['gridB'],
PP.params['gridC'],
]).copy()
gridN = PP.params['gridN']

PP.setFF( FF, cell  )

print " # ============ define atoms "

atoms    = basUtils.loadAtoms('input.xyz', elements.ELEMENT_DICT )
Rs       = np.array([atoms[1],atoms[2],atoms[3]]);
iZs      = np.array( atoms[0])

if not PP.params['PBC' ]:
	print " NO PBC => autoGeom "
	PP.autoGeom( Rs, shiftXY=True,  fitCell=True,  border=3.0 )
	print " NO PBC => params[ 'gridA'   ] ", PP.params[ 'gridA' ]
	print " NO PBC => params[ 'gridB'   ] ", PP.params[ 'gridB'   ]
	print " NO PBC => params[ 'gridC'   ] ", PP.params[ 'gridC'   ]
	print " NO PBC => params[ 'scanMin' ] ", PP.params[ 'scanMin' ]
	print " NO PBC => params[ 'scanMax' ] ", PP.params[ 'scanMax' ]

Rs = np.transpose( Rs, (1,0) ).copy()
Qs = np.array( atoms[4] )

if PP.params['PBC' ]:
	iZs,Rs,Qs = PP.PBCAtoms( iZs, Rs, Qs, avec=PP.params['gridA'], bvec=PP.params['gridB'] )

print "shape( Rs )", np.shape( Rs );
#print "Rs : ",Rs

print " # ============ define Scan and allocate arrays   - do this before simulation, in case it will crash "

dz    = PP.params['scanStep'][2]
zTips = np.arange( PP.params['scanMin'][2], PP.params['scanMax'][2]+0.00001, dz )[::-1];
ntips = len(zTips);
print " zTips : ",zTips
rTips = np.zeros((ntips,3))
rs    = np.zeros((ntips,3))
fs    = np.zeros((ntips,3))

rTips[:,0] = 1.0
rTips[:,1] = 1.0
rTips[:,2] = zTips

PP.setTip()

xTips  = np.arange( PP.params['scanMin'][0], PP.params['scanMax'][0]+0.00001, 0.1 )
yTips  = np.arange( PP.params['scanMin'][1], PP.params['scanMax'][1]+0.00001, 0.1 )
extent=( xTips[0], xTips[-1], yTips[0], yTips[-1] )
fzs    = np.zeros(( len(zTips), len(yTips ), len(xTips ) ));

nslice = 10;

atomTypesFile = os.path.dirname(sys.argv[0]) + '/defaults/atomtypes.ini'
FFparams      = PP.loadSpecies(atomTypesFile)
C6,C12        = PP.getAtomsLJ( PP.params['probeType'], iZs, FFparams )

print " # ============ define Grid "

cell =np.array([
PP.params['gridA'],
PP.params['gridB'],
PP.params['gridC'],
]).copy()

gridN = PP.params['gridN']

# ==============================================
#   The costly part of simulation starts here
# ==============================================

print " # =========== Sample LenardJones "

PP.setFF( FF, cell  )
PP.setFF_Pointer( FF )
PP.getLenardJonesFF( Rs, C6, C12 )

withElectrostatics = ( abs( PP.params['charge'] )>0.001 )
if withElectrostatics:
	print " # =========== Sample Coulomb "
	FF += FFel*PP.params['charge']
	PP.setFF_Pointer( FF )

del FFel

print " # ============  Relaxed Scan 3D "

for ix,x in enumerate( xTips  ):
	print "relax ix:", ix
	rTips[:,0] = x
	for iy,y in enumerate( yTips  ):
		rTips[:,1] = y
		itrav = PP.relaxTipStroke( rTips, rs, fs ) / float( len(zTips) )
		fzs[:,iy,ix] = fs[:,2].copy()

print " # ============  convert Fz -> df "

dfs = PP.Fz2df( fzs, dz = dz, k0 = PP.params['kCantilever'], f0=PP.params['f0Cantilever'], n=int(PP.params['Amplitude']/dz) )

print " # ============  Plot Relaxed Scan 3D "
slices = range( 0, len(dfs) )
for ii,i in enumerate(slices):
	print " plotting ", i
	plt.figure( figsize=( 10,10 ) )
	if(options.dfrange != None):
		fmin = options.dfrange[0]
		fmax = options.dfrange[1]
		plt.imshow( dfs[i], origin='image', interpolation=PP.params['imageInterpolation'], vmin=fmin, vmax=fmax, cmap=PP.params['colorscale'], extent=extent )
	else:
		plt.imshow( dfs[i], origin='image', interpolation=PP.params['imageInterpolation'], cmap=PP.params['colorscale'], extent=extent )
	z = zTips[i] - PP.params['moleculeShift' ][2]
	plt.colorbar();
	plt.xlabel(r' Tip_x $\AA$')
	plt.ylabel(r' Tip_y $\AA$')
	plt.title( r"df Tip_z = %2.2f $\AA$" %z  )
	plt.savefig( 'df_%04i.png' %i, bbox_inches='tight' )

print " ***** ALL DONE ***** "
<|endoftext|>