# 损失函数

import torch.nn as nn
import torch
import math
import torch.nn.functional as F

# log_loss
def log_loss(y, p):
    """
    --- Log_loss computing function
    A function to compute the log loss of a predicted probability p given
    a true target y.

    :param y: True target value
    :param p: Predicted probability
    :return: Log loss.
    """
    p = min(max(p, 10e-15), 1. - 10e-15)
    return -math.log(p) if y == 1 else -math.log(1. - p)

# Cross-Entropy Loss（多分类）用这个 loss 前面不需要加 Softmax 层
def CrossEntropyLoss(predict, target):
    loss = torch.nn.CrossEntropyLoss()(predict, target)
    return loss

# BCELoss(二分类)
def BCELoss(predict, target):
    loss = torch.nn.BCELoss()(predict, target)
    return loss

# MSELoss Mean Square Error
def MSELoss(predict, target):
    loss = torch.nn.MSELoss()(predict, target)
    return loss

# L1Loss Mean Absolute Error
def L1Loss(predict, target):
    loss = torch.nn.L1Loss()(predict, target)
    return loss

# BCEWithLogitsLoss
def BCEWithLogitsLoss(predict, target):
    loss = torch.nn.BCEWithLogitsLoss()(predict, target)
    return loss

# NLLLoss(多分类)
def NLLLoss(predict, target):
    loss = torch.nn.NLLLoss()(predict, target)
    return loss

# SmoothL1Loss(多分类)
def SmoothL1Loss(predict, target):
    loss = torch.nn.SmoothL1Loss()(predict, target)
    return loss

# DiceLoss
class DiceLoss(nn.Module):
    def __init__(self, weight=None, size_average=True):
        super(DiceLoss, self).__init__()

    def forward(self, inputs, targets, smooth=1):
        # comment out if your model contains a sigmoid or equivalent activation layer
        inputs = F.sigmoid(inputs)

        # flatten label and prediction tensors
        inputs = inputs.view(-1)
        targets = targets.view(-1)

        intersection = (inputs * targets).sum()
        dice = (2. * intersection + smooth) / (inputs.sum() + targets.sum() + smooth)

        return 1 - dice

# DiceMeanLoss
class DiceMeanLoss(nn.Module):
    def __init__(self):
        super(DiceMeanLoss, self).__init__()

    def forward(self, logits, targets):
        class_num = logits.size()[1]

        dice_sum = 0
        for i in range(class_num):
            inter = torch.sum(logits[:, i, :, :, :] * targets[:, i, :, :, :])
            union = torch.sum(logits[:, i, :, :, :]) + torch.sum(targets[:, i, :, :, :])
            dice = (2. * inter + 1) / (union + 1)
            dice_sum += dice
        return 1 - dice_sum / class_num

# FocalLoss
class FocalLoss(nn.Module):
    def __init__(self, weight=None, size_average=True):
        super(FocalLoss, self).__init__()
    ALPHA = 0.8
    GAMMA = 2

    def forward(self, inputs, targets, alpha=ALPHA, gamma=GAMMA, smooth=1):
        # comment out if your model contains a sigmoid or equivalent activation layer
        inputs = F.sigmoid(inputs)

        # flatten label and prediction tensors
        inputs = inputs.view(-1)
        targets = targets.view(-1)

        # first compute binary cross-entropy
        BCE = F.binary_cross_entropy(inputs, targets, reduction='mean')
        BCE_EXP = torch.exp(-BCE)
        focal_loss = alpha * (1 - BCE_EXP) ** gamma * BCE

        return focal_loss

# --------------------------- BINARY LOSSES ---------------------------
class BFocalLoss(nn.Module):
    def __init__(self, alpha=0.8, gamma=2, weight=None, ignore_index=255):
        super(BFocalLoss, self).__init__()
        self.alpha = alpha
        self.gamma = gamma
        self.weight = weight
        self.ignore_index = ignore_index
        self.bce_fn = nn.BCEWithLogitsLoss(weight=self.weight)

    def forward(self, preds, labels):
        if self.ignore_index is not None:
            mask = labels != self.ignore_index
            labels = labels[mask]
            preds = preds[mask]

        logpt = -self.bce_fn(preds, labels)
        pt = torch.exp(logpt)
        loss = -((1 - pt) ** self.gamma) * self.alpha * logpt
        return loss
# --------------------------- MULTICLASS LOSSES ---------------------------
class MFocalLoss(nn.Module):
    def __init__(self, alpha=0.8, gamma=2, weight=None, ignore_index=255):
        super(MFocalLoss, self).__init__()
        self.alpha = alpha
        self.gamma = gamma
        self.weight = weight
        self.ignore_index = ignore_index
        self.ce_fn = nn.CrossEntropyLoss(weight=self.weight, ignore_index=self.ignore_index)

    def forward(self, preds, labels):
        logpt = -self.ce_fn(preds, labels)
        pt = torch.exp(logpt)
        loss = -((1 - pt) ** self.gamma) * self.alpha * logpt
        return loss

# IoULoss
class IoULoss(nn.Module):
    def __init__(self, weight=None, size_average=True):
        super(IoULoss, self).__init__()

    def forward(self, inputs, targets, smooth=1):
        # comment out if your model contains a sigmoid or equivalent activation layer
        inputs = F.sigmoid(inputs)

        # flatten label and prediction tensors
        inputs = inputs.view(-1)
        targets = targets.view(-1)

        # intersection is equivalent to True Positive count
        # union is the mutually inclusive area of all labels & predictions
        intersection = (inputs * targets).sum()
        total = (inputs + targets).sum()
        union = total - intersection

        IoU = (intersection + smooth) / (union + smooth)

        return 1 - IoU

def main():
    import numpy

    print(log_loss(0, 0))
    print(log_loss(0, 1))

    predict = torch.rand(2, 2, 24, 24, 48)  # predict是预测结果
    target = torch.empty(2, 2, 24, 24, 48).random_(0, 2)  # target是ground true

    print(BCEWithLogitsLoss(predict, target))

    predict = torch.sigmoid(predict)

    print(DiceLoss()(predict, target))
    print(DiceMeanLoss()(predict, target))
    print(FocalLoss()(predict, target))
    print(BFocalLoss()(predict, target))
    print(IoULoss()(predict, target))

    print(BCELoss(predict, target))
    print(MSELoss(predict, target))

    target = torch.empty(2, 24, 24, 48).random_(0, 2).long()  # target是ground true
    print(NLLLoss(predict, target))
    print(CrossEntropyLoss(predict, target))
    print(MFocalLoss()(predict, target))

if __name__ == '__main__':
    main()


from playsound import playsound
from gtts import gTTS
import speech_recognition as sr
import os

def speak(string):
    tts=gTTS(text=string, lang="tr")
    file="answer.mp3"
    tts.save(file)
    playsound(file)
    os.remove(file)

import random

def sans_oyunu():
    speak("Şans topu oyununa hoşgeldiniz...")
    kac_kez=int(input("kaç kez oynamak istersiniz= "))
    speak(str(kac_kez)+"kez oynamak isterim...")
    puan=kac_kez*10
    speak(str(puan)+"puanla oyuna başlıyorsunuz...")
    hak=0
    for i in range(0,kac_kez):
        hak=hak+1
        sayi=int(input("Lütfen sayıyı giriniz= "))
        speak(str(sayi)+" sayısını değer olarak girdiniz")
        sayi_tahmin=random.randint(1,100)
        if sayi>sayi_tahmin:
            puan=puan-10
            speak("Lütfen daha küçük bir sayı giriniz.")
            speak("Sizin girdiğiniz sayı"+str(sayi))
            speak("Tahmin edilen sayı"+str(sayi_tahmin))
            speak("Puanınız"+str(puan))
        elif sayi<sayi_tahmin:
            puan=puan-10
            speak("Lütfen daha Büyük bir sayı giriniz.")
            speak("Sizin girdiğiniz sayı"+str(sayi))
            speak("Tahmin edilen sayı"+str(sayi_tahmin))
            speak("Puanınız"+str(puan))
        elif sayi==sayi_tahmin:
            puan=puan+10
            speak("Tebrikler doğru tahminde bulundunuz..")
            speak("Sizin girdiğiniz sayı"+str(sayi))
            speak("Tahmin edilen sayı"+str(sayi_tahmin))
            speak("Puanınız"+str(puan))

        if hak==kac_kez:
            speak("Hakkınız sona erdi")
            speak("Puanınız"+str(puan))


import lxml.html
import requests
from bs4 import BeautifulSoup as bs
from datetime import datetime
from subprocess import Popen, STARTUPINFO

'''Path for the file to be written'''

FILE_PATH = 'E:\\Documents\\promocoes.txt'
BACKUP_FILE_PATH = 'E:\Documents\\promocoes_backup.txt'

'''Start up options for process
wShowWindow = 0 -> hidden'''

start_info = STARTUPINFO()
start_info.dwFlags = 1
start_info.wShowWindow = 1

'''current time'''
time = datetime.now()

def get_html_cloudfare(link):
    scraper = cfscrape.create_scraper()
    return scraper.get(link).content

def get_title(soup):
    return soup.title.encode('utf-8')

def complete_links(partial_url, base_url):
    return '{}/{}'.format(base_url, partial_url)

