"""Test the ht.pyfilter.operations.primaryimage module."""

# =============================================================================
# IMPORTS
# =============================================================================

# Python Imports
import argparse
from mock import MagicMock, call, patch
import unittest

# Houdini Toolbox Imports
from ht.pyfilter.manager import PyFilterManager
from ht.pyfilter.operations import primaryimage

reload(primaryimage)

# =============================================================================
# CLASSES
# =============================================================================

class Test_SetPrimaryImage(unittest.TestCase):
    """Test the ht.pyfilter.operations.primaryimage.SetPrimaryImage object."""

    def setUp(self):
        super(Test_SetPrimaryImage, self).setUp()

        self.patcher = patch("ht.pyfilter.operations.operation._logger", autospec=True)
        self.patcher.start()

    def tearDown(self):
        super(Test_SetPrimaryImage, self).tearDown()
        self.patcher.stop()

    def test___init__(self):
        mock_manager = MagicMock(spec=PyFilterManager)

        op = primaryimage.SetPrimaryImage(mock_manager)

        self.assertEqual(op._data, {})
        self.assertEqual(op._manager, mock_manager)

        self.assertFalse(op._disable_primary_image)
        self.assertIsNone(op._primary_image_path)

    # Properties

    @patch.object(primaryimage.SetPrimaryImage, "__init__", lambda x, y: None)
    def test_disable_primary_image(self):
        op = primaryimage.SetPrimaryImage(None)
        op._disable_primary_image = True
        self.assertTrue(op.disable_primary_image)

        op._disable_primary_image = False
        op.disable_primary_image = True
        self.assertTrue(op._disable_primary_image)

    @patch.object(primaryimage.SetPrimaryImage, "__init__", lambda x, y: None)
    def test_manager(self):
        path = "/path/to/image.exr"

        op = primaryimage.SetPrimaryImage(None)
        op._primary_image_path = path
        self.assertEqual(op.primary_image_path, path)

        op._primary_image_path = None
        op.primary_image_path = path
        self.assertEqual(op._primary_image_path, path)

    # Static Methods

    # build_arg_string

    def test_build_arg_string__empty(self):
        result = primaryimage.SetPrimaryImage.build_arg_string()

        self.assertEqual(result, "")

    def test_build_arg_string__path(self):
        path = "/path/to/image.exr"

        result = primaryimage.SetPrimaryImage.build_arg_string(primary_image_path=path)

        self.assertEqual(result, "--primary-image-path={}".format(path))

    def test_build_arg_string__disable(self):
        result = primaryimage.SetPrimaryImage.build_arg_string(disable_primary_image=True)

        self.assertEqual(result, "--disable-primary-image")

    # register_parser_args

    def test_register_parser_args(self):
        mock_parser = MagicMock(spec=argparse.ArgumentParser)

        primaryimage.SetPrimaryImage.register_parser_args(mock_parser)

        calls = [
            call("--primary-image-path", dest="primary_image_path"),
            call("--disable-primary-image", action="store_true", dest="disable_primary_image")
        ]
        mock_parser.add_argument.assert_has_calls(calls)

    # Methods

    @patch("ht.pyfilter.operations.primaryimage._logger")
    @patch("ht.pyfilter.operations.primaryimage.set_property")
    @patch.object(primaryimage.SetPrimaryImage, "__init__", lambda x, y: None)
    def test_filterCamera__disable(self, mock_set, mock_logger):
        op = primaryimage.SetPrimaryImage(None)
        op._disable_primary_image = True

        op.filterCamera()

        mock_set.assert_called_with("image:filename", "null:")

    @patch("ht.pyfilter.operations.primaryimage._logger")
    @patch("ht.pyfilter.operations.primaryimage.set_property")
    @patch.object(primaryimage.SetPrimaryImage, "__init__", lambda x, y: None)
    def test_filterCamera__path(self, mock_set, mock_logger):
        path = "/path/to/images.exr"

        op = primaryimage.SetPrimaryImage(None)
        op._disable_primary_image = False
        op._primary_image_path = path

        op.filterCamera()

        mock_set.assert_called_with("image:filename", path)

    @patch("ht.pyfilter.operations.primaryimage._logger")
    @patch("ht.pyfilter.operations.primaryimage.set_property")
    @patch.object(primaryimage.SetPrimaryImage, "__init__", lambda x, y: None)
    def test_filterCamera__no_op(self, mock_set, mock_logger):
        path = "/path/to/images.exr"

        op = primaryimage.SetPrimaryImage(None)
        op._disable_primary_image = False
        op._primary_image_path = None

        op.filterCamera()

        mock_set.assert_not_called()

    # process_parsed_args

    @patch.object(primaryimage.SetPrimaryImage, "__init__", lambda x, y: None)
    def test_process_parsed_args_noop(self):
        path = "/path/to/image.exr"
        mock_namespace = MagicMock(spec=argparse.Namespace)
        mock_namespace.disable_primary_image = False
        mock_namespace.primary_image_path = None

        op = primaryimage.SetPrimaryImage(None)
        op._disable_primary_image = False
        op._primary_image_path = None

        op.process_parsed_args(mock_namespace)

        self.assertFalse(op.disable_primary_image)

        self.assertIsNone(op.primary_image_path)

    @patch.object(primaryimage.SetPrimaryImage, "__init__", lambda x, y: None)
    def test_process_parsed_args(self):
        path = "/path/to/image.exr"
        mock_namespace = MagicMock(spec=argparse.Namespace)
        mock_namespace.disable_primary_image = True
        mock_namespace.primary_image_path = path

        op = primaryimage.SetPrimaryImage(None)
        op._disable_primary_image = False
        op._primary_image_path = None

        op.process_parsed_args(mock_namespace)

        self.assertTrue(op.disable_primary_image)

        self.assertEqual(op.primary_image_path, path)

    @patch.object(primaryimage.SetPrimaryImage, "__init__", lambda x, y: None)
    def test_should_run__no_op(self):
        op = primaryimage.SetPrimaryImage(None)
        op._disable_primary_image = False
        op._primary_image_path = None

        self.assertFalse(op.should_run())

    @patch.object(primaryimage.SetPrimaryImage, "__init__", lambda x, y: None)
    def test_should_run__disable(self):
        op = primaryimage.SetPrimaryImage(None)
        op._disable_primary_image = True
        op._primary_image_path = None

        self.assertTrue(op.should_run())

    @patch.object(primaryimage.SetPrimaryImage, "__init__", lambda x, y: None)
    def test_should_run__no_op(self):
        op = primaryimage.SetPrimaryImage(None)
        op._disable_primary_image = False
        op._primary_image_path = "/path/to/image.exr"

        self.assertTrue(op.should_run())

# =============================================================================

if __name__ == '__main__':
    unittest.main()


import matplotlib.pyplot as plt
import numpy as np
from scipy.constants import G
case=int(input("Case 1,2 > "))
#Constants
M=1.989e30
m=5.972e24
lamb=7.5e6

# In order to make eccentricity equal to 0.5
gamma=G*M*m
mu=m*M/(m+M)
L=(0.375*gamma**2*mu/3)**(1/3.)
E=-3*L

delta=np.array([-.6,-.1,0,.1,.6])
beta_0=mu*gamma/L**2
beta_1=2*mu*E/L**2-2*mu*gamma*delta/(lamb*L**2*(1+delta))
l=1./beta_0
if case==1:
    epsilon=np.sqrt(1+l**2*beta_1)
if case==2:
    beta_2=mu*gamma*delta/(L**2*lamb**2*(1+delta))
    epsilon=np.sqrt(1+l**2*beta_1+l**3*beta_2c)
#First Graph
count=0
varphi=np.linspace(0,2*np.pi, 1000)
styles=['-.', ':', '-', '--','-.']
e_N=epsilon[2]
r_N=l/(1+e_N*np.cos(varphi))

fig, axes = plt.subplots(2, 1)
for x in delta:
    r=l/(1+epsilon[count]*np.cos(varphi))
    axes[0].plot(r*np.cos(varphi), r*np.sin(varphi),
    label="$\delta=%.1f$"%x, linestyle=styles[count])
    d=abs(r-r_N)
    if count==0:
        r_max=max(d)
        axes[1].scatter(varphi[d.argmax()], r_max)
        axes[1].text(varphi[d.argmax()], r_max-500000, "%f m"%r_max)
    if count!=2:
        axes[1].plot(varphi, d, label="$\delta=%.1f$"%x,
         linestyle=styles[count])
    count+=1
axes[0].axhline(0, color='black')
axes[0].axvline(0, color='black')
axes[0].set_xlabel("x (meters)")
axes[0].set_ylabel("y (meters)")
axes[0].legend()

axes[1].set_xlabel(r"$\theta$")
axes[1].set_ylabel(r"$|r_N(\theta)-r(\theta,\delta)|$")
axes[1].legend()
plt.tight_layout()
plt.show()


#!/usr/bin/env python
from time import sleep, time
from threading import Thread, Event, Lock
from statsmodels.robust import mad
import pandas as pd #pandas is a data analysis library w some easy to use data structures
import matplotlib.pyplot as plt #plotting library
import numpy as np
import random, pywt, serial
from mpipe import OrderedStage, Pipeline
import socket
import json
import struct
import sys
import serial

HOSTClient = '127.0.0.3'
PORTClient = 5555
udpClient = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
origClient = (HOSTClient, PORTClient)
udpClient.connect(origClient)
ttl = struct.pack('b', 1)
udpClient.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
udpClient.settimeout(10)

def waveletDenoising(x, wavelet="db3", level=3):
    # calculate the wavelet coefficients
    coeff = pywt.wavedec(x, wavelet, mode="per")
    # calculate a threshold
    sigma = mad(coeff[-level])

    uthresh = sigma * np.sqrt(2*np.log(len(x)))
    coeff[1:] = (pywt.threshold(i, value=uthresh, mode="soft")
                 for i in coeff[1:])
    # reconstruct the signal using the thresholded coefficients
    return pywt.waverec(coeff, wavelet, mode="per")
    #fig, ax = plt.subplots()
    #plt.plot(x, color="b", alpha=0.4)
    #plt.plot(y, color="b")
    #ax.set_title('Signal Denoising')
    #ax.set_xlim((0, len(y)))
    #plt.show()

def readSerial(ser):
    for i in range(512):
        print(i)
        file = open("data_wfilter.txt", 'a+')
        last = 0
        try:
            line = ser.readline().decode("utf-8","ignore").split(",")
            last = float(line)
        except Exception as e:
            line = last
            pass
        finally:
            print(line)
            file.write('{}'.format(line) + "\n")
            file.close()
    #samples.pop(0)
    #samples.append(float(s))
    #avg = float(sum(samples)/filter_size)
    #print(s, " ", avg)
    #if input() == 'q':
    #  break
    #Aqui libera alguma trava para o envio

ser = serial.Serial('/dev/ttyACM0', 9600)

readSerial(ser)
df = pd.read_csv('data_wfilter.csv', sep="\n", header=None)
signal = np.array(df.values.flatten())

signal = waveletDenoising(signal)
udpClient.sendto(signal.encode(),origClient)


import random

pone = 0
bot = 0
rchoice = random.choice(['true','false'])
choice = rchoice
di = random.randint(1,6)
sn = 0
print("Hello! Welcome to the game Pig! The rules are as follows:\nWe will go in turns, randomly picked at the start.\nIf you roll it and it lands on numbers 2-6,\nyou gain those points and you can decide to go again.\nIf you land on 1, your points reset!\n")
a = input("Press any key and enter to start")
while(bot < 100 and pone < 100):
	if(rchoice == "true"):
		print("Players turn!")
		a = input("Roll?(yes or no): ")
		while(a == "yes" or a== "Yes"):
			di = random.randint(1,6)
			sn = sn + di
			print("You rolled a " + str(di) + "!")
			if(di == 1):
				print("You rolled a one!")
				sn = 0
				rchoice = "false"
			else:
				pone = pone + sn
				print("Your score: " + str(pone))
				sn = 0
				a = input("Roll?(yes or no): ")
		if(a == "no" or a == "No"):
			print("Turn ending score: " + str(pone))
			rchoice = "false"
	while(rchoice == "false"):
		print("Bot's turn!")
		di = random.randint(1,6)
		yesno = random.choice(["yes","no"])
		if(yesno == "yes"):
			print("I'm rolling!")
			yesno = random.choice(["yes","no"])
			di = random.randint(1,6)
			sn = sn + di
			print("I rolled a " + str(di) + "!")
			if(di == 1):
				print("I rolled a one!")
				sn = 0
				rchoice = "true"
			else:
				bot = bot + sn
				print("Bot score: " + str(bot))
				sn = 0
				yesno = random.choice(["yes","no"])
		if(yesno == "no"):
			print("My turn ending score: " + str(bot))
			rchoice = "false"

