import json
import operator

from functools import reduce

from mailchimp3 import MailChimp
from easy_thumbnails.files import get_thumbnailer
from ipware.ip import get_client_ip as get_ip

from cms.models import Title
from django.db.models.functions import Lower
from django.contrib import messages
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import get_language_from_request
from django.utils.html import strip_tags
from django.utils.text import Truncator
from django.shortcuts import redirect
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.template.defaultfilters import slugify
from django.core.management import call_command
from django.core.mail import send_mail
from django.db.models import Q

from rest_framework.generics import GenericAPIView
from rest_framework.permissions import AllowAny
from rest_framework.response import Response as RestResponse
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import PermissionDenied

from shop.models.defaults.customer import Customer
from shop.modifiers.pool import cart_modifiers_pool
from shop.models.order import OrderModel
from shop.rest.renderers import CMSPageRenderer
from shop.views.order import OrderView
from shop.serializers.auth import PasswordResetConfirmSerializer

from dal import autocomplete

from dshop.models import Product, ProductFilterGroup, ProductFilter
from dshop.models import Attribute, \
    AttributeValue, ProductCategory, ProductBrand

from settings import DEFAULT_FROM_EMAIL, DEFAULT_TO_EMAIL, THEME_SLUG
from settings import MAILCHIMP_KEY, MAILCHIMP_LISTID

from shop.views.auth import AuthFormsView as ShopAuthFormView
from django.core.exceptions import NON_FIELD_ERRORS
from rest_framework.response import Response
from shop.models.customer import CustomerModel

from feature_settings import QUOTATION

try:
    from apps.dmRabais.models import dmCustomerPromoCode
except ImportError:
    dmCustomerPromoCode = None

#######################################################################
# ===---   OrderView Bug fix                                   ---=== #
#######################################################################

class OrderPermission(BasePermission):
    """
    Allow access to a given Order if the user is entitled to.
    """
    def has_permission(self, request, view):
        if view.many and request.customer.is_visitor:
            detail = _("Only signed in customers can \
                view their list of orders.")
            raise PermissionDenied(detail=detail)
        return True

    def has_object_permission(self, request, view, order):
        if request.user.is_authenticated and \
           not request.user.is_staff and \
           not request.user.is_superuser:
            return order.customer.pk == request.user.pk
        if order.secret and \
           order.secret == view.kwargs.get('secret') or \
           request.user.is_staff or \
           request.user.is_superuser:
            return True
        detail = _("This order does not belong to you.")
        raise PermissionDenied(detail=detail)

class OrderView(OrderView):

    permission_classes = [OrderPermission]

    def get_queryset(self):
        queryset = OrderModel.objects.all()
        if self.request.customer.user.is_staff or \
           self.request.customer.user.is_superuser:
            return queryset
        if self.request.customer.is_visitor:
            return queryset.none()
        if self.request.customer.is_authenticated:
            queryset = queryset.filter(
                customer=self.request.customer
            ).order_by('-updated_at')
        return queryset

#######################################################################
# ===---   Views used in products                              ---=== #
#######################################################################

class DshopProductListView(APIView):

    permission_classes = [AllowAny]

    def get(self, request, *args, **kwargs):  # noqa: C901
        attribute = self.request.query_params.get('attribute', None)
        category = self.request.query_params.get('category', None)
        fltr = self.request.query_params.get('filter', None)
        brand = self.request.query_params.get('brand', None)
        response_type = self.request.query_params.get('type', None)
        offset = int(request.GET.get("offset", 0))
        limit = int(request.GET.get("limit", 9))
        sortby = request.COOKIES.get("dm_psortby", "default")
        if sortby == "date-new":
            orderby = "-created_at"
        elif sortby == "date-old":
            orderby = "created_at"
        elif sortby == "alpha-asc":
            orderby = Lower("product_name")
        elif sortby == "alpha-des":
            orderby = Lower("product_name").desc()
        elif sortby == "price-asc":
            orderby = "get_p"
        elif sortby == "price-des":
            orderby = "-get_p"
        else:
            orderby = "order"

        products = Product.objects.filter(
            Q(categories__active=True) | Q(categories=None),
            active=True
        )
        if request.LANGUAGE_CODE == "fr":
            title = 'Produits'
        else:
            title = 'Products'
        current_category = None
        current_brand = None
        if 'category_id' in kwargs:
            products = products.filter(categories__id=kwargs['category_id'])
            cat = ProductCategory.objects.filter(
                id=kwargs['category_id']
            ).first()
            if cat:
                current_category = cat
                title = cat.name
        elif 'brand_id' in kwargs:
            products = products.filter(brand=kwargs['brand_id'])
            brnd = ProductBrand.objects.filter(id=kwargs['brand_id']).first()
            if brnd:
                current_brand = brnd
                title = brnd.name

        if category:
            category = [val for val in category.split(',') if val]
            if len(category) > 0:
                q = reduce(
                    operator.and_, (Q(categories__id=i) for i in category)
                )
                products = products.exclude(~q).distinct()
            else:
                products = products.distinct()

        if fltr:
            fltr = [val for val in fltr.split(',') if val]
            if len(fltr) > 0:
                q = reduce(
                    operator.and_, (Q(filters__id=i) for i in fltr)
                )
                products = products.exclude(~q).distinct()
            else:
                products = products.distinct()

        if brand:
            brand = [val for val in brand.split(',') if val]
            if len(brand) > 0:
                q = reduce(
                    operator.and_, (Q(brand__id=i) for i in brand)
                )
                products = products.exclude(~q).distinct()
            else:
                products = products.distinct()

        if attribute:
            attributes = [val for val in attribute.split(',') if val]
            attributes = AttributeValue.objects.filter(id__in=attributes)
            attributes = [atr.value for atr in attributes]
            ids = []
            for q in products:
                attrs = []
                try:
                    for var in q.variants.all():
                        attrs += [
                            val[0] for val in
                            var.attribute.all().values_list('value')
                        ]
                except Exception:
                    continue

                for atr in attributes:
                    if atr in attrs:
                        ids.append(q.id)
                        break
            if len(ids) > 0:
                q = reduce(
                    operator.and_, (Q(id=i) for i in ids)
                )
                products = products.exclude(~q).distinct()
            else:
                products = products.distinct()

        if orderby == 'get_p':
            products = sorted(
                products.distinct(),
                key=lambda product: product.get_price(request)
            )
        elif orderby == '-get_p':
            products = sorted(
                products.distinct(),
                key=lambda product: product.get_price(request),
                reverse=True
            )
        else:
            products = products.order_by(orderby)
        categories = ProductCategory.objects.filter(parent=None, active=True)
        brands = ProductBrand.objects.all()
        filters = ProductFilter.objects.all()
        next_page = False

        if not type(products) == list:
            products = products.distinct()

        if len(products) > offset + limit:
            products = products[offset:limit]
            next_page = True
        else:
            products = products[offset:]
        filter_data = LoadFilters.as_view()(request=request._request).data
        data = {
            'products': products,
            'brands': brands,
            'categories': categories,
            'filters': filters,
            'filter_data': filter_data,
            'is_quotation': QUOTATION,
            'title_str': title,
            'current_category': current_category,
            'current_brand': current_brand,
            'next': next_page
        }

        if not response_type:
            return render(
                request,
                'theme/{}/pages/produits.html'.format(THEME_SLUG),
                context=data
            )
        # ===---
        all_produits = []
        for produit in products:
            data = {}
            data['name'] = produit.product_name_trans
            data['url'] = produit.get_absolute_url()
            data['caption'] = strip_tags(Truncator(produit.caption).words(18))
            data['slug'] = produit.slug
            try:
                if produit.main_image:
                    data['image'] = get_thumbnailer(
                        produit.main_image).get_thumbnail({
                            'size': (540, 600),
                            'upscale': True,
                            'background': "#ffffff"
                        }).url
                elif produit.images.first():
                    data['image'] = get_thumbnailer(
                        produit.images.first()).get_thumbnail({
                            'size': (540, 600),
                            'upscale':
                            True,
                            'background':
                            "#ffffff"
                        }).url
                else:
                    data['image'] = None
            except Exception:
                data['image'] = None
            if produit.filters.all():
                data['filters'] = " ".join(
                    [slugify(d.name) for d in produit.filters.all()]
                )
            else:
                data['filters'] = None
            if produit.label:
                data['label'] = {}
                data['label']['name'] = produit.label.name
                data['label']['colour'] = produit.label.colour
                data['label']['bg_colour'] = produit.label.bg_colour
            else:
                data['label'] = None
            if hasattr(produit, 'variants'):
                data['variants'] = True
                data['variants_count'] = produit.variants.all().count()
                if produit.variants.first():
                    data['variants_product_code'] = produit.variants.first(
                    ).product_code
                    data['price'] = produit.variants.first().get_price(request)
                    data['realprice'] = produit.variants.first().unit_price
                    data['is_discounted'] = False
                    for v in produit.variants.all():
                        if v.is_discounted:
                            data['is_discounted'] = True
                    data['quantity'] = 0
                    for v in produit.variants.all():
                        if v.quantity > 0:
                            data['quantity'] = v.quantity
                else:
                    data['variants_product_code'] = ""
                    data['price'] = "-"
                    data['is_discounted'] = False
                    data['quantity'] = 0
            else:
                data['product_code'] = produit.product_code
                data['price'] = produit.get_price(request)
                data['realprice'] = produit.unit_price
                data['variants'] = False
                data['variants_count'] = 0
                data['is_discounted'] = produit.is_discounted
                data['quantity'] = produit.quantity
            data['is_quotation'] = QUOTATION
            all_produits.append(data)
        # ===---
        result = {"products": all_produits, "next": next_page}
        return RestResponse(result)

