from django.views.generic import TemplateView
from django.conf import settings
from django.contrib import messages
from django.views.decorators.csrf import csrf_exempt
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth import logout
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView, View
from django.shortcuts import redirect
from django.utils import timezone
from django.utils.timezone import make_aware
from django.db.models import Q
from django.contrib.sites.models import Site
from itertools import combinations
from .forms import CheckoutForm, CouponForm, RefundForm, PaymentForm, SearchFAQForm
from .models import *
from core.functions import *
from django.http.response import JsonResponse, HttpResponse

import stripe

stripe.api_key = settings.STRIPE_SECRET_KEY

def is_valid_form(values):
    valid = True
    for field in values:
        if field == '':
            valid = False
    return valid

class CheckoutView(View):
    def get(self, *args, **kwargs):
        try:
            # GDPR check
            gdpr_check = check_gdpr_cookies(self)
            path = self.request.get_full_path()
            is_post = False
            # get the content of the basket
            order = Order.objects.get(user=self.request.user, ordered=False)
            form = CheckoutForm()

            test = str(type(order.shipping_address))
            print("test")
            print(test)
            print(type(test))

            if test == "<class 'NoneType'>":
                # get the users preset adresses if there are some
                shipping_address_qs = Address.objects.get(
                    user=self.request.user,
                    address_type='S',
                    default=True
                )
            else:
                shipping_address_qs = order.shipping_address

            test2 = str(type(order.billing_address))

            if test2 == "<class 'NoneType'>":
                # get the users preset adresses if there are some
                billing_address_qs = Address.objects.get(
                    user=self.request.user,
                    address_type='B',
                    default=True
                )
            else:
                billing_address_qs = order.billing_address

            context = {
                'gdpr_check': gdpr_check,
                'form': form,
                'couponform': CouponForm(),
                'first_load': True,
                'form_not_complete': False,
                'order': order,
                'shipping_address': shipping_address_qs,
                'billing_address': billing_address_qs,
                'DISPLAY_COUPON_FORM': True
            }

            if order.freight:
                freights = Freight.objects.all()

                selectedFreights = []

                for f in freights:
                    if f.id == int(order.freight.id):
                        selectedFreights.append(
                            {"chosen": True, "choice": f})
                    else:
                        selectedFreights.append(
                            {"chosen": False, "choice": f})
                context.update({"chosen_freight": True})
                context.update({"selectedFreights": selectedFreights})

            return render(self.request, "checkout.html", context)
        except ObjectDoesNotExist:
            messages.info(self.request, "Varukorgen är tom.")
            return redirect("core:order-summary")

    def post(self, *args, **kwargs):
        # GDPR check
        gdpr_check = check_gdpr_cookies(self)
        form = CheckoutForm(self.request.POST or None)
        try:
            order = Order.objects.get(user=self.request.user, ordered=False)
            form_not_complete = False
            if form.is_valid():

                use_default_shipping = form.cleaned_data.get(
                    'use_default_shipping')
                if use_default_shipping:
                    address_qs = Address.objects.filter(
                        user=self.request.user,
                        address_type='S',
                        default=True
                    )
                    if address_qs.exists():
                        shipping_address = address_qs[0]
                        order.shipping_address = shipping_address
                        order.save()
                    else:
                        messages.info(
                            self.request, "Ingen förinställd leveransadress funnen.")
                        return redirect('core:checkout')
                else:
                    shipping_address1 = form.cleaned_data.get(
                        'shipping_address')
                    shipping_address2 = form.cleaned_data.get(
                        'shipping_address2')
                    shipping_zip = form.cleaned_data.get('shipping_zip')
                    s_post_town = form.cleaned_data.get('s_post_town')
                    if shipping_address2 == "<input":
                        shipping_address2 = ""
                    if shipping_address1 == "<input":
                        shipping_address1 = ""

                    if is_valid_form([shipping_address1, shipping_zip, s_post_town]):
                        shipping_address = Address(
                            user=self.request.user,
                            street_address=shipping_address1,
                            apartment_address=shipping_address2,
                            zip=shipping_zip,
                            post_town=s_post_town,
                            address_type='S'
                        )
                        shipping_address.save()

                        order.shipping_address = shipping_address
                        order.save()

                        set_default_shipping = form.cleaned_data.get(
                            'set_default_shipping')
                        if set_default_shipping:
                            shipping_address.default = True
                            shipping_address.save()

                    else:
                        form_not_complete = True
                        messages.info(
                            self.request, "Vargod fyll i de obligatoriska fälten för leveransadressen.")

                use_default_billing = form.cleaned_data.get(
                    'use_default_billing')
                same_billing_address = form.cleaned_data.get(
                    'same_billing_address')

                if same_billing_address and not form_not_complete:
                    billing_address = shipping_address
                    order.billing_address = billing_address
                    order.save()

                elif same_billing_address and form_not_complete:
                    billing_address1 = shipping_address1
                    billing_address2 = shipping_address2
                    billing_zip = shipping_zip
                    b_post_town = s_post_town

                elif use_default_billing:
                    address_qs = Address.objects.filter(
                        user=self.request.user,
                        address_type='B',
                        default=True
                    )
                    if address_qs.exists():
                        billing_address = address_qs[0]
                        order.billing_address = billing_address
                        order.save()
                    else:
                        messages.info(
                            self.request, "Ingen förinställd faktureringsadress funnen.")
                        return redirect('core:checkout')
                else:
                    billing_address1 = form.cleaned_data.get(
                        'billing_address')
                    billing_address2 = form.cleaned_data.get(
                        'billing_address2')
                    billing_zip = form.cleaned_data.get('billing_zip')
                    b_post_town = form.cleaned_data.get(
                        'b_post_town')
                    if billing_address1 == "<input":
                        billing_address1 = ""
                    if billing_address2 == "<input":
                        billing_address2 = ""

                    if is_valid_form([billing_address1, billing_zip, b_post_town]):
                        billing_address = Address(
                            user=self.request.user,
                            street_address=billing_address1,
                            apartment_address=billing_address2,
                            zip=billing_zip,
                            post_town=b_post_town,
                            address_type='B'
                        )
                        billing_address.save()

                        order.billing_address = billing_address
                        order.save()

                        set_default_billing = form.cleaned_data.get(
                            'set_default_billing')
                        if set_default_billing:
                            billing_address.default = True
                            billing_address.save()

                    else:
                        form_not_complete = True
                        messages.info(
                            self.request, "Vargod fyll i de obligatoriska fälten under faktureringsadressen.")

                freight_option = form.cleaned_data.get('freight_option')
                freight = Freight.objects.filter(id=int(freight_option))
                order.freight = freight[0]
                order.freight_price = order.freight.amount

                # recalculate order total

                order.total_price = calculate_total_order(order)
                order.ordered_date = make_aware(datetime.now())
                order.save()

                payment_option = form.cleaned_data.get('payment_option')

                if(form_not_complete):

                    # get the content of the basket
                    order = Order.objects.get(
                        user=self.request.user, ordered=False)

                    # create freight choices to go through to preselect if it is selected

                    freights = Freight.objects.all()

                    selectedFreights = []

                    for f in freight:
                        if f.id == int(freight_option):
                            selectedFreights.append(
                                {"chosen": True, "choice": f})
                        else:
                            selectedFreights.append(
                                {"chosen": False, "choice": f})

                    # create payment choices to go through to preselect if it is selected

                    payments = PaymentTypes.objects.all()

                    selectedPayments = []

                    for p in payments:
                        if p.short == payment_option:
                            selectedPayments.append(
                                {"chosen": True, "choice": p})
                        else:
                            selectedPayments.append(
                                {"chosen": False, "choice": p})

                    context = {
                        'gdpr_check': gdpr_check,
                        'form': form,
                        'couponform': CouponForm(),
                        'order': order,
                        'DISPLAY_COUPON_FORM': True,
                        'first_load': False,
                        'form_not_complete': form_not_complete,
                        'shipping_address1': shipping_address1,
                        'shipping_address2': shipping_address2,
                        'shipping_zip': shipping_zip,
                        's_post_town': s_post_town,
                        'billing_address1': billing_address1,
                        'billing_address2': billing_address2,
                        'billing_zip': billing_zip,
                        'b_post_town': b_post_town,
                        'use_default_shipping': use_default_shipping,
                        'use_default_billing': use_default_billing,
                        'same_billing_address': same_billing_address,
                        'selectedPayments': selectedPayments,
                        'selectedFreights': selectedFreights,
                    }

                    # get the users preset adresses if there are some
                    shipping_address_qs = Address.objects.filter(
                        user=self.request.user,
                        address_type='S',
                        default=True
                    )
                    if shipping_address_qs.exists():
                        context.update(
                            {'default_shipping_address': shipping_address_qs[0]})

                    billing_address_qs = Address.objects.filter(
                        user=self.request.user,
                        address_type='B',
                        default=True
                    )
                    if billing_address_qs.exists():
                        context.update(
                            {'default_billing_address': billing_address_qs[0]})

                    return render(self.request, "checkout.html", context)
                else:
                    if payment_option == 'S':
                        return redirect('core:confirm')
                    else:
                        messages.warning(
                            self.request, "Ogiltig betalningsalternativ valt.")
                        return redirect('core:checkout')
        except ObjectDoesNotExist:
            messages.warning(self.request, "Varukorgen är tom.")
            return redirect("core:order-summary")