def get_dom(scrap_url):
    '''html_link -> lxml dom'''
    html_doc = requests.get(scrap_url)
    return lxml.html.fromstring(html_doc.content)

def get_soup(link):
    '''html link -> BeautifulSoup soup'''
    html_doc = requests.get(link)
    return bs(html_doc.content)

def format_adrenaline_link(link):
    '''link (adrenaline) -> formatted link
    '''
    _, t = link.rsplit('/', 1)
    thread_title, _ = t.split('.')
    formatted_title = ' '.join([word for word in thread_title.split('-')])
    return "\nPromo: {}\nLink: {}\n".format(formatted_title.replace(' r ', ' R$').title(), link)

def format_hardmob_links(link):
    '''
    link: hardmob link
    link -> formatted link'''
    _, title = link.split('-', 1)
    c, _ = title.split('.', 1)
    formatted_title = ' '.join(
        [word for word in c.split('-')[1:] if word is not '-'])
    return "\nPromo: {}\nLink: {}\n".format(formatted_title.replace(' r ', ' R$').title(), link)

def gen_adrenaline_links(scrap_url='http://adrenaline.uol.com.br/forum/forums/for-sale.221/', base_url='http://adrenaline.uol.com.br/forum', key_word='thread', n_links=10):
    '''scrap_url: adrenaline url to be scrapped
    n_links: max number of links returned
    base_url: base adrenaline url
    key_word: word to filter pertinent forum entries
    url -> formatted links'''
    dom = get_soup(scrap_url)
    links_list = set()
    for link in dom.findAll('a'):
        href = link.get('href')
        if href:
            if key_word in href and not any(word in href for word in['atencao', 'regras', 'censurados']):
                link, _ = href.rsplit('/', 1)
                links_list.add(complete_links(link, base_url))
            elif len(links_list) == n_links:
                break
    for link in set(links_list):
        corrected_link = format_adrenaline_link(link)
        if corrected_link:
            yield corrected_link

def get_hardmob_links(scrap_url='http://www.hardmob.com.br/promocoes', n_links=5):
    '''scrap_url: hardmob url to be scrapped
    n_links: max number of links returned
    url -> formatted links'''
    dom = get_soup(scrap_url)
    link_count = 0
    for link in dom.findAll('a'):
        if link.get('id'):
            if 'thread_title' in link.get('id') and 'twitter' not in link.get('href') and 'faq' not in link.get('href') and 'descontos' not in link.get('href'):
                thread_link = link.get('href')
                try:
                    FILE.write(format_hardmob_links(thread_link))
                except Exception as e:
                    FILE.write(e)
                link_count += 1
            if link_count == n_links:
                break

def gen_promoforum_links(scrap_url='http://www.promoforum.com.br/forums/promocoes', n_links=5):
    '''scrap_url: promoforum url to be scrapped
    n_links: max number of links returned
    url -> formatted links'''
    base_link = 'http://www.promoforum.com.br/'
    dom = get_soup(scrap_url)
    link_count = 0
    for link in dom.findAll('a'):
        if link.get('class'):
            if link.get('class')[0] == 'PreviewTooltip' and 'postar' not in link.get('href'):
                thread_link = link.get('href')
                yield format_hardmob_links(complete_links(thread_link.encode('utf-8'), base_link))
                link_count += 1
            if link_count == n_links:
                break

def gen_promobit_links(scrap_url='http://www.promobit.com.br/Promocoes/em-destaque/page/1-2', n_links=5):
    '''scrap_url: promobit url to be scrapped
    n_links: max number of links returned
    url -> formatted links'''
    soup = get_soup(scrap_url)
    base_link = 'http://www.promobit.com.br'
    for link in soup.findAll('a'):
        try:
            href = link.get('href').encode('utf-8')
            info = link.text.encode('utf-8')
            if 'ver-promocoes' in href and 'R$' in info:
                title, price = link.text.encode('utf-8').split('R$', 1)
                formatted_title = "\nPromo: {} por R${}Link: {}{}\n".format(
                    title.strip(), price.rsplit(' ', 1)[1], base_link, href)
                yield formatted_title
        except AttributeError:
            continue

def populate_txt(links, cmp_file=BACKUP_FILE_PATH):
    '''checks if link is already on file
    links: formatted promotion links to be written in the file
    links (generator/list) -> write txt'''
    with open(cmp_file, 'a+') as f:
        txt = f.read()
    for link in links:
        if link not in txt:
            with open(FILE_PATH, 'a+') as f:
                f.write(link)

def main():
    with open(FILE_PATH, 'r+') as f:
        with open(BACKUP_FILE_PATH, 'a+') as f2:
            old_text = f.read()
            f2.write(old_text)
            f.seek(0)
            f.truncate()
    populate_txt(gen_promobit_links(n_links=2))
    populate_txt(gen_promoforum_links(n_links=2))
    populate_txt(gen_adrenaline_links(n_links=2))
    with open(FILE_PATH, 'r') as g:
        new_text = g.read()
    if new_text:
        Popen(["notepad.exe", FILE_PATH])

if __name__ == '__main__':
    main()


import json

from app_blog.models import Article
from myweb.utils import JSONEncoder, validateEmail
from app_user.models import UserProfile

from django import forms
from django.apps import apps
from django.contrib.auth import get_user_model
from django.core import serializers
from django.core.cache import cache
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import models
from django.forms.models import modelform_factory
from django.forms.utils import ErrorDict
from django.http import QueryDict, request
from django.http.response import (Http404, HttpResponse, HttpResponseForbidden,
                                  JsonResponse)
from django.shortcuts import get_object_or_404, redirect
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.views.generic.edit import FormView
from django.views.generic.list import BaseListView, View
from loguru import logger

from .forms import CommentForm
from .models import Comments, MpComments

# model_class = apps.get_model('app_blog', 'article')

# 增加评论 old
class CommentPostView(FormView):
    form_class = CommentForm
    template_name = 'tp/文章详情.html' # get 请求返回

    def get(self, request, *args, **kwargs):
        article_slug = self.kwargs['article_slug']

        article = get_object_or_404(Article, slug=article_slug)
        url = article.get_absolute_url()
        print(20*'*')
        return redirect(url + "#comments")

    def form_invalid(self, form):
        '''如果表单无效，则呈现无效表单'''
        article_slug = self.kwargs['article_slug']

        article = get_object_or_404(Article, slug=article_slug)
        user = self.request.user
        if user.is_authenticated:
            form.fields.update({
                'email': forms.CharField(widget=forms.HiddenInput()),
                'name': forms.CharField(widget=forms.HiddenInput()),
            })
            form.fields["email"].initial = user.email
            form.fields["name"].initial = user.username

        return self.render_to_response({
            'comment_form': form,
            'article': article,
            'comments': article.comment_list()
        })

    def form_valid(self, form):
        """表单验证成功后的逻辑"""
        article_slug = self.kwargs['article_slug']

        article = get_object_or_404(Article, slug=article_slug)
        has_commented = self.request.session.get('has_commented', None)
        if (not has_commented) or (has_commented!=article_slug):

            user = self.request.user
            if not user.is_authenticated:
                email = form.cleaned_data['email']
                username = form.cleaned_data['name']
                user = get_user_model().objects.get_or_create(username=username, email=email)[0]
                # auth.login(self.request, user)
            comment = form.save(False)
            comment.content_object = article
            comment.author = user
            comment.save(True)
            # self.request.session['has_commented'] = article.id
            # self.request.session.set_expiry(300)
            return redirect("%s#div-comment-%d" %(article.get_absolute_url(), comment.pk))

        else:
            message = '你已经评论过了, 五分钟后可再次评论.'
            print(message)
            url = article.get_absolute_url()
            return redirect(url + "#comments_你已经评论过了, 五分钟后可再次评论")

class CommentsView(BaseListView):
    model = Comments
    paginate_by = 5

    def get(self, request, *args, **kwargs):
        self.object_list = self.get_queryset()
        allow_empty = self.get_allow_empty()

        if not allow_empty:
            # When pagination is enabled and object_list is a queryset,
            # it's better to do a cheap query than to load the unpaginated
            # queryset in memory.
            if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'):
                is_empty = not self.object_list.exists()
            else:
                is_empty = not self.object_list
            if is_empty:
                raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.") % {
                    'class_name': self.__class__.__name__,
                })

        try:
            context = self.get_context_data()
        except Exception as e:
            print(e)
            if request.is_ajax():
                return HttpResponse({'status':404, 'data': None})
            else:
                raise e

        if request.is_ajax():
            paginator = context['paginator']
            page_obj = context['page_obj']
            is_paginated = context['is_paginated']
            object_list = context['object_list']

            serialize_items = serializers.serialize("json", object_list,
                                                    fields=('body', 'mood', 'img', 'created'),
                                                    ensure_ascii=False)

            data = {
                'status': 200,
                'current_page': page_obj.number,    # 当前页码
                'has_next': page_obj.has_next(),    # 是否有下页
                'page_total': paginator.num_pages,  # 总页数
                'items_count': paginator.count,     # 元素总数
                'data': serialize_items,
            }

            return JsonResponse(data, encoder=JSONEncoder)

        return self.render_to_response(context)