class LoadFilters(APIView):

    def get(self, request, *args, **kwargs):
        groups = ProductFilterGroup.objects.all()
        data = {}
        # ===--- Filters with group
        for group in groups:
            temp = {}
            filters = []
            subfilt = ProductFilter.objects.filter(group=group)
            if subfilt.count() > 0:
                temp['id'] = group.id
                temp['order'] = group.order
                for filt in subfilt:
                    url = ''
                    if filt.image:
                        url = filt.image.url
                    try:
                        if filt.name_trans:
                            name = filt.name_trans
                        else:
                            name = filt.name
                    except Exception:
                        name = filt.name
                    # ===---
                    filters.append({
                        'id': filt.id,
                        'name': name,
                        'order': filt.order,
                        'image': url,
                        'description': ''
                    })
                temp['filter'] = filters
                if group.name_trans:
                    group_name = group.name_trans
                else:
                    group_name = group.name
                data[group_name] = temp
        temp = {}
        # ===--- Filters without group
        filters = []
        for filt in ProductFilter.objects.filter(group=None):
            try:
                name = filt.name_trans if filt.name_trans else filt.name
            except Exception:
                name = filt.name
            filters.append({'id': filt.id, 'name': name, 'order': filt.order})
        data['default'] = {'filter': filters}
        # ===---

        a_data = {}
        for attr in Attribute.objects.all():
            try:
                name = attr.name_trans if attr.name_trans else attr.name
            except Exception:
                name = attr.name
            a_data[name] = {}
            a_data[name]["id"] = attr.id
            a_data[name]["values"] = []
            for val in AttributeValue.objects.filter(attribute=attr):
                try:
                    value = val.value_trans if val.value_trans else val.name
                except Exception:
                    value = val.name
                a_data[name]["values"].append({
                    'id': val.id,
                    'name': value
                })

        categories = ProductCategory.objects.filter(parent=None, active=True)
        cat_data = []
        for cat in categories:
            try:
                name = cat.name_trans if cat.name_trans else cat.name
            except Exception:
                name = cat.name
            cat_d = {'id': cat.id, 'name': name}
            child_c = []
            categories = ProductCategory.objects.filter(
                parent=cat, active=True
            )
            for child in categories:
                try:
                    if child.name_trans:
                        child_name = child.name_trans
                    else:
                        child_name = child.name
                except Exception:
                    child_name = child.name
                child_c.append({'id': child.id, 'name': child_name})
            cat_d['child'] = child_c
            cat_data.append(cat_d)

        brands = []
        for brand in ProductBrand.objects.all():
            brands.append({'id': brand.id, 'name': brand.name})

        return RestResponse({
            'filter': data,
            'attribute': a_data,
            'categories': cat_data,
            'brands': brands
        })

class LoadProduits(APIView):
    """
    Retrieve products.

    GET
    ===

    :param category (int)
    :param offset (int)
    :param limit (int)

    :return An object with the list of Products in "products"
    and the count of Products in the next page in "next".
    """

    permission_classes = [AllowAny]

    def get(self, request, *args, **kwargs):  # noqa: C901
        category = request.GET.get("category", None)
        brand = request.GET.get("brand", None)
        offset = int(request.GET.get("offset", 0))
        limit = int(request.GET.get("limit", 2))
        # ===---
        sortby = request.COOKIES.get("dm_psortby", "default")
        if sortby == "date-new":
            orderby = "-created_at"
        elif sortby == "date-old":
            orderby = "created_at"
        elif sortby == "alpha-asc":
            orderby = "product_name"
        elif sortby == "alpha-des":
            orderby = "-product_name"
        elif sortby == "price-asc":
            orderby = "order"
        elif sortby == "price-des":
            orderby = "order"
        else:
            orderby = "order"
        # ===---
        try:
            is_quotation = QUOTATION_FEATURE # noqa
        except Exception:
            is_quotation = False
        if category is not None:
            category = int(category)
            products = Product.objects.filter(
                Q(categories=category) | Q(categories__parent=category)
                | Q(categories__parent__parent=category)
                | Q(categories__parent__parent__parent=category),
                active=True).order_by(orderby).distinct()
            next_products = Product.objects.filter(
                Q(categories=category) | Q(categories__parent=category)
                | Q(categories__parent__parent=category)
                | Q(categories__parent__parent__parent=category), active=True
            ).order_by(orderby).distinct()[
                offset + limit:offset + limit + limit
            ].count()
        elif brand is not None:
            brand = int(brand)
            products = Product.objects.filter(
                Q(brand=brand), active=True
            ).order_by(orderby).distinct()
            next_products = Product.objects.filter(
                brand=brand, active=True
            ).order_by(orderby).distinct()[
                offset + limit:offset + limit + limit
            ].count()
        else:
            products = Product.objects.filter(
                Q(categories__active=True) | Q(categories=None),
                active=True
            ).order_by(orderby).distinct()
            next_products = Product.objects.filter(
                Q(categories__active=True) | Q(categories=None),
                active=True
            ).order_by(orderby).distinct()[
                offset + limit:offset + limit + limit
            ].count()
        # ===---
        if sortby == "price-asc":
            products = sorted(
                products, key=lambda t: t.get_price(request)
            )
        elif sortby == "price-des":
            products = sorted(
                products, key=lambda t: t.get_price(request),
                reverse=True
            )
        # ===---
        products = products[offset:offset+limit]
        # ===---
        all_produits = []
        for produit in products:
            data = {}
            data['name'] = produit.product_name_trans
            data['url'] = produit.get_absolute_url()
            data['caption'] = strip_tags(Truncator(produit.caption).words(18))
            data['slug'] = produit.slug
            if produit.main_image:
                data['image'] = get_thumbnailer(
                    produit.main_image).get_thumbnail({
                        'size': (540, 600),
                        'upscale': True,
                        'background': "#ffffff"
                    }).url
            elif produit.images.first():
                data['image'] = get_thumbnailer(
                    produit.images.first()).get_thumbnail({
                        'size': (540, 600),
                        'upscale':
                        True,
                        'background':
                        "#ffffff"
                    }).url
            else:
                data['image'] = None
            if produit.filters.all():
                data['filters'] = " ".join(
                    [slugify(d.name) for d in produit.filters.all()])
            else:
                data['filters'] = None
            if produit.label:
                data['label'] = {}
                data['label']['name'] = produit.label.name
                data['label']['colour'] = produit.label.colour
                data['label']['bg_colour'] = produit.label.bg_colour
            else:
                data['label'] = None
            if hasattr(produit, 'variants'):
                data['variants'] = True
                data['variants_count'] = produit.variants.all().count()
                if produit.variants.first():
                    data['variants_product_code'] = produit.variants.first(
                    ).product_code
                    data['price'] = produit.variants.first().get_price(request)
                    data['realprice'] = produit.variants.first().unit_price
                    data['is_discounted'] = False
                    for v in produit.variants.all():
                        if v.is_discounted:
                            data['is_discounted'] = True
                    data['quantity'] = 0
                    for v in produit.variants.all():
                        if v.quantity > 0:
                            data['quantity'] = v.quantity
                else:
                    data['variants_product_code'] = ""
                    data['price'] = "-"
                    data['is_discounted'] = False
                    data['quantity'] = 0
            else:
                data['product_code'] = produit.product_code
                data['price'] = produit.get_price(request)
                data['realprice'] = produit.unit_price
                data['variants'] = False
                data['variants_count'] = 0
                data['is_discounted'] = produit.is_discounted
                data['quantity'] = produit.quantity
            data['is_quotation'] = is_quotation
            all_produits.append(data)
        # ===---
        result = {"products": all_produits, "next": next_products}
        return RestResponse(result)

class LoadProductsByCategory(APIView):
    """
    Retrieve products for plugin Products by Category.
    """

    permission_classes = [AllowAny]

    def get(self, request, *args, **kwargs):  # noqa: C901
        category = request.GET.get("category", None)
        products = None
        all_produits = []
        try:
            is_quotation = QUOTATION_FEATURE # noqa
        except Exception:
            is_quotation = False
        if category is not None:
            category = int(category)
            products = Product.objects.filter(
                Q(categories=category) | Q(categories__parent=category)
                | Q(categories__parent__parent=category)
                | Q(categories__parent__parent__parent=category),
                active=True).distinct()[:8]
            # ===---
            all_produits = []
            for produit in products:
                data = {}
                if produit.product_name_trans:
                    data['name'] = produit.product_name_trans
                else:
                    data['name'] = produit.product_name
                data['url'] = produit.get_absolute_url()
                data['caption'] = strip_tags(
                    Truncator(produit.caption).words(18))
                data['slug'] = produit.slug
                if produit.main_image:
                    try:
                        data['image'] = get_thumbnailer(
                            produit.main_image).get_thumbnail({
                                'size': (540, 600),
                                'upscale':
                                True,
                                'background':
                                "#ffffff"
                            }).url
                    except Exception:
                        data['image'] = None
                elif produit.images.first():
                    try:
                        data['image'] = get_thumbnailer(
                            produit.images.first()).get_thumbnail({
                                'size': (540, 600),
                                'upscale':
                                True,
                                'background':
                                "#ffffff"
                            }).url
                    except Exception:
                        data['image'] = None
                else:
                    data['image'] = None
                if produit.filters.all():
                    data['filters'] = " ".join(
                        [slugify(d.name) for d in produit.filters.all()])
                else:
                    data['filters'] = None
                if produit.label:
                    data['label'] = {}
                    data['label']['name'] = produit.label.name
                    data['label']['colour'] = produit.label.colour
                    data['label']['bg_colour'] = produit.label.bg_colour
                else:
                    data['label'] = None
                if hasattr(produit, 'variants'):
                    data['variants'] = True
                    data['variants_count'] = produit.variants.all().count()
                    if produit.variants.first():
                        data['variants_product_code'] = produit.variants.first(
                        ).product_code
                        data['price'] = produit.variants.first(
                            ).get_price(request)
                        data['realprice'] = produit.variants.first(
                            ).unit_price
                        data['is_discounted'] = False
                        for v in produit.variants.all():
                            if v.is_discounted:
                                data['is_discounted'] = True
                        data['quantity'] = 0
                        for v in produit.variants.all():
                            if v.quantity > 0:
                                data['quantity'] = v.quantity
                    else:
                        data['variants_product_code'] = ""
                        data['price'] = "-"
                        data['is_discounted'] = False
                        data['quantity'] = 0
                else:
                    data['product_code'] = produit.product_code
                    data['price'] = produit.get_price(request)
                    data['realprice'] = produit.unit_price
                    data['variants'] = False
                    data['variants_count'] = 0
                    data['is_discounted'] = produit.is_discounted
                    data['quantity'] = produit.quantity
                data['is_quotation'] = is_quotation
                all_produits.append(data)

        # ===---
        result = {"products": all_produits}
        return RestResponse(result)

class LoadVariantSelect(APIView):
    """
    Retrieve product from attribute selected.
    """

    permission_classes = [AllowAny]

    def get(self, request, *args, **kwargs):  # noqa: C901
        product_pk = request.GET.get("product", None)
        attributes = request.GET.get("attributes", None)
        variants = []
        QUOTATION = False
        try:
            QUOTATION = QUOTATION_FEATURE # noqa
        except Exception:
            pass
        if product_pk is not None and attributes is not None:
            attributes = attributes.replace(",", "//separator//").replace(
                "//comma//", ",")
            product = Product.objects.get(pk=product_pk)
            attr_list = attributes.split("//separator//")
            attrs = AttributeValue.objects.none()
            for a in attr_list:
                attrs |= AttributeValue.objects.filter(
                    value=a.split("_____")[1],
                    attribute__name=a.split("_____")[0]
                )
            print(attrs)
            if attrs.count() > 0:
                variant_all = product.variants.all()
            else:
                variant_all = []
            for a in attrs:
                variant_all = variant_all.filter(
                    attribute=a
                )
            for v in variant_all:
                datas = {}
                datas["product_code"] = v.product_code
                datas["unit_price"] = v.unit_price
                datas["quotation"] = 0
                if QUOTATION:
                    datas["quotation"] = 1
                try:
                    datas["real_price"] = v.get_price(request)
                except Exception:
                    datas["real_price"] = v.unit_price
                datas["is_discounted"] = v.is_discounted
                datas["quantity"] = v.quantity
                variants.append(datas)
        # ===---
        result = {"variants": variants}
        return RestResponse(result)