class NewHomeView(View):
    def get(self, *args, **kwargs):
        # GDPR check
        gdpr_check = True  # check_gdpr_cookies(self)

        categories = Category.objects.all()
        aquire_index = default_pagination_values
        number_products = Item.objects.all().count()
        pagination = {}
        is_paginated = False
        start_extras = False
        end_extras = False
        if(number_products > aquire_index):

            page = which_page(self)

            max_page = number_products/aquire_index

            testM = int(max_page)
            if(testM != max_page):
                max_page = testM + 1
            page_list, where = get_list_of_pages(int(page), int(max_page))

            if page == 1:
                if(page_list[-1] == max_page):
                    hasNext = False
                else:
                    hasNext = True
                pagination = {
                    "has_previous": False,
                    "previous_page_number": 1,
                    "number": 1,
                    "has_next": hasNext,
                    "next_page_number": 2
                }
                is_paginated = True
                products = Item.objects.all()[:aquire_index]
                if where != "no extras":
                    end_extras = True

            else:
                page = int(page)
                # query[offset:offset + limit]
                start_point = (int(page) - 1) * aquire_index
                o_and_l = start_point + aquire_index
                products = Item.objects.all()[start_point:o_and_l]
                is_paginated = True
                if page < max_page:
                    next_page = page + 1
                    previous_page = page - 1
                    if(page == max_page):
                        hasNext = False
                    else:
                        hasNext = True

                    if(len(page_list) == max_page):
                        hasPreivous = False
                    else:
                        hasPreivous = True

                    pagination = {
                        "has_previous": hasPreivous,
                        "previous_page_number": previous_page,
                        "number": page,
                        "has_next": hasNext,
                        "next_page_number": next_page
                    }
                else:
                    previous_page = page - 1

                    if(len(page_list) == max_page):
                        hasPreivous = False
                    else:
                        hasPreivous = True

                    pagination = {
                        "has_previous": hasPreivous,
                        "previous_page_number": previous_page,
                        "number": page,
                        "has_next": False,
                        "next_page_number": page
                    }

                if where == "start":
                    end_extras = True
                elif where == "end":
                    start_extras = True
                elif where == "mid":
                    start_extras = True
                    end_extras = True
        else:
            products = Item.objects.all()[:aquire_index]

            is_paginated = False
            pagination = {
                "has_previous": False,
                "has_next": False,
            }

        GDPR = self.request.COOKIES.get("GDPR")
        gdpr_check = True
        if GDPR == "GDPR":
            gdpr_check = False

        context = {
            'gdpr_check': gdpr_check,
            "category_choices": categories,
            "object_list": products,
            "is_paginated": is_paginated,
            "page_obj": pagination,
            "page_list": page_list,
            "start_extras": start_extras,
            "end_extras": end_extras,
            "max_page": int(max_page),
        }
        response = render(self.request, 'home.html', context)

        if GDPR != "GDPR":
            response.set_cookie("GDPR", "GDPR")

        return response

    def post(self, *args, **kwargs):
        return redirect("core:home")

class OrderSummaryView(LoginRequiredMixin, View):
    def get(self, *args, **kwargs):
        login_url = '/accounts/login/'
        redirect_field_name = 'from'
        redirect_field_value = 'to'
        # GDPR check
        gdpr_check = check_gdpr_cookies(self)
        try:
            # if the user has an old basket and are returning the prices may have changed. Same if there are changes coming into effect before the order has been payed for. We need to check, update and let the user know if there is a change
            order = Order.objects.get(
                user=self.request.user, ordered=False)
            orderItems = order.items.all()
            warning = ""
            info = ""
            recount = False

            for orderItem in orderItems:
                item = orderItem.item
                total_price = 0
                if item.discount_price != None:
                    total_price = item.discount_price * orderItem.quantity
                else:
                    total_price = item.price * orderItem.quantity

                if orderItem.total_price != total_price:
                    recount = True
                    # check if there is a discount
                    # set a warning to the user so they know that there are alterations to the order
                    warning = "Priser ändrade då de antingen är gamla eller inte längre giltiga."
                    if item.discount_price != None:
                        total_price = item.discount_price * orderItem.quantity
                        if orderItem.total_price != total_price:
                            # there is difference in prices this is most likely due to a change in price of the item or discount price no longer valid
                            if item.discount_price != None:
                                total = item.discount_price * orderItem.quantity
                                orderItem.price = item.price
                                orderItem.discount_price = item.discount_price
                                orderItem.total_price = total
                                orderItem.save()
                            else:
                                total = item.price * orderItem.quantity
                                orderItem.price = item.price
                                orderItem.discount_price = item.discount_price
                                orderItem.total_price = total
                                orderItem.save()
                    else:
                        # there is no discount but the price isnt right so correct the prices
                        total = item.price * orderItem.quantity
                        orderItem.price = item.price
                        orderItem.discount_price = item.discount_price
                        orderItem.total_price = total
                        orderItem.save()
                else:
                    # the price is correct towards the regular price but check that there isnt currently a discount
                    if item.discount_price != None and (item.discount_price * orderItem.quantity) != orderItem.total_price:
                        recount = True
                        # there is currently a discount recalculate the price
                        # set a warning to the user so they know that there are alterations to the order
                        info = "Priser ändrade då de för nuvarnde är på rea."
                        total = item.discount_price * orderItem.quantity
                        orderItem.total_price = total
                        orderItem.save()

            if warning != "":
                messages.warning(
                    self.request, warning)

            if info != "":
                messages.info(
                    self.request, info)

            if recount:
                print("recount")
                # prices have changed order needs to be updated
                newTotal = update_order_total(order)
                order.total_price = newTotal
                order.ordered_date = make_aware(datetime.now())
                order.updated_date = make_aware(datetime.now())
                order.save()
                freshOrder = Order.objects.get(id=order.id)
            else:
                # no update can pass order to view without anything
                freshOrder = order

            context = {
                'gdpr_check': gdpr_check,
                'object': freshOrder,
            }
            return render(self.request, 'order_summary.html', context)
        except ObjectDoesNotExist:
            messages.warning(self.request, "Varukorgen är tom.")
            return redirect("/")

class ItemDetailView(DetailView):
    model = Item
    template_name = "product.html"

    def get_context_data(self, **kwargs):
        # GDPR check
        gdpr_check = check_gdpr_cookies(self)
        context = super().get_context_data(**kwargs)
        categories = Category.objects.all()
        context['category_choices'] = categories
        context['gdpr_check'] = gdpr_check
        context['path'] = self.object.get_absolute_url()
        return context

@login_required
def add_to_cart(request, slug):
    item = get_object_or_404(Item, slug=slug)
    order_item, created = OrderItem.objects.get_or_create(
        item=item,
        title=item.title,
        price=item.price,
        discount_price=item.discount_price,
        quantity=1,
        user=request.user,
        ordered=False
    )
    order_qs = Order.objects.filter(user=request.user, ordered=False)
    if order_qs.exists():
        order = order_qs[0]
        order.ordered_date = make_aware(datetime.now())
        order.updated_date = make_aware(datetime.now())
        # check if the order item is in the order
        if order.items.filter(item__slug=item.slug).exists():
            order_item.quantity += 1
            if item.discount_price != None:
                if item.discount_price > 0:
                    if order_item.discount_price != item.discount_price:
                        messages.info(request, "Varans pris har uppdaterats.")
                        order_item.discount_price = item.discount_price
                    order_item.total_price = order_item.quantity * order_item.discount_price
            else:
                order_item.total_price = order_item.quantity * order_item.price
            order_item.save()
            messages.info(request, "Varans mängd har uppdaterats.")
            return redirect("core:order-summary")
        else:
            if item.discount_price:
                order_item.total_price = order_item.discount_price * order_item.quantity
            else:
                order_item.total_price = order_item.price * order_item.quantity
            order_item.save()
            order.items.add(order_item)
            order.total_price = calculate_total_order(order)
            order.save()
            messages.info(request, "Varan lagd i varukorgen.")
            return redirect("core:order-summary")
    else:
        ordered_date = make_aware(datetime.now())
        updated_date = make_aware(datetime.now())
        refCode = create_ref_code()
        rcode = test_order_ref_code(refCode)
        order = Order.objects.create(
            user=request.user, ordered_date=ordered_date, updated_date=updated_date, ref_code=rcode)
        order_item.quantity = 1
        order_item.discount_price = item.discount_price
        order_item.price = item.price
        if item.discount_price != None and item.discount_price > 0:
            order_item.total_price = order_item.discount_price * order_item.quantity
        else:
            order_item.total_price = order_item.price * order_item.quantity
        order_item.save()
        order.items.add(order_item)
        order.total_price = calculate_total_order(order)
        order.save()
        messages.info(request, "Varan lagd i varukorgen.")
        return redirect("core:order-summary")

@login_required
def remove_from_cart(request, slug):
    item = get_object_or_404(Item, slug=slug)
    order_qs = Order.objects.filter(
        user=request.user,
        ordered=False
    )
    if order_qs.exists():
        order = order_qs[0]
        order.ordered_date = make_aware(datetime.now())
        order.updated_date = make_aware(datetime.now())
        # check if the order item is in the order
        if order.items.filter(item__slug=item.slug).exists():
            order_item = OrderItem.objects.filter(
                item=item,
                user=request.user,
                ordered=False
            )[0]
            order.items.remove(order_item)
            order.save()
            order_item.delete()
            messages.info(request, "Varan borttagen ur varukorgen.")
            all_items = order.items.all()
            if len(all_items) == 0:
                order.delete()
            return redirect("core:order-summary")
        else:
            messages.info(request, "Denna vara fanns inte i din varukorg.")
            return redirect("core:product", slug=slug)
    else:
        messages.info(request, "Din varukorg är tom")
        return redirect("core:product", slug=slug)

@login_required
def remove_single_item_from_cart(request, slug):
    item = get_object_or_404(Item, slug=slug)
    order_qs = Order.objects.filter(
        user=request.user,
        ordered=False
    )
    if order_qs.exists():
        order = order_qs[0]
        order.ordered_date = make_aware(datetime.now())
        order.updated_date = make_aware(datetime.now())
        # check if the order item is in the order
        if order.items.filter(item__slug=item.slug).exists():
            order_item = OrderItem.objects.get(
                item=item,
                user=request.user,
                ordered=False
            )
            if order_item.quantity > 1:
                order_item.quantity -= 1
                if item.discount_price != None:
                    if item.discount_price > 0:
                        if order_item.discount_price != item.discount_price:
                            order_item.discount_price = item.discount_price
                        order_item.total_price = order_item.quantity * order_item.discount_price
                else:
                    order_item.total_price = order_item.quantity * order_item.price
                order_item.save()
            else:
                order.items.remove(order_item)
                order_item.delete()
                if len(order.items.all()) == 0:
                    order.delete()
            messages.info(request, "Varans mängd har uppdaterats.")
            return redirect("core:order-summary")
        else:
            messages.info(request, "Denna vara fanns inte i din varukorg.")
            return redirect("core:product", slug=slug)
    else:
        messages.info(request, "Varukorgen är tom.")
        return redirect("core:product", slug=slug)

def get_coupon(request, code):
    try:
        coupon = Coupon.objects.get(code=code)
        return coupon
    except ObjectDoesNotExist:
        messages.info(request, "Denna rabattkod är inte giltig.")
        return redirect("core:checkout")