class CommentsView(View):
    paginate_by = 5

    # 查询评论
    def get(self, request, *args, **kwargs):
        '''
        /comment/?content_type=article&object_id=1
        content_type: 关联模型名称 Model name
        object_id: 关联模型实例 ID
        '''

        try:
            content_type_model = request.GET['content_type']
            object_id = int(request.GET['object_id'])
            page = int(request.GET.get('page', 0))

            if page:
                start = self.paginate_by * (page-1)
                end = self.paginate_by * page
            else:
                start = end = None
        except Exception as e:
            return HttpResponse(json.dumps({'status':403,'err_msg':'请求参数错误'}, ensure_ascii=False), content_type="application/json; charset=UTF-8")

        comments = self.get_comments(start, end, serialize=True, content_type_model=content_type_model, object_id=object_id)
        if len(comments) < 1:
            return HttpResponse(json.dumps({'status':404,'err_msg':'请求数据为空'}, ensure_ascii=False), content_type="application/json; charset=UTF-8")

        data = {'status': 200, 'current_page':page, 'comments': comments}
        json_data = json.dumps(data, cls=JSONEncoder, separators=(',',':'))
        return HttpResponse(json_data, content_type="application/json; charset=UTF-8")

    def get_comments(self, start, end, serialize, content_type_model, object_id):
        cache_key = f'comments_s_{start}_e_{end}_ser_{serialize}_ctm_{content_type_model}_oid_{object_id}'
        data = cache.get(cache_key)
        if data != None:
            logger.info(f'获取文章评论缓存:{cache_key}')
            return data
        else:
            data = Comments.objects.visible_comments(start, end, serialize=True, content_type__model=content_type_model, object_id=object_id)
            cache.set(cache_key, data, 60 * 100)
            logger.info(f'设置文章评论缓存:{cache_key}')
            return data

    # 增加评论
    def post(self, request, *args, **kwargs):
        if request.is_ajax():

            article_slug = request.POST.get('object_slug', '')
            comment_body = request.POST.get('comment_body', '')

            replyto = request.POST.get('replyto', '')

            username = request.POST.get('username', '')
            nickname = request.POST.get('nickname', '')
            email = request.POST.get('email', '')

            if article_slug and comment_body:
                try:
                    article = Article.objects.get(slug=article_slug)
                except:
                    return JsonResponse({'status': 404, 'msg':'数据获取失败'})

                if request.user.is_authenticated and request.user.username==username:
                    wanderer = False
                    author = request.user.profile
                elif username and not (nickname and email):
                    return JsonResponse({'status': 402, 'msg':'页面过期请刷新页面'})
                else:
                    if not 0 < len(str(nickname)) < 20:
                        return JsonResponse({'status': 401, 'msg':'请求数据非法(nickname 控制在20字以内)'})
                    if not 0 < len(str(email)) < 50:
                        return JsonResponse({'status': 401, 'msg':'请求数据非法(email 控制在50字以内)'})
                    if not validateEmail(email):
                        return JsonResponse({'status': 401, 'msg':'请求数据非法(Email 格式错误)'})
                    if UserProfile.objects.filter(w_email=email).exists():
                        return JsonResponse({'status': 401, 'msg':f'{email} 已存在'})
                    try:
                        author = UserProfile.objects.create(w_name=nickname, w_email=email)
                        wanderer = True
                    except Exception as e:
                        return JsonResponse({'status': 401, 'msg':e})
                if replyto:
                    try:
                        parent_comment = Comments.objects.get(uuid=replyto)
                    except:
                        return JsonResponse({'status': 401, 'msg':'请求数据非法(目标评论不存在)'})
                else:
                    parent_comment = None
                try:
                    ip = request.META.get('REMOTE_ADDR')  # 这里获得代理ip
                    comment = Comments.objects.create(
                        body=comment_body,
                        author=author,
                        parent_comment=parent_comment,
                        ip_address=ip,
                        content_object=article
                    )
                    # mpcomment = MpComments.objects.create(
                    #     body=comment_body,
                    #     author=author,
                    #     parent=parent_comment,
                    #     ip_address=ip,
                    #     content_object=article
                    # )

                    # print(20*'++++++++++++++')
                    # print(mpcomment)
                except Exception as e:
                    if wanderer:
                        author.delete()
                    return JsonResponse({'status': 401, 'msg':e})
                return JsonResponse({'status': 200, 'msg':'评论成功'})
            else:
                return JsonResponse({'status': 401, 'msg':'请求数据非法'})
        else:
            return HttpResponseForbidden()

    # 置顶评论
    def patch(self, request, *args, **kwargs):
        '''
        接受的数据:
            {
                uid: comment 唯一id
                要修改的字段: 对应值
            }
        '''
        data = QueryDict(request.body)
        model_fields = [f.name for f in Comments._meta.fields]

        uuid = data.get('uid')
        if not uuid:
            return JsonResponse({'status':404, 'msg': 'uuid错误'})

        try:
            uuid = Comments._meta.get_field('uuid').to_python(uuid)
            obj = Comments.objects.get(uuid=uuid)
        except (ObjectDoesNotExist, ValidationError):
            return JsonResponse({'status':404, 'msg': 'uuid查询失败, 数据不存在'})

        fields = [f for f in data.keys() if f in model_fields]

        defaults = {
            "form": forms.ModelForm,
            "fields": fields,
            # "formfield_callback": self.formfield_for_dbfield,
        }
        form_class = modelform_factory(Comments, **defaults)
        form = form_class(instance=obj, data=data, files=request.FILES)

        result = {}
        if form.is_valid():
            try:
                form.save(commit=True)
                result['msg'] = 'success'
                result['status'] = 200

            except Exception as e:
                result['msg'] = str(e)
                result['status'] = 403
        else:
            result['msg'] = ErrorDict(form.errors).as_json()
            result['status'] = 403

        return JsonResponse(result)

    # 删除评论
    def delete(self, request, *args, **kwargs):
        data = QueryDict(request.body)
        uuid = data.get('uid')
        if not uuid:
            return JsonResponse({'status':401, 'msg': 'uuid 不存在'})

        try:
            comment = Comments.objects.get(uuid=uuid)
            comment.delete()
            return JsonResponse({'status':200, 'msg': '删除成功'})
        except Exception as e:
            return JsonResponse({'status':404, 'msg': str(e)})


#we should create a program to calculate if there is still a ticket
#for the game tonight
#we are given two variable.Capasity of the stadium an the amount
#of tickets solt
#print True if i can still by a ticket,false otherswise

soldTickets=2000
maxCapacity=3400

is_there_ticket=soldTickets<maxCapacity
print("There is a ticket for the game tonight", is_there_ticket)


import numpy
from PIL import Image, ImageDraw
import os

def get_image(path):
	for filename in os.listdir(path):
		if 'jpg' in filename or 'jpeg' in filename or 'png' in filename:
			img = Image.open(filename)
			shape = img.size
			img2 = img.crop((10, 10, shape[0], shape[1]*0.7))
			index = filename.find('.')
			newname = filename[0:index] + '_crop' + filename[index:]
			img2.save(os.path.join(path,newname))

def main():
	get_image('/Users/lxb/Documents/yyc/scripts/booksproject/the_tale_of_peter_rabbit/')

if __name__ == '__main__':
	main()


from datetime import datetime

import albumentations as A
import pytorch_lightning as pl
import torch
from albumentations.pytorch import ToTensorV2
from clearml import Task
from matplotlib import pyplot as plt
from pytorch_lightning.callbacks import ModelCheckpoint, RichProgressBar
from pytorch_lightning.callbacks.progress.rich_progress import RichProgressBarTheme
from simple_parsing import ArgumentParser
from torch.utils.data import Subset

from config import config
from config.args import Args
from config.config import logger
from dataloader import *
from model import Classifier

# Preprocessing function
def get_transform(dataset):

    resize = A.Resize(224, 224)
    normalize = A.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))
    bright_contrast = A.RandomBrightnessContrast(
        brightness_limit=0.1, contrast_limit=0.1, p=0.2
    )
    rgb_shift = A.RGBShift(p=0.05)
    hue_sat = A.HueSaturationValue(p=0.05)
    channel_shuffle = A.ChannelShuffle(p=0.05)
    gamma = A.RandomGamma(p=0.05)
    gray = A.ToGray(p=0.05)
    jitter = A.ColorJitter(p=0.05)
    hor_flip = A.HorizontalFlip(p=0.1)
    rotate = A.Rotate(limit=15, p=0.1)
    crop = A.RandomCrop(height=100, width=100, p=0.1)
    translate = A.Affine(translate_percent=0.1, p=0.1)
    shear = A.Affine(shear=20, p=0.05)
    scale = A.Affine(scale=1.2, p=0.1)
    to_tensor = ToTensorV2()

    if dataset == "train":
        return A.Compose([resize, normalize, to_tensor])
    elif dataset == "val":
        return A.Compose([resize, normalize, to_tensor])

# Dataset function
def prepare_dataset(data_dir):
    try:
        train_dir = str(data_dir) + "/train"
        logger.debug(train_dir)
        val_dir = str(data_dir) + "/val"
        trainset = CustomDataset(data_dir=train_dir, transforms=get_transform("train"))
        valset = CustomDataset(data_dir=val_dir, transforms=get_transform("val"))
        return trainset, valset
    except Exception as e:
        logger.error(f"Got an exception: {e}")