#######################################################################
# ===---   Views used in frontend                              ---=== #
#######################################################################

class CustomerView(APIView):
    """
    Retrieve current customer data
    to be used in the frontend app.

    GET
    ===

    Check if a customer is authenticated.

    Check if customer's shipping address exist.

    Check if customer's billing address exist.

    :return An object with customer basic informations,
    customer's shipping address and customer's billing address.
    """

    permission_classes = [AllowAny]

    def get(self, request, *args, **kwargs):
        # ===---
        tos = Title.objects.filter(page__reverse_id="terms-and-conditions",
                                   language=request.LANGUAGE_CODE)
        if tos.count() > 0:
            tos = "/" + request.LANGUAGE_CODE + "/" + str(tos.first().slug)
        else:
            tos = ""
        # ===---
        is_visitor = True if request.customer.is_visitor else False
        # ===---
        if request.user.is_authenticated:
            customer = {
                "salutation": request.user.customer.salutation,
                "first_name": request.user.first_name,
                "last_name": request.user.last_name,
                "email": request.user.email,
                "is_visitor": is_visitor
            }
            aso = request.user.customer.shippingaddress_set.first()
            if aso is not None:
                address_shipping = {
                    "active_priority": 1,
                    "plugin_order": 1,
                    "name": aso.name if aso.name is not None else "",
                    "address1":
                    aso.address1 if aso.address1 is not None else "",
                    "address2":
                    aso.address2 if aso.address2 is not None else "",
                    "country": aso.country if aso.country is not None else "",
                    "province":
                    aso.province if aso.province is not None else "",
                    "city": aso.city if aso.city is not None else "",
                    "zip_code":
                    aso.zip_code if aso.zip_code is not None else "",
                    "siblings_summary": []
                }
            else:
                address_shipping = {
                    "plugin_order": 1,
                    "active_priority": "add",
                }
            abo = request.user.customer.billingaddress_set.first()
            if abo is not None:
                address_billing = {
                    "plugin_order": 1,
                    "use_primary_address": False,
                    "name": abo.name if abo.name is not None else "",
                    "address1":
                    abo.address1 if abo.address1 is not None else "",
                    "address2":
                    abo.address2 if abo.address2 is not None else "",
                    "country": abo.country if abo.country is not None else "",
                    "province":
                    abo.province if abo.province is not None else "",
                    "city": abo.city if abo.city is not None else "",
                    "zip_code":
                    abo.zip_code if abo.zip_code is not None else "",
                    "siblings_summary": []
                }
            else:
                address_billing = {
                    "plugin_order": 1,
                    "use_primary_address": True
                }
            ###############
            return RestResponse({
                "customer": customer,
                "address_shipping":
                address_shipping if address_shipping is not None else {},
                "address_billing":
                address_billing if address_billing is not None else {},
                "tos": tos
            })
            ###############
        else:
            return RestResponse({
                "customer": {
                    "plugin_order": 1,
                    "guest": True,
                    "is_visitor": is_visitor
                },
                "address_shipping": {
                    "plugin_order": 1,
                    "active_priority": "add",
                },
                "address_billing": {
                    "plugin_order": 1,
                    "use_primary_address": True,
                },
                "tos": tos
            })

class CustomerCheckView(APIView):
    permission_classes = [AllowAny]

    def post(self, request, *args, **kwargs):
        email = request.data.get("email", None)
        if email is not None:
            customer = Customer.objects.filter(
                email=email,
                user__is_active=True
            ).count()
            if customer > 0:
                return RestResponse({"exist": True})
            else:
                return RestResponse({"exist": False})
        else:
            return RestResponse({"valid": False})

class ShippingMethodsView(APIView):
    """
    Retrieve all shipping methods
    to be used in the frontend app.

    GET
    ===

    :return An object with all shipping methods.
    """

    permission_classes = [AllowAny]

    def get(self, request, *args, **kwargs):
        result = [
            m.get_choice()
            for m in cart_modifiers_pool.get_shipping_modifiers()
        ]
        return RestResponse({"shipping_methods": result})

class BillingMethodsView(APIView):
    """
    Retrieve all billing methods
    to be used in the frontend app.

    GET
    ===

    :return An object with all billing methods.
    """

    permission_classes = [AllowAny]

    def get(self, request, *args, **kwargs):
        result = [
            m.get_choice()
            for m in cart_modifiers_pool.get_payment_modifiers()
        ]
        return RestResponse({"billing_methods": result})

def make_stored_request(request):
    """
    Create some data from request and
    return an object to be stored in some shop's models
    """

    return {
        'language': get_language_from_request(request),
        'absolute_base_uri': request.build_absolute_uri('/'),
        'remote_ip': get_ip(request),
        'user_agent': request.META.get('HTTP_USER_AGENT'),
    }

def mailchimp(request):
    """
    Evaluate a "calcul" answer.
    If okay, create a member in the client's mailchimp list.

    MAILCHIMP_KEY in settings.py

    MAILCHIMP_LISTID in settings.py
    """

    client = MailChimp(mc_api=MAILCHIMP_KEY)
    email = request.POST.get('email_infolettre', '')
    calcul = request.POST.get('calcul_infolettre', '')
    if calcul == '6':
        try:
            client.lists.members.create(MAILCHIMP_LISTID, {
                'email_address': email,
                'status': 'subscribed',
            })
            messages.success(
                request, _("You successfully been added to our newsletter."))
        except Exception as e:
            print(e)
            messages.error(request, _("An error occurred, sorry."))
            redirect("/")
    else:
        messages.error(request, _("Your answer was wrong."))
    return redirect("/")

def sendemail(request):
    """
    Retrieve form data and send an email
    to the client.
    Then, redirect to the page /message-envoye/.

    DEFAULT_FROM_EMAIL in settings.py

    DEFAULT_TO_EMAIL in settings.py
    """

    send_mail(
        'Message du formulaire de contact de votre site web',
        'Bonjour, voici le message:\n\nNom: ' + request.POST.get('name') +
        '\nCourriel: ' + request.POST.get('email') + '\nTéléphone: ' +
        request.POST.get('phone') + '\nSujet: ' + request.POST.get('subject') +
        '\nMessage:\n' + request.POST.get('message'),
        DEFAULT_FROM_EMAIL,
        [DEFAULT_TO_EMAIL],
        fail_silently=False,
    )
    call_command('send_queued_mail')
    return redirect('/message-envoye/')

#######################################################################
# Password Reset
#######################################################################

class PasswordResetConfirmView(GenericAPIView):
    renderer_classes = (CMSPageRenderer, JSONRenderer, BrowsableAPIRenderer)
    serializer_class = PasswordResetConfirmSerializer
    permission_classes = (AllowAny, )
    form_name = 'password_reset_confirm_form'

    def post(self, request, uidb64=None, token=None):
        try:
            data = dict(request.data['form_data'])
        except (KeyError, TypeError, ValueError):
            errors = {'non_field_errors': [_("Invalid POST data.")]}
        else:
            serializer = self.get_serializer(data=data)
            if serializer.is_valid():
                serializer.save()
                response_data = {
                    self.form_name: {
                        'success_message':
                        _("Password has been reset with the new password."),
                    }
                }
                return RestResponse(response_data)
            else:
                errors = serializer.errors
        return RestResponse({self.form_name: errors},
                            status=status.HTTP_422_UNPROCESSABLE_ENTITY)

@csrf_exempt
def unclone_customers(request):
    data = json.loads(request.body)["form_data"]
    email = data.get("email", None)
    if email is not None:
        users = User.objects.filter(email=email)
        if users.count() > 1:
            i = 0
            for u in users:
                if i > 0:
                    u.email = ""
                    u.save()
                i = i + 1
    return HttpResponse(json.dumps({"valid": True}))

def send_queued_mail(request):
    call_command('send_queued_mail')
    return HttpResponse(json.dumps({"valid": True}))

class AttributeAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        if not self.request.user.is_authenticated:
            return AttributeValue.objects.none()

        qs = AttributeValue.objects.all()

        if self.q:
            qs = qs.filter(
                Q(value__istartswith=self.q) |
                Q(attribute__name__istartswith=self.q)
            )

        return qs

class DshopAuthFormView(ShopAuthFormView):
    serializer_class = None
    form_class = None

    def post(self, request, *args, **kwargs):
        if request.customer.is_visitor:
            customer = CustomerModel.objects.get_or_create_from_request(
                request
            )
        else:
            customer = request.customer
        form_data = request.data.get(self.form_class.scope_prefix, {})
        form = self.form_class(data=form_data, instance=customer)

        if form.is_valid():
            form.save(request=request)
            # Code to merge all inactive user's order
            if form.form_name == "register_user_form":
                new_user = request.user
                new_customer = CustomerModel.objects.get(user=new_user)
                email = form.cleaned_data['email']
                customers = CustomerModel.objects.filter(
                    email=email, user__is_active=False
                )
                for customer in customers:
                    for order in OrderModel.objects.filter(customer=customer):
                        order.customer = new_customer
                        order.save()
                    customer.email = ""
                    customer.save()
                    customer.user.email = ""
                    customer.user.save()
            # End of code
            response_data = {form.form_name: {
                'success_message': _("Successfully registered yourself."),
            }}
            return Response(response_data, status=status.HTTP_200_OK)
        errors = dict(form.errors)
        if 'email' in errors:
            errors.update({NON_FIELD_ERRORS: errors.pop('email')})
        return Response(
            {form.form_name: errors},
            status=status.HTTP_422_UNPROCESSABLE_ENTITY
        )


import uvicorn
from app.api import levels, login, students, tags, users
from app.api.quizzes import sentences
from fastapi import FastAPI
from fastapi_pagination import add_pagination

tags_metadata = [
    {
        "name": "users",
        "description": "Only admin can create users. User can get information about itself. "
                       "The user's email is unique",
    },
    {
        "name": "students",
        "description": "The administrator can create and read a student. "
        "The user himself can also create and read his student entity. "
        "The user cannot see or change the student entity of other users. "
        "The user can use `student_id` or `tg_id` to get the student entity.",
    },
]