class AddCouponView(View):
    def get(self, *args, **kwargs):
        # reroute
        message = get_message('error', 136)
        messages.warning(
            self.request, message)
        return redirect("core:home")

    def post(self, *args, **kwargs):
        form = CouponForm(self.request.POST or None)
        if form.is_valid():
            try:
                code = form.cleaned_data.get('code')
                order = Order.objects.get(
                    user=self.request.user, ordered=False)
                order.updated_date = make_aware(datetime.now())
                order.coupon = get_coupon(self.request, code)
                order.save()
                messages.success(self.request, "Rabattkod tillagd.")
                return redirect("core:checkout")
            except ObjectDoesNotExist:
                messages.info(self.request, "Din varukorg är tom.")
                return redirect("core:checkout")
        else:
            messages.info(self.request, "Denna rabattkod är ej giltig.")
            return redirect("core:checkout")

# Category views

class CategoryView(View):
    def get(self, *args, **kwargs):
        # GDPR check
        gdpr_check = check_gdpr_cookies(self)
        try:
            page, am_i = where_am_i_and_page(self)
            print(page)
            print(am_i)
            categoryquery = Category.objects.get(slug=am_i)

            # alter this to a set number of products and add pagination
            aquire_index = default_pagination_values
            number_products = Item.objects.filter(
                category=categoryquery).count()
            pagination = {}
            is_paginated = False
            start_extras = False
            end_extras = False

            if(number_products > aquire_index):

                max_page = number_products/aquire_index
                testM = int(max_page)
                if(testM != max_page):
                    max_page = testM + 1
                page_list, where = get_list_of_pages(int(page), int(max_page))
                if page == 1:
                    if(page == max_page):
                        hasNext = False
                    else:
                        hasNext = True
                    pagination = {
                        "has_previous": False,
                        "previous_page_number": 1,
                        "number": 1,
                        "has_next": hasNext,
                        "next_page_number": 2
                    }
                    is_paginated = True
                    products = Item.objects.filter(
                        category=categoryquery)[:aquire_index]
                    if where != "no extras":
                        end_extras = True
                else:

                    # query[offset:offset + limit]
                    start_point = (int(page) - 1) * aquire_index
                    o_and_l = start_point + aquire_index
                    products = Item.objects.filter(category=categoryquery)[
                        start_point:o_and_l]
                    is_paginated = True
                    number_of_pages = number_products / aquire_index
                    test = int(number_of_pages)
                    if number_of_pages > test:
                        number_of_pages += 1

                    if page < number_of_pages:
                        next_page = page + 1
                        previous_page = page - 1
                        hasNext = True
                    else:
                        next_page = page
                        previous_page = page - 1
                        hasNext = False
                    hasPreivous = True

                    pagination = {
                        "has_previous": hasPreivous,
                        "previous_page_number": previous_page,
                        "number": page,
                        "has_next": hasNext,
                        "next_page_number": next_page
                    }

                if where == "start":
                    end_extras = True
                elif where == "end":
                    start_extras = True
                elif where == "mid":
                    start_extras = True
                    end_extras = True

            else:
                products = Item.objects.filter(
                    category=categoryquery)[:aquire_index]

                is_paginated = False
                pagination = {
                    "has_previous": False,
                    "has_next": False,
                }

            # we need to create a list of objects to loop through to mark the apropriate category

            category_choices = Category.objects.all()

            new_list = []
            for cat in category_choices:
                if cat.title == categoryquery.title:
                    new_list.append({
                        'title': cat.title,
                        'url': cat.get_absolute_cat_url,
                        'selected': True
                    })
                else:
                    new_list.append({
                        'title': cat.title,
                        'url': cat.get_absolute_cat_url,
                        'selected': False
                    })

            context = {
                'gdpr_check': gdpr_check,
                'object_list': products,
                'category_list': new_list,
                'selected_cateogory': categoryquery,
                "is_paginated": is_paginated,
                "page_obj": pagination,                    "page_list": page_list,
                "start_extras": start_extras,
                "end_extras": end_extras,
                "max_page": max_page,
            }
            return render(self.request, "category.html", context)
        except ObjectDoesNotExist:
            messages.info(
                self.request, "Något har gått fel, vargod kontakta supporten.")
            return redirect("core:home")

# FAQ