print("Final Score:")
print("Player = " + str(pone))
print("bot = " + str(bot))


import sys

def sorter(t):
    return int(t[1])

def main():
    d = dict()
    illegals = []

    for line in sys.stdin:
        team_name, points = line.strip().split(":")
        score = points.strip().split()

        total = 0
        for num in score:
            try:
                total += int(num)

            except ValueError:
                illegals.append(team_name)

        if team_name not in illegals:
            d[team_name] = str(total)

    max_name = max(d.keys(), key=len)
    max_score = max(d.values(), key=len)

    for (k, v) in sorted(d.items(), key=sorter, reverse=True):
        print("{:>{}}: {:>{}} points".format(k, len(max_name), v, len(max_score)))

if __name__ == "__main__":
    main()


from django import forms
from django.forms import ModelForm
from .models import Visits
from django.utils.timezone import now
from datetime import date
from apps.visitdrug.tables import MedicineTable
from apps.patientdata.models import Patients

from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _

# from django.contrib.postgres.search import SearchVector

def validate_none(value):
    if value == None:
        raise ValidationError(_('%(value)s must be not NONE'),
            params={'value': '0'},
        )

class VisitsForm(forms.ModelForm):

    # id = forms.IntegerField(required=False, label='Visit No.',
    #                        widget=forms.NumberInput(
    #                            attrs={
    #                                'class': 'form-control',
    #                                'readonly': 'readonly',
    #                             #    'style': ('background-color:lightgreen')
    #                            })
    #                        )
    # patient = forms.ModelChoiceField(queryset=Patients.objects.all(), required=True, label='Name',
    #                        widget=forms.Select(
    #                            attrs={
    #                                'class': 'form-control',
    #                                 'id': 'patient',
    #                                 # 'disabled':'disabled'
    #                            }
    #                        ))

    complain = forms.CharField(required=False, label='Complain',
                           widget=forms.Textarea(
                               attrs={
                                   'class': 'form-control',
                                #    'id': '',

                               })
                            )
    sign = forms.CharField(required=False, label='Sign',
                           widget=forms.Textarea(
                               attrs={
                                   'class': 'form-control',
                                #    'id': '',

                               })
                            )
    visitdate = forms.DateField(required=False, label='Visit Date',
                           widget=forms.TextInput(
                               attrs={
                                    'class': 'form-control',
                                    'placeholder':'Click here to enter the visit date ...',
                                    'value': date.today(),
                                    'id': 'visitdate',
                                    'type':'date',
                                    # 'readonly': 'readonly'
                               }
                           ))
    diagnosis = forms.CharField(required=False, label='Daignosis',
                            widget=forms.TextInput(
                                attrs={
                                   'class': 'form-control',
                                #    'id': '',

                               })
                            )
    intervention = forms.CharField(required=False, label='Intervention',
                            widget=forms.TextInput(
                                attrs={
                                   'class': 'form-control',
                                #    'id': '',

                               })
                            )
    amount = forms.IntegerField(required=False, label='Amount', #validators=[validate_none],
                           widget=forms.NumberInput(
                               attrs={
                                   'class': 'form-control',
                                #    'id': '',
                                    'value':'0'
                               }
                           ))

    def clean(self): # this method for prevent save or update the field 'amount' if it is None
        cleaned_data = super().clean()
        amount = cleaned_data.get('amount')
        visitdate = cleaned_data.get('visitdate')
        if amount == None:
            # self.add_error('amount', 'can not be None') # the error as outline (red line) of the input
            raise ValidationError('Amount Can Not Be Empty')
        if visitdate == None:
            self.add_error('visitdate', 'Date can\'t be Empty')
            raise ValidationError('Visit Date Can Not Be Empty')
            # return msg
        return cleaned_data

    class Meta:
        model = Visits
        fields = ('__all__')#('id', 'patient')#('__all__')
        # fields = ('__str__', 'address', )

    def __init__(self, *args, **kwargs):
        super(VisitsForm, self).__init__(*args, **kwargs)
        # self.id = self.fields['id']
        # self.fields['id'].widget.attrs['class'] = 'input'


import logging

import django.template
from django.template import TemplateSyntaxError

logger = logging.getLogger(__name__)
register = django.template.Library()

CTX_PREFIX = "__splango__experiment__"

UNDECLARED_EXPERIMENT_WARNING = (
    "Experiment has not yet been declared. Please declare it "
    "and supply variant names using an experiment tag before "
    "using hyp tags.")
REQUEST_CONTEXT_PROCESSOR_WARNING = (
    "Use of splangotags requires the request context processor. "
    "Please add django.core.context_processors.request to your "
    "settings.TEMPLATE_CONTEXT_PROCESSORS.")
SPLANGO_MIDDLEWARE_WARNING = (
    "Use of splangotags requires the splango middleware. Please "
    "add splango.middleware.ExperimentsMiddleware to your "
    "settings.MIDDLEWARE_CLASSES.")

class ExperimentNode(django.template.Node):

    """Template node for the {% experiment ... %} template tag.

    This

    :meth:`render` returns an empty string (thus
    ``{% experiment "..." variants "...,...,..." %}`` renders nothing) but
    it must be called so that the experiment is recorded appropriately.

    """

    def __init__(self, exp_name, variants_str):
        """Save the experiment and variants names, splitting ``variants_str``.

        :attr:`variants` is a list of strings, the name of each variant

        :param exp_name: experiment name
        :param variants_str: variants names concatenated by ``","`` e.g.
          ``"red,blue,green"``

        """
        self.exp_name_var = django.template.Variable(exp_name)
        self.variants_str_var = django.template.Variable(variants_str)

    def render(self, context):
        """Declare the experiment and enroll a variant. Render nothing.

        :param context: template context
        :type context: :class:`django.template.context.Context`
        :return: empty string
        :rtype: basestring
        :raises: :class:`django.template.TemplateSyntaxError` if ``'request'``
          is not in ``context``, or if the former does not have an experiments
          manager.

        """
        if "request" not in context:
            logger.error(REQUEST_CONTEXT_PROCESSOR_WARNING)
            raise TemplateSyntaxError(REQUEST_CONTEXT_PROCESSOR_WARNING)

        request = context["request"]
        exp_manager = request.experiments_manager
        if not exp_manager:
            logger.error(SPLANGO_MIDDLEWARE_WARNING)
            raise TemplateSyntaxError(SPLANGO_MIDDLEWARE_WARNING)

        #resolve template vars, throws an error
        exp_name = self.exp_name_var.resolve(context)
        variants = self.variants_str_var.resolve(context)
        variants = [v.strip() for v in variants.split(u',')]

        variant = exp_manager.declare_and_enroll(exp_name, variants)
        context[CTX_PREFIX + exp_name] = variant
        msg = ("Completed ExperimentNode.render"
               "\nexp name: %s, exp variants: %s, enrolled variant: %s" %
               (exp_name, variants, variant))
        logger.debug(msg)

        return ""

class HypNode(django.template.Node):

    """Template node for a ``{% hyp %}`` template tag.

    This :meth:`render` method of this class either returns an empty string
    or the inner nodes rendered.

    """

    def __init__(self, exp_name, exp_variant, node_list):
        self.exp_name_var = django.template.Variable(exp_name)
        self.exp_variant_var = django.template.Variable(exp_variant)

        self.node_list = node_list

    def render(self, context):
        """Render the node list if :attr:`exp_variant` is the enrolled variant.

        :param context: template context
        :type context: :class:`django.template.context.Context`
        :return: :attr:`node_list` rendered or an empty string
        :rtype: basestring
        :raises: :class:`django.template.TemplateSyntaxError` if the experiment
          named :attr:`exp_name` has not been declared yet

        """

        #resolve template vars, throws an error
        exp_name = self.exp_name_var.resolve(context)
        exp_variant = self.exp_variant_var.resolve(context)

        msg = ("Rendering HypNode. exp name: %s, exp variant: %s" %
               (exp_name, exp_variant))
        logger.debug(msg)

        enrolled_variant_name = self._get_enrolled_variant_name(context)
        logger.debug("enrolled variant name %s" % enrolled_variant_name)

        if exp_variant == enrolled_variant_name:
            # render the contents within {% hyp %} and {% endhyp %}
            return self.node_list.render(context)
        else:
            # render nothing and the contents are discarded
            logger.debug("HypNode(%s, %s) not rendered" %
                         (exp_name, exp_variant))
            return ""

    def _get_enrolled_variant_name(self, context):
        exp_name = self.exp_name_var.resolve(context)
        ctx_var = CTX_PREFIX + exp_name
        if ctx_var not in context:
            logger.error(UNDECLARED_EXPERIMENT_WARNING)
            raise TemplateSyntaxError(UNDECLARED_EXPERIMENT_WARNING)
        return context[ctx_var].name

@register.simple_tag(takes_context=True)
def enrolled_variant_name(context, exp_name):
    '''
    Returns the enrolled variant's name
    '''
    ctx_var = CTX_PREFIX + exp_name
    if ctx_var not in context:
        logger.error(UNDECLARED_EXPERIMENT_WARNING)
        raise TemplateSyntaxError(UNDECLARED_EXPERIMENT_WARNING)
    return context[ctx_var].name

@register.tag
def experiment(parser, token):
    """Return a :class:`ExperimentNode` according to the contents of ``token``.

    Example::
        {% experiment "signup_button" variants "red,blue" %}

    :param parser: template parser object, not used
    :param token: tag contents i.e. between ``{% `` and `` %}``
    :type token: :class:`django.template.base.Token`
    :return: experiment node
    :rtype: :class:`ExperimentNode`
    :raises: :class:`django.template.TemplateSyntaxError` if tag arguments
      in ``token`` are different than three

    """
    try:
        tag_name, exp_name, variants_label, variants_str = token.split_contents()
    except ValueError:
        tag_name = token.contents.split()[0]
        msg = ('%r tag requires exactly three arguments, e.g. {%% experiment '
               '"signuptext" variants "control,free,trial" %%}' % tag_name)
        logger.error(msg)
        raise TemplateSyntaxError(msg)

    return ExperimentNode(exp_name, variants_str)

@register.tag
def hyp(parser, token):
    """Return a :class:`HypNode` according to the contents of ``token``.

    Example::
        {% with exp_name="home_signup" variant_name="blue" %}
        {% hyp exp_name variant_name %}

    :param parser: template parser object
    :type parser: :class:`django.template.base.Parser`
    :param token: tag contents i.e. between ``{% `` and `` %}``
    :type token: :class:`django.template.base.Token`
    :return: experiment node
    :rtype: :class:`ExperimentNode`
    :raises: :class:`django.template.TemplateSyntaxError` if tag arguments
      in ``token`` are different than two

    """
    try:
        tag_name, exp_name, exp_variant = token.split_contents()
    except ValueError:
        tag_name = token.contents.split()[0]
        msg = "%r tag requires exactly two arguments" % tag_name
        logger.error(msg)
        raise TemplateSyntaxError(msg)

    # parse until "endhyp" and then remove that token from parser
    node_list = parser.parse(("endhyp",))
    parser.next_token()

    return HypNode(exp_name, exp_variant, node_list)