def create_application() -> FastAPI:
    application = FastAPI(
        title="English Quiz", version="0.3.1", openapi_tags=tags_metadata
    )
    application.include_router(users.router, prefix="/users", tags=["users"])
    application.include_router(students.router, prefix="/students", tags=["students"])
    application.include_router(levels.router, prefix="/levels", tags=["levels"])
    application.include_router(
        sentences.router, prefix="/sentences", tags=["sentences"]
    )
    application.include_router(tags.router, prefix="/tags", tags=["tags"])
    application.include_router(login.router, tags=["login"])
    return application

app = create_application()
add_pagination(app)

if __name__ == "__main__":
    uvicorn.run("main:app", host="localhost", port=8000, reload=True)


import moviepy.editor as mp
import os
import sys

if __name__ == '__main__':
    if len(sys.argv) == 1:
        #return help
        print("Please specify filename(s) to convert")
        exit(0)
    else:
        for f in sys.argv[1:]:
            clip = mp.VideoFileClip((f))
            clip.write_videofile(os.path.splitext(f)[0]+'.mp4')


from copy import deepcopy
from dataclasses import dataclass

import pennylane as qml
import pennylane.numpy as pnp
from catalyst_benchmark.types import Problem

@dataclass
class ProblemPL(Problem):
    """Catalyst implementation details of the VQE problem"""

    def __init__(self, dev, nlayers=None, **qnode_kwargs):
        super().__init__(dev, **qnode_kwargs)
        self.qcircuit = None
        self.nlayers = nlayers if nlayers else 1

    def trial_params(self, i: int):
        return pnp.array([1.0 / (2.0 * (1 + i) * pnp.pi)], dtype=pnp.float64)

def qcompile(p: ProblemPL, params):
    """Compile the quantum parts of the problem"""

    def _circuit(params):
        N = p.nqubits
        L = p.nlayers
        for wG in range(N):
            qml.Hadamard(wires=[wG])
        for _ in range(L):
            for wG in range(N):
                for wC in range(wG + 1, N):
                    phi = (2 ** (wC - wG)) / params[0]
                    qml.ctrl(qml.PhaseShift, control=wC)(phi=phi, wires=[wG])
        return qml.state()

    qcircuit = qml.QNode(_circuit, p.dev, **p.qnode_kwargs)
    qcircuit.construct([params], {})
    p.qcircuit = qcircuit
    return p

def workflow(p: ProblemPL, params):
    """Problem workflow"""
    return p.qcircuit(params)

def size(p: ProblemPL) -> int:
    """Compute the size of the problem circuit"""
    qnode_kwargs = deepcopy(p.qnode_kwargs)
    qnode_kwargs.update({"expansion_strategy": "device"})
    qcompile(p, p.trial_params(0))
    return len(p.qcircuit.tape.operations)

SHOTS = None

def run_jax_lightning_qubit(N=6):
    """Test problem entry point"""

    import jax  # pylint: disable=import-outside-toplevel

    jax.config.update("jax_enable_x64", True)

    p = ProblemPL(dev=qml.device("lightning.qubit", wires=N, shots=SHOTS), interface="jax")

    @jax.jit
    def _main(params):
        qcompile(p, params)
        return workflow(p, params)

    params = p.trial_params(0)
    result = _main(params)
    print(f"Result: {result}")

def run_lightning_qubit(N=6):
    """Test problem entry point"""

    p = ProblemPL(dev=qml.device("lightning.qubit", wires=N, shots=SHOTS))

    def _main(params):
        qcompile(p, params)
        return workflow(p, params)

    params = p.trial_params(0)
    result = _main(params)
    print(f"Result: {result}")

def run_default_qubit(N=6):
    """Test problem entry point"""

    p = ProblemPL(dev=qml.device("default.qubit", wires=N, shots=SHOTS))

    def _main(params):
        qcompile(p, params)
        return workflow(p, params)

    params = p.trial_params(0)
    result = _main(params)
    print(f"Result: {result}")


"""Benchmarking software for human sensory input latency"""

import random
import time
import tkinter as tk
import winsound
from threading import Thread
import pandas as pd

import keyboard

class Logger:
    """A class to log messages"""
    logging_level = 1
    DEBUG = 0
    INFO = 1
    WARNING = 2
    ERROR = 3

    def __init__(self, logging_level=1):
        self.logging_level = logging_level

    def log(self, message, logging_level):
        """A function to log messages"""
        if logging_level >= self.logging_level:
            if logging_level == self.DEBUG:
                print("[DEBUG] " + message)
            elif logging_level == self.INFO:
                print("[INFO] " + message)
            elif logging_level == self.WARNING:
                print("[WARNING] " + message)
            elif logging_level == self.ERROR:
                print("[ERROR] " + message)

l = Logger(logging_level=Logger.INFO)

class Register:
    """A class to log data and store them in an excel file"""
    name = ""
    frame: pd.DataFrame
    temp_time = 0

    def __init__(self, name):
        self.name = name
        self.frame = pd.DataFrame(columns=["Type", "Variation", "Duration", "Reactiontime"])

    def log(self, stimulus, variation, duration):
        """A function to log data and save it in a temporary pandas dataframe"""
        data = pd.Series({"Type": stimulus, "Variation": variation,
                         "Duration": duration, "Reactiontime": self.temp_time})
        self.frame = pd.concat([self.frame, data.to_frame().T], ignore_index=True)

    def save(self):
        """A function to save the data in an excel file"""
        self.frame.to_excel("data/" + self.name + ".xlsx", index=True, header=True)

class Display:
    """A class to display the stimulus using tkinter"""
    root = 0

    def __init__(self):
        self.root = tk.Tk()
        self.root.title("Sensory Organ tester")
        self.root.attributes("-fullscreen", True)
        self.root.bind("<Escape>", lambda e: e.widget.quit())
        self.root.configure(bg="black")

    def update(self):
        """A function to update the display"""
        self.root.update()

    def stimulus(self, duration, color):  # Color must be hex
        """A function to show the stimulus"""
        self.root.configure(bg=color)
        self.root.update()
        self.root.after(duration, self.root.configure(bg="black"))
        self.root.update()

class SensoryOrganTester:
    """A class to test the latency of sensory organs"""
    display = 0
    run = True
    no_of_stimuli = 0

    register = 0

    def __init__(self, no_of_stimuli=10):
        self.no_of_stimuli = no_of_stimuli

    def auditory_stimulus(self):
        """A function to generate an auditory stimulus"""
        frequency = random.randint(50, 7000)
        duration = random.randint(40, 400)
        l.log(
            f"Creating auditory stimulus at frequency {frequency}, duration {duration}", Logger.INFO)
        winsound.Beep(frequency, duration)
        return frequency, duration

    def visual_stimulus(self):
        """A function to generate a visual stimulus"""
        color = random.randint(0, 0xffffff)
        duration = random.randint(10, 400)
        l.log(f"Creating visual stimulus with color {color} and duration {duration}", Logger.INFO)
        self.display.stimulus(duration, f"#{color:06x}")
        return color, duration

    def timer(self):
        """A function to measure the time between the stimulus and the input"""
        time_start = time.time()
        l.log("Timer started", Logger.DEBUG)
        while True:
            if keyboard.is_pressed("space"):
                time_end = time.time()
                l.log("Timer stopped", Logger.DEBUG)
                l.log("Time between stimulus and input: " + str(time_end - time_start), Logger.INFO)
                self.register.temp_time = time_end - time_start
                break

    def startup(self):
        """A function to start the tester"""
        # First, ask for the name of the person
        name = input("Subject Name or Number (first_last):")
        self.register = Register(name)
        l.log(f"Subject {name} registered", Logger.INFO)

        print("Subject registered, test will start in 10 seconds")
        time.sleep(5)
        self.display = Display()
        self.display.update()
        time.sleep(5)
        l.log("Starting benchmark", Logger.INFO)

    def start(self):
        """A function to run the tester"""
        self.startup()

        count = 0
        while self.run:
            count += 1
            if keyboard.is_pressed("escape"):
                l.log("Stopping benchmark", Logger.INFO)
                self.stop()

            if random.randint(0, 2) == 1:  # Visual stimulus
                timer_thread = Thread(target=self.timer)
                timer_thread.start()
                color, duration = self.visual_stimulus()
                timer_thread.join()
                self.register.log("Visual", color, duration)

            else:  # Auditory stimulus
                timer_thread = Thread(target=self.timer)
                timer_thread.start()
                frequency, duration = self.auditory_stimulus()
                timer_thread.join()
                self.register.log("Auditory", frequency, duration)

            time.sleep(random.randint(3, 7))

            if count == self.no_of_stimuli:
                self.register.save()
                l.log("Saved data", Logger.INFO)
                l.log("Stopping benchmark", Logger.INFO)
                self.stop()

    def stop(self):
        """A function to stop the tester"""
        self.run = False
        self.display.root.destroy()

tester = SensoryOrganTester(no_of_stimuli=10)
tester.start()
input("Press enter to exit")


import os
from collections import Counter

import spacy

DATA_DIR = "data"
DATA_FILES = [os.path.join(DATA_DIR, f) for f in os.listdir(DATA_DIR) if f.endswith(".txt")]

nlp = spacy.load("en")
all_pos = set()
hists = {}
for data_file in DATA_FILES:
    with open(data_file, encoding="utf-8") as f:
        pos_hist = Counter(token.pos_ for doc in nlp.pipe(f) for token in doc)
    all_pos.update(pos_hist)
    hists[data_file] = pos_hist

all_pos = sorted(all_pos)
print("", *all_pos, sep="\t")
for data_file, pos_hist in sorted(hists.items()):
    print(os.path.basename(os.path.splitext(data_file)[0]), *[pos_hist[p] for p in all_pos], sep="\t")


from collections import defaultdict
from typing import List

class AlienDictionary:
    def alienOrder(self, words: List[str]) -> str:

        def hasCycle(node):
            colors[node] = GRAY
            for nei in graph[node]:
                if colors[nei] == GRAY:
                    return True
                elif colors[nei] == BLACK:
                    continue
                else:
                    if hasCycle(nei):
                        return True

            colors[node] = BLACK
            stack.append(node)
            return False

        if not words:
            return ""

        graph = defaultdict(list)
        for w1, w2 in zip(words, words[1:]):
            if w1!=w2 and w1[:len(w2)]==w2:
                return ''
            for c1, c2 in zip(w1, w2):
                if c1 != c2:
                    graph[c1].append(c2)
                    break

        colors = defaultdict(int)
        WHITE, GRAY, BLACK = 0, 1, 2

        stack = []

        allnodes=[c for word in words for c in word]

        for node in set(allnodes):
            if colors[node] == WHITE:
                if hasCycle(node):
                    return ''

        return ''.join(reversed(stack))