class FAQView(View):
    def get(self, *args, **kwargs):
        # GDPR check
        gdpr_check = check_gdpr_cookies(self)

        try:
            # need to add language tests here at a later date
            theLanguage = LanguageChoices.objects.get(language_short="swe")
            aquire_index = default_pagination_values
            number_faqs = FAQ.objects.filter(language=theLanguage).count()
            pagination = {}
            page_list = []
            is_paginated = False
            start_extras = False
            end_extras = False
            max_page = 0
            if(number_faqs > aquire_index):
                # we only land here if we are on page one without a search and we have more FAQs than fit on one page
                max_page = number_faqs / aquire_index
                testM = int(max_page)
                if(testM != max_page):
                    max_page = testM + 1
                page_list, where = get_list_of_pages(1, int(max_page))

                if(1 != max_page):
                    hasNext = False
                else:
                    hasNext = True

                pagination = {
                    "has_previous": False,
                    "previous_page_number": 1,
                    "number": 1,
                    "has_next": hasNext,
                    "next_page_number": 2
                }
                is_paginated = True
                try:
                    faqs = FAQ.objects.filter(language=theLanguage)[
                        :aquire_index]
                except ObjectDoesNotExist:
                    message = get_message('error', 135)
                    faqs = [
                        {
                            "question": "Ett FAQ fel har uppstått:",
                            "answer": message,
                        }
                    ]

                if where != "no extras":
                    end_extras = True

            else:
                # we have less FAQs then we want from aquire index, so no pagination here and no need to do a specialised search
                try:
                    faqs = FAQ.objects.filter(language=theLanguage)
                except ObjectDoesNotExist:
                    message = get_message('error', 135)
                    faqs = [
                        {
                            "question": "Ett FAQ fel har uppstått:",
                            "answer": message,
                        }
                    ]

            try:
                searchForm = SearchFAQForm()
                aButtonType = ButtonType.objects.get(buttonType="search")
                searchButton = ButtonText.objects.filter(
                    language=theLanguage, theButtonType=aButtonType)
            except ObjectDoesNotExist:
                message = get_message('error', 135)
                # flag it support
                searchForm = SearchFAQForm()
                searchButton = {"buttonText": "Search"}

        except ObjectDoesNotExist:
            pagination = {}
            page_list = []
            is_paginated = False
            start_extras = False
            end_extras = False
            max_page = 0
            faqs = [
                {
                    "question": "Ett språk fel har uppstått:",
                    "answer": message,
                }
            ]
            searchForm = SearchFAQForm()
            searchButton = {"buttonText": "Search"}
        comment = ""

        context = {
            'gdpr_check': gdpr_check,
            'search': False,
            'faqs': faqs,
            "searchTerms": "",
            'searchForm': searchForm,
            "searchButton": searchButton,
            'is_paginated': is_paginated,
            'start_page': start_extras,
            'end_page': end_extras,
            'page_list': page_list,
            'max_page': max_page,
            'page_obj': pagination,
        }
        return render(self.request, "faq.html", context)

    def post(self, *args, **kwargs):
        # GDPR check
        gdpr_check = check_gdpr_cookies(self)
        if "searchTerm" in self.request.POST.keys():
            # check that the search field isnt empty, if empty redirect to get section
            searchTest = self.request.POST["searchTerm"]

            if searchTest != "":
                # we just did a search, no matter what we are on page 1
                form = SearchFAQForm(self.request.POST)
                comment = ""
                if form.is_valid():
                    # need to add language tests here at a later date
                    theLanguage = LanguageChoices.objects.get(
                        language_short="swe")
                    search_terms = form.cleaned_data.get('searchTerm')
                    search_term_split = search_terms.split()
                    len_search_term = len(search_term_split)

                    # make all the combinations of the search

                    a = len_search_term
                    searchTermList = []
                    while a > 0:
                        searchCombinations = combinations(search_term_split, a)
                        for combination in searchCombinations:
                            term = ""
                            for word in combination:
                                if term == "":
                                    term = word
                                else:
                                    term = term + " " + word
                            searchTermList.append(term)
                        a -= 1
                    search = []
                    search_no_duplicates = []
                    aquire_index = default_pagination_values
                    pagination = {}
                    page_list = []
                    is_paginated = False
                    start_extras = False
                    end_extras = False
                    max_page = 1

                    # get all results

                    for term in searchTermList:
                        faqs = FAQ.objects.filter(
                            Q(subject__contains=term) | Q(content__contains=term))
                        search.append(faqs)

                    # place all query entries in a new array

                    for_sorting = []

                    for query in search:
                        for entry in query:
                            for_sorting.append(entry)

                    # remove all duplicates
                    for entry in for_sorting:
                        if(len(search_no_duplicates) == 0):
                            search_no_duplicates.append(entry)
                        else:
                            i = 0
                            same = False
                            while i < len(search_no_duplicates):
                                if search_no_duplicates[i].id == entry.id:
                                    i = len(search_no_duplicates)
                                    same = True
                                else:
                                    same = False
                                i += 1

                            if not same:
                                search_no_duplicates.append(entry)

                    # remove those not to be used

                    final_search_array = []

                    if len(search_no_duplicates) > aquire_index:
                        i = 0
                        while i < aquire_index:
                            final_search_array.append(search_no_duplicates[i])
                            i += 1
                    else:
                        final_search_array = search_no_duplicates

                    # create pagination

                    number_faqs = len(search_no_duplicates)
                    if(number_faqs > aquire_index):
                        max_page = number_faqs/aquire_index
                        testM = int(max_page)
                        if(testM != max_page):
                            max_page = testM + 1

                        if(max_page > 1):

                            page_list, where = get_list_of_pages(
                                1, int(max_page))

                            if(page_list[-1] == max_page):
                                hasNext = False
                            else:
                                hasNext = True
                            pagination = {
                                "has_previous": False,
                                "previous_page_number": 1,
                                "number": 1,
                                "has_next": hasNext,
                                "next_page_number": 2
                            }
                            if where != "no extras":
                                end_extras = True

                            is_paginated = True

                    try:
                        aButtonType = ButtonType.objects.get(
                            buttonType="search")
                        searchButton = ButtonText.objects.filter(
                            language=theLanguage, theButtonType=aButtonType)
                    except ObjectDoesNotExist:
                        searchButton = {"buttonText": "Search"}

                context = {
                    'gdpr_check': gdpr_check,
                    'search': True,
                    'faqs': final_search_array,
                    "searchTerms": searchTest,
                    'searchForm': form,
                    "searchButton": searchButton,
                    'is_paginated': is_paginated,
                    'start_page': start_extras,
                    'end_page': end_extras,
                    'page_list': page_list,
                    'max_page': max_page,
                    'page_obj': pagination,
                }
                return render(self.request, "faq.html", context)
            else:
                return redirect("core:faq")

        elif "SearchTerms" in self.request.POST.keys():
            # we are paginating a search this didnt start in the form
            search_terms = self.request.POST['SearchTerms']
            page = int(self.request.POST['page'])

            # need to add language tests here at a later date
            theLanguage = LanguageChoices.objects.get(
                language_short="swe")
            search_term_split1 = search_terms.split("\"")
            if len(search_term_split1) == 1:
                search_term_split = search_term_split1[0].split()
            elif len(search_term_split1) > 1:
                search_term_split = search_term_split1[1].split()
            else:
                search_term_split = search_term_split1
            len_search_term = len(search_term_split)

            # check if the search is empty

            if len_search_term > 0:

                # make all the combinations of the search

                a = len_search_term
                searchTermList = []
                while a > 0:
                    searchCombinations = combinations(search_term_split, a)
                    for combination in searchCombinations:
                        term = ""
                        for word in combination:
                            if term == "":
                                term = word
                            else:
                                term = term + " " + word
                        searchTermList.append(term)
                    a -= 1
                search = []
                search_no_duplicates = []
                aquire_index = default_pagination_values
                pagination = {}
                page_list = []
                is_paginated = False
                start_extras = False
                end_extras = False
                max_page = 1

                # get all results

                for term in searchTermList:
                    faqs = FAQ.objects.filter(
                        Q(subject__contains=term) | Q(content__contains=term))
                    search.append(faqs)

                # place all query entries in a new array

                for_sorting = []

                for query in search:
                    for entry in query:
                        for_sorting.append(entry)

                # remove all duplicates
                for entry in for_sorting:
                    if(len(search_no_duplicates) == 0):
                        search_no_duplicates.append(entry)
                    else:
                        i = 0
                        same = False
                        while i < len(search_no_duplicates):
                            if search_no_duplicates[i].id == entry.id:
                                i = len(search_no_duplicates)
                                same = True
                            else:
                                same = False
                            i += 1
                        if not same:
                            search_no_duplicates.append(entry)
                # remove those not to be used

                final_search_array = []

                finish = (int(page) * aquire_index)
                j = finish - aquire_index
                while j < finish:
                    if(j < len(search_no_duplicates)):
                        final_search_array.append(search_no_duplicates[j])
                    j += 1

                # create pagination

                number_faqs = len(search_no_duplicates)
                if(number_faqs > aquire_index):
                    max_page = number_faqs/aquire_index
                    testM = int(max_page)
                    if(testM != max_page):
                        max_page = testM + 1

                    if(max_page > 1):

                        page_list, where = get_list_of_pages(
                            int(page), int(max_page))

                        if(where == "no extras"):
                            start_extras = False
                            end_extras = False
                            hasNext = False
                            has_previous = False
                            previous_page_number = int(page)
                            next_page_number = int(page)
                        elif(where == "start"):
                            start_extras = False
                            end_extras = True
                            has_previous = False
                            hasNext = True
                            previous_page_number = int(page)
                            next_page_number = int(page) - 1
                        elif(where == "end"):
                            start_extras = True
                            end_extras = False
                            has_previous = True
                            hasNext = False
                            previous_page_number = int(page) - 1
                            next_page_number = int(page)
                        else:
                            start_extras = True
                            end_extras = True
                            has_previous = True
                            hasNext = True
                            previous_page_number = int(page) - 1
                            next_page_number = int(page) + 1

                        pagination = {
                            "has_previous": has_previous,
                            "previous_page_number": previous_page_number,
                            "number": int(page),
                            "has_next": hasNext,
                            "next_page_number": next_page_number
                        }

                        is_paginated = True

                try:
                    searchForm = SearchFAQForm()
                    aButtonType = ButtonType.objects.get(buttonType="search")
                    searchButton = ButtonText.objects.filter(
                        language=theLanguage, theButtonType=aButtonType)
                except ObjectDoesNotExist:
                    message = get_message('error', 135)
                    # flag it support
                    searchForm = SearchFAQForm()
                    searchButton = {"buttonText": "Search"}

                context = {
                    'gdpr_check': gdpr_check,
                    'search': True,
                    'faqs': final_search_array,
                    "searchTerms": search_terms,
                    'searchForm': searchForm,
                    "searchButton": searchButton,
                    'is_paginated': is_paginated,
                    'start_page': start_extras,
                    'end_page': end_extras,
                    'page_list': page_list,
                    'max_page': max_page,
                    'page_obj': pagination,
                }
                return render(self.request, "faq.html", context)
            else:
                # GDPR check
                gdpr_check = check_gdpr_cookies(self)

                try:
                    # need to add language tests here at a later date
                    theLanguage = LanguageChoices.objects.get(
                        language_short="swe")
                    aquire_index = default_pagination_values
                    number_faqs = FAQ.objects.filter(
                        language=theLanguage).count()
                    pagination = {}
                    page_list = []
                    is_paginated = False
                    start_extras = False
                    end_extras = False
                    max_page = 0
                    if(number_faqs > aquire_index):
                        # we only land here if we are on page one without a search and we have more FAQs than fit on one page
                        max_page = number_faqs / aquire_index
                        testM = int(max_page)
                        if(testM != max_page):
                            max_page = testM + 1
                        page_list, where = get_list_of_pages(1, int(max_page))

                        if(1 != max_page):
                            hasNext = False
                        else:
                            hasNext = True

                        if page - 1 >= 1:
                            previous = page - 1
                        else:
                            previous = page
                        if page > 1:
                            has_previous = True
                        else:
                            has_previous = False
                        if page + 1 <= max_page:
                            next = page + 1
                        else:
                            next = page
                        pagination = {
                            "has_previous": has_previous,
                            "previous_page_number": previous,
                            "number": page,
                            "has_next": hasNext,
                            "next_page_number": next
                        }
                        is_paginated = True
                        try:
                            if page - 1 < 1:
                                faqs = FAQ.objects.filter(language=theLanguage)[
                                    :aquire_index]
                            else:
                                offset = aquire_index * (page - 1)
                                o_l = offset + aquire_index
                                faqs = FAQ.objects.filter(language=theLanguage)[
                                    offset:o_l]
                        except ObjectDoesNotExist:
                            message = get_message('error', 135)
                            faqs = [
                                {
                                    "question": "Ett FAQ fel har uppstått:",
                                    "answer": message,
                                }
                            ]

                        if where != "no extras":
                            end_extras = True

                        if where == "start" or where == "mid":
                            start_extras = True

                        if max_page > 5 and where == "end":
                            start_extras = True

                    else:
                        # we have less FAQs then we want from aquire index, so no pagination here and no need to do a specialised search
                        try:
                            faqs = FAQ.objects.filter(language=theLanguage)
                        except ObjectDoesNotExist:
                            message = get_message('error', 135)
                            faqs = [
                                {
                                    "question": "Ett FAQ fel har uppstått:",
                                    "answer": message,
                                }
                            ]

                    try:
                        searchForm = SearchFAQForm()
                        aButtonType = ButtonType.objects.get(
                            buttonType="search")
                        searchButton = ButtonText.objects.filter(
                            language=theLanguage, theButtonType=aButtonType)
                    except ObjectDoesNotExist:
                        message = get_message('error', 135)
                        # flag it support
                        searchForm = SearchFAQForm()
                        searchButton = {"buttonText": "Search"}

                except ObjectDoesNotExist:
                    pagination = {}
                    page_list = []
                    is_paginated = False
                    start_extras = False
                    end_extras = False
                    max_page = 0
                    faqs = [
                        {
                            "question": "Ett språk fel har uppstått:",
                            "answer": message,
                        }
                    ]
                    searchForm = SearchFAQForm()
                    searchButton = {"buttonText": "Search"}
                comment = ""

                context = {
                    'gdpr_check': gdpr_check,
                    'search': False,
                    'faqs': faqs,
                    "searchTerms": "",
                    'searchForm': searchForm,
                    "searchButton": searchButton,
                    'is_paginated': is_paginated,
                    'start_page': start_extras,
                    'end_page': end_extras,
                    'page_list': page_list,
                    'max_page': max_page,
                    'page_obj': pagination,
                }
                return render(self.request, "faq.html", context)

        else:
            try:
                # need to add language tests here at a later date
                theLanguage = LanguageChoices.objects.get(language_short="swe")

                try:
                    faqs = FAQ.objects.filter(language=theLanguage)
                except ObjectDoesNotExist:
                    message = get_message('error', 135)
                    faqs = [
                        {
                            "question": "Ett fel har uppstått:",
                            "answer": message,
                        }
                    ]

                try:
                    searchForm = SearchFAQForm()
                    searchForm.language(theLanguage)
                    aButtonType = ButtonType.objects.get(buttonType="search")
                    searchButton = ButtonText.objects.filter(
                        language=theLanguage, theButtonType=aButtonType)
                except ObjectDoesNotExist:
                    message = get_message('error', 135)
                    # flag it support
                    searchForm = SearchFAQForm()
                    searchButton = {"buttonText": "Search"}

            except ObjectDoesNotExist:
                faqs = [
                    {
                        "question": "Ett fel har uppstått:",
                        "answer": message,
                    }
                ]
                searchForm = SearchFAQForm()
                searchButton = {"buttonText": "Search"}

            context = {
                'gdpr_check': gdpr_check,
                'search': False,
                'faqs': faqs,
                'searchForm': searchForm,
                "searchButton": searchButton,
            }
            return render(self.request, "faq.html", context)

# om_oss_view

class om_oss_view(View):
    def get(self, *args, **kwargs):
        # GDPR check
        gdpr_check = check_gdpr_cookies(self)
        context = {
            'gdpr_check': gdpr_check,
        }
        return render(self.request, "omoss.html", context)

    def post(self, *args, **kwargs):
        return redirect("core:omoss")

# teamet_view