# Sanity check subset function
def create_subset(trainset, valset):

    train_subset = Subset(trainset, range(100))
    val_subset = Subset(valset, range(5))

    return train_subset, val_subset

# Dataloaders function
def create_dataloaders(args, train_subset, val_subset):
    from torch.utils.data import DataLoader

    train_dataloader = DataLoader(
        train_subset, batch_size=args.batch_size, num_workers=24, shuffle=True
    )
    val_dataloader = DataLoader(
        val_subset, batch_size=args.batch_size, num_workers=24, shuffle=False
    )
    return train_dataloader, val_dataloader

def set_device():
    if torch.cuda.is_available():
        device = "gpu"
    else:
        device = "cpu"
    return device

def main():

    device = set_device()
    logger.info(f"Currently using {device} device...")

    # Read args
    logger.info("Reading arguments...")
    parser = ArgumentParser()
    parser.add_arguments(Args, dest="options")
    args_namespace = parser.parse_args()
    args = args_namespace.options

    # Prepare dataset
    logger.info("Preparing datasets...")
    trainset, valset = prepare_dataset(data_dir=config.DATA_DIR)
    logger.info(
        f"""Total training images: {len(trainset)}
Total validation images: {len(valset)}"""
    )

    # Create subset
    # train_subset, val_subset = create_subset(trainset, valset)

    # Create dataloaders
    train_dataloader, val_dataloader = create_dataloaders(args, trainset, valset)

    # Initialize clearml task
    logger.info("Initializing clearml task...")
    task = Task.init(
        project_name="streamlit/image-classification",
        task_name=f"streamlit-image-classification-{datetime.now()}",
    )
    task.connect(args)

    # Saves top-K checkpoints based on "val_loss" metric
    checkpoint_callback = ModelCheckpoint(
        save_top_k=1,
        monitor="loss/val_loss",
        mode="min",
        filename="streamlit-image-classification-{epoch:02d}-{val_loss:.2f}",
    )

    # Create progress bar
    progress_bar = RichProgressBar(
        theme=RichProgressBarTheme(
            description="white",
            progress_bar="#50C878",
            progress_bar_finished="#50C878",
            progress_bar_pulse="#50C878",
            batch_progress="orange",
            time="grey54",
            processing_speed="grey70",
            metrics="white",
        ),
        console_kwargs=None,
        refresh_rate=10,
    )

    # Train
    # configure trainer
    trainer = pl.Trainer.from_argparse_args(
        args,
        callbacks=[checkpoint_callback, progress_bar],
        default_root_dir=config.LOGS_DIR,
        accelerator=device,
        devices=1,
        log_every_n_steps=1,
    )

    # define classifier
    classifier = Classifier()

    # fit the model
    logger.info("Starting training...")
    trainer.fit(classifier, train_dataloader, val_dataloader)

if __name__ == "__main__":
    main()


from socket import *
import sys

serverSocket = socket(AF_INET, SOCK_STREAM)

serverPort = 6789

serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print("the web server is up on: localhost:6789")
while True:
    try:
        connectionSocket, addr = serverSocket.accept()
        print("Ready to serve...")
        message = connectionSocket.recv(1024)
        message.decode()
        filename = message.split()[1]
        f = open(filename[1:])
        outputData = f.read()

        message0 = "\nHTTP\1.1 200 OK\n"
        connectionSocket.send(message0.encode())
        for i in range(0, len(outputData)):
            connectionSocket.send(outputData[i].encode())
        connectionSocket.send("\r\n".encode())
        connectionSocket.close()

    except IOError:
        message1 = "\nHTTP\1.1 404 Not Found\n"
        print("Inside Exception")
        connectionSocket.send(message1.encode())
        connectionSocket.close()

serverSocket.close()
sys.exit()


from ComputerVision.Values_Transformations.filter_kernel import sobel_operators, box_kernel
from ComputerVision.Values_Transformations.filter import Filter
from tqdm.notebook import tqdm
import numpy as np

class CannyEdge:
    """
    Canny Edge Detection algorithm
    """

    @staticmethod
    def group_angle(x):
        """
        Group angles by groups
        :param x: angle
        :return: new angle
        """
        if -22.5 <= x <= 22.5 or 157.5 <= x or -157.5 >= x:
            return 0
        if 22.5 <= x <= 67.5 or -112.5 >= x >= -157.5:
            return 45
        if 67.5 <= x <= 112.5 or -67.5 >= x >= -112.5:
            return 90
        if 112.5 <= x <= 157.5 or -22.5 >= x >= -67.5:
            return 135

    @staticmethod
    def compare_magnitude(x, y, i, j):
        """
        Magnitude comparison
        :param x: magnitude
        :param y: image
        :param i: coordinate image x
        :param j: coordinate image y
        :return: value
        """
        if x == 0:
            if y[i, j] < y[i - 1, j] or y[i, j] < y[i + 1, j]:
                return 0
        if x == 45:
            if y[i, j] < y[i - 1, j + 1] or y[i, j] < y[i + 1, j - 1]:
                return 0
        if x == 90:
            if y[i, j] < y[i - 1, j] or y[i, j] < y[i + 1, j]:
                return 0
        if x == 135:
            if y[i, j] < y[i - 1, j] or y[i, j] < y[i + 1, j]:
                return 0
        return y[i, j]

    @staticmethod
    def compare_magnitudes(x, y):
        """
        Compare magnitudes
        :param x: image x
        :param y: image y
        :return: new image
        """
        aux = np.zeros(x.shape)
        for i in tqdm(range(x.shape[0])):
            for j in range(x.shape[1]):
                try:
                    aux[i, j] = CannyEdge.compare_magnitude(x[i, j], y, i, j)
                except IndexError:
                    pass
        return aux

    @staticmethod
    def thresholding(x, th, tl):
        """
        Apply thresholds
        :param x: image
        :param th: small threshold
        :param tl: big threshold
        :return: value
        """
        if x >= th:
            return 2
        if th > x >= tl:
            return 1
        return 0

    @staticmethod
    def get_neighbours(i, j, shape_):
        """
        Get neighbours pixel
        :param i: coordinate x
        :param j: coordinate y
        :param shape_: shape image
        :return: neighbours
        """
        list_indexes = [(i, j)]
        if i - 1 >= 0:
            if j - 1 >= 0:
                list_indexes.append((i - 1, j - 1))
            if j >= 0:
                list_indexes.append((i - 1, j))
            if j + 1 < shape_[1]:
                list_indexes.append((i - 1, j + 1))
        if j - 1 >= 0:
            list_indexes.append((i, j - 1))
        if j + 1 < shape_[1]:
            list_indexes.append((i, j + 1))
        if i + 1 < shape_[0]:
            if j - 1 >= 0:
                list_indexes.append((i + 1, j - 1))
            if j >= 0:
                list_indexes.append((i + 1, j))
            if j + 1 < shape_[1]:
                list_indexes.append((i + 1, j + 1))
        return list_indexes

    @staticmethod
    def region_grow(f, f5):
        """
        Do region grow
        :param f: filter function
        :param f5: image
        :return: new image
        """
        while True:
            xy = np.nonzero(f(f5))
            if len(xy[0]) > 0:
                x = xy[0][0]
                y = xy[1][0]
                num = 0
                for (i, j) in CannyEdge.get_neighbours(x, y, f5.shape):
                    if f5[i, j] == 2:
                        num += 1
                        f5[x, y] = 2
                        break
                if num == 0:
                    f5[x, y] = 0
            else:
                break
        return f5

    @staticmethod
    def apply(img, tl=0.05, th=0.15, do_grow=True, kernel_size=3):
        """
        Apply algorithm
        :param img: image
        :param tl: low threshold
        :param th: upper threshold
        :param do_grow: apply incremental grow
        :param kernel_size: kernel size
        :return: new image
        """
        print("Applying Canny edge detector")
        # Step 1
        print("    (1/5) Integration")
        g = box_kernel(kernel_size)
        f1 = Filter.apply_filter(img, g)

        # Step 2
        print("    (2/5) Differentiation")
        # Sobbel
        g_x, g_y = sobel_operators()
        f2_x = Filter.apply_filter(f1, g_x)
        f2_y = Filter.apply_filter(f1, g_y)

        # Magnitude
        G = np.sqrt(f2_x ** 2 + f2_y ** 2)
        # Orientation
        # to don't divide by 0
        f = np.vectorize(lambda x: 10e-19 if x == 0. else x)
        teta = np.degrees(np.arctan(f(f2_y) / f(f2_x)))

        # Step 3
        print("    (3/5) Non-maxima suppression")
        # Group angles
        f = np.vectorize(lambda x: CannyEdge.group_angle(x))
        teta2 = f(teta)
        f3 = CannyEdge.compare_magnitudes(teta2, G)

        # Step 4
        print("    (4/5) Hysteresis (or Dual) thresholding")
        f = np.vectorize(CannyEdge.thresholding)
        f3n = f3 / np.max(f3)  # Normalize
        f4 = f(f3n, th, tl)

        # Step 5
        print("    (5/5) Connectivity analysis")
        f = np.vectorize(lambda x: 0 if x == 2 else x)
        f5 = np.copy(f4)
        if do_grow:
            f5 = CannyEdge.region_grow(f, f5)
        print("Complete!")
        return f5