if __name__ == '__main__':
    init = AlienDictionary()
    print(init.alienOrder(["abc", "ab"])) #""
    print(init.alienOrder([
        "z",
        "z"
    ]))  # zx
    print(init.alienOrder([
        "z",
        "x"
    ]))  # zx
    print(init.alienOrder([
        "wrt",
        "wrf",
        "er",
        "ett",
        "rftt"
    ]))  # wertf

    #print(init.alienOrder(["abc", "ab"]))

    print(init.alienOrder([
        "z",
        "x",
        "z"
    ]))  # ""


#!/usr/bin/python
#coding:utf-8

import os
import time
import logging
import mimetypes

import config

logger = logging.getLogger()
from gunicorn.app.base import Application

from gzipper import GzipMiddelware
from utils.helper import set_environ

from base import handler_factory

titan_handlers=[
    {'url': '/uploadfiles/(.*)', 'static_files': config.UPLOAD_DIR_PATH+'/\\1'},
    {'url': '/static/(.*)', 'static_files': 'static/\\1'}, \
    {'url': '/.*', 'wsgi_app': 'app:app'}, \
]

class TitanApp(Application):
    def __init__(self, usage=None, on_init=None):
        self.on_init = on_init
        super(TitanApp, self).__init__(usage=usage)

    def init(self, parser, opts, args):
        if len(args) != 1:
            parser.error("No application root specified.")

        self.root_path = args[0]
        if callable(self.on_init):
            self.on_init(self)

    def load(self):
        app = WSGIApplication()
        app = GzipMiddelware(app)
        return app

class WSGIApplication(object):
    def __init__(self):
        self.handlers = None

    def __call__(self, environ, start_response):
        set_environ(environ)
        path_info = environ['PATH_INFO'] or '/'
        if self.handlers is None:
            self.handlers = []
            for h in titan_handlers:
                app_handler = handler_factory(h)
                self.handlers.append(app_handler)

        for handler in self.handlers:
            m = handler.match(path_info)
            if m:
                environ['titan.matched'] = m
                return handler(environ, start_response)

        start_response('404 Not Found', [])
        return ["404 Not Found"]

class StaticFilesApplication(object):
    def __new__(cls, path_template):
        def call(self, environ, start_response):
            path = environ['PATH_INFO'] or '/'
            if not path.startswith('/'):
                path = '/' + path
            start_response('301 Moved Permanently', \
                        [('Location', path), ])
            return ''
        obj = object.__new__(StaticFilesApplication, path_template)
        return obj

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

    def __call__(self, environ, start_response):
        m = environ['titan.matched']
        path = m.expand(self.path_template)
        return StaticFileApplication(path)(environ, start_response)

class StaticFileApplication(object):
    def __init__(self, path):
        self.path = path

    def _get_last_modified(self, path):
        return os.stat(path).st_mtime

    def _generate_last_modified_string(self, path):
        mtime = self._get_last_modified(path)
        return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(mtime))

    def _if_modified_since(self, path, timestr):
        try:
            t = time.mktime(time.strptime(timestr, "%a, %d %b %Y %H:%M:%S GMT"))
        except ValueError:
            return True
        else:
            t -= time.timezone  # convert gmt to local time
            mtime = self._get_last_modified(path)
            return mtime > t

    def __call__(self, environ, start_response):
        path = os.path.join(os.environ['TITAN_APPROOT'], self.path)
        if os.path.isfile(path):
            mimetype = mimetypes.guess_type(path)[0] or 'text/plain'
            last_modified = self._generate_last_modified_string(path)
            headers = [
                ('Content-type', mimetype),
                ('Last-Modified', last_modified),
            ]

            ims = environ.get('HTTP_IF_MODIFIED_SINCE')
            if ims and not self._if_modified_since(path, ims):
                start_response('304 Not Modified', headers)
                return ''

            start_response('200 OK', headers)
            return open(path)
        else:
            start_response('404 Not Found', [])
            return ['File not found']


import numpy as np
from sns_toolbox.networks import Network
from sns_toolbox.neurons import NonSpikingNeuron
from sns_toolbox.connections import NonSpikingSynapse
from utilities import activity_range, reversal_in, reversal_ex, dt, backend
import matplotlib.pyplot as plt
from scipy.fft import rfft, rfftfreq

# c_slow = 10 * c_fast
t = np.arange(0, 1000, dt)
def create_bandpass_w_input(conductance_retina, reversal_retina, c_slow, c_fast):
    net = Network()
    neuron_fast = NonSpikingNeuron(membrane_capacitance=c_fast, membrane_conductance=1.0, bias=activity_range)
    neuron_slow = NonSpikingNeuron(membrane_capacitance=c_slow, membrane_conductance=1.0, bias=activity_range)
    neuron_retina = NonSpikingNeuron(membrane_capacitance=c_fast, membrane_conductance=1.0)

    conductance_in = -activity_range/reversal_in
    conductance_ex = conductance_in*(reversal_in-activity_range)/(activity_range-reversal_ex)
    synapse_in = NonSpikingSynapse(max_conductance=conductance_in, reversal_potential=reversal_in, e_lo=0.0, e_hi=activity_range)
    synapse_ex = NonSpikingSynapse(max_conductance=conductance_ex, reversal_potential=reversal_ex, e_lo=0.0, e_hi=activity_range)

    synapse_retina = NonSpikingSynapse(max_conductance=conductance_retina, reversal_potential=reversal_retina, e_lo=0.0, e_hi=activity_range)

    net.add_neuron(neuron_retina, name='Retina')
    net.add_neuron(neuron_fast, name='a', initial_value=activity_range)
    net.add_neuron(neuron_fast, name='b')
    net.add_neuron(neuron_slow, name='c')
    net.add_neuron(neuron_fast, name='d', initial_value=activity_range)

    # net.add_connection(synapse_retina, 'Retina', 'a')
    net.add_connection(synapse_in, 'a', 'b')
    net.add_connection(synapse_in, 'a', 'c')
    net.add_connection(synapse_in, 'b', 'd')
    net.add_connection(synapse_ex, 'c', 'd')

    net.add_input('a')
    net.add_output('d')

    model = net.compile(dt=dt, backend=backend)

    return model

def run_net(model, stim):
    data = np.zeros_like(t)
    model.reset()
    for i in range(len(t)):
        data[i] = model([stim[i]])

    return data

def step_response(model):
    stim = np.ones_like(t)-2
    data = run_net(model, stim)
    return data

def impulse_response(model):
    stim = np.zeros_like(t)
    stim[0] = -1.0
    data = run_net(model, stim)
    return data

def cutoff_calc(capacitance):
    cond_scaled = 1.0*1e-6
    cap_scaled = capacitance*1e-9
    # print(cond_scaled)
    # print(cap_scaled)
    cutoff = cond_scaled/(cap_scaled*2*np.pi)
    # print(cutoff)
    return cutoff

# def cutoff_calc_z(capacitance):
#     alpha = dt / capacitance
#     cutoff = 1000 / (2 * np.pi * dt) * np.arccos(1 - (alpha ** 2 / (2 * (1 - alpha))))
#     return cutoff
# def cutoff_calc_wiki(capacitance):
#     cond_scaled = 1.0 * 1e-6
#     cap_scaled = capacitance * 1e-9
#     dt_scaled = dt/1000
#
#     alpha = dt_scaled/(cond_scaled*cap_scaled+dt_scaled)
#     cutoff = alpha/((1-alpha)*2*np.pi*dt_scaled)
#     return cutoff/(10**12)
#
# def cutoff_calc_comb(c_slow, c_fast):
#     g_scaled = 1.0 * 1e-6
#     c_slow_scaled = c_slow * 1e-9
#     c_fast_scaled = c_fast * 1e-9
#
#     a = c_slow_scaled*g_scaled
#     b = c_fast_scaled*g_scaled
#
#     num0 = np.sqrt(a**2 - 6*a*b + b**2) - a + b
#     num1 = np.sqrt(a**2 - 6*a*b + b**2) + a - b
#     den = 2*a*b
#     return num0/den, num1/den

def freq_response(data, c_slow, c_fast):
    N = len(data)   # number of sample pts
    T = dt/1000

    yf = rfft(data)
    xf = rfftfreq(N, T)#[:N//2]
    plt.plot(xf, 20*np.log10(np.abs(yf/np.max(yf))), label='Frequency Response')
    plt.axhline(20*np.log10(1/np.sqrt(2)), color='black', linestyle='--', label='-3 dB')
    plt.axvline(cutoff_calc(c_fast), color='orange', label='C_fast')
    plt.axvline(cutoff_calc(c_slow), color='green', label='C_slow')

    plt.xscale('log')
    # plt.title('Frequency Response')
    plt.legend()
    # plt.yscale('log')
    plt.grid()

c_slow = np.linspace(5,100, num=3)
c_fast = np.linspace(1,50, num=3)

for slow in c_slow:
    for fast in c_fast:
        if slow > fast:
            title = 'C_fast: {}, C_slow: {}'.format(fast, slow)
            file_prefix = '{}_{}_'.format(fast, slow)
            print(title)

            test_model = create_bandpass_w_input(1.0, reversal_in, slow, fast)
            data_step = step_response(test_model)
            data_imp = impulse_response(test_model)

            fig = plt.figure()
            plt.plot(t, data_step)
            plt.title(title)
            plt.xlabel('t (ms)')
            plt.ylabel('Step Response')
            fig.savefig('Step Responses/png/'+file_prefix+'step.png')
            fig.savefig('Step Responses/svg/' + file_prefix + 'step.svg')
            plt.close(fig)

            imp_cond = -(data_imp-1)

            fig1 = plt.figure()
            plt.plot(t, data_imp)
            plt.title(title)
            plt.xlabel('t (ms)')
            plt.ylabel('Impulse Response')
            fig1.savefig('Impulse Responses/png/' + file_prefix + 'imp.png')
            fig1.savefig('Impulse Responses/svg/' + file_prefix + 'imp.svg')
            plt.close(fig1)

            fig2 = plt.figure()
            plt.xlim([1,1000])
            freq_response(imp_cond, slow, fast)
            plt.title(title)
            plt.xlabel('Hz')
            plt.ylabel('Frequency Response')
            fig2.savefig('Frequency Responses/png/' + file_prefix + 'freq.png')
            fig2.savefig('Frequency Responses/svg/' + file_prefix + 'freq.svg')
            # plt.close(fig2)
            # plt.xlim([10,1000])

plt.show()


import theano
import theano.tensor as T
import numpy as np
from theano.printing import Print
from theano_toolkit import utils as U
from theano_toolkit.parameters import Parameters
import scipy
import head
from theano.printing import Print
from theano_toolkit import ops
def cosine_sim(k, M):
    # k: batch_size x mem_width
    # M: batch_size x mem_size x mem_width
    k = k.dimshuffle(0,'x',1)
    dot_prod = T.sum(k * M,axis=2)
    norm_prod = T.sqrt(T.sum(T.sqr(k),axis=2)) * T.sqrt(T.sum(T.sqr(M),axis=2)) + 1e-5
    batch_sim = dot_prod / norm_prod
    return batch_sim