class teamet_view(View):
    def get(self, *args, **kwargs):
        # GDPR check
        gdpr_check = check_gdpr_cookies(self)

        try:

            team_staff = TeamStaff.objects.all()
            people = []
            for ts in team_staff:
                if ts.active:
                    people.append(ts)

        except ObjectDoesNotExist:

            team_staff = [
                {
                    'image': "http://127.0.0.1:8000/media/media-root/89-896473_-strawberry-png-strawberry-clipart-strawberry-strawberry-clipart.png",
                    'name': "Mr Strawberry",
                    'position': "CEO",
                    'discription': "Dumtidumtidum",
                }
            ]

        context = {
            'gdpr_check': gdpr_check,
            "people": team_staff,
        }

        return render(self.request, "team.html", context)

    def post(self, *args, **kwargs):
        return redirect("core:team")

# vision_view

class vision_view(View):
    def get(self, *args, **kwargs):
        # GDPR check
        gdpr_check = check_gdpr_cookies(self)
        context = {
            'gdpr_check': gdpr_check,
        }
        return render(self.request, "vision.html", context)

    def post(self, *args, **kwargs):
        return redirect("core:vision")

# freight info

class freight_view(View):
    def get(self, *args, **kwargs):
        # GDPR check
        gdpr_check = check_gdpr_cookies(self)
        context = {
            'gdpr_check': gdpr_check,
        }
        return render(self.request, "freight.html", context)

    def post(self, *args, **kwargs):
        return redirect("core:freight")

class LogOutModView(LoginRequiredMixin, View):
    def get(self, *args, **kwargs):
        theUser = self.request.user
        orders = Order.objects.filter(who=theUser)
        for order in orders:
            order.who = None
            order.being_read = False
            order.save()
        logout(self.request)
        return redirect("core:home")

class SuccessView(View):
    def get(self, *args, **kwargs):
        gdpr_check = check_gdpr_cookies(self)
        theUser = self.request.user

        # get the content of the basket
        order = Order.objects.get(
            user=theUser, ordered=False)

        # update the order dates and set to ordered
        order.ordered = True
        order.ordered_date = make_aware(datetime.now())
        order.updated_date = make_aware(datetime.now())
        # to find this on the confirmation page set who to user
        order.who = theUser
        order.save()
        return redirect("core:confirmation")

class ConfirmationView(View):
    def get(self, *args, **kwargs):
        gdpr_check = check_gdpr_cookies(self)
        theUser = self.request.user

        # get the order

        order = Order.objects.get(who=theUser)
        # set who to null
        order.who = None
        order.save()

        # display confirmation

        context = {
            "gdpr_check": gdpr_check,
            "order": order,
        }

        return render(self.request, "success.html", context)

class CancelledView(View):
    def get(self, *args, **kwargs):
        # payment cancelled set message and redirect to basket
        message = "Betalning avbruten."
        messages.warning(
            self.request, message)
        return redirect("core:order-summary")

@csrf_exempt
def stripe_config(request):
    if request.method == 'GET':
        stripe_config = {'publicKey': settings.STRIPE_PUBLISHABLE_KEY}
        return JsonResponse(stripe_config, safe=False)

@csrf_exempt
def create_checkout_session(request):
    if request.method == 'GET':
        # FIX THIS ON UPLOAD
        domain_url = 'http://127.0.0.1:8000/'
        stripe.api_key = settings.STRIPE_SECRET_KEY
        # get the content of the basket
        theUser = request.user
        order = Order.objects.get(
            user=theUser, ordered=False)
        theUserInfo = UserInfo.objects.get(user=theUser)
        theName = "Orderreferens: " + order.ref_code
        # sent in öre
        theAmount = int(order.total_price * 100)
        try:
            # Create new Checkout Session for the order
            checkout_session = stripe.checkout.Session.create(

                client_reference_id=theUser.id if theUser.is_authenticated else None,
                customer_email=theUserInfo.email,
                success_url=domain_url +
                'success/',
                cancel_url=domain_url + 'cancelled/',
                payment_method_types=['card'],
                mode='payment',
                line_items=[
                    {
                        'name': theName,
                        'quantity': 1,
                        'currency': 'SEK',
                        'amount': theAmount,
                    }
                ]
            )
            return JsonResponse({'sessionId': checkout_session['id']})
        except Exception as e:
            return JsonResponse({'error': str(e)})

@csrf_exempt
def stripe_webhook(request):
    stripe.api_key = settings.STRIPE_SECRET_KEY
    endpoint_secret = settings.STRIPE_ENDPOINT_SECRET
    payload = request.body
    sig_header = request.META['HTTP_STRIPE_SIGNATURE']
    event = None

    try:
        event = stripe.Webhook.construct_event(
            payload, sig_header, endpoint_secret
        )
    except ValueError as e:
        # Invalid payload
        return HttpResponse(status=400)
    except stripe.error.SignatureVerificationError as e:
        # Invalid signature
        return HttpResponse(status=400)

    # Handle the checkout.session.completed event
    if event['type'] == 'checkout.session.completed':
        print("Payment was successful.")
        # TODO: run some custom code here

    return HttpResponse(status=200)

class ConfirmInfo(View):
    def get(self, *args, **kwargs):
        gdpr_check = check_gdpr_cookies(self)
        theUser = self.request.user

        # get the content of the basket
        order = Order.objects.get(
            user=self.request.user, ordered=False)

        context = {
            "gdpr_check": gdpr_check,
            "order": order,
        }

        return render(self.request, "confirmInfo.html", context)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import matplotlib
matplotlib.use('Agg')

from datetime import datetime
import math
import time
import cv2
import csv
import re
from glob import glob as glb
from tqdm import *
import os
from subprocess import call

import numpy as np
import tensorflow as tf

import sys
sys.path.append('../')

import model.flow_net as flow_net
from model.pressure import calc_force
from model.optimizer import *
from utils.boundary_utils import wing_boundary_3d
from utils.experiment_manager import make_checkpoint_path

import matplotlib.pyplot as plt

FLAGS = tf.app.flags.FLAGS

FLOW_DIR = make_checkpoint_path(FLAGS.base_dir_flow, FLAGS, network="flow")
BOUNDARY_DIR = make_checkpoint_path(FLAGS.base_dir_boundary_flow, FLAGS, network="boundary")

shape = FLAGS.shape.split('x')
shape = map(int, shape)
batch_size=1
fig_pos = 0

def run_flow_solver(params, boundary, flow, sess, drag_lift_ratio_op):
  drag_lift_ratio = np.zeros(params.shape[0])
  for i in xrange(params.shape[0]):
    wing_filename = './figs/param_' + str(i)
    wing_image = wing_boundary_2d(params[i,0], params[i,1], params[i,2],
                                  params[i,3:int((FLAGS.nr_boundary_params-4)/2)],
                                  params[i,int((FLAGS.nr_boundary_params-4)/2):-1],
                                  params[i,-1], FLAGS.dims*[FLAGS.obj_size])
    wing_image = np.greater(wing_image, 0.5)

    print("wing image")
    print(wing_image.shape)
    #wing_image = np.rot90(wing_image, 1)
    np.save(wing_filename,wing_image)

    run_cmd = ("python steady_state_flow_" + str(FLAGS.dims) + "d.py "
             + "--vox_filename=../Flow_Sculpter/test/" + wing_filename + ".npy "
             + "--vox_size=" + str(FLAGS.obj_size) + " "
             + "--output=../Flow_Sculpter/test/figs/flow_simulation_store/param_"  + str(i) + "/step")

    call(("rm ./figs/flow_simulation_store/param_" + str(i) + "/*").split(' '), cwd="../../sailfish_flows/")
    call(run_cmd.split(' '), cwd="../../sailfish_flows/")

    wing_boundary = np.load("./figs/flow_simulation_store/param_"  + str(i) + "/step_boundary.npy")
    wing_boundary = np.expand_dims(wing_boundary, axis=0)
    wing_boundary = wing_boundary.astype(np.float32)

    wing_flow = np.load("./figs/flow_simulation_store/param_"  + str(i) + "/step_steady_flow.npy")
    wing_flow = np.expand_dims(wing_flow, axis=0)
    wing_flow = wing_flow.astype(np.float32)
    print(wing_boundary.shape)
    print(wing_flow.shape)

    #plt.imshow(wing_flow[0,:,:,2])
    #plt.show()

    drag_lift_ratio[i] = sess.run(drag_lift_ratio_op, feed_dict={boundary: wing_boundary, flow: wing_flow})

  return drag_lift_ratio