# I couldn't make this work well. Probably needs much more thought to work like
# a switch statement. See:
# http://djangosnippets.org/snippets/967/
#
# @register.tag
# def elsehyp(parser, token):
#     try:
#         tag_name, exp_variant = token.split_contents()
#     except ValueError:
#         raise TemplateSyntaxError(
#             "%r tag requires exactly one argument" % token.contents.split()[0]

#     #import pdb;pdb.set_trace()

#     print "*** elsehyp looking for next tag"
#     #print "parser.tokens = %r" % [ t.contents for t in parser.tokens ]

#     node_list = parser.parse(("elsehyp","endhyp"))

#     return HypNode(None, exp_variant, node_list)


#!/usr/bin/env python3
"""
Very simple HTTP server in python3.

Usage::
    ./dummy-web-server.py [<port>]

Send a GET request::
    curl http://localhost

Send a HEAD request::
    curl -I http://localhost

Send a POST request::
    curl -d "green=on/off&red=on/off" http://localhost
    curl -d "" http://localhost  - is the same "green=off&red=off"

"""
#from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from http.server import BaseHTTPRequestHandler, HTTPServer
#import SocketServer
import socketserver
import re
import OPi.GPIO as GPIO

class HTTP_GPIOCtrl(BaseHTTPRequestHandler):

  _unknown = """

unknown page

"""

  _form = """

GPIO LED control

<form method="post">

<input type="checkbox" name="green" value="on">green LED

<input type="checkbox" name="red" value="on">red LED

<input type="submit" value="Submit">

</form>

"""

  def __init__(self, request, client_address, server):
    BaseHTTPRequestHandler.__init__(self, request, client_address, server)

  def _set_headers(self, code=200):
    if code == 200:
      self.send_response(code)
      self.send_header('Content-type', 'text/html')
      self.end_headers()
    else:
      self.send_error(code)
      self.send_header('Content-type', 'text/html')
      self.end_headers()

  def do_GET(self):
    print('GET:->'+self.path+'<-')
    if self.path == '/':
      self._set_headers()
      self.wfile.write(bytes(self._form, "utf-8"))
      print("form")
    elif self.path == '/favicon.ico':
      self._set_headers(200)
      self.wfile.write(bytes("", "utf-8"))
      print("favicon")