def build(mem_size, mem_width,
          similarity=cosine_sim,
          shift_width=3):
    shift_conv = scipy.linalg.circulant(np.arange(mem_size)).T[
            np.arange(-(shift_width // 2), (shift_width // 2) + 1)
        ][::-1]

    def log_shift_convolve(log_weight, log_shift):
        # weight: batch_size x mem_size
        # shift:  batch_size x shift_width
        log_shift = log_shift.dimshuffle(0,1,'x')
        log_weight_windows = log_weight[:,shift_conv]
        # batch_size x shift_width x mem_size
        log_shifted_weight = ops.log_sum_exp(log_shift + log_weight_windows,axis=1)
        return log_shifted_weight

    def compute_memory_curr(M_prev, weights, erase_values, add_values):
        # M_prev:     batch_size x mem_size x mem_width
        # weight:     batch_size x mem_size
        # erase_head: batch_size x mem_width
        # add_head:   batch_size x mem_width
        weights    = [ w.dimshuffle(0,1,'x') for w in weights ]

        add   = sum( w * a.dimshuffle(0,'x',1)
                            for w,a in zip(weights,add_values) )
        erase = sum( w * e.dimshuffle(0,'x',1)
                            for w,e in zip(weights,erase_values) )

        M_curr_ = M_prev * (1 - erase)
        M_curr  = M_curr_ + add

        # output: batch_size x mem_size x mem_width
        return M_curr

    def compute_read(M_curr, weight):
        # M_curr:   batch_size x mem_size x mem_width
        # weight:   batch_size x mem_size

        # output: batch_size x mem_width
        return T.sum(
                weight.dimshuffle(0,1,'x') * M_curr,
                axis=1
            )

    def compute_weight_curr(weight_prev, M, key, beta, g, shift, gamma):
        """
        This function is best described by Figure 2 in the paper.
        """
        # 3.3.1 Focusing b Content
        score_c = T.addbroadcast(beta,1) * similarity(key, M)
        log_weight_c  = ops.log_softmax(score_c)
        # log_weight_c: batch_size x mem_size

        # 3.3.2 Focusing by Location
        g = (1 - 1e-8) * T.addbroadcast(g,1) + 1e-8 * 0.5
        log_weight_prev = T.log((1 - 1e-8) * weight_prev +\
                1e-8 * (1/T.cast(weight_prev.shape[1],'float32')))
        log_weight_prev.name = 'log_weight_prev'
        log_weight_g = ops.log_add(
                        T.log(g) + log_weight_c,
                        T.log(1 - g) + log_weight_prev
                    )
        log_weight_shifted = log_shift_convolve(log_weight_g, T.log(shift))
        log_weight_shifted.name = 'log_weight_shifted'
        log_weight_sharp = T.addbroadcast(gamma,1) * log_weight_shifted
        weight_curr = ops.softmax(log_weight_sharp)
        return weight_curr

    def ntm_step(M_prev, heads, weights_prev):
        weights_curr = []
        for (read_weight_prev, write_weight_prev), head in zip(weights_prev,heads):
            write_weight_curr = compute_weight_curr(
                            weight_prev=write_weight_prev,
                            M=M_prev,
                            key=head["write_key"],
                            beta=head["write_beta"],
                            g=head["write_g"],
                            shift=head["write_shift"],
                            gamma=head["write_gamma"]
                        )

            read_weight_curr = compute_weight_curr(
                            weight_prev=write_weight_prev,
                            M=M_prev,
                            key=head["read_key"],
                            beta=head["read_beta"],
                            g=head["read_g"],
                            shift=head["read_shift"],
                            gamma=head["read_gamma"]
                        )
            weights_curr.append((read_weight_curr,write_weight_curr))

        M_curr = compute_memory_curr(M_prev,
                weights=[ w for _,w in weights_curr ],
                add_values=[ head["write_add"] for head in heads ],
                erase_values=[ head["write_erase"] for head in heads ]
            )
        return M_curr, weights_curr
    return ntm_step


from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

class NcafeWriteAtt:
    # 초기화 실행(webdriver 설정)
    def __init__(self):
        # chrome_options = Options()
        # chrome_options.add_argument("--headless")
        # self.driver = webdriver.Chrome(chrome_options=chrome_options, executable_path='/Users/soo/PycharmProjects/crawling/driver/chrome/chromedriver')
        self.driver = webdriver.Chrome('/Users/soo/PycharmProjects/crawling/driver/chrome/chromedriver')
        self.driver.implicitly_wait(5)

        # 네이버 카페 로그인 및 출석 체크
    def writeAttendCheck(self):
        self.driver.get('https://nid.naver.com/nidlogin.login')
        self.driver.find_element_by_name('id').send_keys('suyohnee')
        self.driver.find_element_by_name('pw').send_keys('password')
        self.driver.find_element_by_xpath('//*[@id="frmNIDLogin"]/fieldset/input').click()
        self.driver.implicitly_wait(30)
        self.driver.get('https://cafe.naver.com/AttendanceView.nhn?search.clubid=25997591&search.menuid=56')
        self.driver.implicitly_wait(10)
        self.driver.switch_to_frame('cafe_main')
        self.driver.find_element_by_id('cmtinput').send_keys('출석합니다')
        self.driver.find_element_by_xpath('//*[@id="btn-submit-attendance"]').click()
        time.sleep(3)

if __name__ == '__main__':
    a = NcafeWriteAtt()
    start_time = time.time()
    a.writeAttendCheck()
    end_time = time.time()

    print("------ Total %s seconds ------" %(end_time - start_time))


import cv2
import numpy as np
from os.path import join

if __name__=="__main__":
    root_dir = "/Users/sfhan/Dropbox/stereoRepoj/largeThreshold"

    img_file= join(root_dir, "right_frame130_16.png")
    img2_file = join(root_dir, "right_frame130_100.png")
    gt_file = join(root_dir, "gt_right_frame130.png")
    out_file = join(root_dir, "largethreshold.png")

    I1 = cv2.imread(img_file)
    I2 = cv2.imread(img2_file)
    gtI = cv2.imread(gt_file)

    x1, y1 = 356, 146
    x2, y2 = 580, 290
    width = x2- x1
    height = y2 - y1

    x3, y3 = 384, 163
    x4, y4 = 519, 246

    mark_I1 = cv2.rectangle(I1, (x3, y3), (x4, y4), color=(0, 255, 00), thickness=3)
    mark_I2 = cv2.rectangle(I2, (x3, y3), (x4, y4), color=(0, 255, 00), thickness=3)

    crop_I1 = mark_I1[y1:y2, x1:x2, :]
    crop_I2 = mark_I2[y1:y2, x1:x2, :]
    crop_gtI = gtI[y1:y2, x1:x2, :]

    outI = np.concatenate((crop_I1, crop_I2, crop_gtI), axis=1)
    cv2.imwrite(out_file, outI.astype(np.uint8))


# -*- coding: utf-8 -*-
"""
Created on Sat Apr 10 15:11:49 2021

@author: Vishal Shah
"""

import yfinance as yf
import time
import streamlit as st
import plotly.graph_objs as go
import numpy as np
import pandas as pd
import statistics

st.set_page_config(
    page_title="Stock Analysis App",
    page_icon="ðŸ¤‘",
    layout="wide",
    initial_sidebar_state="expanded",
)

st.title('STOCK VOLATILITY')

st.sidebar.image('https://media.captrust.com/wordpress-content/2019/03/volatility.jpg', width=290)
st.sidebar.write('')

st.sidebar.info(
        "**Volatility is a measure of risk and shows how values are spread out around the average price. A stock with a price that fluctuates wildly hits new highs and lows or moves erratically, is taken under consideration as highly volatile. A highly volatile stock is inherently riskier, but that risk cuts both ways.**"
    )

months = st.selectbox(
    'SELECT NUMBER OF MONTHS',
    ('1','2', '3', '4', '5', '6', '7','8','9', '10', '11', '12', '13', '14')
)

tf = months + 'mo'
#st.write(periods)

st.markdown(
    """
    <style>
    .selector-rect {
        fill: grey  !important;
    }
    p{
    color: black;
    text-align: justify;
    }
    img{
    margin-top: 10px;
    margin-left: 7px;
    }
    div.row-widget.stRadio > div[role='radiogroup'] > label[data-baseweb='radio'] > div:first-child{
    background-color: #5e829f;
    }
    .st-av{
    background-color: #5e829f ;
    }
    .st-ch {
    background-color: #5e829f;
    }
    .st-cc{
       font-size: 17px;
       font-weight: 510;
       }
    .css-vfskoc{
    font-size: 20px;
    color: white;
    font-weight: 900;
    }
    .st-bj {
    margin-top: 11px;
    }
    #MainMenu {visibility : hidden;}
    footer {visibility : hidden;}
    footer:after {
    font-size: 15px;
    content: 'Made By: Namrata Patel, Bansi Shah, Darshi Shah, Vishal Shah';
    visibility: visible;
    position: relative;
    display: block;
    background-color: #5e829f;
    color: white;
    text-align: center;
    }
    h3{
    font-size: 18px;
    font-weight: 700;
    color: #2cab18;
    }
    h1{
      text-align: center;}
    </style>
    """,
    unsafe_allow_html=True
)

data_apple = yf.download(tickers='AAPL', period=tf, interval="1d")
data_google = yf.download(tickers='GOOG', period=tf, interval="1d")
data_microsoft = yf.download(tickers='MSFT', period=tf, interval="1d")
data_tesla = yf.download(tickers='TSLA', period=tf, interval="1d")
data_accenture = yf.download(tickers='ACN', period=tf, interval="1d")
data_ibm = yf.download(tickers='IBM', period=tf, interval="1d")
var_apple = statistics.pstdev(data_apple['Close'])
var_google = statistics.pstdev(data_google['Close'])
var_microsoft = statistics.pstdev(data_microsoft['Close'])
var_tesla = statistics.pstdev(data_tesla['Close'])
var_accenture = statistics.pstdev(data_accenture['Close'])
var_ibm = statistics.pstdev(data_ibm['Close'])
arr = [['Apple', var_apple], ['Google', var_google], ['Microsoft', var_microsoft], ['Tesla', var_tesla], ['Accenture', var_accenture], ['IBM', var_ibm]]
for i in range(6):
    for j in range(0, 6-i-1):
        if arr[j][1] > arr[j+1][1] :
          arr[j], arr[j+1] = arr[j+1], arr[j]

col1, col2, col3 = st.beta_columns((7,1,7))

x_values = ['Apple', 'Google', 'Microsoft', 'Tesla', 'IBM', 'Accenture']
y_values = [var_apple, var_google, var_microsoft, var_tesla, var_ibm, var_accenture]

fig = go.Figure(data=[go.Bar(
    x=x_values,
    y=y_values,
    marker={'color': 'darkorange'},
    )
])
fig.update_layout(
        barmode='group',
        width=550,
        margin=dict(l=0),
        plot_bgcolor='darkgrey')
col1.plotly_chart(fig)

v = np.array(arr)

df = pd.DataFrame()

df["Stock"], df["Volatility"] = v.T

#st.write(data_google)

fig = go.Figure(data=[go.Table(
    header=dict(values=['Stock', 'Volatility'],
                line_color='darkslategray',
                fill_color='#085089',
                align='center',
                font=dict(color='black', size=25),
                height=40),
    cells=dict(values=[df["Stock"],
                      df["Volatility"]],
                line_color='darkslategray',
                fill=dict(color=['#b7d3e9', '#b7d3e9']),
                align='center',
                font=dict(color='black', size=20),
                height=35))
])

fig.update_layout(

        width=550,
        margin=dict(l=0))

col3.plotly_chart(fig)


import requests
import os
import time
r = requests.get("http://c3166bbd.ngrok.io/subjects")
respuesta = r.json()

def lista():
  print("Cargando...")
  time.sleep(3)
  os.system("cls")
  contador = 0
  for resultado in respuesta:
    print (f"El estudiante Santiago a obtenido  {respuesta[contador]['mark']['$numberDecimal']} en {respuesta[contador]['name']} ")
    contador += 1
  menu2()

def Promedio():
  print("Cargando...")
  time.sleep(3)
  os.system("cls")
  r = requests.get("http://c3166bbd.ngrok.io/subjects/average")
  respuesta = r.json()
  print (f"El promedio del estudiante es {respuesta['studentAvg']}")
  menu2()

def menu():
    os.system("cls")
    resp = int(input("""Oprime segun corresponda
     1 Obtener Lista completa de materias
     2 Obtener Promedio
     >>"""))
    if resp == 1:
      lista()
    elif resp == 2:
      Promedio()
    else:
      print("Responda 1 o 2 segun lo desee")
      time.sleep(2)
      menu()

def menu2():
    resp2 = int(input("""Oprime segun corresponda
     1 Salir
     2 Menu
     >>"""))
    if resp2 == 1:
        os.system("exit")
    elif resp2 == 2:
        print("Cargando...")
        time.sleep(3)
        menu()
    else:
        print("Responda 1 o 2 segun desee")
        time.sleep(2)
        os.system("cls")
        menu2()

menu()


import json
import pandas as pd
from flask import render_template, request
from app import app
from ..models.pub import Pub
from ..models.review import Review
from config import Configurations
from functions.functions import Functions

config = Configurations().get_config()
function = Functions()

@app.route("/pub/<pub_id>", methods=['GET', 'POST'])
def pub_read(pub_id):
    print('/pub/<pub_id>')
    # try:
    df_pub_review = function.get_pub_review(pub_id)
    if request.method == 'GET':
        print('/pub/<pub_id>/GET')
        pub_review_json = function.df_to_dict(df_pub_review)
        return render_template("pub_read.html", form='read', google_key=config['google_key'],
                               pub_review=pub_review_json,
                               pub_review_fields=json.loads(config['column_all']),
                               pub_fields=json.loads(config['column_pub']),
                               review_fields=json.loads(config['column_review']),
                               pub_visible=json.loads(config['visible_pub']),
                               review_visible=json.loads(config['visible_review']),
                               dropdown_controls=json.loads(config['control_dropdown']),
                               slider_controls=json.loads(config['control_slider']),
                               input_controls=json.loads(config['control_input']),
                               score_list=json.loads(config['column_score']))
    if request.method == 'POST':
        print('/pub/<id_code>/POST')
        new_pub = Pub(pub_identity=pub_id, pub_deletion=request.form['pub_deletion'], place=request.form['place'],
                      name=request.form['name'], address=request.form['address'],
                      latitude=request.form['latitude'], longitude=request.form['longitude'],
                      station_identity=request.form['station_identity'], category=request.form['category'].lower())
        df_new_pub = pd.DataFrame([new_pub.__dict__])
        new_review = Review(review_identity=request.form['pub_identity'], pub_identity=pub_id,
                            review_deletion=request.form['review_deletion'],
                            visit=request.form['visit'],
                            star=request.form.get('star').lower(), atmosphere=request.form['atmosphere'],
                            cleanliness=request.form['cleanliness'], clientele=request.form['clientele'],
                            decor=request.form['decor'], entertainment=request.form['entertainment'],
                            food=request.form['food'], friendliness=request.form['friendliness'],
                            opening=request.form['opening'], price=request.form['price'],
                            selection=request.form['selection'], reviewer=request.form['reviewer'])
        df_new_review = pd.DataFrame([new_review.__dict__])
        print(df_new_review)
        if df_pub_review.empty:
            print('NEW RECORD')
            # # # # # NEW RECORD # # # # #
            place = request.form['place']
            df_place = df_pub_review.loc[df_pub_review['place'] == str(place)]
            if df_place.empty:
                print('UNIQUE PLACE ID')
                df_pubs = function.get_pubs()
                # # # # # NEW and UNIQUE PLACE ID RECORD - save record # # # # #
                df_pubs_appended = pd.concat([df_pubs, df_new_pub], ignore_index=True)
                s3_resp = function.write_csv_to_s3(df_pubs_appended.to_csv(sep=',', encoding='utf-8', index=False),
                                                   config['aws_key_pub'])
                # print(s3_resp)
                df_reviews = function.get_reviews()
                df_reviews_appended = pd.concat([df_reviews, df_new_review], ignore_index=True)

                s3_resp = function.write_csv_to_s3(df_reviews_appended.to_csv(sep=',', encoding='utf-8', index=False),
                                                   config['aws_key_review'])
                df_pub_review = function.get_pub_review(pub_id)
                pub_review_json = function.df_to_dict(df_pub_review)
                return render_template('pub_read.html', form='read', google_key=config['google_key'],
                                       pub_review=pub_review_json,
                                       pub_review_fields=json.loads(config['column_all']),
                                       pub_fields=json.loads(config['column_pub']),
                                       review_fields=json.loads(config['column_review']),
                                       pub_visible=json.loads(config['visible_pub']),
                                       review_visible=json.loads(config['visible_review']),
                                       dropdown_controls=json.loads(config['control_dropdown']),
                                       slider_controls=json.loads(config['control_slider']),
                                       input_controls=json.loads(config['control_input']),
                                       score_list=json.loads(config['column_score']))
            else:
                print('DUPLCATE PLACE ID')
                df_pubs_reviews = function.get_pubs_reviews()
                df_pub_review = df_pubs_reviews.loc[df_pubs_reviews['place'] == str(place)]
                pub_review_json = df_to_dict(df_pub_review)
                dupe_id = df_pub_review['pub_identity']
                return render_template("pop_up_dupe.html", pub_review=pub_review_json, dupe_id=dupe_id)
        else:
            print('EDITED PUB')
            # # # # # EDITED OLD RECORD - return to edit screen without saving # # # # #
            df_pubs = function.get_pubs()
            df_pubs.loc[df_pubs['pub_identity'] == pub_id, 'pub_deletion'] = request.form['pub_deletion']
            df_pubs.loc[df_pubs['pub_identity'] == pub_id, 'place'] = request.form['place']
            df_pubs.loc[df_pubs['pub_identity'] == pub_id, 'name'] = request.form['name']
            df_pubs.loc[df_pubs['pub_identity'] == pub_id, 'address'] = request.form['address']
            df_pubs.loc[df_pubs['pub_identity'] == pub_id, 'latitude'] = request.form['latitude']
            df_pubs.loc[df_pubs['pub_identity'] == pub_id, 'longitude'] = request.form['longitude']
            df_pubs.loc[df_pubs['pub_identity'] == pub_id, 'station_identity'] = request.form['station_identity']
            df_pubs.loc[df_pubs['pub_identity'] == pub_id, 'category'] = request.form['category'].lower()

            s3_resp = function.write_csv_to_s3(df_pubs.to_csv(sep=',', encoding='utf-8', index=False),
                                               config['aws_key_pub'])

            df_reviews = function.get_reviews()
            df_reviews.loc[df_reviews['pub_identity'] == pub_id, 'visit'] = request.form['visit']
            df_reviews.loc[df_reviews['pub_identity'] == pub_id, 'star'] = request.form.get('star').lower()
            df_reviews.loc[df_reviews['pub_identity'] == pub_id, 'atmosphere'] = request.form['atmosphere']
            df_reviews.loc[df_reviews['pub_identity'] == pub_id, 'cleanliness'] = request.form['cleanliness']
            df_reviews.loc[df_reviews['pub_identity'] == pub_id, 'clientele'] = request.form['clientele']
            df_reviews.loc[df_reviews['pub_identity'] == pub_id, 'decor'] = request.form['decor']
            df_reviews.loc[df_reviews['pub_identity'] == pub_id, 'entertainment'] = request.form['entertainment']
            df_reviews.loc[df_reviews['pub_identity'] == pub_id, 'food'] = request.form['food']
            df_reviews.loc[df_reviews['pub_identity'] == pub_id, 'friendliness'] = request.form['friendliness']
            df_reviews.loc[df_reviews['pub_identity'] == pub_id, 'opening'] = request.form['opening']
            df_reviews.loc[df_reviews['pub_identity'] == pub_id, 'price'] = request.form['price']
            df_reviews.loc[df_reviews['pub_identity'] == pub_id, 'selection'] = request.form['selection']
            df_reviews.loc[df_reviews['pub_identity'] == pub_id, 'reviewer'] = request.form['reviewer']

            s3_resp = function.write_csv_to_s3(df_reviews.to_csv(sep=',', encoding='utf-8', index=False),
                                               config['aws_key_review'])
            # print(s3_resp)
            df_pub_review = function.get_pub_review(pub_id)
            pub_review_json = function.df_to_dict(df_pub_review)
            # print('NO REVIEW')
            return render_template('pub_read.html', form='read', google_key=config['google_key'],
                                   pub_review=pub_review_json,
                                   pub_review_fields=json.loads(config['column_all']),
                                   pub_fields=json.loads(config['column_pub']),
                                   review_fields=json.loads(config['column_review']),
                                   pub_visible=json.loads(config['visible_pub']),
                                   review_visible=json.loads(config['visible_review']),
                                   dropdown_controls=json.loads(config['control_dropdown']),
                                   slider_controls=json.loads(config['control_slider']),
                                   input_controls=json.loads(config['control_input']),
                                   score_list=json.loads(config['column_score']))
    # except Exception as e:
    #     print(e)
    #     return render_template('404.html', error=e, identity=id_code)


# encoding: utf-8
# Created on 2014-6-12
# @author: binge
import logging

logger = logging.getLogger("bookshelf")

logger.setLevel(logging.DEBUG)

fh = logging.FileHandler("bookshelf.log")
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)

formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
fh.setFormatter(formatter)

logger.addHandler(fh)
logger.addHandler(ch)


# -*- coding: utf-8 -*-
from __future__ import annotations

from collections import Counter
from pprint import pformat
from types import ModuleType

import pytest

import shellfish

from shellfish import _types as shellfish_types, aios, dotenv, fs, process, sh
from shellfish.aios import _path as aiospath
from shellfish.fs import promises as fsp

modules = [shellfish, fs, sh, dotenv, process, fsp, aiospath, aios, fsp]

def _test_module_all_tuple(mod: ModuleType, check_sorted: bool = True) -> None:
    assert hasattr(mod, "__all__"), f"{mod} has no __all__"
    mod_all = getattr(mod, "__all__")  # noqa: B009
    mod_name = mod.__name__
    assert isinstance(mod_all, tuple), "__all__ should be tuple"

    members_count = Counter(mod_all)
    duplicates = [el for el, count in members_count.items() if count > 1]
    assert not duplicates, f"duplicates in __all__: {duplicates}"
    assert len(set(mod_all)) == len(mod_all), "all should be " + str(
        tuple(sorted(set(mod_all)))
    )
    if check_sorted:
        sorted_all_tuple = tuple(sorted(mod_all))
        try:
            assert sorted_all_tuple == mod_all
        except AssertionError as e:
            print(f"{mod_name} should be:")  # noqa: T201
            if len(sorted_all_tuple) > 10:
                print("__all__ = " + str(sorted_all_tuple))  # noqa: T201
            else:
                print("__all__ = " + pformat(sorted_all_tuple))  # noqa: T201
            raise e

@pytest.mark.parametrize("mod", modules)
def test_module_exports(mod: ModuleType) -> None:
    check_sorted = mod.__name__ not in {
        "shellfish.sh",
    }

    _test_module_all_tuple(mod, check_sorted=check_sorted)

@pytest.mark.parametrize("member", fs.__all__)
def test_sh_exports_fs_member(member: str) -> None:
    member_val = getattr(sh, member)
    assert member_val is not None, f"{member} is not exported by sh"

@pytest.mark.parametrize("member", shellfish_types.__all__)
def test_shellfish_exports_types_member(member: str) -> None:
    member_val = getattr(shellfish, member)
    assert member_val is not None, f"{member} is not exported by shellfish"


from django.contrib import admin
from django.urls import path, re_path, include
from app import views

urlpatterns = [

    # The home page
    path('', views.index, name='home'),
    path('device/', include('basicdevice.urls')),
    path('lock/', include('door_lock.urls')),
    path('reader/', include('card_reader.urls')),
    path('admin/', admin.site.urls),          # Django admin route

    # Matches any html file
    re_path(r'^.*\.*', views.pages, name='pages'),

]


from django.shortcuts import redirect, render
from .models import Notification

# Create your views here.

def notified(request, pk):
    noti = Notification.objects.get(pk=pk)
    noti.seen = True
    noti.save()

    return redirect(noti.target_url)


from re import T
from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from blog.models import Category, Post

def index(request):
    slideposts = Post.objects.order_by('id')[:2]
    recentreviews = Post.objects.order_by('id')[:4]
    categories = Category.objects.all()
    congngheposts = Post.objects.filter(category_id = 2)[:7]
    thethaoposts = Post.objects.filter(category_id = 3)[:6]
    xecoposts = Post.objects.filter(category_id=4)[:4]
    dulichposts = Post.objects.filter(category_id=5)[:4]
    giaitriposts = Post.objects.filter(category_id=6)[:4]
    bottomposts = Post.objects.order_by('id')[:4]
    return render(request, "pages/home.html", {
        "slideposts": slideposts,
        "recentreviews": recentreviews,
        "categories": categories,
        "congngheposts": congngheposts,
        "thethaoposts": thethaoposts,
        "bottomposts": bottomposts,
        "xecoposts": xecoposts,
        "dulichposts": dulichposts,
        "giaitriposts": giaitriposts,
    })

def category(request, slug):
    category = Category.objects.get(slug=slug)
    posts_list = Post.objects.filter(category_id=category)
    paginator = Paginator(posts_list, 6)

    pageNumber = request.GET.get('page')
    try:
        posts = paginator.page(pageNumber)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)

    return render(request, "pages/category.html", {"slug": slug, "posts": posts})