def evaluate():
  """Run Eval once.

  Args:
    saver: Saver.
    summary_writer: Summary writer.
    top_k_op: Top K op.
    summary_op: Summary op.
  """

  num_angles = 9
  max_angle =  0.10
  min_angle = -0.30
  set_params          = np.array(num_angles*[FLAGS.nr_boundary_params*[0.0]])
  set_params[:,:]     = 0.0
  set_params_pos      = np.array(num_angles*[FLAGS.nr_boundary_params*[0.0]])
  set_params_pos[:,:] = 1.0

  for i in xrange(num_angles):
    set_params[i,0]      = -i
  set_params[:,0] = ((max_angle - min_angle) * (set_params[:,0]/(num_angles-1))) - min_angle
  print(set_params[:,0])

  set_params[:,2]      = 0.5
  set_params[:,3]      = 1.0
  set_params[:,-1]     = 0.0

  set_params_pos[:,0]  = 0.0 # set angle to 0.0
  set_params_pos[:,1]  = 0.0 # set angle to 0.0
  set_params_pos[:,2]  = 0.0 # set n_1 to .5
  set_params_pos[:,3]  = 0.0 # set n_2 to 1.0
  set_params_pos[:,-1] = 0.0 # set tail hieght to 0.0

  with tf.Graph().as_default():
    # Make image placeholder
    params_op, params_op_init, params_op_set, squeeze_loss = flow_net.inputs_boundary_learn(batch_size, set_params=set_params, set_params_pos=set_params_pos, noise_std=0.01)

    # Make placeholder for flow computed by lattice boltzmann solver
    solver_boundary, solver_flow = flow_net.inputs_flow(1, shape, FLAGS.dims)
    sharp_boundary, blaa = flow_net.inputs_flow(batch_size*set_params.shape[0], shape, FLAGS.dims)

    # Make boundary
    params_op_0, params_op_1, params_op_2 = tf.split(params_op, 3, axis=0)
    with tf.device('/gpu:0'):
      boundary_0 = flow_net.inference_boundary(batch_size*int(set_params.shape[0]/3), FLAGS.dims*[FLAGS.obj_size], params_op_0, full_shape=shape)
    with tf.device('/gpu:1'):
      boundary_1 = flow_net.inference_boundary(batch_size*int(set_params.shape[0]/3), FLAGS.dims*[FLAGS.obj_size], params_op_1, full_shape=shape)
    with tf.device('/gpu:2'):
      boundary_2 = flow_net.inference_boundary(batch_size*int(set_params.shape[0]/3), FLAGS.dims*[FLAGS.obj_size], params_op_2, full_shape=shape)

    # predict steady flow on boundary
    grads = []
    loss_gen = []
    with tf.device('/gpu:0'):
      predicted_flow_0 = flow_net.inference_network(boundary_0, network_type="flow", keep_prob=FLAGS.keep_prob)
      force_0 = calc_force(boundary_0, predicted_flow_0[...,-1:])
      drag_x_0 = tf.reduce_sum(force_0[...,0], axis=[1,2,3])/batch_size
      drag_y_0 = tf.reduce_sum(force_0[...,1], axis=[1,2,3])/batch_size
      drag_z_0 = tf.reduce_sum(force_0[...,2], axis=[1,2,3])/batch_size
      drag_lift_ratio_0        = -(drag_x_0/drag_z_0)
      loss_0 = -tf.reduce_sum(drag_lift_ratio_0)
      loss_0 += squeeze_loss
      variables_to_train = tf.all_variables()
      variables_to_train = [variable for i, variable in enumerate(variables_to_train) if "params" in variable.name[:variable.name.index(':')]]
      loss_gen.append(loss_0)
      # store grads
      grads.append(tf.gradients(loss_gen[0], variables_to_train))
    with tf.device('/gpu:1'):
      predicted_flow_1 = flow_net.inference_network(boundary_1, network_type="flow", keep_prob=FLAGS.keep_prob)
      force_1 = calc_force(boundary_1, predicted_flow_1[...,-1:])
      drag_x_1 = tf.reduce_sum(force_1[...,0], axis=[1,2,3])/batch_size
      drag_y_1 = tf.reduce_sum(force_1[...,1], axis=[1,2,3])/batch_size
      drag_z_1 = tf.reduce_sum(force_1[...,2], axis=[1,2,3])/batch_size
      drag_lift_ratio_1        = -(drag_x_1/drag_z_1)
      loss_1 = -tf.reduce_sum(drag_lift_ratio_1)
      loss_1 += squeeze_loss
      variables_to_train = tf.all_variables()
      variables_to_train = [variable for i, variable in enumerate(variables_to_train) if "params" in variable.name[:variable.name.index(':')]]
      loss_gen.append(loss_1)
      # store grads
      grads.append(tf.gradients(loss_gen[1], variables_to_train))
    with tf.device('/gpu:2'):
      predicted_flow_2 = flow_net.inference_network(boundary_2, network_type="flow", keep_prob=FLAGS.keep_prob)
      force_2 = calc_force(boundary_2, predicted_flow_2[...,-1:])
      drag_x_2 = tf.reduce_sum(force_2[...,0], axis=[1,2,3])/batch_size
      drag_y_2 = tf.reduce_sum(force_2[...,1], axis=[1,2,3])/batch_size
      drag_z_2 = tf.reduce_sum(force_2[...,2], axis=[1,2,3])/batch_size
      drag_lift_ratio_2        = -(drag_x_2/drag_z_2)
      loss_2 = -tf.reduce_sum(drag_lift_ratio_2)
      loss_2 += squeeze_loss
      variables_to_train = tf.all_variables()
      variables_to_train = [variable for i, variable in enumerate(variables_to_train) if "params" in variable.name[:variable.name.index(':')]]
      loss_gen.append(loss_2)
      # store grads
      grads.append(tf.gradients(loss_gen[2], variables_to_train))

    # store up the loss and gradients on gpu:0
    with tf.device('/gpu:0'):
      for i in range(1, 3):
        loss_gen[0] += loss_gen[i]
        for j in range(len(grads[0])):
          grads[0][j] += grads[i][j]

      train_step = tf.group(adam_updates(variables_to_train, grads[0], lr=FLAGS.boundary_learn_lr, mom1=0.95, mom2=0.9995))

    #with tf.device('/cpu:0'):
    #  sharp_predicted_flow = flow_net.inference_network(sharp_boundary, network_type="flow", keep_prob=FLAGS.keep_prob)

    # quantities to optimize
    #force = calc_force(boundary, predicted_flow[...,-1:])
    #sharp_force = calc_force(sharp_boundary, sharp_predicted_flow[...,-1:])
    #solver_force = calc_force(solver_boundary, solver_flow[...,-1:])
    #drag_x = tf.reduce_sum(force[...,0], axis=[1,2,3])/batch_size
    #drag_y = tf.reduce_sum(force[...,1], axis=[1,2,3])/batch_size
    #drag_z = tf.reduce_sum(force[...,2], axis=[1,2,3])/batch_size
    """
    sharp_drag_x = tf.reduce_sum(sharp_force[...,0], axis=[1,2,3])/batch_size
    sharp_drag_y = tf.reduce_sum(sharp_force[...,1], axis=[1,2,3])/batch_size
    sharp_drag_z = tf.reduce_sum(sharp_force[...,2], axis=[1,2,3])/batch_size
    solver_drag_x = tf.reduce_sum(solver_force[...,0], axis=[1,2,3])/batch_size
    solver_drag_y = tf.reduce_sum(solver_force[...,1], axis=[1,2,3])/batch_size
    solver_drag_z = tf.reduce_sum(solver_force[...,2], axis=[1,2,3])/batch_size
    """

    #drag_x = tf.concat([drag_x_0, drag_x_1, drag_x_2], axis=0)
    #drag_y = tf.concat([drag_y_0, drag_y_1, drag_y_2], axis=0)
    #drag_z = tf.concat([drag_z_0, drag_z_1, drag_z_2], axis=0)
    #drag_lift_ratio        = -(drag_x/drag_z)
    #sharp_drag_lift_ratio  = -(sharp_drag_x/sharp_drag_z)
    #solver_drag_lift_ratio = -(solver_drag_x/solver_drag_z)

    # loss
    #loss = - tf.abs(tf.constant([-25.0, 100.0, 200.0]) - drag_x) - drag_z
    #loss = drag_x - drag_z/2.0
    #loss = -tf.reduce_sum(drag_lift_ratio)
    #loss += squeeze_loss

    # train_op
    #variables_to_train = tf.all_variables()
    #variables_to_train = [variable for i, variable in enumerate(variables_to_train) if "params" in variable.name[:variable.name.index(':')]]
    #train_step = flow_net.train(loss, FLAGS.boundary_learn_lr, train_type="boundary_params", variables=variables_to_train)

    # init graph
    init = tf.global_variables_initializer()

    # Restore the moving average version of the learned variables for eval.
    variables_to_restore = tf.all_variables()
    variables_to_restore_boundary = [variable for i, variable in enumerate(variables_to_restore) if "boundary_network" in variable.name[:variable.name.index(':')]]
    variables_to_restore_flow = [variable for i, variable in enumerate(variables_to_restore) if "flow_network" in variable.name[:variable.name.index(':')]]
    saver_boundary = tf.train.Saver(variables_to_restore_boundary)
    saver_flow = tf.train.Saver(variables_to_restore_flow)

    # start ses and init
    sess = tf.Session()
    sess.run(init)
    ckpt_boundary = tf.train.get_checkpoint_state(BOUNDARY_DIR)
    ckpt_flow = tf.train.get_checkpoint_state(FLOW_DIR)
    saver_boundary.restore(sess, ckpt_boundary.model_checkpoint_path)
    saver_flow.restore(sess, ckpt_flow.model_checkpoint_path)

    graph_def = tf.get_default_graph().as_graph_def(add_shapes=True)

    params_np = (np.random.rand(1,FLAGS.nr_boundary_params) - .5)/2.0
    #params_np = (np.random.rand(1,FLAGS.nr_boundary_params) - .5)/2.0
    #params_np = np.zeros((1,FLAGS.nr_boundary_params-1))

    sess.run(params_op_init, feed_dict={params_op_set: params_np})
    run_time = FLAGS.boundary_learn_steps

    # make store vectors for values
    plot_error = np.zeros((run_time))
    plot_drag_x = np.zeros((run_time))
    plot_drag_y = np.zeros((run_time))
    plot_drag_z = np.zeros((run_time))

    # make store dir
    os.system("mkdir ./figs/boundary_learn_image_store")
    for i in tqdm(xrange(run_time)):
      #l_0, _ = sess.run([loss_0, train_step_0], feed_dict={})
      l, _, d_x, d_y, d_z = sess.run([loss_gen[0], train_step, drag_x_2, drag_y_2, drag_z_2], feed_dict={})
      #l_2, _ = sess.run([loss_2, train_step_2], feed_dict={})
      plot_error[i] = np.sum(l)
      plot_drag_x[i] = np.sum(d_x[fig_pos])
      plot_drag_y[i] = np.sum(d_y[fig_pos])
      plot_drag_z[i] = np.sum(d_z[fig_pos])
      if ((i+1) % 20 == 0) or i == run_time-1:
        # make video with opencv
        """
        s_params = sess.run(params_op)
        wing_boundary = []
        for p in xrange(s_params.shape[0]):
          wing_boundary.append(wing_boundary_3d(s_params[p,0], s_params[p,1], s_params[p,2],
                                                s_params[p,3], s_params[p,4], s_params[p,5],
                                                s_params[p,6:int((FLAGS.nr_boundary_params-7)/3+6)],
                                                s_params[p,int((FLAGS.nr_boundary_params-7)/3+6):int(2*(FLAGS.nr_boundary_params-7)/3+6)],
                                                s_params[p,int(2*(FLAGS.nr_boundary_params-7)/3+6):-1],
                                                s_params[p,-1], FLAGS.dims*[FLAGS.obj_size]))
        wing_boundary = np.stack(wing_boundary)
        wing_boundary = np.pad(wing_boundary, [[0,0],[24,24],[24,24],[24,24],[0,0]], 'constant', constant_values=0.0)
        #print(sharp_boundary.get_shape())
        #print(wing_boundary.shape)
        p_flow, p_boundary, d_l_ratio, sharp_d_l_ratio = sess.run([sharp_predicted_flow, boundary, drag_lift_ratio, sharp_drag_lift_ratio],feed_dict={sharp_boundary: wing_boundary})
        """
        p_flow, p_boundary, d_l_ratio_0, d_l_ratio_1, d_l_ratio_2 = sess.run([predicted_flow_2, boundary_2, drag_lift_ratio_0, drag_lift_ratio_1, drag_lift_ratio_2])
        d_l_ratio = np.concatenate([d_l_ratio_0, d_l_ratio_1, d_l_ratio_2], axis=0)

        # save plot image to make video
        #p_pressure = p_flow[fig_pos,:,:,72,2]
        p_boundary = np.concatenate([p_boundary[fig_pos,:,71,:,0], p_boundary[fig_pos,:,:,71,0]], axis=0)
        p_pressure = np.concatenate([p_flow[fig_pos,:,71,:,3], p_flow[fig_pos,:,:,71,3]], axis=0)
        #p_pressure = p_flow[:,:,76,:,3].reshape((p_boundary.shape[0]*p_boundary.shape[1], p_boundary.shape[2]))
        #p_boundary = p_boundary[:,:,76,:,0].reshape((p_boundary.shape[0]*p_boundary.shape[1], p_boundary.shape[2]))

        fig = plt.figure()
        fig.set_size_inches(20, 5)
        #a = fig.add_subplot(1,5,1)
        #plt.imshow(p_pressure)
        a = fig.add_subplot(1,4,1)
        plt.imshow(p_boundary)
        a = fig.add_subplot(1,4,2)
        plt.plot(plot_error, label="Sum(Lift/Drag)")
        plt.xlabel("Step")
        plt.legend()
        a = fig.add_subplot(1,4,3)
        plt.plot(plot_drag_x, label="Lift Angle 0")
        plt.plot(-plot_drag_z, label="Drag Angle 0")
        plt.ylim(0.0, np.max(plot_drag_x)+30.0)
        plt.xlabel("Step")
        plt.legend()
        a = fig.add_subplot(1,4,4)
        plt.plot(np.degrees(set_params[:,0]), d_l_ratio, 'bo', label="Lift/Drag Network")
        #plt.plot(-np.degrees(set_params[3:6,0]), sharp_d_l_ratio, 'ro', label="Lift/Drag Sharp")
        #if i == run_time-1:
        #  solver_d_l_ratio = run_flow_solver(sess.run(params_op), solver_boundary, solver_flow, sess, solver_drag_lift_ratio)
        #  plt.plot(-np.degrees(set_params[:,0]), solver_d_l_ratio, 'go', label="Lift/Drag Solver")
        plt.xlabel("Angle of Attack (Degrees)")
        plt.xlim(min(np.degrees(set_params[:,0]))-3, max(np.degrees(set_params[:,0]))+3)
        plt.ylim(np.min(d_l_ratio)-1.0, np.max(d_l_ratio)+1.0)
        plt.legend()
        plt.suptitle("3D Wing Optimization Using Gradient Descent", fontsize=20)
        plt.savefig("./figs/boundary_learn_image_store/plot_" + str(i).zfill(5) + ".png")
        if run_time - i <= 100:
          plt.savefig("./figs/" + FLAGS.boundary_learn_loss + "_plot.png")
        if i == run_time - 1:
          plt.savefig("./figs/learn_gradient_descent.pdf")
          plt.show()
        plt.show()
        plt.close(fig)

    np.save("figs/3d_wing_params_op", sess.run(params_op[6]))
    print(sess.run(params_op[6]))
    # generate video of plots
    #os.system("rm ./figs/" + FLAGS.boundary_learn_loss + "_plot_video.mp4")
    #os.system("cat ./figs/boundary_learn_image_store/*.png | ffmpeg -f image2pipe -r 30 -vcodec png -i - -vcodec libx264 ./figs/" + FLAGS.boundary_learn_loss + "_plot_video.mp4")
    #os.system("rm -r ./figs/boundary_learn_image_store")