#    self.wfile.write(bytes("
You accessed path: %s
" % self.path, "utf-8"))
    else:
      self._set_headers(404)
      self.wfile.write(bytes(self._unknown,"utf-8"))
      print("unknown")

  def do_HEAD(self):
    self._set_headers()

  def do_POST(self):
    content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
    post_data = self.rfile.read(content_length) # <--- Gets the data itself
    print (str(content_length) +' '+ str(post_data)) # <-- Print post data
    self._set_headers()
    self.wfile.write(bytes("
POST!
", "utf-8"))
    gpio24 = GPIO.LOW
    gpio26 = GPIO.LOW
    if content_length > 0:
      m = re.search('green=on', str(post_data))
      if m:
        gpio24 = GPIO.HIGH
      m = re.search('red=on', str(post_data))
      if m:
        gpio26 = GPIO.HIGH
    GPIO.output(24, gpio24)
    GPIO.output(26, gpio26)

#<- class HTTP_GPIOCtrl

def run(server_class=HTTPServer, handler_class=HTTP_GPIOCtrl, port=80):
  server_address = ('', port)
  httpd = server_class(server_address, handler_class)
  print('Starting httpd...')
  try:
    httpd.serve_forever()
  except KeyboardInterrupt:
    return httpd

if __name__ == "__main__":
  from sys import argv, exit

  GPIO.setmode(GPIO.BOARD)
  GPIO.setup(24, GPIO.OUT)
  GPIO.setup(26, GPIO.OUT)

  GPIO.output(24, GPIO.LOW)
  GPIO.output(26, GPIO.LOW)

  if len(argv) == 2:
      run(port=int(argv[1]))
  else:
      run().server_close()

  GPIO.cleanup()
  print('httpd exited')

  exit(0)


import streamlit as st
# To make things easier later, we're also importing numpy and pandas for
# working with sample data.
import numpy as np
import pandas as pd
from PIL import Image
from components import search,features
import os, torch, matplotlib, time, joblib, SessionState
from sklearn.neighbors import NearestNeighbors
from annoy import AnnoyIndex
from sklearn.decomposition import PCA
import streamlit.components.v1 as components

matplotlib.use('Agg')
np.random.seed(0)
session_state = SessionState.get(image='', pca='', list='')

def find(uploaded_file):
    model = features.get_model()
    preprocess = features.get_preprocess_pipeline()

    feature_list = np.load(os.path.join("output/", "features.npy"))
    filename_list = np.load(os.path.join("output/", "filenames.npy"))
    feature_list = feature_list.reshape(9997,2048)

    im = Image.open(uploaded_file)
    im = preprocess(im)
    im = im.unsqueeze(0)
    with torch.no_grad():
        input_features = model(im).numpy()
        input_features = [input_features.reshape(2048,1).flatten()]

    n_components = 128
    pca = PCA(n_components=n_components)
    components = pca.fit_transform(feature_list)
    joblib.dump(pca, os.path.join("pca.joblib"))

    feature_length = n_components
    index = AnnoyIndex(feature_length, 'angular')
    for i, j in enumerate(components):
        index.add_item(i, j)

    index.build(15, n_jobs=-1)
    index.save(os.path.join("output/", "index.annoy"))

    pca = joblib.load(os.path.join("output/", "pca.joblib"))
    components = pca.transform(input_features)[0]

    ann_index = AnnoyIndex(components.shape[0], 'angular')
    ann_index.load(os.path.join("output/", "index.annoy"))

    tic = time.perf_counter()
    indices = ann_index.get_nns_by_vector(components, 5, search_k=-1, include_distances=False)
    toc = time.perf_counter()
    st.write(f"Search finished in {toc - tic:0.4f} seconds")
    similar_image_paths = filename_list[indices]

    cols = st.beta_columns(5)
    count = 0
    for image in similar_image_paths:
        image = image.replace("\\","/")
        if count == 0:
            cols[count].image(image,caption=image[13:-4])
            count+=1
        elif count == 1:
            cols[count].image(image,caption=image[13:-4])
            count+=1
        elif count == 2:
            cols[count].image(image,caption=image[13:-4])
            count+=1
        elif count == 3:
            cols[count].image(image,caption=image[13:-4])
            count+=1
        else:
            cols[count].image(image,caption=image[13:-4])
            count-=4

    session_state.image = input_features
    session_state.pca = components
    session_state.list = feature_list

def main():
    menu = ["Home","Visualization","Abyssinian","American Bobtail","American Curl"]
    choice = st.sidebar.selectbox("Menu", menu)

    if choice == "Home":
        st.title("Visual Search Engine")
        st.header("Cat image classification example")
        st.subheader("Searching Page")
        st.text("Upload a random cat image for searching")

        uploaded_file = st.file_uploader("Choose a cat image ...", type=["png","jpg","jpeg"])
        if uploaded_file is not None:
            image = Image.open(uploaded_file)
            st.image(image, caption='Uploaded cat', use_column_width=True)
            if st.button('Find'):
                find(uploaded_file)

    elif choice == "Visualization":
        image = session_state.image
        pca = session_state.pca
        features_list = session_state.list
        cols = st.beta_columns(3)
        cols[0].dataframe(image[0])
        cols[1].text("")
        cols[1].text("")
        cols[1].text("")
        cols[1].text("")
        cols[1].text("")
        cols[1].text("")
        cols[1].text("")
        cols[1].markdown("<h1 style='display: flex; justify-content: center; align-items: center; color: red;'> ===> </h1>", unsafe_allow_html=True)
        cols[2].dataframe(pca)
        st.dataframe(features_list[0:100])

    elif choice == "Abyssinian":
        st.subheader("List of Abyssinian cats")
        filenames = os.listdir("data/images/Abyssinian")
        cols = st.beta_columns(4)
        count=0
        for idx,file in enumerate(filenames):
            if count == 0:
                cols[count].image("data/images/Abyssinian/" + file, caption="Abyssian "+file[0:-4])
                count+=1
            elif count == 1:
                cols[count].image("data/images/Abyssinian/" + file, caption="Abyssian "+file[0:-4])
                count+=1
            elif count == 2:
                cols[count].image("data/images/Abyssinian/" + file, caption="Abyssian "+file[0:-4])
                count+=1
            else:
                cols[count].image("data/images/Abyssinian/" + file, caption="Abyssian "+file[0:-4])
                count-=3

    elif choice == "American Bobtail":
        st.subheader("List of American Bobtail cats")
        filenames = os.listdir("data/images/American Bobtail")
        cols = st.beta_columns(4)
        count=0
        for idx,file in enumerate(filenames):
            if count == 0:
                cols[count].image("data/images/American Bobtail/" + file, caption="Abyssian "+file[0:-4])
                count+=1
            elif count == 1:
                cols[count].image("data/images/American Bobtail/" + file, caption="Abyssian "+file[0:-4])
                count+=1
            elif count == 2:
                cols[count].image("data/images/American Bobtail/" + file, caption="Abyssian "+file[0:-4])
                count+=1
            else:
                cols[count].image("data/images/American Bobtail/" + file, caption="Abyssian "+file[0:-4])
                count-=3

    else:
        st.subheader("List of American Curl cats")
        filenames = os.listdir("data/images/American Curl")
        cols = st.beta_columns(4)
        count=0
        for idx,file in enumerate(filenames):
            if count == 0:
                cols[count].image("data/images/American Curl/" + file, caption="Abyssian "+file[0:-4])
                count+=1
            elif count == 1:
                cols[count].image("data/images/American Curl/" + file, caption="Abyssian "+file[0:-4])
                count+=1
            elif count == 2:
                cols[count].image("data/images/American Curl/" + file, caption="Abyssian "+file[0:-4])
                count+=1
            else:
                cols[count].image("data/images/American Curl/" + file, caption="Abyssian "+file[0:-4])
                count-=3

if __name__ == '__main__':
    main()


#imie = 'Ala'
#if imie == 'Ania':
#    print('Czesc, Aniu!')
#elif imie == 'Ola':
#    print == ('Czesc, Ola!')
#else:
#    print('czesc, nieznajomy')

# odleglosc = 7
# if odleglosc < 5:
#     print('wow ale blisko')
# elif 5 <= odleglosc < 10:
#     print('dosyc blisko')
# elif 10 <= odleglosc < 20:
#     print('zaczyna sie robic daleko')
# else:
#     print('o matko, jak daleko!')

# def hej(imie):
#     print('Hello '+ imie)

# imiona = ['Ania', 'Kasia', 'Tomek']

# for imie in imiona:
#     hej(imie)

def jak_daleko(odleglosc):
    if odleglosc < 5:
        print('wow ale blisko')
    elif 5 <= odleglosc < 10:
        print('dosyc blisko')
    elif 10 <= odleglosc < 20:
        print('zaczyna sie robic daleko')
    else:
        print('o matko, jak daleko!')

odleglosci = [11, 7, 166]
for odleglosc in odleglosci:
    jak_daleko(odleglosc)

for i in range(1, 10):
    print(i)

# jak_daleko(11)
# jak_daleko(7)
# jak_daleko(166)


import os, sys, glob

def getFiles(pathDir):
	listOfFiles = []
	#os.walk returns a 3-tuple [directorypath,directoryname,filename]
	#directorypath is the absolute path to directory
	#directory name is the assigned name of the directory
	#filename is the assigned name of the file
	for (dirpath, dirnames, filenames) in os.walk(pathDir):
		listOfFiles.extend(filenames)
	return listOfFiles

#returns a filename without tags
#assuming, tags occur in pairs
def correctFileName(filename,listOfTags):
	for tag in listOfTags:
		pos1 = filename.find(tag[0])
		if pos1 >= 0:
			pos2 = filename.find(tag[1],pos1+1)
			if pos2 >= 0:
				filename = filename[:pos1] + filename[pos2+1:]
	return filename

#returns the filepath of a given file
def filepath(filename,directory):
	return os.path.join(directory,filename)

#Rename files using os.rename
def removeTags(directory,listOfTags):
	#listOfTags is a list of tuples like [ ( '(', ')' ), ( '[' , ']' ), ( '@' , '@' ) ]
	#this function finds looks at all the files and occurences of these tags and slices away everything between them
	for (dirpath, dirnames, filenames) in os.walk(directory):
		#for all files, iterate and rename correctly
		for files in filenames:
			#function filepath joins the filename with the directory name
			os.rename(filepath(files,dirpath),filpath(correctFileName(files,listOfTags),dirpath))


#!/user/bin/env python3
# -*- coding: utf-8 -*-
#
# Print triangle
#

# num >= 2
def print_solid_triangle(num = 2, ch = '*'):
    '''

    '''
    if num < 2:
        num = 2
    empty_num = num - 1
    solid_num = 1
    for i in range(num):
        print(" " * empty_num, end="")
        empty_num -= 1
        print("%s" % (ch) * solid_num)
        solid_num += 2

# num >= 3
# width = 2 * num - 1
def print_hollow_triangle(num = 3, ch = '*'):
    '''

    '''
    if num < 3:
        num = 3
    empty_num = num - 1
    for i in range(num):
        if i == 0:
            print(" " * empty_num + ch)
        elif i == num - 1:
            print(ch * (2 * num - 1))
        else:
            print(" " * empty_num, end="")
            print(ch + " " * (2 * (i + 1) - 3) + ch)
        empty_num -= 1

# num >= 7
# triangle num = (num + 1) / 4
def print_complex_triangle(num = 7, ch = '*'):
    '''

    '''
    if num < 7:
        num = 7
    empty_num = num - 1
    for i in range(num):
        if i == 0:
            print(" " * empty_num + ch)
        elif i == num - 1:
            print(ch * (2 * num - 1))
        else:
            print(" " * empty_num, end="")
            print(ch + print_triangle(num - 4, i, ch) + ch)
        empty_num -= 1

def print_triangle(num, line, ch):
    row = line - 1
    if row == 1:
        return ' ' + ch + ' '
    elif row == num:
        return ' ' + ch * (2 * num - 1) + ' '
    elif row > 1 and row < num:
        return ' ' + ch + " " * (2 * row - 3) + ch + ' '
    else:
        return " " * (2 * line - 1)

# 空心三角形套空心三角形
# 用比较笨的办法，找规律做出来的
def print_xxx_triangle(num = 7, ch = '*'):
    triangle_num = int((num + 1) / 4)
    empty_num = num - 1
    tmp_triangle = triangle_num - 2
    middle_empty = 2
    empty_line = 0
    start = 0
    right_triangle = (num + 1) % 4
    fix_num = 0
    for line in range(num):
        line = line + 1
        # 每行输出开始的空格，在输入第一个字符
        print(" " * empty_num + ch, end='')

        # 第一行
        if line == 1:
            print("")
        # 最后一行
        elif line == num:
            print(ch * (2 * num - 1 - 1))

        # 输出到最里面一个三角形的顶部
        elif line >= 1 and line <= triangle_num * 2:
            print((' ' + ch) * (line - 1))
        # 输出到最里面一个三星形的底部(不输出底部)
        elif line > triangle_num * 2 and line < (num - (triangle_num - 1) * 2):
            print((' ' + ch) * (triangle_num - 1) + ' ' * middle_empty + (' ' + ch) * triangle_num)
            middle_empty += 2

        # 从最里面三角形的底部开始输出
        elif line >= (num - (triangle_num - 1) * 2):
            high = 0
            # 先计算最里面三角形的高，根据高来算出底部要填充多少位字符
            if right_triangle != 0: # 要分开不是正嵌套三角形
                if start == 0 and empty_line == 0:
                    fix_num = line - 2 * triangle_num + 2
                high = fix_num + start * 4
            else: # 和正嵌套三角形
                high = 3 + start * 4

            # 填充三角形底部字符的
            if empty_line == 0:
                print((' ' + ch) * tmp_triangle + ' ' + ch * (high * 2 -1)  + (' ' + ch) * (tmp_triangle + 1) )
                empty_line = 1
            # 填充三角形底部下面的空白行
            elif empty_line == 1:
                print((' ' + ch) * tmp_triangle + '  ' + ' ' * (high * 2 -1) + ' ' + (' ' + ch) * (tmp_triangle + 1) )
                empty_line = 0
                tmp_triangle -= 1
                start += 1

        empty_num -= 1

if __name__ == "__main__":
    title = 0
    num = 0
    while True:
        print("\n\n请选择你要打印的三角形:")
        print("1. 等腰三角形")
        print("2. 等腰空心三角形")
        print("3. 等腰空心三角形套等腰空心三角形")
        print("0. 退出")

        title = input(">>> ")
        if int(title) in [1, 2, 3]:
            while True:
                num = input("\n请选择三角形的高度(返回上一层请输0)\n>>> ")
                if int(num) > 0:
                    if int(title) == 1:
                        print_solid_triangle(int(num))
                    elif int(title) == 2:
                        print_hollow_triangle(int(num))
                    elif int(title) == 3:
                        print_xxx_triangle(int(num))
                    break
                elif int(num) == 0:
                    break
                else:
                    print("\n请重新输入正确数字\n")
        elif int(title) == 0:
            print("Bye~")
            break
        else:
            print("\n选择错误，请重新选择\n")


import nibabel as nib
from time import time

import pimms

from AFQ.tasks.decorators import as_file, as_img
from AFQ.tasks.utils import with_name
from AFQ.definitions.utils import Definition
import AFQ.tractography as aft

outputs = ["seed_file", "stop_file", "streamlines_file"]

@pimms.calc("seed_file")
@as_file('_seed_mask.nii.gz')
@as_img
def export_seed_mask(subses_dict, dwi_affine, tracking_params):
    seed_mask = tracking_params['seed_mask']
    seed_mask_desc = dict(source=tracking_params['seed_mask'])
    return seed_mask, seed_mask_desc

@pimms.calc("stop_file")
@as_file('_stop_mask.nii.gz')
@as_img
def export_stop_mask(subses_dict, dwi_affine, tracking_params):
    stop_mask = tracking_params['stop_mask']
    stop_mask_desc = dict(source=tracking_params['stop_mask'])
    return stop_mask, stop_mask_desc

@pimms.calc("stop_file")
def export_stop_mask_pft(pve_wm, pve_gm, pve_csf):
    return {"stop_file": [pve_wm, pve_gm, pve_csf]}

@pimms.calc("streamlines_file")
@as_file('_tractography.trk', include_track=True)
def streamlines(subses_dict, data_imap, seed_file, stop_file,
                tracking_params):
    this_tracking_params = tracking_params.copy()

    # get odf_model
    odf_model = this_tracking_params["odf_model"]
    if odf_model == "DTI":
        params_file = data_imap["dti_params_file"]
    elif odf_model == "CSD" or odf_model == "MSMT":
        params_file = data_imap["csd_params_file"]
    elif odf_model == "DKI":
        params_file = data_imap["dki_params_file"]
    else:
        raise TypeError((
            f"The ODF model you gave ({odf_model}) was not recognized"))

    # get masks
    this_tracking_params['seed_mask'] = nib.load(seed_file).get_fdata()
    if isinstance(stop_file, str):
        this_tracking_params['stop_mask'] = nib.load(stop_file).get_fdata()
    else:
        this_tracking_params['stop_mask'] = stop_file

    # perform tractography
    start_time = time()
    sft = aft.track(params_file, **this_tracking_params)
    sft.to_vox()
    meta_directions = {
        "det": "deterministic",
        "prob": "probabilistic"}
    meta = dict(
        TractographyClass="local",
        TractographyMethod=meta_directions[
            tracking_params["directions"]],
        Count=len(sft.streamlines),
        Seeding=dict(
            ROI=seed_file,
            n_seeds=tracking_params["n_seeds"],
            random_seeds=tracking_params["random_seeds"]),
        Constraints=dict(ROI=stop_file),
        Parameters=dict(
            Units="mm",
            StepSize=tracking_params["step_size"],
            MinimumLength=tracking_params["min_length"],
            MaximumLength=tracking_params["max_length"],
            Unidirectional=False),
        Timing=time() - start_time)

    return sft, meta

@pimms.calc("streamlines_file")
def custom_tractography(custom_tract_file):
    return custom_tract_file

def get_tractography_plan(custom_tractography_bids_filters, tracking_params):
    tractography_tasks = with_name([
        export_seed_mask, export_stop_mask, streamlines])

    if custom_tractography_bids_filters is not None:
        tractography_tasks["streamlines_res"] = custom_tractography

    stop_mask = tracking_params['stop_mask']
    if tracking_params["tracker"] == "pft":
        probseg_funcs = stop_mask.get_mask_getter()
        tractography_tasks["wm_res"] = pimms.calc("pve_wm")(probseg_funcs[0])
        tractography_tasks["gm_res"] = pimms.calc("pve_gm")(probseg_funcs[1])
        tractography_tasks["csf_res"] = pimms.calc("pve_csf")(probseg_funcs[2])
        tractography_tasks["export_stop_mask_res"] = \
            export_stop_mask_pft
    else:
        if isinstance(stop_mask, Definition):
            tractography_tasks["export_stop_mask_res"] =\
                pimms.calc("stop_file")(as_file('_stop_mask.nii.gz')(
                    stop_mask.get_mask_getter()))

    if isinstance(tracking_params['seed_mask'], Definition):
        tractography_tasks["export_seed_mask_res"] = pimms.calc("seed_file")(
            as_file('_seed_mask.nii.gz')(
                tracking_params['seed_mask'].get_mask_getter()))

    return pimms.plan(**tractography_tasks)


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import interpolate

data = pd.read_csv('phys_dat.csv') # Lectura de datos: k, cp, rho
Dth_data = data['k'] / (data['rho']*data['cp']) # Cálculo del coeficiente Dth

print('\nDatos del problema \n{}'.format(data))
print('\n Dth : \n{}'.format(Dth_data))

def arithmeticMean(a, b):
    """
    Calcula la media aritmética entre a y b.

    Parameters
    ----------
    a, b: int
    Valores a interpolar.

    Returns
    -------
    La media aritmética.
    """
    return 0.5 * (a + b)

def harmonicMean(a, b):
    """
    Calcula la media harmónica entre a y b.

    Parameters
    ----------
    a, b: int
    Valores a interpolar.

    Returns
    -------
    La media harmónica.
    """
    return 2 * a * b / (a + b)

def Laplaciano1D(N, d, f=None):
    """
    Calcula la matriz del Laplaciano usando diferencias finitas en 1D.

    Parameters
    ----------
    N: int
    Tamaño de la matriz

    d: float
    Valores del coeficiente Gamma de la ecuación.

    f: function
    Función para calcular el promedio entre dos valores.

    Returns
    -------
    A: ndarray
    La matriz del sistema.
    """
    if f == None:
        A = np.zeros((N,N))
        A[0, 0] = -2 * d[1]
        A[0, 1] = d[1]

        for i in range(1,N-1):
            A[i,i] = -2 * d[i+1]
            A[i,i+1] = d[i+1] #harmonicMean(d[i], d[i+1])
            A[i,i-1] = d[i] #harmonicMean(d[i], d[i+1])

        A[N-1,N-2] = d[N]
        A[N-1,N-1] = -2 * d[N]

    else:
        A = np.zeros((N,N))
        A[0, 0] -= ( f(d[0], d[1]) + f(d[1], d[2]) )
        A[0, 1] = f(d[1], d[2])

        for i in range(1,N-1):
            A[i,i] -= ( f(d[i], d[i+1]) + f(d[i+1], d[i+2]) )
            A[i,i+1] = f(d[i+1], d[i+2])
            A[i,i-1] = f(d[i+1], d[i])

        A[N-1,N-2] = f(d[N-1], d[N])
        A[N-1,N-1] -= ( f(d[N-1], d[N]) + f(d[N], d[N+1]) )

    return A

def Laplaciano1D_NS(N, d, f=None):
    """
    Calcula la matriz del Laplaciano usando diferencias finitas en 1D.

    Parameters
    ----------
    N: int
    Tamaño de la matriz

    d: float
    Valores del coeficiente Gamma de la ecuación.

    f: function
    Función para calcular el promedio entre dos valores.

    Returns
    -------
    A: ndarray
    La matriz del sistema.
    """
    if f == None:
        A = np.zeros((N,N))
        A[0, 0] = ( 2 * d[1] + 1 )
        A[0, 1] = -d[1]

        for i in range(1,N-1):
            A[i,i] = ( 2 * d[i+1] + 1 )
            A[i,i+1] = -harmonicMean(d[i], d[i+1])
            A[i,i-1] = -harmonicMean(d[i], d[i+1])

        A[N-1,N-2] = -d[N]
        A[N-1,N-1] = ( 2 * d[N] + 1)

    else:
        A = np.zeros((N,N))
        A[0, 0] = ( f(d[0], d[1]) + f(d[1], d[2]) + 1 )
        A[0, 1] = -f(d[1], d[2])
        for i in range(1,N-1):
            A[i,i] = ( f(d[i], d[i+1]) + f(d[i+1], d[i+2]) + 1 )
            A[i,i+1] = -f(d[i+1], d[i+2])
            A[i,i-1] = -f(d[i+1], d[i])

        A[N-1,N-2] = -f(d[N-1], d[N])
        A[N-1,N-1] = ( f(d[N-1], d[N]) + f(d[N], d[N+1]) + 1)

    return A

def calcDth(Dth_data, z, N):
    """
    Calcula el Dth.

    Parameters
    ----------
    z, N: int

    """
    Dth = np.zeros((N+2))
    for k in range(0, N+2):
        if (z[k] <= 50.0):
            Dth[k] = Dth_data[0]
        elif ((z[k] > 50.0) and (z[k] <= 250.0)):
            Dth[k] = Dth_data[1]
        elif ((z[k] > 250.0) and (z[k] <= 400.0)):
            Dth[k] = Dth_data[2]
        elif ((z[k] > 400.0) and (z[k] <= 600.0)):
            Dth[k] = Dth_data[3]
        elif ((z[k] > 600.0) and (z[k] <= 800.0)):
            Dth[k] = Dth_data[4]
        elif ((z[k] > 800.0) and (z[k] <= 1000.0)):
            Dth[k] = Dth_data[5]
        elif ((z[k] > 1000.0) and (z[k] <= 1500.0)):
            Dth[k] = Dth_data[6]
        elif ((z[k] > 1500.0) and (z[k] <= 1900.0)):
            Dth[k] = Dth_data[7]
        else:
            Dth[k] = Dth_data[8]

    return Dth

def interpTemp(z_dat, T_dat):
    """
    Calcula la interpolacion de los datos de funcion.

    Parameters
    ----------
    z_dat, T_dat: int

    """

    z_dat = [0, 100, 200, 400, 710, 803, 1100, 1200, 1400, 1500, 1600, 1700, 1800, 2000, 2500, 3000, 3500, 4000]

    T_dat = [15, 113, 145, 178, 155, 201, 215, 282, 223, 226, 252, 284, 310, 350, 450, 550, 650, 750]
    tck_1 = interpolate.splrep(z_dat, T_dat, s = 0)

    return tck_1


from WMCore.Configuration import Configuration

config = Configuration()

config.section_("General")
config.General.requestName = "Pythia8_EmEnrichedDijet30_TuneCUETP8M1_8160GeV_EposLHC_GEN_SIM_PU" # Defaults to <time-stamp>, where the time stamp is of the form <YYYYMMDD>_<hhmmss> and corresponds to the submission time.
config.General.transferLogs = False

config.section_("JobType")
config.JobType.pluginName = "PrivateMC"
config.JobType.psetName = "Pythia8_EmEnrichedDijet30_TuneCUETP8M1_8160GeV_EposLHC_GEN_SIM_PU.py"
config.JobType.pyCfgParams=["maxEventsOutput=200"]
# config.JobType.maxMemoryMB = 3000    # request high memory machines.

## CMSSW_8_0_22
## gen fragment : https://github.com/CmsHI/genproductions/blob/master/python/HI/photon_analysis/pPb8TeV/Pythia8_EmEnrichedDijet30_TuneCUETP8M1_8160GeV_SingleParticleFilter_cff.py

config.section_("Data")
config.Data.outputPrimaryDataset = "HIRun2016PA"
config.Data.splitting = "EventBased"
## Filter efficiency (taking into account weights)= (10) / (2096) = 4.771e-03 +- 1.505e-03
## Filter efficiency (event-level)= (10) / (2096) = 4.771e-03 +- 1.505e-03
## conservative assumption : 4000 trials will give 10 events. Try 80000 units per job to output 200 events per job
TRIALPEROUTPUT = 400
OUTPUTPERJOB = 200
config.Data.unitsPerJob = TRIALPEROUTPUT * OUTPUTPERJOB
NJOBS = 250
config.Data.totalUnits = config.Data.unitsPerJob * NJOBS

config.Data.outputDatasetTag = "Pythia8_EmEnrichedDijet30_TuneCUETP8M1_8160GeV_EposLHC_GEN_SIM_PU"
config.Data.outLFNDirBase = "/store/user/katatar/"

config.section_("Site")
config.Site.storageSite = "T2_US_MIT"
config.Site.whitelist = ["T2_US_MIT"]
# config.Debug.extraJDL = ["+CMS_ALLOW_OVERFLOW=False"]


# -*- coding: utf-8 -*-
import scrapy
from book.items import BookItem

#爬取小说阅读网的免费玄幻小说(信息)
class GetbookinfoSpider(scrapy.Spider):
    name = 'getbookinfo'
    allowed_domains = ['www.readnovel.com']
    pageNum = 1
    baseURL = 'https://www.readnovel.com/finish?pageSize=10&gender=1&catId=20001&isFinish=1&isVip=1&size=-1&updT=-1&orderBy=0&pageNum='
    start_urls = [baseURL + str(pageNum)]

    def parse(self, response):
        try:

            node_list = response.xpath("//div[@class='book-info']")

            for node in node_list:

                item = BookItem()

                item['book_name'] = node.xpath("./h3/a/text()").extract()[0]

                item['book_type'] = node.xpath("./p[1]/span[1]/text()").extract()[0]

                item['book_stat'] = node.xpath("./p[1]/span[2]/text()").extract()[0]

                item['book_author'] = node.xpath("./p[1]/span[3]/text()").extract()[0]

                yield item

            if self.pageNum != 16:
                self.pageNum += 1
                yield scrapy.Request(self.baseURL + str(self.pageNum), callback=self.parse)
        except Exception as e:
            print(e)


# -*- coding: utf-8 -*-
"""
Created on Wed Sep  5 10:55:15 2018

@author: zt
"""

import os
import numpy as np
import pandas as pd
import pydicom
import matplotlib.pyplot as plt
from PIL.Image import fromarray
from  datetime import datetime

test_dir='stage_1_test_images/'
train_dir= 'stage_1_train_images/'
labels_dir='model_data/stage_1_train_labels.csv'
detailed_info_dir='model_data/stage_1_detailed_class_info.csv'

train_output_dir='train_images_jpg/'
test_output_dir= 'test_images_jpg/'
annot_path='model_data/annotation.txt'

#返回一个文件目录下面所有文件的名字
def file_name(file_dir):
    file_names=[]
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            if os.path.splitext(file)[1] == '.dcm':
                file_names.append(os.path.join(root, file))
    return file_names

#创建文件夹
def mkdir(path):

	folder = os.path.exists(path)
	if not folder:                   #判断是否存在文件夹如果不存在则创建为文件夹
		os.makedirs(path)            #makedirs 创建文件时如果路径不存在会创建这个路径
	else:pass

#讲dcm文件转换为jpg文件,提取性别 年龄信息
def dcm_to_jpg(input_dir,output_dir,isTransform=True):
    patient=pd.DataFrame()
    patientID=[]
    patientAge=[]
    patientSex=[]
    begin=datetime.now()
    files=file_name(input_dir)
    mkdir(output_dir)
    for file in files:
        ds=pydicom.dcmread(file)
#        plt.imshow(ds.pixel_array, cmap=plt.cm.bone)
#        plt.show()
        out_name=os.path.split(file)[1]
        out_name=os.path.splitext(out_name)[0]

        assert out_name==ds.PatientID,"patientID doesn't match"
        patientID.append(ds.PatientID)
        patientAge.append(ds.PatientAge)
        patientSex.append(ds.PatientSex)
        if isTransform:
            im = fromarray(ds.pixel_array)##返回的是一个Image对象
            im.save(output_dir+out_name+'.jpg')#8位像素 黑白

    print("Image format transform finished,total {} iamges".format(len(files)))
    print("It takes time:{}".format(datetime.now()-begin))
    patient['patientId'] = pd.Series(patientID)
    patient['age'] = pd.Series(patientAge,dtype=np.int16)
    patient['sex'] = pd.Series(patientSex)
    patient.sex=patient.sex.apply(lambda x :1 if x=='M' else 0)
    patient.to_csv('model_data/patient_sex_age.csv')
    return patient

#将label转换成yolov3所需的annotation格式
def image_annotations(labels,annot_path):
    labels.x=labels.x.astype(str)
    labels.y=labels.y.astype(str)
    labels.width=labels.width.astype(str)
    labels.height=labels.height.astype(str)
    labels.Target=labels.Target.astype(str)
    unique_label=labels.groupby('patientId').agg(lambda x:':'.join(x)).reset_index()

    with open(annot_path,'w') as f:
        for i in range(unique_label.shape[0]):##every patient
            patientId=unique_label.patientId[i]
            targets=unique_label.Target[i].split(':')
            f.write(patientId+'.jpg ')
            if targets[0]=='1':#means have target,maybe more than one
                for bi in range(len(targets)):
                    x=unique_label.x[i].split(':')[bi]
                    y=unique_label.y[i].split(':')[bi]
                    width=unique_label.width[i].split(':')[bi]
                    height=unique_label.height[i].split(':')[bi]
                    target='1'
                    box=x+','+y+','+width+','+height+','+target+'     '
                    f.write(box)
            else:pass
            f.write('\n')

if __name__=='__main__':
    if 0:
        patient_test=dcm_to_jpg(test_dir,test_output_dir,isTransform=True)#1000
        patient_train=dcm_to_jpg(train_dir,train_output_dir,isTransform=True)#25684

    if 1:
        labels=pd.read_csv(labels_dir)
        detailed_info=pd.read_csv(detailed_info_dir)

        patient_train=pd.read_csv('model_data/patient_sex_age.csv')
        target=labels[['patientId','Target']].groupby('patientId').agg(sum).reset_index()
        target.Target=target.Target.apply(lambda x:1 if x>0 else x)
        patient=patient_train.merge(target,on='patientId',how='left')
        patient_men=patient[patient.sex==1]
        patient_women=patient[patient.sex==0]
#        plt.scatter(list(patient_men.age.values), patient_men.Target.values, c = patient_men.Target.values)

        image_annotations(labels,annot_path)

        del test_dir,train_dir,labels_dir,detailed_info_dir,train_output_dir,test_output_dir,annot_path


def max_prod_subarr(nums):
    if not nums:
        return 0
    currProd, maxProd = nums[0], float("-inf")
    for i in nums[1:]:
        currProd = max(i, currProd * i)
        maxProd = max(currProd, maxProd)

    return maxProd

expected = 6
actual = max_prod_subarr([2, 3, -2, 4])
print(expected == actual)


import os
import pandas as pd
import librosa
import librosa.display
import numpy as np
import keras
from sklearn.preprocessing import LabelEncoder

from config import settings

def extract_emotion(file_name):
    #print("voice_test 경로", os.path.dirname( os.path.abspath( __file__ ) ))

    WAV_FILE_PATH = os.path.join(settings.MEDIA_ROOT , file_name)

    # mfcc로 특징 추출
    X, sample_rate = librosa.load(WAV_FILE_PATH, res_type='kaiser_fast', duration=2.5, sr=22050*2, offset=0.5)
    sample_rate = np.array(sample_rate)
    mfccs = np.mean(librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=13), axis=0)
    featurelive = mfccs
    livedf2 = featurelive

    # shape (216,0)으로 맞추기
    array_len = len(livedf2)
    count = array_len%216

    if int(array_len/216) > 0:
        for i in range(count):
            livedf2 = np.delete(livedf2, [len(livedf2)-1])
    else:
        for i in range(216 - count):
            livedf2 = np.append(livedf2, 0)

    array_len = len(livedf2)

    # DataFrame 객체 생성
    livedf2 = pd.DataFrame(data=livedf2)
    livedf2 = livedf2.stack().to_frame().T

    # 모델 불러오기
    from keras.models import model_from_json
    json_file = open(os.path.join(os.path.dirname( os.path.abspath( __file__ ) ),'saved_models/model.json'), 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = model_from_json(loaded_model_json)
    # load weights into new model
    loaded_model.load_weights(os.path.join(os.path.dirname( os.path.abspath( __file__ ) ),'saved_models/Emotion_Voice_Detection_Model.h5'))

    # evaluate loaded model on test data
    opt = keras.optimizers.rmsprop(lr=0.00001, decay=1e-6)
    loaded_model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])

    # 배열의 차원 확장하기
    twodim = np.expand_dims(livedf2, axis=2)

    # 테스트 데이터 예측
    livepreds = loaded_model.predict(twodim, batch_size=32, verbose=1)

    livepreds1=livepreds.argmax(axis=1)
    liveabc = livepreds1.astype(int).flatten()

    # 라벨 리스트
    labels = ['female_angry', 'female_calm', 'female_fearful', 'female_happy', 'female_sad', 'male_angry', 'male_calm', 'male_fearful', 'male_happy', 'male_sad']

    lb = LabelEncoder()
    lb.fit(labels)
    livepredictions = (lb.inverse_transform(liveabc))

    print('livepredictions: ',livepredictions)

    emotion_prediction = livepredictions[0].split('_')[1]
    return emotion_prediction