def contact(request):
    return render(request, "pages/contact.html")

def detail(request, slug):
    post = Post.objects.get(slug=slug)
    categories = Category.objects.all()
    latestposts = Post.objects.order_by('id')[:4]
    return render(request, "pages/blog-single.html", {"post": post, "categories": categories, "latestposts": latestposts})

# Create your views here.


import copy

import numpy as np
import z3

from env.utils.probes_reader import ProbesReader
from env.utils.tactic_handler import TacticHandler

class EnvRendering:
    """
    Env for z3 tactics to render learned policy.
    Each state in this env is made from formula probes that achieved even.
    Initial state is a state without any tactic.
    Final state is state in which formula satisfiability is trivially decidable or we achieve max step count or timeout.
    Actions are one tactic with one of the its params (or maybe without param).
    This Environment is created to prevent Disk I/O overhead, because this env using smt string to work and not
    file with .smt2 format.
    """

    def __init__(self, smt_string, actions, verbose=False):
        """
        Create env instance (Constructor)
        :param smt_string: smt as string
        :param actions: actions of environment
        :param verbose: specify prints done or not
        """

        # Read formula from file and remove check-sat or check-sat-using from it and then pass it to z3
        self.formula = self.__read_formula(smt_string)

        # Get available actions
        self.action_space = ActionBox(actions)

        # Create required objects and env config
        self.tactic_handler = TacticHandler()
        self.max_step = self.action_space.n  # Max step count in each episode
        self.verbose = verbose

        # Generate start state
        # Start state have a random tactic
        self.formula_goal = z3.Goal()
        self.formula_goal.add(self.formula)
        self.start_state = ProbesReader.get_probes(self.formula_goal)
        self.state = copy.deepcopy(self.start_state)

        # Create observation state
        self.observation_space = StateBox(self.state)

    def step(self, action):
        """
        Run action on env and get the result.
        :param action: index of action in actions to do in env (one tactic and one of the its params)
        :return: (nex_state, reward, done) tuple
        """

        # Get action by it index
        action = self.action_space.get(action)

        # Append new tactic (action) to exist tactics
        tactic_in_z3_format = self.tactic_handler.convert_tactic_tuple_str_to_z3_format(action)

        # Apply new tactics to goal
        z3_tactic_str = self.tactic_handler.combine_tactics([tactic_in_z3_format])
        z3_tactic = self.tactic_handler.convert_string_to_z3_tactic(z3_tactic_str) if z3_tactic_str != "" else None
        if z3_tactic:
            goal = z3_tactic(self.formula_goal)[0]
        else:
            goal = self.formula_goal
        probes = ProbesReader.get_probes(goal)

        # Just create next state
        next_state = probes

        if self.verbose:
            print("{ new_state: " + str(probes) + ", tactic: " + str(tactic_in_z3_format) + " }")

        self.state = copy.deepcopy(next_state)
        return next_state

    def reset(self):
        """
        Reset env and change env state to initial state.
        :return: return current/initial state
        """
        self.state = copy.deepcopy(self.start_state)
        return self.state

    @staticmethod
    def __read_formula(smt_string):
        """
        Read formula from smt2 file.
        :param smt_string: assertion as string
        :return: z3 formula
        """
        temp_smt_string = ""
        for line in smt_string.split("\n"):
            new_line = line
            if 'check-sat' not in line:
                temp_smt_string += new_line + "\n"
        formula = z3.parse_smt2_string(temp_smt_string)
        return formula