def main(argv=None):  # pylint: disable=unused-argument
  evaluate()

if __name__ == '__main__':
  tf.app.run()


"""A tiny English to Spanish dictionary is created,
using the Python dictionary type dict.
Then the dictionary is used, briefly.
"""

def createDictionary():
    '''Returns a tiny Spanish dictionary'''
    spanish = dict()
    spanish['hello'] = 'hola'
    spanish['yes'] = 'si'
    spanish['one'] = 'uno'
    spanish['two'] = 'dos'
    spanish['three'] = 'tres'
    spanish['red'] = 'rojo'
    spanish['black'] = 'negro'
    spanish['green'] = 'verde'
    spanish['blue'] = 'azul'
    return spanish

def main():
    dictionary = createDictionary()
    print(dictionary['two'])
    print(dictionary['red'])

main()


#Given an integer n, return an array ans of length n + 1 such that for each i...
# ... (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.

class Solution:
    # Brute-Force Solution
    def countBits(self, n: int) -> list[int]:
        result = []

        for i in range(0, n + 1):
            binary = bin(i)
            one_count = 0

            for num in binary[2:]:
                if num == '1':
                    one_count += 1
            result.append(one_count)

        return result


import time
from enum import Enum

import typer

from api.fb_api import post_message
from scrapers.flashscore import scrape_fs_page, get_match_info_url

LAST_INCIDENT_POSTED = -1

class IncidentType(Enum):
    LFC_GOAL = 1
    OPPONENT_GOAL = 2
    LFC_RED_CARD = 3
    OPPONENT_RED_CARD = 4
    LFC_VAR_DISSALOWED = 5
    OPPONENT_VAR_DISSALOWED = 6
    LFC_PENALTY_MISSED = 7
    OPPONENT_PENALTY_MISSED = 8
    OTHER = 9

def post_comment(incident: dict):
    if incident["type"] == IncidentType.LFC_GOAL:
        message = f"""⚽ GÓÓÓÓÓÓÓÓÓÓÓÓÓL!!!
        {incident['time']}' {incident['player']} {incident['assist']}
        {incident['home_score']}-{incident['away_score']}
        """
    elif incident["type"] == IncidentType.OPPONENT_GOAL:
        message = f"""⚽ Gól!
        {incident['time']}' {incident['player']}
        {incident['home_score']}-{incident['away_score']}
        """
    # TODO: Add support for other incidents
    # elif incident["type"] == IncidentType.LFC_RED_CARD:
    #     message = ""
    # elif incident["type"] == IncidentType.OPPONENT_RED_CARD:
    #     message = ""
    # elif incident["type"] == IncidentType.LFC_PENALTY_MISSED:
    #     message = ""
    # elif incident["type"] == IncidentType.OPPONENT_PENALTY_MISSED:
    #     message = ""
    else:
        return None
    post_message(message)

def comment_the_match(url: str):
    global LAST_INCIDENT_POSTED
    while True:
        soup = scrape_fs_page(url)
        status = soup.find(class_="fixedHeaderDuel__detailStatus").text
        if status == "Prestávka" or status == "Koniec":
            break
        is_lfc_home_team = (
            soup.find(class_="participant__participantName").text == "Liverpool"
        )
        score = soup.find(class_="detailScore__wrapper").text
        home_score, away_score = score.split("-")
        incident_tags = soup.find_all(class_="smv__participantRow")
        incidents = []
        for incident_tag in incident_tags:
            incident = {
                "time": incident_tag.find(class_="smv__timeBox").text[:-1],
                "home_score": home_score,
                "away_score": away_score,
                "player": incident_tag.find(class_="smv__playerName").text,
            }

            if incident_tag.find(class_="smv__incidentAwayScore") is not None:
                incident["type"] = (
                    IncidentType.OPPONENT_GOAL
                    if is_lfc_home_team
                    else IncidentType.LFC_GOAL
                )
                assist = incident_tag.find(class_="smv__assist")
                incident["assist"] = assist.text if assist is not None else ""
                incidents.append(incident)
            elif incident_tag.find(class_="smv__incidentHomeScore") is not None:
                incident["type"] = (
                    IncidentType.LFC_GOAL
                    if is_lfc_home_team
                    else IncidentType.OPPONENT_GOAL
                )
                assist = incident_tag.find(class_="smv__assist")
                incident["assist"] = assist.text if assist is not None else ""
                incidents.append(incident)
            # TODO: Add support for other incidents
            else:
                incident["type"] = IncidentType.OTHER
        for i in range(LAST_INCIDENT_POSTED + 1, len(incidents)):
            post_comment(incidents[i])
        LAST_INCIDENT_POSTED = len(incidents) - 1
    time.sleep(60)

def main():
    url = get_match_info_url()
    # First half
    comment_the_match(url)
    time.sleep(60 * 15)
    # Second half
    comment_the_match(url)

if __name__ == "__main__":
    typer.run(main)


class Solution:
    def findLength(self, nums1: List[int], nums2: List[int]) -> int:
        result = 0
        n1, n2 = len(nums1), len(nums2)
        dp = [[0 for _ in range(n1)] for _ in range(n2)]
        for i2 in range(n2):
            for i1 in range(n1):
                if nums1[i1] == nums2[i2]:
                    if i1 == 0 or i2 == 0:
                        dp[i2][i1] = 1
                    else:
                        dp[i2][i1] = 1 + dp[i2-1][i1-1]
                result = max(result, dp[i2][i1])
        return result


import random

FIRST_PRIMES_LIST = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
                     31, 37, 41, 43, 47, 53, 59, 61, 67,
                     71, 73, 79, 83, 89, 97, 101, 103,
                     107, 109, 113, 127, 131, 137, 139,
                     149, 151, 157, 163, 167, 173, 179,
                     181, 191, 193, 197, 199, 211, 223,
                     227, 229, 233, 239, 241, 251, 257,
                     263, 269, 271, 277, 281, 283, 293,
                     307, 311, 313, 317, 331, 337, 347, 349]

NUMBER_OF_TRIES = 20

def random_n_bits_number(n):
    return random.randrange(2 ** (n-1) + 1, 2 ** n - 1)

def low_level_prime(n):
		while True:
				prime_candidate = random_n_bits_number(n)
				for divisor in FIRST_PRIMES_LIST:
						if prime_candidate % divisor == 0 and divisor**2 <= prime_candidate:
								break
				else:
					return prime_candidate