if __name__ == '__main__':
    print(extract_emotion('../.media_root/001.wav'))


#Номера столбцов
class Ranges:
    """Class for ranges"""
    def __init__(self):
        self.date=3
        self.reason=17
        self.version=27
        self.os=28
        self.ip=4
        self.email=26
        self.reasonsRange=range(9,17)
    def __init__(self,type):
        if type=="custo":
            self.date=3
            self.reason=16
            self.version=17
            self.os=18
            self.ip=4
            self.email=5
            self.reasonsRange=range(9,16)
        if type=="current":
            self.date=3
            self.reason=17
            self.version=54
            self.os=55
            self.ip=4
            self.email=53
            self.reasonsRange=range(9,17)
            self.clid=59
            self.partner_id=58
            self.brand_id=57
            self.date_install=56
        if type=="10.2014":
            self.date=3
            self.reason=17
            self.version=64
            self.os=65
            self.ip=4
            self.email=62
            self.reasonsRange=range(9,18)
        if type=="04.2014":
            self.date=3
            self.reason=17
            self.version=24
            self.os=25
            self.ip=4
            self.email=22
            self.reasonsRange=range(9,17)


# 生成随机验证码

class Captcha(object):
    # 生成随机验证码
    def create_code(self):
        import random
        code = ""
        for i in range(6):
            code += str(random.randint(0, 9))
        return code

    # 将手机号与验证码存入redis
    def save_code(self, phone, code):
        from redis import Redis
        import time
        time = time.time()
        redis = Redis(host='123.57.70.140', port=6379)
        info = {"phone": phone, "code": code, "time": time}
        redis.set(phone, info)

    # 获取redis中的手机号0的验证码
    def get_code(self, phone):
        from redis import Redis
        redis = Redis(host='123.57.70.140', port=6379)
        info = redis.get(phone)
        print(info)