import gcode

IMG_WIDTH  = 1000
IMG_HEIGHT = 1000
IMG_DEPTH  = 5.0
BOTTOM_LEFT = (-2, -1.0)
TOP_RIGHT   = ( 0.5,  1.0)
MAX_ITERATIONS = 256

def mandelbrot(px, py):
    count = 0
    widthRatio = px/float(IMG_WIDTH)
    heightRatio = py/float(IMG_HEIGHT)
    px = BOTTOM_LEFT[0] + widthRatio * (TOP_RIGHT[0]-BOTTOM_LEFT[0])
    py = BOTTOM_LEFT[1] + heightRatio * (TOP_RIGHT[1]-BOTTOM_LEFT[1])
    x, y = 0, 0

    while (x**2+y**2)**0.5 < 2 and count < MAX_ITERATIONS:
        x, y = (x**2 - y**2 + px), (2*x*y + py)
        count += 1

    depth = ((count - 1) / 255.0)*5
    return depth

def createMandelbrotGCode(gcode):
    previousDepth = IMG_DEPTH + 1

    for y in range(IMG_HEIGHT):
        for x in range(IMG_WIDTH):
            currentDepth = mandelbrot(x, y)

            if currentDepth > previousDepth: # if currentdepth higher than prevdepth
                gcode.cutAbsolute(z=currentDepth) # then first rise, then move

            gcode.cutAbsolute(x=float(x), y=float(y))

            if currentDepth < previousDepth: # currentdepth lower than prevdepth
                gcode.cutAbsolute(z=currentDepth) # then move first, then sink

            previousDepth = currentDepth
        gcode.moveAbsolute(x=0, y=y)

def main():
    o = gcode.simpleGenerator(open('output.txt', 'w'))
    createMandelbrotGCode(o)

main()


import math
class Solution:
    def __init__(self):
        self.examples = [[3,3,5,0,0,3,1,4], [1,2,3,4,5], [7,6,4,3,1]]
        self.solutions = [6,4,0]
    def maxProfit(self, prices) -> int:
        if len(prices)==0:
            return 0
        n = len(prices)
        max_prices_from = [0 for i in range(n)]
        min_prices_until = [0 for i in range(n)]
        max_prices_from[n-1] = prices[n-1]
        min_prices_until[0] = prices[0]
        one_trans_from = [0 for i in range(n)] #max profit with one transaction STARTING at index i
        one_trans_until = [0 for i in range(n)] #max profit with one transaction UNTIL (including) index i
        for i in range(n-2,-1,-1):
            max_prices_from[i] = max(prices[i],max_prices_from[i+1])
            min_prices_until[n-1-i] = min(prices[n-1-i], min_prices_until[n-2-i])
            one_trans_from[i] = max(max_prices_from[i+1]-prices[i],one_trans_from[i+1])
            one_trans_until[n-1-i] = max(one_trans_until[n-2-i],prices[n-1-i] - min_prices_until[n-2-i])

        return max([one_trans_until[i-1] + one_trans_from[i] for i in range(1,n)]+[one_trans_from[0]])

    def test_examples(self):
        for i in range(len(self.examples)):
            print(self.maxProfit(self.examples[i]), self.maxProfit(self.examples[i])==self.solutions[i])


def parse_instruct(instruct):
    return instruct[0], int(instruct[1:])

def change_dir(cur, action, val):
    count = val / 90

    for i in range(int(count)):
        if action == 'R':
            if cur == 'N': cur = 'E'
            elif cur == 'E': cur = 'S'
            elif cur == 'S': cur = 'W'
            elif cur == 'W': cur = 'N'
        elif action == 'L':
            if cur == 'N': cur = 'W'
            elif cur == 'W': cur = 'S'
            elif cur == 'S': cur = 'E'
            elif cur == 'E': cur = 'N'

    return cur

def main():
    instrucs = open('etc/data.txt').read().splitlines()

    x_pos = 0
    y_pos = 0

    d = 'E'
    for i in instrucs:
        a,v = parse_instruct(i)

        if (a == 'L' or a == 'R'):
            d = change_dir(d, a, v)
        else:
            if a == 'F':
                if d == 'E':
                    x_pos += v
                elif d == 'W':
                    x_pos -= v
                elif d == 'N':
                    y_pos += v
                elif d == 'S':
                    y_pos -= v
            elif a == 'N': y_pos += v
            elif a == 'S': y_pos -= v
            elif a == 'E': x_pos += v
            elif a == 'W': x_pos -= v

    print("x:{}, y:{}".format(x_pos, y_pos))
    print("manhatten pos: {}".format(abs(x_pos)+ abs(y_pos)))

main()


'''
活动安排问题
'''
from queue import PriorityQueue as PQueue

class TimeCompareAble:
    def __init__(self, start, finish):
        self.start  = start
        self.finish = finish

    # 这里是按python3语法，定义的 < 方法
    def __lt__(self, other):
        if self.finish <= other.finish:
            return True
        else:
            return False

def greedyEventSchedule(n, timeStart, timeFinish):
    pq = PQueue()
    for i in range(n):
        time = TimeCompareAble(timeStart[i], timeFinish[i])
        pq.put(time)

    # 记录已安排活动的最后结束时间
    lastFinishTime = 0
    s = []
    while pq.qsize() > 0:
        time = pq.get()
        if time.start >= lastFinishTime:
            s.append(time)
            lastFinishTime = time.finish
            print(time.start, time.finish)

    return s

#
S = [1, 0, 3, 3, 5, 5, 6, 8, 8, 2, 12]
F = [4, 6, 5, 8, 7, 9, 10, 11, 12, 13, 14]

result = greedyEventSchedule(len(S), S, F)
print(len(result))


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome('chromedriver.exe')
driver.maximize_window()
URL ='https://bdjobs.com'

driver.get(URL)
time.sleep(7)

url_elements = driver.find_elements_by_xpath("//a[@href]")
url_elements_list = []
for url_element in url_elements:
    url_elements_list.append(url_element.get_attribute("href"))
    print(url_elements_list)

driver.close()


import random
from turtle import Turtle,Screen
import random

def start_race(turtles):
    is_race_on = True
    winner = ''
    while is_race_on:
        for tim in turtles:
            step = random.randint(0, 10)
            tim.forward(step)
            if tim.xcor() > 230:
                winner = tim.pencolor()
                is_race_on = False

    return winner

def check_bet_won(winner, bet):
    result = ''
    if bet == winner:
        result = f'your bet for {bet} won :) {winner} indeed knock this race'
    else:
        result = f'your bet for {bet} lost :( {winner} has won this race'
    return result

def create_turtles():
    colors = ['red', 'blue', 'green', 'black', 'purple']
    x_axis = -230
    y_axis = [-100, -50, 0, 50, 100]
    turtles = []

    for i, y in enumerate(y_axis):
        tim = Turtle(shape="turtle")
        tim.penup()
        tim.goto(x_axis, y)
        tim.color(colors[i])
        turtles.append(tim)

    return turtles

def main():
    screen = Screen()
    screen.setup(width=500, height=400)
    bet = screen.textinput(title='Make your bet', prompt="Which turtle would win the race")
    turtles = create_turtles()
    winner = start_race(turtles)
    print(check_bet_won(winner, bet))
    screen.exitonclick()

if __name__ == '__main__':
    main()


import numpy as np
import matplotlib.pyplot as plt
import math as mt

def cond_check(m):
    p=np.array([4,7])
    return np.matmul(p,m)**2 >=(np.linalg.norm(p)**2-9)

num=0
radius=3
p=np.array([4,7])
norm_p=np.linalg.norm(p)
m_lim1=p/mt.sqrt(norm_p**2-9)
m_lim2=-p/mt.sqrt(norm_p**2-9)
theta_line=np.linspace(0,mt.pi/2,20)

for theta in theta_line:
    m=np.array([mt.cos(theta),mt.sin(theta)])
    if cond_check(m):
        lambda_1=-np.matmul(p,m)+mt.sqrt((np.matmul(p,m)**2)+9-norm_p**2)
        lambda_2=-np.matmul(p,m)-mt.sqrt((np.matmul(p,m)**2)+9-norm_p**2)
        A=p+lambda_1*m
        B=p+lambda_2*m
        PA_PB=np.linalg.norm(p-A)*np.linalg.norm(p-B)
        print('m=',m,'   '+'PA.PB=',PA_PB)
        plt.plot(np.array([p[0],A[0],B[0]]),np.array([p[1],A[1],B[1]]))
        plt.text(A[0]*(1+0.1),A[1]*(1-0.1),'A'+str(num))
        plt.text(B[0]*(1+0.1),B[1]*(1-0.1),'B'+str(num))
        num=num+1
theta=np.linspace(0,2*mt.pi,100)
plt.plot(radius*np.cos(theta),radius*np.sin(theta))
plt.plot(p[0],p[1])
plt.text(p[0],p[1],'P')
plt.grid()
plt.show()


import os.path

from PIL import Image