def trial_composite(round_tester, even_component, prime_candidate, max_divisions_by_two):
		if pow(round_tester, even_component, prime_candidate) == 1:
				return False
		for i in range(max_divisions_by_two):
				if pow(round_tester, 2**i * even_component, prime_candidate) == prime_candidate-1:
						return False
		return True

def miller_rabin(prime_candidate):
    max_divisions_by_two = 0
    even_component = prime_candidate-1

    while even_component % 2 == 0:
        even_component >>= 1
        max_divisions_by_two += 1
    assert(2 ** max_divisions_by_two * even_component == prime_candidate-1)

    for _ in range(NUMBER_OF_TRIES):
        round_tester = random.randrange(2, prime_candidate)
        if trial_composite(round_tester, even_component, prime_candidate, max_divisions_by_two):
            return False
    return True

def get_prime_n_bits(n):
		prime = 0
		while True:
				prime_candidate = low_level_prime(n)
				if not miller_rabin(prime_candidate):
						continue
				else:
						prime = prime_candidate
						break
		return prime


import datetime
import time
import urllib3
import serial #Import Serial Library
import linecache

arduinoSerialData = serial.Serial("/dev/cu.usbmodem1411", 9600, timeout=1)

try:
	urllib3.disable_warnings()
except:
	print('urllib3.disable_warnings() failed - get a recentenough urllib3 version to avoid potential InsecureRequestWarning warnings! Can and will continue though.')

http = urllib3.PoolManager()
url = 'https://iotmmsb7af91ae6.us1.hana.ondemand.com/com.sap.iotservices.mms/v1/api/http/data/'
#url = 'https://iotmmsi843568trial.hanatrial.ondemand.com/com.sap.iotservices.mms/v1/api/http/data/'
#deviceID = 'b7e75e6a-0364-494b-a6c4-7a25af775ea9'
deviceID = '34d074e3-ad45-42b7-bc9f-d3ee28765424'
url = url +deviceID
headers = urllib3.util.make_headers()
#headers['Authorization'] = 'Bearer ' + '64a33a2048da5ed80a854b6789084da'
headers['Authorization'] = 'Bearer ' + 'ecde36ac5bf57a96943c3bc34c338a6b'
headers['Content-Type'] = 'application/json;charset=utf-8'

while (1==1):
	current_time = int (time.time() *100)
	timestamp =str (current_time)
	#sensores()
	if (arduinoSerialData.inWaiting()>0):
		myData = arduinoSerialData.readline()
		lista = myData.split(" ")
		inumber = 1850231
		Temperatura = lista[0]
		Distancia = lista[1]
		Peso1 = lista[2]
		Peso2 = lista[3]
		Peso3 = lista[4]
		Pasos = lista[5]
		stringID =  str (inumber)
		stringTemperature = str (Temperatura)
		stringDistance = str(Distancia)
		stringWeight1 = str(Peso1)
		stringWeight2 = str (Peso2)
		stringWeight3 = str(Peso3)
		stringSteps = str(Pasos)
		print (str (current_time))
		# send message body and the corresponding payload layout that you defined in the IoT Services Cockpit
		# replace messagetypeid with id from IOT cockpit
		#body='{"messageType":"c5e3394e68bfa5f73ad1","mode":"sync","messages":[{"timestamp":'
		body='{"messageType":"ae2de8779c5e443cbefd","mode":"sync","messages":[{"timestamp":'

		body=body+timestamp
		body = body +',"ID":'+ stringID
		body = body +',"Temperature":'+stringTemperature
		body = body +',"ActivePause":'+stringDistance
		body = body +',"Weight1":'+stringWeight1
		body = body +',"Weight2":'+stringWeight2
		body = body +',"Weight3":'+stringWeight3
		body = body +',"Steps":'+stringSteps +'}]}'

		print ("")
		print (body)
		r = http.urlopen('POST', url, body=body, headers=headers)
		print ("")
		print(r.status)
		print(r.data)


import json
import os.path as op
from os import makedirs
import sys
import numpy as np
import pandas as pd
from tqdm import tqdm
import matplotlib.pyplot as plt

from utils import html_intro, html_outro

import plotly.express as px

def parse_sulci_list(keys):
    ss_list = set()
    for k in keys:
        sp = k.split('_')
        if len(sp) > 1:
            ss_list.add('_'.join(sp[1:]))
    return list(sorted(ss_list))

def subject_name_from_graph_name(name):
    return op.split(name)[1].split('_')[1:]

if __name__ == "__main__":
    eval_dir = "/neurospin/dico/bcagna/data/deepsulci_models_comparison/evaluations/"
    models = [
        'cohort-pclean50A_hemi-L_model-unet3d',
        'cohort-pclean50A_hemi-L_model-unet3d_ext-archi50A_hemi-L'
    ]
    cohort = 'cohort-pclean12A_hemi-L'
    out_dir = "/var/tmp/model_comp_report"

    html_f = op.join(out_dir, "models_comparison.html")
    fig_dir = op.join(out_dir, "figures")
    makedirs(fig_dir, exist_ok=True)

    print("Loading scores...")
    ss_list = None
    scores = {k: [] for k in ['model', 'subject', 'name', 'sens', 'spec']}
    for model in models:
        print(model)
        data = pd.read_csv(op.join(eval_dir, model, cohort + ".csv"))

        if not ss_list:
            ss_list = parse_sulci_list(data.keys())

        for ig, g in tqdm(enumerate(data['Unnamed: 0.1'])):
            s = subject_name_from_graph_name(g)
            for ss in ss_list:
                scores['model'].append(model)
                scores['subject'].append(s)
                scores['name'].append(ss)
                scores['sens'].append(data["sens_" + ss][ig])
                scores['spec'].append(data["spec_" + ss][ig])
    scores = {k: np.array(scores[k]) for k in scores.keys()}
    print("Done")

    print("Generating figures...")
    for ss in tqdm(ss_list):
        colors = ['g', 'm']
        fig = plt.figure(figsize=(4, 4))
        for m in models:
            specs = scores['spec'][scores['model'] == m]
            sens = scores['sens'][scores['model'] == m]
            plt.scatter(np.log10(specs), np.log10(sens))
        plt.title(ss)
        fig.savefig(op.join(fig_dir, ss + ".png"))
        del fig

    print("Generating html report...")
    html = '
Models comparison

'
    for m in models:
        html += "
" + m + "/
"
    html += "

"
    for ss in ss_list:
        html += ''
    html += "
"

    with open(html_f, "w+") as f:
        f.write(html_intro() + html + html_outro())
    print('Done')


import datetime
import pandas as pd
import numpy as np
import re
import nltk
from nltk.corpus import stopwords
from gensim.models.doc2vec import TaggedDocument
from gensim.models import Doc2Vec
from random import shuffle
from sklearn.model_selection import train_test_split

def main():
    travel = pd.read_csv('data/travel.csv.zip', index_col='id')
    prepare_data(travel)
    labels = prepare_labels(travel)
    model = train(labels)

def prepare_text(text):
    clean_text = re.sub("<.*?>", "", text).lower()
    splitter = re.compile("[^a-zA-Z0-9_\\+\\-/]")
    words = splitter.split(clean_text)
    stops = set(stopwords.words("english"))
    meaningful_words = [w.strip() for w in words if not w in stops]
    return " ".join(filter(None, meaningful_words))

def prepare_data(df):
    df['content'] = df['content'].apply(prepare_text)
    df['title'] = df['title'].apply(prepare_text)

def prepare_labels(df):
    sentences = []
    for i, row in df.iterrows():
        tags = tokenize_text(row['tags'])
        sentences.append(TaggedDocument(words=tokenize_text(row['content']), tags=tags))
    return sentences

def count_tags(df):
    tags = set()
    df['tags'].str.split(' ').apply(tags.update)
    return tags

def tokenize_text(text):
    tokens = []
    for sent in nltk.sent_tokenize(text):
        for word in nltk.word_tokenize(sent):
            if len(word) < 2:
                continue
            tokens.append(word.lower())
    return tokens

def jaccard_similarity(labels, preds):
    lset = set(labels)
    pset = set(preds)
    return len(lset.intersection(pset)) / len(lset.union(pset))

def test(test_sents, model):
    results = []
    for test_sent in test_sents:
        pred_vec = model.infer_vector(test_sent.words)
        pred_tags = model.docvecs.most_similar([pred_vec], topn=5)
        results.append(jaccard_similarity(test_sent.tags, [p[0] for p in pred_tags]))
    return np.array(results)

def train(sentences):
    model = Doc2Vec(dm=0, size=100, negative=5, hs=0, min_count=2, workers=4)
    model.build_vocab(sentences)
    train_sents, test_sents = train_test_split(sentences, test_size=0.2, random_state=42)
    alpha = 0.025
    min_alpha = 0.001
    num_epochs = 200
    alpha_delta = (alpha - min_alpha) / num_epochs

    for epoch in range(num_epochs):
        start_time = datetime.datetime.now()
        shuffle(train_sents)
        model.alpha = alpha
        model.min_alpha = alpha
        model.train(train_sents)
        alpha -= alpha_delta
        end_time = datetime.datetime.now()
        accuracy = test(test_sents, model).mean()
        print("Complete epoch {}: {}; Accuracy: {}".format(epoch, end_time - start_time, accuracy))

    return model

if __name__ == '__main__':
    main()


# -*- encoding: utf-8 -*-
'''
@File    :   Test_Example.py
@Time    :   2021/12/09 17:17:57
@Author  :   Xianqi
@Contact :   chenxianqi12@qq.com
@Function:   This an example for fitness evaluation.
'''

import numpy as np
from utils import getObjectiveConstraint, plot_layout
from Param import domain, component, heatpipe

def main():

    dim = component.x_opt_dim
    x = np.random.rand(1, dim) * (component.x_opt_max - component.x_opt_min) + component.x_opt_min

    objective, constraint = getObjectiveConstraint(x, domain, component, heatpipe)
    obj = objective[0]
    cons1, cons2, cons3, cons4 = constraint
    print()
    print("Objective value: ", obj, "W")
    print("Constraint 1 voilation: ", cons1)
    print("Constraint 2 voilation: ", cons2)
    print("Constraint 3 voilation: ", cons3)
    print("Constraint 4 voilation: ", cons4)

    # draw layout
    plot_layout(x, domain, component, heatpipe, savefig=False, disfig=True, dismass=True, prefix_name='p1')

if __name__ == "__main__":
    main()