if __name__ == '__main__':
    captcha = Captcha()
    captcha.save_code(15234958824,123456)
    # captcha.get_code(15234958824)


# Copyright (c) 2011-2020 Eric Froemling
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# -----------------------------------------------------------------------------
"""UIs for debugging purposes."""

from __future__ import annotations

from typing import TYPE_CHECKING, cast

import ba

if TYPE_CHECKING:
    pass

class DebugWindow(ba.Window):
    """Window for debugging internal values."""

    def __init__(self, transition: str = 'in_right'):
        # pylint: disable=too-many-statements
        # pylint: disable=cyclic-import
        from bastd.ui import popup

        self._width = width = 580
        self._height = height = (350 if ba.app.small_ui else
                                 420 if ba.app.med_ui else 520)

        self._scroll_width = self._width - 100
        self._scroll_height = self._height - 120

        self._sub_width = self._scroll_width * 0.95
        self._sub_height = 520

        self._stress_test_game_type = 'Random'
        self._stress_test_playlist = '__default__'
        self._stress_test_player_count = 8
        self._stress_test_round_duration = 30

        self._r = 'debugWindow'
        super().__init__(root_widget=ba.containerwidget(
            size=(width, height),
            transition=transition,
            scale=(
                2.35 if ba.app.small_ui else 1.55 if ba.app.med_ui else 1.0),
            stack_offset=(0, -30) if ba.app.small_ui else (0, 0)))

        self._done_button = btn = ba.buttonwidget(
            parent=self._root_widget,
            position=(40, height - 67),
            size=(120, 60),
            scale=0.8,
            autoselect=True,
            label=ba.Lstr(resource='doneText'),
            on_activate_call=self._done)
        ba.containerwidget(edit=self._root_widget, cancel_button=btn)
        ba.textwidget(parent=self._root_widget,
                      position=(0, height - 60),
                      size=(width, 30),
                      text=ba.Lstr(resource=self._r + '.titleText'),
                      h_align='center',
                      color=ba.app.title_color,
                      v_align='center',
                      maxwidth=260)

        self._scrollwidget = ba.scrollwidget(
            parent=self._root_widget,
            highlight=False,
            size=(self._scroll_width, self._scroll_height),
            position=((self._width - self._scroll_width) * 0.5, 50))
        ba.containerwidget(edit=self._scrollwidget, claims_left_right=True)

        self._subcontainer = ba.containerwidget(parent=self._scrollwidget,
                                                size=(self._sub_width,
                                                      self._sub_height),
                                                background=False)

        v = self._sub_height - 70
        button_width = 300
        btn = ba.buttonwidget(
            parent=self._subcontainer,
            position=((self._sub_width - button_width) * 0.5, v),
            size=(button_width, 60),
            autoselect=True,
            label=ba.Lstr(resource=self._r + '.runCPUBenchmarkText'),
            on_activate_call=self._run_cpu_benchmark_pressed)
        ba.widget(edit=btn,
                  up_widget=self._done_button,
                  left_widget=self._done_button)
        v -= 60

        ba.buttonwidget(parent=self._subcontainer,
                        position=((self._sub_width - button_width) * 0.5, v),
                        size=(button_width, 60),
                        autoselect=True,
                        label=ba.Lstr(resource=self._r +
                                      '.runGPUBenchmarkText'),
                        on_activate_call=self._run_gpu_benchmark_pressed)
        v -= 60

        ba.buttonwidget(
            parent=self._subcontainer,
            position=((self._sub_width - button_width) * 0.5, v),
            size=(button_width, 60),
            autoselect=True,
            label=ba.Lstr(resource=self._r + '.runMediaReloadBenchmarkText'),
            on_activate_call=self._run_media_reload_benchmark_pressed)
        v -= 60

        ba.textwidget(parent=self._subcontainer,
                      position=(self._sub_width * 0.5, v + 22),
                      size=(0, 0),
                      text=ba.Lstr(resource=self._r + '.stressTestTitleText'),
                      maxwidth=200,
                      color=ba.app.heading_color,
                      scale=0.85,
                      h_align='center',
                      v_align='center')
        v -= 45

        x_offs = 165
        ba.textwidget(parent=self._subcontainer,
                      position=(x_offs - 10, v + 22),
                      size=(0, 0),
                      text=ba.Lstr(resource=self._r +
                                   '.stressTestPlaylistTypeText'),
                      maxwidth=130,
                      color=ba.app.heading_color,
                      scale=0.65,
                      h_align='right',
                      v_align='center')

        popup.PopupMenu(
            parent=self._subcontainer,
            position=(x_offs, v),
            width=150,
            choices=['Random', 'Teams', 'Free-For-All'],
            choices_display=[
                ba.Lstr(resource=a) for a in [
                    'randomText', 'playModes.teamsText',
                    'playModes.freeForAllText'
                ]
            ],
            current_choice='Auto',
            on_value_change_call=self._stress_test_game_type_selected)

        v -= 46
        ba.textwidget(parent=self._subcontainer,
                      position=(x_offs - 10, v + 22),
                      size=(0, 0),
                      text=ba.Lstr(resource=self._r +
                                   '.stressTestPlaylistNameText'),
                      maxwidth=130,
                      color=ba.app.heading_color,
                      scale=0.65,
                      h_align='right',
                      v_align='center')

        self._stress_test_playlist_name_field = ba.textwidget(
            parent=self._subcontainer,
            position=(x_offs + 5, v - 5),
            size=(250, 46),
            text=self._stress_test_playlist,
            h_align='left',
            v_align='center',
            autoselect=True,
            color=(0.9, 0.9, 0.9, 1.0),
            description=ba.Lstr(resource=self._r +
                                '.stressTestPlaylistDescriptionText'),
            editable=True,
            padding=4)
        v -= 29
        x_sub = 60

        # Player count.
        ba.textwidget(parent=self._subcontainer,
                      position=(x_offs - 10, v),
                      size=(0, 0),
                      text=ba.Lstr(resource=self._r +
                                   '.stressTestPlayerCountText'),
                      color=(0.8, 0.8, 0.8, 1.0),
                      h_align='right',
                      v_align='center',
                      scale=0.65,
                      maxwidth=130)
        self._stress_test_player_count_text = ba.textwidget(
            parent=self._subcontainer,
            position=(246 - x_sub, v - 14),
            size=(60, 28),
            editable=False,
            color=(0.3, 1.0, 0.3, 1.0),
            h_align='right',
            v_align='center',
            text=str(self._stress_test_player_count),
            padding=2)
        ba.buttonwidget(parent=self._subcontainer,
                        position=(330 - x_sub, v - 11),
                        size=(28, 28),
                        label='-',
                        autoselect=True,
                        on_activate_call=ba.Call(
                            self._stress_test_player_count_decrement),
                        repeat=True,
                        enable_sound=True)
        ba.buttonwidget(parent=self._subcontainer,
                        position=(380 - x_sub, v - 11),
                        size=(28, 28),
                        label='+',
                        autoselect=True,
                        on_activate_call=ba.Call(
                            self._stress_test_player_count_increment),
                        repeat=True,
                        enable_sound=True)
        v -= 42

        # Round duration.
        ba.textwidget(parent=self._subcontainer,
                      position=(x_offs - 10, v),
                      size=(0, 0),
                      text=ba.Lstr(resource=self._r +
                                   '.stressTestRoundDurationText'),
                      color=(0.8, 0.8, 0.8, 1.0),
                      h_align='right',
                      v_align='center',
                      scale=0.65,
                      maxwidth=130)
        self._stress_test_round_duration_text = ba.textwidget(
            parent=self._subcontainer,
            position=(246 - x_sub, v - 14),
            size=(60, 28),
            editable=False,
            color=(0.3, 1.0, 0.3, 1.0),
            h_align='right',
            v_align='center',
            text=str(self._stress_test_round_duration),
            padding=2)
        ba.buttonwidget(parent=self._subcontainer,
                        position=(330 - x_sub, v - 11),
                        size=(28, 28),
                        label='-',
                        autoselect=True,
                        on_activate_call=ba.Call(
                            self._stress_test_round_duration_decrement),
                        repeat=True,
                        enable_sound=True)
        ba.buttonwidget(parent=self._subcontainer,
                        position=(380 - x_sub, v - 11),
                        size=(28, 28),
                        label='+',
                        autoselect=True,
                        on_activate_call=ba.Call(
                            self._stress_test_round_duration_increment),
                        repeat=True,
                        enable_sound=True)
        v -= 82
        btn = ba.buttonwidget(
            parent=self._subcontainer,
            position=((self._sub_width - button_width) * 0.5, v),
            size=(button_width, 60),
            autoselect=True,
            label=ba.Lstr(resource=self._r + '.runStressTestText'),
            on_activate_call=self._stress_test_pressed)
        ba.widget(btn, show_buffer_bottom=50)

    def _stress_test_player_count_decrement(self) -> None:
        self._stress_test_player_count = max(
            1, self._stress_test_player_count - 1)
        ba.textwidget(edit=self._stress_test_player_count_text,
                      text=str(self._stress_test_player_count))

    def _stress_test_player_count_increment(self) -> None:
        self._stress_test_player_count = self._stress_test_player_count + 1
        ba.textwidget(edit=self._stress_test_player_count_text,
                      text=str(self._stress_test_player_count))

    def _stress_test_round_duration_decrement(self) -> None:
        self._stress_test_round_duration = max(
            10, self._stress_test_round_duration - 10)
        ba.textwidget(edit=self._stress_test_round_duration_text,
                      text=str(self._stress_test_round_duration))

    def _stress_test_round_duration_increment(self) -> None:
        self._stress_test_round_duration = (self._stress_test_round_duration +
                                            10)
        ba.textwidget(edit=self._stress_test_round_duration_text,
                      text=str(self._stress_test_round_duration))

    def _stress_test_game_type_selected(self, game_type: str) -> None:
        self._stress_test_game_type = game_type

    def _run_cpu_benchmark_pressed(self) -> None:
        from ba.internal import run_cpu_benchmark
        run_cpu_benchmark()

    def _run_gpu_benchmark_pressed(self) -> None:
        from ba.internal import run_gpu_benchmark
        run_gpu_benchmark()

    def _run_media_reload_benchmark_pressed(self) -> None:
        from ba.internal import run_media_reload_benchmark
        run_media_reload_benchmark()

    def _stress_test_pressed(self) -> None:
        from ba.internal import run_stress_test
        run_stress_test(
            playlist_type=self._stress_test_game_type,
            playlist_name=cast(
                str,
                ba.textwidget(query=self._stress_test_playlist_name_field)),
            player_count=self._stress_test_player_count,
            round_duration=self._stress_test_round_duration)
        ba.containerwidget(edit=self._root_widget, transition='out_right')

    def _done(self) -> None:
        # pylint: disable=cyclic-import
        from bastd.ui.settings.advanced import AdvancedSettingsWindow
        ba.containerwidget(edit=self._root_widget, transition='out_right')
        ba.app.main_menu_window = (AdvancedSettingsWindow(
            transition='in_left').get_root_widget())