# 读取原始图像
srcImage = r"E:\code\google-chrome-extensions\project-litongjava\google-chrome-apps-chatgpt\icons\src.png"
dirname = os.path.dirname(srcImage)

# 输出不同尺寸的图像
# Image.open(srcImage).resize((256, 256)).save(os.path.join(dirname, "icon.ico"))
srcImage = Image.open(srcImage)
srcImage.resize((16, 16)).save(os.path.join(dirname, "icon16.png"))
srcImage.resize((48, 48)).save(os.path.join(dirname, "icon48.png"))
srcImage.resize((128, 128)).save(os.path.join(dirname, "icon128.png"))
print("done")


from aiogram import types
from aiogram.dispatcher import FSMContext

from app import bot, dp
from database import TelegramChannel
from states import CreatedGivesStates
from keyboards import *

@dp.message_handler(
    state=CreatedGivesStates.add_channel,
)
async def get_channel_data(
    jam: types.Message,
    state: FSMContext
):
    try:

        channel_data = jam.forward_from_chat

        if channel_data.type == 'channel':

            try:
                member_info = await bot.get_chat_member(
                    chat_id=channel_data.id,
                    user_id=bot.id
                )

                if member_info.status == 'administrator':
                    model = TelegramChannel()

                    if not await model.exists_channel(
                            channel_id=channel_data.id
                    ):

                        state_data = await state.get_data()

                        await model.add_channel(
                            owner_id=jam.from_user.id,
                            channel_id=channel_data.id,
                            give_callback_value=state_data['give_callback_value'],
                            name=channel_data.title
                        )

                        await jam.answer(
                            '✅  Канал успешно добавлен',
                            reply_markup=kb_admin_manage_channels
                        )
                        await CreatedGivesStates.manage_channels.set()

                    else:
                        await jam.answer(
                            '🚫  Данный канал уже добавлен, попробуйте другой: ',
                            reply_markup=kb_admin_cancel_action
                        )

                else:
                    await jam.answer(
                        '🚫  Ошибка! Проверьте права бота и перешлите репостом сообщение из канала еще раз: ',
                        reply_markup=kb_admin_cancel_action
                    )

            except Exception as error:
                print(error)
                await jam.answer(
                    '🚫  Ошибка! Проверьте права бота и перешлите репостом сообщение из канала еще раз: ',
                    reply_markup=kb_admin_cancel_action
                )

        else:
            await jam.answer(
                '🚫  Это не канал, попробуйте еще раз:',
                reply_markup=kb_admin_cancel_action
            )

    except AttributeError:
        await jam.answer(
            '🚫  Это не канал, попробуйте еще раз:',
            reply_markup=kb_admin_cancel_action
        )


""" show_ip_route.py

IOSXE parsers for the following show commands:
    * 'show ip route bgp'
    * 'show ip route vrf <WORD> bgp'
    * 'show ipv6 route bgp'
    * 'show ipv6 route vrf <WORD> bgp'
"""
import re
from genie.metaparser import MetaParser
from genie.metaparser.util.schemaengine import Any, Optional

class ShowIpRouteSchema(MetaParser):
    """Schema for:
         show ip route bgp
         show ip route vrf <WORD> bgp
         show ipv6 route bgp
         show ipv6 route vrf <WORD> bgp"""

    schema = {
        'vrf':
            {Any():
                {Optional('address_family'):
                    {Any():
                        {'ip':
                            {Any():
                                {Optional('nexthop'):
                                    {Optional(Any()):
                                        {Optional('protocol'):
                                            {Optional(Any()):
                                                {Optional('route_table'): str,
                                                Optional('candidate_default'): bool,
                                                Optional('uptime'): str,
                                                Optional('preference'): str,
                                                Optional('metric'): str,
                                                Optional('attribute'): str,
                                                }
                                            },
                                        }
                                    },
                                }
                            },
                        }
                    },
                }
            },
        }

class ShowIpRoute(ShowIpRouteSchema):
    """Parser for:
        show ip route bgp
        show ip route vrf <vrf> bgp
        show ipv6 route bgp
        show ipv6 route vrf <vrf> bgp"""
    cli_command = ['show {ip} route vrf {vrf} {protocol}','show {ip} route {protocol}','show ip route vrf {vrf} {protocol}',\
                   'show route {protocol}']
    def cli(self, protocol, vrf='', ip='ip',output=None):
        if output is None:
            # Calling the corresponding show command
            if ip:
                if vrf:
                    cmd = self.cli_command[0].format(ip=ip,vrf=vrf, protocol= protocol)
                else:
                    vrf = 'default'
                    cmd = self.cli_command[1].format(ip=ip,protocol= protocol)
            else:
                if vrf:
                    cmd = self.cli_command[2].format(vrf=vrf,protocol= protocol)
                else:
                    vrf = 'default'
                    cmd = self.cli_command[3].format(protocol= protocol)

            out = self.device.execute(cmd)
        else:
            out = output

        # Init dict
        bgp_dict = {}
        sub_dict = {}
        address_family = None
        preference = None
        metric = None
        mask = ''
        candidate_dafault = False

        source_protocol_dict = {}
        source_protocol_dict['ospf'] = ['O', 'IA', 'N1', 'N2', 'E1', 'E2']
        source_protocol_dict['odr'] = ['o']
        source_protocol_dict['isis'] = ['i', 'su', 'L1', 'L2', 'ia']
        source_protocol_dict['eigrp'] = ['D', 'EX']
        source_protocol_dict['static'] = ['S']
        source_protocol_dict['mobile'] = ['M']
        source_protocol_dict['rip'] = ['R']
        source_protocol_dict['lisp'] = ['I']
        source_protocol_dict['nhrp'] = ['H']
        source_protocol_dict['local'] = ['L']
        source_protocol_dict['connected'] = ['C']
        source_protocol_dict['bgp'] = ['B']

        # Setting the address_family
        if vrf == 'default' and ip =='ip':
            address_family = 'ipv4 unicast'
        elif vrf != 'default' and ip =='ip':
            address_family = 'vpnv4 unicast'
        elif vrf == 'default' and ip =='ipv6':
            address_family = 'ipv6 unicast'
        elif vrf != 'default' and ip =='ipv6':
            address_family = 'vpnv6 unicast'

        for line in out.splitlines():
            line = line.strip()

            # 10.225.0.0/24 is subnetted, 5 subnets
            p1 = re.compile(r'^\s*(?P<address>[0-9\.]+)(?P<mask>[0-9\/]+)'
                             ' +is +subnetted,'
                             ' +(?P<subnets>[0-9]+) +subnets$')
            m = p1.match(line)
            if m:
                address = str(m.groupdict()['address'])
                mask = str(m.groupdict()['mask'])
                subnets = int(m.groupdict()['subnets'])

                continue

            # B   646:11:11:1::/64 [20/2219]
            # B   646:22:22::/64 [20/2219]
            # B   615:11:11::/64 [200/2219]
            # B   2001:2:2:2::2/128 [200/0]
            # B        10.1.1.0 [200/2219] via 10.4.1.1, 01:40:40
            # B        10.9.2.0 [20/2219] via 10.66.6.6 (VRF2), 01:36:26
            # S*    0.0.0.0/0 [20/0] via 10.1.1.1, 4d22h
            p2 = re.compile(r'^\s*(?P<protocol>[a-zA-Z0-9\+\%]+)(?P<candidate_dafault>\*)?'
                             ' +(?P<ip_add>[0-9\.\:\/]+)'
                             ' +(\[(?P<preference>[0-9]+)/(?P<metric>[0-9]+)\])'
                             '( +via +(?P<next_hop>[0-9\.]+)(\s)?(\()?'
                             '(?P<table>[a-zA-Z0-9]+)?(\)?),'
                             ' +(?P<up_time>[\w\:]+))?$')
            m = p2.match(line)
            if m:
                protocol_abr = str(m.groupdict()['protocol'])
                for key, val in source_protocol_dict.items():
                    if protocol_abr in val:
                        protocol = key

                ip_add = str(m.groupdict()['ip_add'])
                if mask:
                    ip_add = ip_add+mask
                preference = m.groupdict()['preference']
                metric = m.groupdict()['metric']
                if m.groupdict()['candidate_dafault']:
                    candidate_dafault = True

                # Init vrf dict
                if 'vrf' not in bgp_dict:
                    bgp_dict['vrf'] = {}
                if vrf and vrf not in bgp_dict['vrf']:
                    bgp_dict['vrf'][vrf] = {}

                # Init address_family dict
                if 'address_family' not in bgp_dict['vrf'][vrf]:
                    bgp_dict['vrf'][vrf]['address_family'] = {}
                if address_family is not None and \
                   address_family not in bgp_dict['vrf'][vrf]['address_family']:
                   bgp_dict['vrf'][vrf]['address_family'][address_family] = {}

                # Create sub_dict
                sub_dict = bgp_dict['vrf'][vrf]['address_family'][address_family]

                # Init address_family dict
                if 'ip' not in sub_dict:
                    sub_dict['ip'] = {}
                if ip_add not in sub_dict['ip']:
                    sub_dict['ip'][ip_add] = {}
                if m.groupdict()['next_hop']:
                    next_hop = str(m.groupdict()['next_hop'])
                    if 'nexthop' not in sub_dict['ip'][ip_add]:
                        sub_dict['ip'][ip_add]['nexthop'] = {}
                    if next_hop not in sub_dict['ip'][ip_add]['nexthop']:
                        sub_dict['ip'][ip_add]['nexthop'][next_hop] = {}
                    if 'protocol' not in sub_dict['ip'][ip_add]['nexthop'][next_hop]:
                        sub_dict['ip'][ip_add]['nexthop'][next_hop]['protocol'] = {}
                    if protocol not in sub_dict['ip'][ip_add]['nexthop'][next_hop]['protocol']:
                        sub_dict['ip'][ip_add]['nexthop'][next_hop]['protocol'][protocol] = {}

                    # Create sub_dict
                    prot_dict = sub_dict['ip'][ip_add]['nexthop'][next_hop]['protocol']
                    if m.groupdict()['table']:
                        table = m.groupdict()['table']
                        prot_dict[protocol]['route_table'] = table

                    prot_dict[protocol]['preference'] = preference
                    if candidate_dafault == True:
                        prot_dict[protocol]['candidate_dafault'] = True
                    metric = m.groupdict()['metric']
                    prot_dict[protocol]['metric'] = metric

                    if m.groupdict()['up_time']:
                        up_time = m.groupdict()['up_time']
                        prot_dict[protocol]['uptime'] = up_time

                continue

            #      via 2001:DB8:1:1::2
            #      via 10.4.1.1%default, indirectly connected
            #      via 2001:DB8:4:6::6
            #      via 2001:DB8:20:4:6::6%VRF2
            p3 = re.compile(r'^\s*via +(?P<next_hop>[a-zA-Z0-9\.\/\:]+)'
                             '(\%(?P<table>[a-zA-Z0-9]+))?'
                             '(,)?(\s+)?(?P<attribute>[a-zA-Z\s]+)?$')
            m = p3.match(line)
            if m:
                next_hop = str(m.groupdict()['next_hop'])
                if 'nexthop' not in sub_dict['ip'][ip_add]:
                    sub_dict['ip'][ip_add]['nexthop'] = {}
                if next_hop not in sub_dict['ip'][ip_add]['nexthop']:
                    sub_dict['ip'][ip_add]['nexthop'][next_hop] = {}
                if 'protocol' not in sub_dict['ip'][ip_add]['nexthop'][next_hop]:
                    sub_dict['ip'][ip_add]['nexthop'][next_hop]['protocol'] = {}
                if protocol not in sub_dict['ip'][ip_add]['nexthop'][next_hop]['protocol']:
                    sub_dict['ip'][ip_add]['nexthop'][next_hop]['protocol'][protocol] = {}

                # Create sub_dict
                prot_dict = sub_dict['ip'][ip_add]['nexthop'][next_hop]['protocol']

                if m.groupdict()['table']:
                    table = m.groupdict()['table']
                    prot_dict[protocol]['route_table'] = table

                if m.groupdict()['attribute']:
                    attribute = m.groupdict()['attribute']
                    prot_dict[protocol]['attribute'] = attribute

                if preference:
                    prot_dict[protocol]['preference'] = preference

                if metric:
                    prot_dict[protocol]['metric'] = metric

        return bgp_dict