class ActionBox:
    def __init__(self, actions):
        self.actions = actions
        self.n = len(actions)

    def sample(self):
        """
        Generate one random action and return it index in actions list.
        :return: index of randomly generated action
        """
        actions_array = np.array(self.actions)
        index = np.random.choice(len(actions_array), 1)
        return index[0]

    def get(self, index):
        """
        Get action by index
        :param index index of action
        :return: action
        """
        return self.actions[index]

class StateBox:
    def __init__(self, state):
        self.state = state
        self.n = len(state)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This script checks dbus for spotify information and writes it to xroot
also tries to subscribe for the Seeked signal"""
import dbus
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib

DBusGMainLoop(set_as_default=True)

BUSNAME = 'org.mpris.MediaPlayer2.spotify'
PATH = '/org/mpris/MediaPlayer2'
INTERFACENAME = 'org.mpris.MediaPlayer2.Player'

def init():
    """init"""
    DBusGMainLoop(set_as_default=True)
    bus = dbus.SessionBus()
    bus_object = bus.get_object(BUSNAME, PATH)
    interface = dbus.Interface(bus_object, dbus_interface=INTERFACENAME)

    loop = GLib.MainLoop()
    def handler(sender=None):
        """handler"""
        print("got signal from %r" % sender)

    interface.connect_to_signal(None, handler, sender_keyword='sender')
    print("interface connected to Seeked signal, now loop")
    try:
        loop.run()
    except KeyboardInterrupt:
        loop.quit()

if __name__ == "__main__":
    init()


import discord
import os
import random
import app.utils
from app.handlers import *
from app.embeds import helpEmbed
from discord.ext import commands

prefix = os.environ['PREFIX']

client = commands.Bot(command_prefix=prefix, help_command=None, intents=discord.Intents.all())

response = responseHandler.ResponseHandler(client)

@client.event
async def on_message(message: discord.Message):
    if message.author == client.user or message.author.bot:
        return

    if await response.handle(message):
        return

    await client.process_commands(message)

    await response.handleLast(message)

@client.event
async def on_ready():
    print('User: {}'.format(client.user.name))
    print('Client ID: {}'.format(client.user.id))
    print('------')

    await client.add_cog(imageHandler.ImageHandler(client))
    await client.add_cog(gameUtilHandler.GameUtilHandler(client))
    await client.add_cog(masterHandler.MasterHandler(client))
    await client.add_cog(utilHandler.UtilHandler(client))

with open(os.environ['SECRET'], 'r') as f:
    client.run(f.readline())


import json

times = []

with open('test_data.json') as json_data:
    d = json.load(json_data)

for item in d:
	if item['status'] == 8951:
		if item['start_time'] is not None and item['end_time'] is not None:
			time = item['end_time'] - item['start_time']
			times.append(time)

totalTime = 0
for t in times:
	totalTime += t

avgTime = totalTime / len(times)
print(avgTime)