import tensorflow as tf

@tf.function
def get_loss(y_actual, y_prediccion):
    b, f, _ = y_prediccion.get_shape()
    labels, long_labels, long_frames = y_actual
    long_frames = tf.fill([b, 1], f)

    long_labels = tf.reshape(long_labels, [-1])
    long_frames = tf.reshape(long_frames, [-1])

    loss = tf.nn.ctc_loss(labels, y_prediccion, long_labels,
            long_frames, logits_time_major=False, blank_index=-1)

    return tf.reduce_mean(loss)


from scipy.misc import imread
import scipy
import copy,os
import numpy as np
class ImagePool(object):
    def __init__(self, maxsize=50):
        self.maxsize = maxsize
        self.num_img = 0
        self.images = []

    def __call__(self, image):
        if self.maxsize <= 0:
            return image
        if self.num_img < self.maxsize:
            self.images.append(image)
            self.num_img += 1
            return image
        if np.random.rand() > 0.5:
            idx = int(np.random.rand()*self.maxsize)
            tmp1 = copy.copy(self.images[idx])[0]
            self.images[idx][0] = image[0]
            idx = int(np.random.rand()*self.maxsize)
            tmp2 = copy.copy(self.images[idx])[1]
            self.images[idx][1] = image[1]
            return [tmp1, tmp2]
        else:
            return image

def load_test_data(image_path, fine_size=256):
    img = imread(image_path, mode='RGB').astype(np.float)
    img = scipy.misc.imresize(img, [fine_size, fine_size])
    img = img / 127.5 - 1.
    return img

def xingkong():
    img_path = 'G:/xingkong.jpg'
    img = imread(img_path, mode='RGB').astype(np.float)
    h1 = int(np.ceil(np.random.uniform(1e-2, 1080 - 512)))
    w1 = int(np.ceil(np.random.uniform(1e-2, 863 - 512)))
    img = img[h1:h1 + 512, w1:w1 + 512]
    return scipy.misc.imresize(img, [256, 256])
def load_train_data(image_path, load_size=286, fine_size=256, is_testing=False,star=False):
    if star==False:
        img_A = scipy.misc.imread(image_path[0], mode='RGB').astype(np.float)
        img_B = scipy.misc.imread(image_path[1], mode='RGB').astype(np.float)
        if not is_testing:
            img_A = scipy.misc.imresize(img_A, [load_size, load_size])
            img_B = scipy.misc.imresize(img_B, [load_size, load_size])
            h1 = int(np.ceil(np.random.uniform(1e-2, load_size - fine_size)))
            w1 = int(np.ceil(np.random.uniform(1e-2, load_size - fine_size)))
            img_A = img_A[h1:h1 + fine_size, w1:w1 + fine_size]
            img_B = img_B[h1:h1 + fine_size, w1:w1 + fine_size]
            if np.random.random() > 0.5:
                img_A = np.fliplr(img_A)
                img_B = np.fliplr(img_B)
        else:
            img_A = scipy.misc.imresize(img_A, [fine_size, fine_size])
            img_B = scipy.misc.imresize(img_B, [fine_size, fine_size])
    else:
        img_A = xingkong()
        img_B = scipy.misc.imread(image_path[1], mode='RGB').astype(np.float)
        img_B = scipy.misc.imresize(img_B, [load_size, load_size])
        h1 = int(np.ceil(np.random.uniform(1e-2, load_size - fine_size)))
        w1 = int(np.ceil(np.random.uniform(1e-2, load_size - fine_size)))
        img_B = img_B[h1:h1 + fine_size, w1:w1 + fine_size]
        if np.random.random() > 0.5:
            img_A = np.fliplr(img_A)
            img_B = np.fliplr(img_B)

    img_A = img_A/127.5 - 1.
    img_B = img_B/127.5 - 1.

    img_AB = np.concatenate((img_A, img_B), axis=2)
    # img_AB shape: (fine_size, fine_size, input_c_dim + output_c_dim)
    return img_AB

def save_images(images, size, image_path):
    images=(images+1.)/2.
    h, w = images.shape[1], images.shape[2]
    img = np.zeros((h * size[0], w * size[1], 3))
    for idx, image in enumerate(images):
        i = idx % size[1]
        j = idx // size[1]
        img[j*h:j*h+h, i*w:i*w+w, :] = image
    return scipy.misc.imsave(image_path,img)
def load_train(rootdir):
    filelist=[]
    list = os.listdir(rootdir)
    for i in range(0, len(list)):
        if '.jpg' in os.path.basename(list[i]).lower():
            filelist.append(rootdir+list[i])
    return filelist

#sample_image = np.expand_dims(load_test_data('G:/cyclegan/horse2zebra/trainA/n02381460_2.jpg'), axis=0)
#save_images(sample_image, [1, 1],  'G:/1.jpg')


import os
#reading the source file from the standard input device i.e., keyboard
sourceFileName = input('Enter the Source filename: ')

#verifying the existence of the source file
fileExists = os.path.isfile(sourceFileName)

if not fileExists:
	print(sourceFileName," does not exist")

else:
	#logic for creating a duplicate file name with source filename ending with string _Duplicate_File
	print(sourceFileName," is available for copying")
	tempFileName = sourceFileName.split('.')
	print(tempFileName)
	print('The source filename is: ',tempFileName[0])
	print('The source file extension is: ',tempFileName[1])

	destinationFileName = tempFileName[0]+'_Duplicate_File.'+tempFileName[1]
	print('The destination file name created is: ',destinationFileName)

	#reading the source file contents through the source file object named as fileReadObject
	fileReadObject = open(sourceFileName,'r')
	sourceFileContents = fileReadObject.read()
	#writing the source file contents in to the destination duplicate file
	fileWriteObject = open(destinationFileName,'w')
	fileWriteObject.write(sourceFileContents)
	fileReadObject.close()
	fileWriteObject.close()


from datetime import datetime
from flask import Flask, render_template, redirect, request, url_for, session
from flask_wtf import Form
from flask_wtf.file import FileField
from werkzeug import secure_filename
from flask import send_from_directory
from flask.ext.login import login_user, logout_user, login_required, current_user
from flask import *
from flask import send_file
from . import outputs
from .. import db
from bs4 import BeautifulSoup
from urllib2 import urlopen
from werkzeug.utils import secure_filename
from forms import Average, AddDatabaseForm, UploadForm
import numpy as np
import pandas as pd
import wtforms as wtf
import re
import os
from ..models import Permission, Role, User, \
                    IUCNStatus, OrganismType, GrowthFormRaunkiaer, ReproductiveRepetition, \
                    DicotMonoc, AngioGymno, SpandExGrowthType, SourceType, Database, Purpose, MissingData, ContentEmail, Ecoregion, Continent, InvasiveStatusStudy, InvasiveStatusElsewhere, StageTypeClass, \
                    TransitionType, MatrixComposition, StartSeason, EndSeason, StudiedSex, Captivity, Species, Taxonomy, PurposeEndangered, PurposeWeed, Trait, \
                    Publication, AuthorContact, AdditionalSource, Population, Stage, StageType, Treatment, \
                    MatrixStage, MatrixValue, Matrix, Interval, Fixed, Small, CensusTiming, Institute, Status, Version, ChangeLogger, DigitizationProtocol

#news
@outputs.route('/termsofuse')
def termsofuse():
    return render_template('outputs/terms_of_use.html')

##Downloading models as csvs - useful for Admins and Compadrinos to check things, for csv downloads for normal users please look at data-manage/views.py

@outputs.route('/populations')
def population_export():
    import csv

    # First, grab all matrices, as these will be each 'row'
    all_populations = Population.query.all()

    #function to merge dictionaries to a super dictionary
    def merge_dicts(*dict_args):
        result = {}
        for dictionary in dict_args:
            result.update(dictionary)
        return result

    w_file = open('app/outputs/populations.csv','w')

    #looping through rows
    for i, population in enumerate(all_populations):

        # Grab all of the parent objects
        population = population
        species = population.species
        publication = population.publication

        # Merge all of them to one single dict, as dict
        entry = merge_dicts(vars(population), vars(species), vars(publication))

        entry["date_digitised"] = str(entry["date_digitised"])
        entry["col_check_date"] = str(entry["col_check_date"])
        #If this is the first matrix, construct the headers too
        if i == 0:
            #get all the headings from entry - the super dict
            headings = [key for key in entry.keys()]
            headings = str(headings)
            w_file.write(headings[1:-1] + '\n')

        entry = str(entry.values())
        # cleaning needed to be added here

        w_file.write(entry[1:-1] + '\n')

    return ('populations success')

# outputs/downloads
#@outputs.route('/download_csv', methods=['GET', 'POST']) # this is a job for GET, not POST
#def download_csv():
#    return send_file('outputs/test.csv',
#                     mimetype='text/csv',
#                     attachment_filename='test.csv',
#                     as_attachment=True)