class ShowIpv6Route(ShowIpRoute):
    """Parser for:
        show ipv6 route bgp
        show ipv6 route vrf <vrf> bgp"""

    def cli(self, protocol, ip='ipv6', vrf = '',output=None):
        return(super().cli(protocol=protocol, ip='ipv6', vrf=vrf,output=output))


import copy
import random

import cv2
import numpy as np
from scipy.io import loadmat

input = "../input/"

data = loadmat(input + 'matches.mat')
r1 = data['r1']
r2 = data['r2']
c1 = data['c1']
c2 = data['c2']
matches = data['matches']

x1 = c1[matches[:, 0] - 1]
y1 = r1[matches[:, 0] - 1]
x2 = c2[matches[:, 1] - 1]
y2 = r2[matches[:, 1] - 1]

def approxFunda(p1, p2):
    p1 = np.array(p1)
    p2 = np.array(p2)

    mn1 = np.sum(p1, axis=0) / p1.shape[0]
    mn2 = np.sum(p2, axis=0) / p2.shape[0]
    mn1 = np.reshape(mn1, (1, mn1.shape[0]))
    mn2 = np.reshape(mn2, (1, mn2.shape[0]))
    trnsl_p1 = p1 - mn1
    trnsl_p2 = p2 - mn2

    added_sqs1 = np.sum(trnsl_p1 ** 2, axis=1)
    added_sqs1 = np.reshape(added_sqs1, (trnsl_p1.shape[0], 1))

    mn_dist1 = np.sum(added_sqs1 ** (1 / 2), axis=0) / trnsl_p1.shape[0]
    factor1 = 2 ** (1 / 2) / mn_dist1[0]

    added_sqs2 = np.sum(trnsl_p2 ** 2, axis=1)
    added_sqs2 = np.reshape(added_sqs2, (trnsl_p2.shape[0], 1))

    mn_dist2 = np.sum(added_sqs2 ** (1 / 2), axis=0) / trnsl_p2.shape[0]
    factor2 = 2 ** (1 / 2) / mn_dist2[0]

    nmlz1 = factor1 * trnsl_p1
    nmlz2 = factor2 * trnsl_p2

    trnslmtrx1 = np.array([[1, 0, -mn1[0][0]], [0, 1, -mn1[0][1]], [0, 0, 1]])
    scmtrx1 = np.array([[factor1, 0, 0], [0, factor1, 0], [0, 0, 1]])

    trnslmtrx2 = np.array([[1, 0, -mn2[0][0]], [0, 1, -mn2[0][1]], [0, 0, 1]])
    scmtrx2 = np.array([[factor2, 0, 0], [0, factor2, 0], [0, 0, 1]])

    T1 = np.dot(scmtrx1, trnslmtrx1)
    T2 = np.dot(scmtrx2, trnslmtrx2)

    A = np.zeros((p1.shape[0], 9))
    for i in range(p1.shape[0]):
        A[i, :] = [nmlz2[i][0] * nmlz1[i][0], nmlz2[i][0] * nmlz1[i][1], nmlz2[i][0], nmlz2[i][1] * nmlz1[i][0],
                   nmlz2[i][1] * nmlz1[i][1], nmlz2[i][1], nmlz1[i][0], nmlz1[i][1], 1]

    U, S, Vt = np.linalg.svd(A)

    V = Vt.T
    V = V[:, -1]
    F = np.zeros((3, 3))
    count = 0
    for i in range(3):
        for j in range(3):
            F[i, j] = V[count]
            count += 1

    u, s, vt = np.linalg.svd(F)

    s[-1] = 0
    newS = np.zeros((3, 3))
    for i in range(3):
        newS[i, i] = s[i]

    newF = np.dot((np.dot(u, newS)), vt)

    regF = np.dot(np.dot(T2.T, newF), T1)
    regF = regF / regF[-1, -1]

    return regF

def RANSAC(feature1, feature2):
    thresh = 0.05
    prsntInliers = 0
    perfF = []
    p = 0.99
    N = 2000
    count = 0
    while count < N:
        inlier_count = 0
        random_feature1 = []
        random_feature2 = []
        RandList = np.random.randint(len(feature1), size=8)
        for k in RandList:
            random_feature1.append(feature1[k])
            random_feature2.append(feature2[k])
        F = approxFunda(random_feature1, random_feature2)

        One = np.ones((len(feature1), 1))
        X_1 = np.hstack((feature1, One))
        X_2 = np.hstack((feature2, One))
        E_1, E_2 = X_1 @ F.T, X_2 @ F
        err = np.sum(E_2 * X_1, axis=1, keepdims=True) ** 2 / np.sum(np.hstack((E_1[:, :-1], E_2[:, :-1])) ** 2, axis=1,
                                                                     keepdims=True)
        Inl = err <= thresh
        InlCnt = np.sum(Inl)
        if prsntInliers < InlCnt:
            prsntInliers = InlCnt
            coor = np.where(Inl == True)
            x1_ar = np.array(feature1)
            x2_ar = np.array(feature2)
            inlier_x1 = x1_ar[coor[0][:]]
            inlier_x2 = x2_ar[coor[0][:]]

            perfF = F

        RatioInl = InlCnt / len(feature1)
        if np.log(1 - (RatioInl ** 8)) == 0: continue
        N = np.log(1 - p) / np.log(1 - (RatioInl ** 8))
        count += 1
    return perfF, inlier_x1, inlier_x2

def randomPts(pt1_list, pt2_list, val):
    index = []
    for i in range(val):
        num = random.randint(0, len(pt1_list) - 1)
        index.append(num)
    new_pts1 = []
    new_pts2 = []
    for i in range(len(index)):
        val = index[i]
        new_pts1.append(pt1_list[val])
        new_pts2.append(pt2_list[val])

    new_pts1 = np.asarray(new_pts1)
    new_pts2 = np.asarray(new_pts2)
    return new_pts1, new_pts2

def drawlines(img1, lines, pts):
    i1 = copy.deepcopy(img1)
    r, c, _ = img1.shape
    for r, pt1 in zip(lines, pts):
        color1 = (0, 255, 0)
        color2 = (0, 0, 255)
        x0, y0 = map(int, [0, -r[2] / r[1]])
        x1, y1 = map(int, [c, -(r[2] + r[0] * c) / r[1]])
        i1 = cv2.line(i1, (x0, y0), (x1, y1), color1, 1)
        i1 = cv2.circle(i1, tuple(pt1), 2, color2, -1)
    return i1

def genPts(x1, y1):
    p1 = []
    for i in range(len(x1)):
        temp = [x1[i][0], y1[i][0]]
        p1.append(temp)

    return p1

def computeEpilines(img1, img2, x1, x2, y1, y2):
    p1 = genPts(x1, y1)
    p2 = genPts(x2, y2)
    F, pt1, pt2 = RANSAC(p1, p2)

    points1, points2 = randomPts(pt1, pt2, 7)

    ones = np.ones((points1.shape[0], 1))
    final_p1 = np.append(points1, ones, axis=1)
    final_p2 = np.append(points2, ones, axis=1)

    lines1 = np.dot(F, final_p1.T)
    lines2 = np.dot(final_p2, F)

    i1 = drawlines(img2, lines1.T, points2)
    i2 = drawlines(img1, lines2, points1)

    final_image = np.hstack((i1, i2))
    return final_image, F

img1 = cv2.imread(input + "chapel00.png")
img2 = cv2.imread(input + "chapel01.png")

final_image, F = computeEpilines(img1, img2, x1, x2, y1, y2)
# print("Fundamenal Matrix: \n", F)

out = "../output/"

cv2.imshow("Epilines", final_image)
cv2.imwrite(out + "epilines.jpg", final_image)
cv2.waitKey(0)
cv2.destroyAllWindows()


import numpy as np

def function(x1, x2):
    return np.matrix([[1], [x1], [x2], [x1 * x2], [x1 ** 2], [x2 ** 2]])

def print_iteration(iter, M):
    print("iter = {}".format(iter) + "\ttrD = {:10.7f}".format(np.trace(np.linalg.inv(M))))

def print_plan(p):
    print("x1\tx2\tp")
    for i in range(n):
        if p[i] != 0:
            print("{:4}".format(x[i][0]) + "\t{:4}".format(x[i][1]) + "\t{:9.7f}".format(p[i]))
    print()

def generate_plan(x_t):
    x = np.zeros((n, 2))
    i = 0
    for x1 in x_t:
        for x2 in x_t:
            x[i][0] = x1
            x[i][1] = x2
            i += 1
    p = np.ones(n) / n
    return x, p

def optimal_plan(x, p):
    proj, grad = np.zeros(n), np.zeros(n)
    solution, iter = 0, 1
    eps = 1e-07
    while solution == 0:
        λ = 0.1
        solution = 1
        M = np.zeros((6, 6)) # Информационная матрица Фишера
        for i in range(0, n):
            M += p[i] * function(x[i][0], x[i][1]) *np.transpose(function(x[i][0], x[i][1]))
        M2 = np.linalg.matrix_power(M, -2)
        for i in range(0, n):
            grad[i] = np.trace(M2 * function(x[i][0], x[i][1]) *np.transpose(function(x[i][0], x[i][1])))
        grad /= np.linalg.norm(grad)
        avg = 0.0
        for i in range(0, n):
            if p[i] != 0.0:
                avg += grad[i]
        avg /= np.count_nonzero(p) # Количество ненулевых элементов весов p
        for i in range(0, n):
            if p[i] != 0 and abs(grad[i] - avg) > eps:
                solution = 0
        for j in range(0, n):
            proj[j] = grad[j] - avg
            if p[j] == 0:
                if proj[j] > 0:
                    solution = 0
                else:
                    proj[j] = 0
        if iter % 500 == 0:
            print_iteration(iter, M)
            print_plan(p)
        if solution == 0:
            for i in range(0, n):
                if proj[i] < 0 and λ > - p[i] / proj[i]:
                    λ = - p[i] / proj[i]
            for i in range(0, n):
                p[i] += λ * proj[i]
        iter += 1
    print("\nРезультат:")
    print_iteration(iter, M)
    max = 0.0
    for i in range(n):
        tr = np.trace(M2 * (function(x[i][0], x[i][1]) * np.transpose(function(x[i][0], x[i][1]))))
        if tr > max:
            max = tr
    print("max:", '%.7f' % max)
    print("Оптимальный план:")
    print_plan(p)

x_t = [-1, -0.75, -0.25, 0, 0.25, 0.75, 1]
n = len(x_t) ** 2
x, p = generate_plan(x_t)
optimal_plan(x, p)


#!/usr/bin/python2

import rospy
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Pose2D
from nav_msgs.msg import Odometry
import numpy as np
from std_srvs.srv import Empty
import math

right = 0
right_front = 0
front = 0
left = 0
behind = 0

pub = ""

def scan_callback(msg):
    global right, right_front, front, left, behind
    right = msg.ranges[0]
    right_front = msg.ranges[45]
    front = msg.ranges[90]
    left = msg.ranges[180]
    behind = msg.ranges[270]

PI = 3.14159

def close_far_l(val):
    if val <= 0.5: return 0 # close
    else: return 1 # far

def close_far_rf(val):
    if val <= 1.2: return 0 # close
    else: return 1 # far

def close_far_ext(val):
    # return 0 for too close, 1 for med, 2 for far, 3 for too far
    if val <= 0.5: return 0 # too close
    elif val <= 0.6: return 1 # close
    elif val <= 0.8: return 2 # medium
    elif val <= 1.2: return 3 # far
    return 4                  # too far

def orientation():
    nearest = min(front, left, right, behind)
    if nearest == front: return 0     # approaching
    if nearest == behind: return 1    # moving away
    if nearest == right: return 2     # parallel
    return 3

def get_discrete_state():
    toReturn = []
    toReturn.append(close_far_ext(right))
    toReturn.append(close_far_rf(right_front))
    toReturn.append(close_far_ext(front))
    toReturn.append(close_far_l(left))
    toReturn.append(orientation())
    print(toReturn)
    return toReturn

def step(action):
    print(action)
    # declare a publisher to move the robot
    new_pose = Pose2D()
    if action == 0:
        new_pose.x = 0.3
    elif action == 1: # left
        new_pose.theta = math.pi / 4
    else: # right
        new_pose.theta = - math.pi / 4
    pub.publish(new_pose)

def main():

    try:
        # initialize publisher and subscribers
        global pub
        pub = rospy.Publisher('/triton_lidar/vel_cmd', Pose2D, queue_size=10)
        rospy.init_node('wall_follow', anonymous=True)

        q_table = np.zeros([5,2,5,2,4,3])

        for i in range(5):
            for j in range(2):
                for k in range(2):
                    for l in range(4):
                        q_table[i][j][4][k][l][0] = 5
                        q_table[i][j][3][k][l][0] = 5
                        q_table[i][j][2][k][l][1] = 5

        for i in range(2):
            for j in range(5):
                for k in range(2):
                    for l in range(4):
                        q_table[2][i][j][k][l][0] = 5
                        q_table[3][i][j][k][l][0] = 5
                        q_table[1][i][j][k][l][0] = 5
                        q_table[0][i][j][k][l][1] = 50

        # step through q table
        steps = 1000
        # while steps > 0:
        while not rospy.is_shutdown():
            state = rospy.wait_for_message('/scan', LaserScan)
            scan_callback(state)

            params = get_discrete_state()
            rew0 = q_table[params[0]][params[1]][params[2]][params[3]][params[4]][0]
            rew1 = q_table[params[0]][params[1]][params[2]][params[3]][params[4]][1]
            rew2 = q_table[params[0]][params[1]][params[2]][params[3]][params[4]][2]

            actionMax = max(rew0, rew1, rew2)
            if actionMax == rew2: step(2)
            elif actionMax == rew1: step(1)
            else: step(0)

            steps = steps - 1

    except rospy.ROSInterruptException:
        rospy.loginfo("node terminated" )

if __name__ == '__main__':
    main()


import bisect
class RangeModule:

  def __init__(self):
    self.track = []

  def addRange(self, left: int, right: int) -> None:
    left_idx = bisect.bisect_left(self.track, left)
    right_idx = bisect.bisect_right(self.track, right)

    subtrack = []
    if left_idx % 2 == 0:
      subtrack.append(left)

    if right_idx % 2 == 0:
      subtrack.append(right)

    self.track[left_idx:right_idx] = subtrack

  def removeRange(self, left: int, right: int) -> None:
    left_idx = bisect.bisect_left(self.track, left)
    right_idx = bisect.bisect_right(self.track, right)

    subtrack = []
    if left_idx % 2 != 0:
      subtrack.append(left)

    if right_idx % 2 != 0:
      subtrack.append(right)

    self.track[left_idx:right_idx] = subtrack

  def queryRange(self, left: int, right: int) -> bool:
    left_idx = bisect.bisect_right(self.track, left)
    right_idx = bisect.bisect_left(self.track, right)

    return left_idx == right_idx and left_idx % 2 != 0

# Your RangeModule object will be instantiated and called as such:
# obj = RangeModule()
# obj.addRange(left,right)
# param_2 = obj.queryRange(left,right)
# obj.removeRange(left,right)