@outputs.route('/species')
def species_export():
    import csv

    # First, grab all matrices, as these will be each 'row'
    all_species = Species.query.all()

    #function to merge dictionaries to a super dictionary
    def merge_dicts(*dict_args):
        result = {}
        for dictionary in dict_args:
            result.update(dictionary)
        return result

    w_file = open('app/outputs/species.csv','w')

    #looping through rows
    for i, species in enumerate(all_species):

        # Grab all of the parent objects
        species = species
        traits = species.trait[0]
        taxonomy = species.taxonomy[0]

        # Merge all of them to one single dict, as dict
        entry = merge_dicts(vars(species), vars(taxonomy), vars(traits))

        entry["col_check_date"] = str(entry["col_check_date"])
        #If this is the first matrix, construct the headers too
        if i == 0:
            #get all the headings from entry - the super dict
            headings = [key for key in entry.keys()]
            headings = str(headings)
            w_file.write(headings[1:-1] + '\n')

        entry = str(entry.values())
        # cleaning needed to be added here

        w_file.write(entry[1:-1] + '\n')

    return ('species list success')

@outputs.route('/publications')
def publication_export():
    import csv

    # First, grab all matrices, as these will be each 'row'
    all_publications = Publication.query.all()

    #function to merge dictionaries to a super dictionary
    def merge_dicts(*dict_args):
        result = {}
        for dictionary in dict_args:
            result.update(dictionary)
        return result

    w_file = open('app/outputs/publications.csv','w')

    #looping through rows
    for i, publication in enumerate(all_publications):

        # Grab all of the parent objects
        publication = publication

        # Merge all of them to one single dict, as dict
        entry = merge_dicts(vars(publication))
        #turn date into string
        entry["date_digitised"] = str(entry["date_digitised"])
        #If this is the first matrix, construct the headers too
        if i == 0:
            #get all the headings from entry - the super dict
            headings = [key for key in entry.keys()]
            headings = str(headings)
            w_file.write(headings[1:-1] + '\n')

        entry = str(entry.values())
        # cleaning needed to be added here

        w_file.write(entry[1:-1] + '\n')

    return ('publications success')

@outputs.route('/matrices')
def matrices_export():
    import csv

    # First, grab all matrices, as these will be each 'row'
    all_matrices = Matrix.query.all()

    #function to merge dictionaries to a super dictionary
    def merge_dicts(*dict_args):
        result = {}
        for dictionary in dict_args:
            result.update(dictionary)
        return result

    w_file = open('app/outputs/matrix.csv','w')

    #looping through rows
    for i, matrix in enumerate(all_matrices):

        # Grab all of the parent objects
        matrix = matrix
        if matrix.fixed:
            fixed = matrix.fixed[0]

        # Merge all of them to one single dict, as dict
        entry = merge_dicts(vars(matrix),  vars(fixed))

        #If this is the first matrix, construct the headers too
        if i == 0:
            #get all the headings from entry - the super dict
            headings = [key for key in entry.keys()]
            headings = str(headings)
            w_file.write(headings[1:-1] + '\n')

        entry = str(entry.values())

        # cleaning
        # remove quotes from strings
        # remove u from unicode strings
        #[<taxonomy 1l="">] to 1
        # remove L from numbers
        # study purposes
        # remove fields we don't want
        # date time

        #re.sub("u'","",entry)

        w_file.write(entry[1:-1] + '\n')

    return ('matrices successful')
#if __name__ == '__main__':
#   app.run(debug = True)


#!/usr/bin/env python

""" A simple script to test the performance of a selected controller on a vehicle for Carla0.9.6 """
import glob
import os
import sys

try:
    sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
        sys.version_info.major,
        sys.version_info.minor,
        'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
    pass

import carla

import random

import image_converter

# Controllers for the vehicle
#from learning_agents.imitation.imitation_agent import ImitationAgent
from CAL_agent.CAL_controller import CAL
from measurements import Measurements

try:
    import pygame
except ImportError:
    raise RuntimeError('cannot import pygame, make sure pygame package is installed')

try:
    import numpy as np
except ImportError:
    raise RuntimeError('cannot import numpy, make sure numpy package is installed')

try:
    import queue
except ImportError:
    import Queue as queue

# High level direction commands for agents' run step input
REACH_GOAL = 0.0
GO_STRAIGHT = 5.0
TURN_RIGHT = 4.0
TURN_LEFT = 3.0
LANE_FOLLOW = 2.0

class CarlaSyncMode(object):
    """
    Context manager to synchronize output from different sensors. Synchronous
    mode is enabled as long as we are inside this context

        with CarlaSyncMode(world, sensors) as sync_mode:
            while True:
                data = sync_mode.tick(timeout=1.0)

    """

    def __init__(self, world, *sensors, **kwargs):
        self.world = world
        self.sensors = sensors
        self.frame = None
        self.delta_seconds = 1.0 / 20
        self._queues = []
        self._settings = None

    def __enter__(self):
        self._settings = self.world.get_settings()
        self.frame = self.world.apply_settings(carla.WorldSettings(
            no_rendering_mode=False,
            synchronous_mode=True,
            fixed_delta_seconds=self.delta_seconds))
        self.world.set_weather(carla.WeatherParameters.ClearNoon)

        def make_queue(register_event):
            q = queue.Queue()
            register_event(q.put)
            self._queues.append(q)

        make_queue(self.world.on_tick)
        for sensor in self.sensors:
            make_queue(sensor.listen)
        return self

    def tick(self, timeout):
        self.frame = self.world.tick()
        data = [self._retrieve_data(q, timeout) for q in self._queues]
        assert all(x.frame == self.frame for x in data)
        return data

    def __exit__(self, *args, **kwargs):
        self.world.apply_settings(self._settings)

    def _retrieve_data(self, sensor_queue, timeout):
        while True:
            data = sensor_queue.get(timeout=timeout)
            if data.frame == self.frame:
                return data

def draw_image(surface, image, blend=False):
    array = np.frombuffer(image.raw_data, dtype=np.dtype("uint8"))
    array = np.reshape(array, (image.height, image.width, 4))
    array = array[:, :, :3]
    array = array[:, :, ::-1]
    image_surface = pygame.surfarray.make_surface(array.swapaxes(0, 1))
    if blend:
        image_surface.set_alpha(100)
    surface.blit(image_surface, (0, 0))

def get_font():
    fonts = [x for x in pygame.font.get_fonts()]
    default_font = 'ubuntumono'
    font = default_font if default_font in fonts else fonts[0]
    font = pygame.font.match_font(font)
    return pygame.font.Font(font, 14)

def should_quit():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            return True
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_ESCAPE:
                return True
    return False

def apply_agent_control(image, player, agent):
    """ Function to pack up the data into the necessary format for the agent to process """
    # print out the timestatmp of the image
    meas =  Measurements()
    meas.update_measurements(image, player)
    # Do some processing of the image dat
    # Store processed data to pass to agent
    sensor_data = {}
    sensor_data['CameraRGB'] = image_converter.to_rgb_array(image)

    # Process next control step from the agent and execute it
    control = agent.run_step(meas, sensor_data, LANE_FOLLOW, None)

    player.apply_control(control)

def main():
    actor_list = []
    # Init client connection
    client = carla.Client('localhost', 2000)
    client.set_timeout(2.0)
    client.load_world('Town01')
    world = client.get_world()

    # Set up PYGAME window for easier visualization
    pygame.init()
    display = pygame.display.set_mode((800, 600),pygame.HWSURFACE | pygame.DOUBLEBUF)
    font = get_font()
    clock = pygame.time.Clock()

    try:
        # Load the approapite settings for the experiment
        bp_lib = world.get_blueprint_library()

        # Spawn the agent's vehicle into the scene
        vehicle_bp = bp_lib.find('vehicle.ford.mustang')
        vehicle_tf = carla.Transform(carla.Location(2, 120, 2), carla.Rotation(yaw=-90))
        vehicle = world.spawn_actor(vehicle_bp, vehicle_tf)
        actor_list.append(vehicle)
        # Advance to the next simulation step in the simulator to ensure car is spawned
        world.tick()

        # Create RGB camera
        camera_bp = bp_lib.find('sensor.camera.rgb')
        camera_bp.set_attribute('image_size_x', '800')
        camera_bp.set_attribute('image_size_y', '600')
        # Config for CAL
        camera_bp.set_attribute('fov', '90')
        camera_rgb = world.spawn_actor(camera_bp, carla.Transform(carla.Location(x=1.44, z=1.2), carla.Rotation(pitch=0)), attach_to=vehicle)

        # Config for IML
        # camera_bp.set_attribute('fov', '100')
        # camera_rgb = world.spawn_actor(camera_bp, carla.Transform(carla.Location(x=2, z=1.4), carla.Rotation(pitch=-15)), attach_to=vehicle)
        actor_list.append(camera_rgb)

        # Finally, attach a controller to the vehicle
        #agent = ImitationAgent('Town01', True, vehicle)
        agent = CAL('Town01', vehicle)

        #Spawn a pedestrian in front of the car
        ped_bp = random.choice(bp_lib.filter('pedestrian'))
        ped_tf = carla.Transform(carla.Location(2, 80, 2), carla.Rotation())
        ped_actor = world.spawn_actor(ped_bp, ped_tf)
        actor_list.append(ped_actor)
        world.tick() # Advance on step to ensure
        world.wait_for_tick(seconds = 2.0) # Wait up to two seconds for step update

        # Create a synchronous mode context.
        with CarlaSyncMode(world, camera_rgb, fps=20) as sync_mode:
            while True:
                if should_quit():
                    return
                clock.tick()

                # Advance the simulation and wait for the data.
                snapshot, image_rgb = sync_mode.tick(timeout=2.0)

                apply_agent_control(image_rgb, vehicle, agent)

                fps = round(1.0 / snapshot.timestamp.delta_seconds)

                # Draw the display.
                draw_image(display, image_rgb)

                display.blit(
                    font.render('% 5d FPS (real)' % clock.get_fps(), True, (255, 255, 255)),
                    (8, 10))
                display.blit(
                    font.render('% 5d FPS (simulated)' % fps, True, (255, 255, 255)),
                    (8, 28))
                pygame.display.flip()

    finally:
        print('destroying actors.')
        for actor in actor_list:
            actor.destroy()

        pygame.quit()
        print('done.')

if __name__ == '__main__':

    try:

        main()

    except KeyboardInterrupt:
        print('\nCancelled by user. Bye!')


import sys
from PySide.QtGui import QApplication
from controllers.main import MainController

class App(QApplication):
    def __init__(self, args):
        super(App, self).__init__(args)
        self.controller = MainController()
        self.controller.show()

if __name__ == '__main__':
    app = App(sys.argv)
    sys.exit(app.exec_())


import psutil
import os
import requests
import json
import subprocess

#ORDER OF UNAME COMMANDS:
    #uname -n
    #uname -sro
    #uname -m

#TO GET PUBLIC IP ADDR: curl ipecho.net/plain ; echo
pub_ip = subprocess.getoutput("wget -qO- http://ipecho.net/plain ; echo")

#TO GET PRIMARY IP ADDR: ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'
prim_ip = subprocess.getoutput("ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'")

machine_name = subprocess.getoutput("uname -n")
os_info = subprocess.getoutput("uname -sro")
arc = subprocess.getoutput("uname -m")

curr_user = subprocess.getoutput("whoami")

print(machine_name, os_info, arc) #prefect
print (curr_user)
print(prim_ip)
print(pub_ip)

def info_runner():
    with open("stats.json", "r+") as f:
        systats = json.load(f)
        # update json here
        systats["MACHINE_INFO"] = machine_name + " " + os_info + " " + arc + " " + curr_user
        systats["IP_ADDR"] = prim_ip + " / " + pub_ip
        f.seek(0)
        f.truncate()
        json.dump(systats, f)

#info_runner()

'''
headers = {'Content-Type': 'application/json'}
r = requests.post("http://127.0.0.1:5000", headers=headers, json=get_disks())
'''