from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic
from django.views.generic.edit import CreateView
from django.shortcuts import redirect
from django.urls import reverse
from collections import OrderedDict
from operator import itemgetter
from django.http import QueryDict
from collections import defaultdict
from django.http import Http404
from django.conf import settings
from math import ceil
from django.contrib.auth import get_user_model
from django.forms.models import model_to_dict
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.response import Response
from django.http import JsonResponse
from rest_framework import status
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from . import models
import course
from course import algos
from course import tags
import cdn
import provider
import student
import re
import profiles
import payments
import json
from django.http import HttpResponse
from access.views import parse_user_agents

User = get_user_model()
OFUSCATE_JW = True
# url is https://obfuscator.io/

def getCartCourses(request):
    studentObj = student.views.getStudent(request)
    allCourses = []
    tcost = 0
    if studentObj:
        cartCoursesList = algos.getCartCourses(studentObj)
        for item in cartCoursesList:
            courseDetails = model_to_dict(item)
            providerObj = provider.models.Provider.objects.filter(id=item.provider_id)[0]
            userDetails = algos.getUserNameAndPic(providerObj.user_id)
            courseDetails["provider_name"] = userDetails['name']
            tcost = tcost + int(courseDetails["cost"])
            allCourses.append(courseDetails)
    return tcost,allCourses

# Create your views here.
class fillCartCourses(generic.TemplateView):
    http_method_names = ['get']

    def get(self, request, *args, **kwargs):
        tcost,allCourses = getCartCourses(request)
        kwargs["tcost"] = tcost
        kwargs["cartCourses"] = allCourses
        return super().get(request, *args, **kwargs)

def getCourseReview(reviewSummary, userReviewList, courseid):
    reviewObj = course.models.CourseReview.objects.filter(course_id=courseid)
    reviewSummary['star_count'] = range(1, 6)
    reviewSummary['totalReviews'] = len(reviewObj)
    reviewSummary['1'] = 0
    reviewSummary['2'] = 0
    reviewSummary['3'] = 0
    reviewSummary['4'] = 0
    reviewSummary['5'] = 0
    totalRating = 0
    for review in reviewObj:
        if review.rating > 0 and review.rating <= 5:
            reviewSummary[str(review.rating)] += 1
            totalRating += review.rating
            userDetails = algos.getUserNameAndPic(review.student_id)

            userDetails['review'] = review.review
            userDetails['rating'] = int(review.rating)
            userDetails['reviewedTime'] = review.reviewed

            userReviewList.append(userDetails)

    if totalRating > 0:
        reviewSummary['averageRating'] = (int(totalRating*10.0/len(reviewObj)))/10.0
        reviewSummary['1Avg'] = str((int(reviewSummary['1']*100.0/len(reviewObj)))) + "%"
        reviewSummary['2Avg'] = str((int(reviewSummary['2']*100.0/len(reviewObj)))) + "%"
        reviewSummary['3Avg'] = str((int(reviewSummary['3']*100.0/len(reviewObj)))) + "%"
        reviewSummary['4Avg'] = str((int(reviewSummary['4']*100.0/len(reviewObj)))) + "%"
        reviewSummary['5Avg'] = str((int(reviewSummary['5']*100.0/len(reviewObj)))) + "%"

class courseDetails(fillCartCourses):
    template_name = 'coursePage.html'
    http_method_names = ['get', 'post']

    def get(self, request, id, *args, **kwargs):
        courseid = id
        courseObj = course.models.Course.objects.filter(id=courseid)

        if len(courseObj) == 0:
            raise Http404()

        courseObj = courseObj[0]
        kwargs["disableKeys"] = "true"
        # this code is for the provider preview.
        # show everything to the provider
        providerObj = provider.models.Provider.objects.filter(user_id=request.user.id)
        checkPublished = True
        courseOverviewMap = {}
        courseOverviewMap["id"] = courseid
        courseOverviewMap["myCourse"] = False

        if providerObj and providerObj[0].id == courseObj.provider_id:
            providerObj = providerObj[0]
            checkPublished = False
            courseOverviewMap["myCourse"] = True
        else:
            providerObj = provider.models.Provider.objects.filter(id=courseObj.provider_id)
            providerObj = providerObj[0]

        if checkPublished and courseObj.published == False:
            kwargs["not_published"] = True
            raise Http404()

        #################Get review details########################

        reviewSummary = {}
        #userReviewList = []

        #getCourseReview(reviewSummary, userReviewList, courseid)

        #kwargs['userReviewList'] = userReviewList

        ##########################################################

        allowedModules = []
        populateCourseDetails = False
        if request.user.is_authenticated:
            if request.user.is_staff == False:
                studentObj = student.models.Student.objects.filter(user_id=request.user.id)[0]
                enrolledCourse = course.models.EnrolledCourse.objects.filter(student_id=studentObj.id).filter(course_id=courseid,active=True)
                if len(enrolledCourse) > 0:
                    courseOverviewMap["myCourse"] = True
                    reviewSummary["enrolledCourse"] = True

                    # calculate duration completed
                    durationCompleted = 0
                    totalDuration = 0
                    enrolledCourseObj = enrolledCourse[0]
                    if enrolledCourseObj.chapteraccess != '':
                        allowedModules = enrolledCourseObj.chapteraccess.split(',')
                    # check for view hours restriction
                    if enrolledCourseObj.viewhours > 0:
                        courseOverviewMap["viewhours"] = enrolledCourseObj.viewhours
                        courseOverviewMap["completedminutes"] = enrolledCourseObj.completedminutes + enrolledCourseObj.completedminuteslive

                    if enrolledCourseObj.sessions != '':
                        sessionsPlayed = course.algos.strToIntList(enrolledCourseObj.sessions)
                        for s in sessionsPlayed:
                            sessionObj = provider.models.Session.objects.filter(id=s)[0]
                            durationCompleted = durationCompleted + sessionObj.duration
                    populateCourseDetails = True

                    courseDetailMap = algos.getCourseDetails(id,checkPublished,True,allowedModules)
                    kwargs["course_detail"] = courseDetailMap
                    for subj in courseDetailMap:
                        chapters = courseDetailMap[subj]
                        for chapDetails in chapters:
                            for chapId in chapDetails:
                                chapDetail = chapDetails[chapId]
                                totalDuration = totalDuration + chapDetail["duration"]

                    if totalDuration > 0:
                        courseOverviewMap["progress"] = str(ceil(durationCompleted*100/totalDuration)) + '%'
                    else:
                        courseOverviewMap["progress"] = "0%"

                addedCourse = payments.models.Cart.objects.filter(course_id=courseid).filter(student_id=studentObj.id)
                if len(addedCourse) > 0:
                    courseOverviewMap["addedCourse"] = True
        if populateCourseDetails == False:
            courseDetailMap = algos.getCourseDetails(id,checkPublished,True,allowedModules)
            kwargs["course_detail"] = courseDetailMap
        courseOverviewMap["Name"] = courseObj.name
        courseOverviewMap["Description"] = courseObj.description
        courseOverviewMap["Subject"] = courseObj.subjects
        courseOverviewMap["Exam"] = courseObj.exam
        courseOverviewMap["Cost"] = courseObj.cost
        courseOverviewMap["Duration"] = courseObj.duration
        courseOverviewMap["Published"] = courseObj.created
        courseOverviewMap["picture"] = courseObj.picture

        kwargs["course_overview"] = courseOverviewMap
        kwargs['reviewSummary'] = reviewSummary

        kwargs["uploadMaterial"] = False
        kwargs["providerLogo"] = algos.getLogoForProvider(providerObj.user_id)
        planObj = provider.models.Plan.objects.filter(provider_id=courseObj.provider_id)
        if planObj:
            planObj = planObj[0]
            if planObj.uploadMaterial == True:
                kwargs["uploadMaterial"] = True
        return super().get(request, id, *args, **kwargs)

    def post(self, request, id, *args, **kwargs):
        courseid = id
        studentObj = student.models.Student.objects.filter(user_id=request.user.id)[0]
        courseObj = course.models.Course.objects.filter(id=courseid)[0]
        cart = payments.models.Cart()
        cart.student = studentObj
        cart.course = courseObj

        if "join" in request.POST:
            if not settings.COURSE_ENROLLING_ALLOWED:
                return render(request, 'join_block.html')
            cart.checkout = True
            cart.save()
            query_dictionary = QueryDict('', mutable=True)
            query_dictionary.update({'id': courseid})
            url = '{base_url}?{querystring}'.format(base_url=reverse("payments:process"),
                                                querystring=query_dictionary.urlencode())
            return redirect(url)

class playSession(LoginRequiredMixin, generic.TemplateView):
    http_method_names = ['get']
    template_name = 'playSession.html'

    def updateSessionStats(self, userId, sessionid):
        # updating the playing session stats
        sessionStatsObj = models.SessionStats.objects.filter(session_id=sessionid)
        statsDict = {}
        if len(sessionStatsObj) == 0:
            sessionStatsObj = models.SessionStats()
            sessionStatsObj.session = provider.models.Session.objects.filter(id=sessionid)[0]
        else:
            sessionStatsObj = sessionStatsObj[0]
            statsDict = json.loads(sessionStatsObj.stats)

        sessionStudentId = str(userId)
        if sessionStudentId in statsDict:
            statsDict[sessionStudentId] += 1
        else:
            statsDict[sessionStudentId] = 1

        sessionStatsObj.stats = json.dumps(statsDict)
        sessionStatsObj.save()

    def get(self, request, chapterid, sessionid, *args, **kwargs):
        if OFUSCATE_JW:
            kwargs["offuscate"] = True
        else:
            kwargs["offuscate"] = False
        if settings.DEBUG:
            kwargs["debug"] = "on"
        else:
            kwargs["debug"] = "off"
        # Allow playSession to super users
        # for debugging
        isAdmin = False
        if request.user.is_superuser:
            isAdmin = True
            kwargs["isOwner"] = 'yes'
            checkPublished = False

        courseChapterObj = course.models.CourseChapter.objects.filter(id=chapterid)
        checkPublished = True
        if len(courseChapterObj) == 0:
            raise Http404()
        kwargs["disableKeys"] = "true"
        courseChapterObj = courseChapterObj[0]
        sessions = str.split(courseChapterObj.sessions, ",")
        #kwargs["cdnName"] = "sgp1.cdn.digitaloceanspaces.com"
        kwargs["cdnName"] = "b-cdn.net"
        # check whether the session is in that course
        if str(sessionid) not in sessions:
            raise Http404()
        allowedModules = []

        # get details for dynamic watermark

        user_ip = request.META.get('HTTP_X_FORWARDED_FOR', request.META.get('REMOTE_ADDR', '')).split(',')[-1].strip()
        user_email = request.user.email
        kwargs["userip"] = user_ip
        kwargs["user_email"] = user_email
        kwargs["user_name"] = request.user.name

        # if user is provider, allow only if he is the course owner and session is added to the course (draft or published)
        courseObj = course.models.Course.objects.filter(id=courseChapterObj.course_id)[0]
        courseOwnerObj = provider.models.Provider.objects.filter(id=courseObj.provider_id)[0]
        kwargs["providerLogo"] = algos.getLogoForProvider(courseOwnerObj.user_id)

        if isAdmin == False and courseOwnerObj.approved == False:
            raise Http404()
        # if user is student, allow only if enrolled for the course and session is published
        if request.user.is_staff == False:
            index = sessions.index(str(sessionid))
            if courseChapterObj.published[index] == False:
                raise Http404()

            studentObj = student.models.Student.objects.filter(user_id=request.user.id)[0]
            #if studentObj.id == 9:
            #    kwargs["cdnName"] = "b-cdn.net"
            courseObj = course.models.Course.objects.filter(id=courseChapterObj.course_id)[0]

            if not algos.isCourseAllowed(request,courseObj.id):
                raise Http404()

            enrolledCourse = course.models.EnrolledCourse.objects.filter(student_id=studentObj.id).filter(course_id=courseChapterObj.course_id,active=True)
            if len(enrolledCourse) == 0:
                raise Http404()

            ecObj = enrolledCourse[0]
            if ecObj.chapteraccess != '':
                allowedModules = ecObj.chapteraccess.split(',')
                if str(chapterid) not in allowedModules:
                    raise Http404()

            # check if view hours have completed
            kwargs["enrolledcourseid"] = ecObj.id
            viewMinutes,allotedHours = student.views.getStudentViewAllotedHoursProviderWise(studentObj.id,courseObj.provider_id)
            #if allotedHours > 0 and viewMinutes >= allotedHours*60:
            if viewMinutes >= allotedHours*60:
                raise Http404()
            if ecObj.chapteraccess != '':
                allowedModules = ecObj.chapteraccess.split(',')
            # dont do device verification if restricted viewing for student is set
            if allotedHours > 0:
                kwargs["disableaccess"] = True

            deviceinfo = parse_user_agents(request)
            kwargs["isOwner"] = 'no'
            # save student stats here
            student.views.fillStudentPlayStats(studentObj.id,sessionid,user_ip,user_email,deviceinfo)

            # updating the playing session stats
            self.updateSessionStats(request.user.id, sessionid)

            coursesWithSession = algos.getCoursesForSession(sessionid)

            for c in coursesWithSession:
                enrolledCourseObj = models.EnrolledCourse.objects.filter(student_id=studentObj.id).filter(course_id=c.id,active=True)
                if len(enrolledCourseObj) > 0:
                    enrolledCourseObj = enrolledCourseObj[0]
                    sessionsPlayed = algos.strToIntList(enrolledCourseObj.sessions)
                    if sessionid in sessionsPlayed:
                        continue

                    sessionsPlayed.append(sessionid)
                    enrolledCourseObj.sessions = algos.intListToStr(sessionsPlayed)
                    enrolledCourseObj.save()

        if isAdmin == False and request.user.is_staff:
            providerObj = provider.models.Provider.objects.filter(user_id=request.user.id)[0]

            if courseObj.provider_id != providerObj.id:
                raise Http404()

            kwargs["isOwner"] = 'yes'
            checkPublished = False
        sessionObj = provider.models.Session.objects.filter(id=sessionid)[0]

        kwargs["coursedetails"] = algos.getCourseDetails(courseChapterObj.course_id,checkPublished,True,allowedModules)
        kwargs["course"] = course.models.Course.objects.filter(id=courseChapterObj.course_id)[0]
        kwargs["session"] = sessionObj
        kwargs["chapter"] = courseChapterObj
        kwargs["ContentHeading"] = 'Contents'
        kwargs["bucketname"] = courseOwnerObj.bucketname
        if sessionObj.bucketname != 'gyaanhive':
            # that means this session is not coming from DO
            # pick bucketname from provider.Storage table
            storageObj = provider.models.Storage.objects.filter(name=sessionObj.bucketname)
            if storageObj:
                storageObj = storageObj[0]
                kwargs["bucketname"] = storageObj.pullzone
            else:
                kwargs["bucketname"] = sessionObj.bucketname
        else:
            kwargs["bucketname"] = 'gyaanhivedo'
        kwargs["videokey"] = sessionObj.videoKey
        kwargs["isLive"] = "false"
        kwargs["providerLogo"] = algos.getLogoForProvider(courseOwnerObj.user_id)
        return super().get(request, chapterid, sessionid, *args, **kwargs)

class playSessionEnc(playSession):
    http_method_names = ['get']
    template_name = 'playSessionEnc.html'

    def check(self, kwargs):
        for tag in tags.playSessionEncTags:
            if not tag in kwargs:
                kwargs[tag] = ""

    def get(self, request, chapterid, sessionid, *args, **kwargs):
        sessionObj = provider.models.Session.objects.filter(id=sessionid)[0]

        if not sessionObj.encrypted:
            raise Http404()

        drmsessionObj = provider.models.DrmSession.objects.filter(session_id=sessionObj.id)
        if len(drmsessionObj) != 0 :
            drmsessionObj = drmsessionObj[0]
            kwargs["keyid"] = drmsessionObj.keyid
            kwargs["key"] = drmsessionObj.key
        else:
            kwargs["keyid"] = settings.DRM_KEY_ID
            kwargs["key"] = settings.DRM_KEY

        self.check(kwargs)
        return super().get(request, chapterid, sessionid, *args, **kwargs)

class addReview(LoginRequiredMixin, generic.TemplateView):
    http_method_names = ['post']

    def post(self, request, id, *args, **kwargs):
        courseid = id
        studentObj = student.models.Student.objects.filter(user_id=request.user.id)[0]
        courseObj = course.models.Course.objects.filter(id=courseid)[0]

        CourseReviewObj = models.CourseReview()
        CourseReviewObj.student = studentObj
        CourseReviewObj.course = courseObj
        CourseReviewObj.review = request.POST.get('review')
        CourseReviewObj.rating = int(request.POST.get('stars'))
        CourseReviewObj.save()

        url = "course:coursePage"
        return redirect(url,courseid)

@api_view(['GET'])
@authentication_classes((SessionAuthentication, ))
@permission_classes((IsAuthenticated, ))
def updateDuration(request, enrolledcourseid, duration, live, format=None):
    try:
        enrolledCourseObj = models.EnrolledCourse.objects.filter(id=enrolledcourseid)[0]
        if live:
            enrolledCourseObj.completedminuteslive = enrolledCourseObj.completedminuteslive + duration/60
        else:
            enrolledCourseObj.completedminutes = enrolledCourseObj.completedminutes + duration/60
        enrolledCourseObj.save()
        return Response({"result":True})
    except:
        logger.error('Update Duration failed for enrolledCourseId : {}.'.format(enrolledcourseid))
        logger.error('Update Duration failed, Duration lost : {}.'.format(duration))
        return Response({"result":False})

@api_view(['GET'])
@authentication_classes((SessionAuthentication, ))
@permission_classes((IsAuthenticated, ))
def updateDurationProvider(request, courseid, duration, format=None):
    courseObj = models.Course.objects.filter(id=courseid)[0]
    courseObj.completedseconds = courseObj.completedseconds + duration
    courseObj.save()
    return Response({"result":True})


# improvement over harris corner detection

import cv2
import numpy as np

# load the image

image = cv2.imread('../images/sudoku.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# we specify the top 50 corners

corners = cv2.goodFeaturesToTrack(gray,50,0.01,15)

# 0.01 -- minimum accepted quality of image corners

for corner in corners:
    x, y = corner[0]
    x = int(x)
    y = int(y)
    cv2.rectangle(image, (x-10,y-10),(x+10,y+10), (0,255,0), 2)

cv2.imshow("Corners found", image)
cv2.waitKey(0)
cv2.destroyAllWindows()


#coding=utf-8
# 网络图片的爬取和存储--结合os库和文件操作的使用

import requests
import os

url = "http://tc.sinaimg.cn/maxwidth.800/tc.service.weibo.com/p3_pstatp_com/6da229b421faf86ca9ba406190b6f06e.jpg"
root = "//root//桌面//zmp//"
path = root + url.split('/')[-1]
try:
    if not os.path.exists(root):
        os.mkdir(root)
    if not os.path.exists(path):
        r = requests.get(url)
        with open(path, 'wb') as f:
            f.write(r.content)
            f.close()
            print("文件保存成功")
    else:
        print("文件已存在")
except:
    print("爬取失败")


# -*- coding: utf-8 -*-
"""
Created on Mon Oct  7 20:06:29 2019

@author: Iikka
"""

import pandas as pd
import requests
import shutil
import os
from io import BytesIO
from PIL import Image

path = 'faces'
if not os.path.exists(path):
    os.makedirs(path)

df=pd.read_csv('facescrub_actresses.txt', sep='\t')
count = 0

for index, row in df.iterrows():
    print(index)

    try:
        response = requests.get(row['url'], stream=True, timeout=2)
    except requests.exceptions.Timeout:
        print('The request timed out')
        continue
    except requests.exceptions.ConnectionError:
        print("Connection refused")
        continue
    except:
        continue
    else:
        print('OK')

    if response.status_code != 200:
        continue

    if(response.headers.get('Content-Length') and int(response.headers.get('Content-Length')) < 2000):
        continue

    bbox = row['bbox']
    split_bbox = bbox.split(',')

    try:
        img = Image.open(BytesIO(response.content))
    except:
        continue

    crop = img.crop((int(split_bbox[0]),int(split_bbox[1]),int(split_bbox[2]),int(split_bbox[3])))

    name = row['name'].replace(" ", "_")
    if not os.path.exists(path + '\\' + name):
        os.makedirs(path + '\\' + name)

    fn = path + '\\' + name + '\\' + name + '_' + str(row['image_id']) + '.jpg'

    crop.convert('RGB').save(fn)


# 班教合规性考核
import pandas as pd
import openpyxl
import numpy as  np
import os

#结果存放目录

base_path = os.path.dirname(os.path.realpath(__file__))\
    .replace(os.path.join('hugh', 'data'), '')
print(base_path)
file_dir = os.path.join(os.path.join(base_path, 'files'), 'data')
# output_file = 'F:/cyt/kettle/【班教】集团教务合规性考核/结果数据'
output_file = os.path.join(file_dir, '结果数据')
# 读取基础数据
df_class = pd.DataFrame(pd.read_excel(os.path.join(file_dir, '一体化班级查询基础数据.xlsx'),sheet_name = 'Sheet1', encoding='gbk', nrows=100))

# 1-0人班处理
df_01 =  df_class[
    (~df_class['班级名称（外）'].str.contains('取消')) &
    (df_class['当前人数(占名额)'] == 0)
]

# 2-网课班级
df_02 =  df_class[
    (~df_class['班级名称（外）'].str.contains('取消')) &  (~df_class['产品体系'].isin(['计费体系'])) &
    (df_class['当前人数(占名额)'] == 0)
]

#18-非本部门项目
# 筛选出班级名称不含取消；非计费体系
# 标准部门为少儿部、中学班课部、中学小组课部
df_18 = df_class [( ~df_class['班级名称（外）'].str.contains('取消')) &  (~df_class['产品体系'].isin(['计费体系'])) &
            (
                ( (df_class['标准部门'].isin(['少儿部','中学班课部','中学小组课部','中学一对一部'])) &
                  (df_class['班级名称（外）'].str.contains('托福|雅思|TOEFL|ISEE|IELTS|考研|四级|六级'))) |
                ( (df_class['标准部门'].isin(['国内大学部','国外考试部','英语学习部'])) &
                  (df_class['班级名称（外）'].str.contains('中学|少儿|小学|中考|高考|初一|初二|高一|高二|年级')))
            )
        ]

#输出获取数据条数
#返回列数：df.shape[1]
# 返回行数：len(df) 或者 df.shape[0]

# df_12.to_excel('F:/cyt/kettle/【班教】集团教务合规性考核/结果数据/合规性考核【班教】.xlsx' ,sheet_name='12-非本部门项目',index = False)

# 19-对内外科目年级
# 列包含列 df_test  = df_class[df_class.apply(lambda x: str(x['科目(内)']) in x['班级名称（外）'], axis=1)]
#df = df[df.apply(lambda x: str(x['id']) in x['class'], axis=1)]
# axis 是维度轴 =1 是行计算； =0是列结算
# 这个的意思是在df中用apply函数 x代表一行数据；返回的是id这个字段的str型是否包含在class中的布尔值
df_19 = df_class [( ~df_class['班级名称（外）'].str.contains('取消|全科')) &  (~df_class['产品体系'].isin(['计费体系'])) &
                  ((df_class['标准部门'].isin(['少儿部', '中学班课部', '中学小组课部'])) & (
                      (~ df_class.apply(lambda x: str(x['科目(内)']) in x['班级名称（外）'], axis=1)  ) |
                      (~ df_class.apply(lambda x: str(x['年级序数']) in x['班级名称（内）'], axis=1)  )
                       )
                   )
                  ]

# df_13.to_excel('F:/cyt/kettle/【班教】集团教务合规性考核/结果数据/合规性考核【班教】.xlsx' ,sheet_name='13-对内外科目年级',index = False)

#20-功能型班级
df_20 = df_class[( ~df_class['班级名称（外）'].str.contains('取消')) &
                 (~df_class['产品体系'].isin(['计费体系','专项体系']))  &
                 (df_class['班级名称（外）'].str.contains('活动|辅导|督导|赠送|自习|定金|订金|预收|引流|费|礼品')) ]

#21-学费0
df_21 = df_class[( ~df_class['班级名称（外）'].str.contains('取消')) &
                 (~df_class['产品体系'].isin(['计费体系']))  &
                 (~df_class['班级名称（外）'].str.contains('活动|辅导|督导|赠送|自习')) &
                 (df_class['班级标价'] == 0)]

#22-课时0
#班级课次时长是财务结转表内的字段
# 一体化班级查询内无该字段，此条合规性换成【班级课次数】
df_22 = df_class[( ~df_class['班级名称（外）'].str.contains('取消|订金|定金|预收|引流')) &
                 (~df_class['产品体系'].isin(['计费体系']))  &
                 (df_class['班级课次数'] == 0)]

#23-关联班号

df_23 = df_class[( ~df_class['班级名称（外）'].str.contains('取消')) &
                 (df_class['标准部门'].isin(['少儿部', '中学班课部', '中学小组课部', '中学一对一部'])) &
                 (~df_class['产品体系'].isin(['计费体系']) ) &(
                 ( (df_class['关联班号'].isnull() ) & (df_class['季度'].str.contains('春季上|春季下|秋季上|秋季下')) ) |
                 ( (~df_class['关联班号'].isnull() ) & (df_class['季度'].isin(['暑假','秋季','寒假','春季'])) ) |
                 ( (~df_class['关联班号'].isnull() ) &
                   (df_class['标准部门'].isin([ '中学班课部', '中学小组课部', '中学一对一部'])) &
                   ((df_class['班级编码'].str.endswith('A',na=False))
                    | (df_class['班级编码'].str.endswith('B',na=False)) ) ) |
                 ( (~df_class['关联班号'].isnull() ) &
                   (df_class['标准部门'].isin(['少儿部'])) &
                   ((df_class['班级编码'].str.endswith('1',na=False))  | (df_class['班级编码'].str.endswith('2',na=False)) ) )
                )]

#24-班级类型
df_24 = df_class[( ~df_class['班级名称（外）'].str.contains('取消|全科')) &
                 (~df_class['产品体系'].isin(['计费体系']))  &
                 (df_class['标准部门'].isin(['少儿部', '中学班课部', '中学小组课部'])) & (
                     ( ((df_class['科目(外)'].isin(['英语','数学','语文','物理','化学','生物','地理','政治','历史','科学'])) &
                      (~df_class.apply(lambda x: str(x['科目(外)']) in x['班级类型'], axis=1) )) ) |
                     ((df_class['科目(外)'].isin('科学')) & (~df_class['班级类型'].isin(['初一物理','初二化学','小升初衔接物理'])))
                 )]

#25-住宿标志
df_25 = df_class[( ~df_class['班级名称（外）'].str.contains('取消')) &
                 (~df_class['产品体系'].isin(['计费体系']))  &
                 (df_class['班级名称（外）'].str.contains('住宿|营')) &
                 (~df_class['上课形式'].str.contains('住宿', na=False))]

#26-班级状态
df_26 = df_class[(df_class['班级状态'].isin(['修改待审核','取消待审核']))]

#27-主带课教师空
df_27 = df_class[( ~df_class['班级名称（外）'].str.contains('取消')) &
                 (~df_class['产品体系'].isin(['计费体系']))  &
                 (df_class['标准部门'].isin(['少儿部', '中学班课部', '中学小组课部', '中学一对一部'])) &
                 (df_class['标准人数'] >= 6) &
                 (df_class['续班类型'].isin(['可续','连季续','隔季续']))  &
                 (df_class['主带课老师'].isnull())
                 ]

#在一个excel当中写入多个sheet
# 这里需要提前安装openpyxl 库
excel_writer = pd.ExcelWriter('F:/cyt/kettle/【班教】集团教务合规性考核/结果数据/合规性考核【班教】.xlsx')  # 定义writer，选择文件（文件可以不存在）

df_01.to_excel(excel_writer, sheet_name='1-0人班处理', index=False)  # 写入指定表单
df_18.to_excel(excel_writer, sheet_name='18-非本部门项目', index=False)  # 写入指定表单
df_19.to_excel(excel_writer, sheet_name='19-对内外科目年级', index=False)  # 写入指定表单
df_20.to_excel(excel_writer, sheet_name='20-功能型班级', index=False)  # 写入指定表单
df_21.to_excel(excel_writer, sheet_name='21-学费0', index=False)  # 写入指定表单
df_22.to_excel(excel_writer, sheet_name='22-课时0', index=False)  # 写入指定表单
df_23.to_excel(excel_writer, sheet_name='23-关联班号', index=False)  # 写入指定表单
df_24.to_excel(excel_writer, sheet_name='24-班级类型', index=False)  # 写入指定表单
df_25.to_excel(excel_writer, sheet_name='25-住宿标志', index=False)  # 写入指定表单
df_26.to_excel(excel_writer, sheet_name='26-班级状态', index=False)  # 写入指定表单
df_27.to_excel(excel_writer, sheet_name='27-主带课教师空', index=False)  # 写入指定表单

excel_writer.save()  # 储存文件
excel_writer.close()  # 关闭writer


from intake.container.base import RemoteSource, get_partition
from intake.source.base import Schema

class RemoteSequenceSource(RemoteSource):
    """Sequence-of-things source on an Intake server"""

    name = "remote_sequence"
    container = "python"

    def __init__(self, url, headers, **kwargs):
        self.url = url
        self.npartitions = kwargs.get("npartition", 1)
        self.partition_access = self.npartitions > 1
        self.headers = headers
        self.metadata = kwargs.get("metadata", {})
        self._schema = Schema(npartitions=self.npartitions, extra_metadata=self.metadata)
        self.bag = None
        super(RemoteSequenceSource, self).__init__(url, headers, **kwargs)

    def _load_metadata(self):
        import dask
        import dask.bag as db

        if self.bag is None:
            self.parts = [dask.delayed(get_partition)(self.url, self.headers, self._source_id, self.container, i) for i in range(self.npartitions)]
            self.bag = db.from_delayed(self.parts)
        return self._schema

    def _get_partition(self, i):
        self._load_metadata()
        return self.parts[i].compute()

    def read(self):
        self._load_metadata()
        return self.bag.compute()

    def to_dask(self):
        self._load_metadata()
        return self.bag

    def _close(self):
        self.bag = None

    @staticmethod
    def _persist(source, path, encoder=None, **kwargs):
        """Save list to files using encoding

        encoder : None or one of str|json|pickle
            None is equivalent to str
        """
        import json
        import pickle

        encoder = {None: str, "str": str, "json": json.dumps, "pickle": pickle.dumps}[encoder]
        try:
            b = source.to_dask()
        except NotImplementedError:
            b = source.read()
        return RemoteSequenceSource._data_to_source(b, path, encoder, **kwargs)

    @staticmethod
    def _data_to_source(b, path, encoder=None, storage_options=None, **kwargs):
        import json
        import pickle
        import posixpath

        import dask
        import dask.bag as db
        from fsspec import open_files

        from intake.source.textfiles import TextFilesSource

        encoder = {None: str, "str": str, "json": json.dumps, "pickle": pickle.dumps}.get(encoder, encoder)

        if not hasattr(b, "to_textfiles"):
            try:
                b = db.from_sequence(b, npartitions=1)
            except TypeError:
                raise NotImplementedError

        files = open_files(posixpath.join(path, "part.*"), mode="wt", num=b.npartitions, **(storage_options or {}))
        dwrite = dask.delayed(write_file)
        out = [dwrite(part, f, encoder) for part, f in zip(b.to_delayed(), files)]
        dask.compute(out)
        s = TextFilesSource(posixpath.join(path, "part.*"), storage_options=storage_options)
        return s

def write_file(data, fo, encoder):
    with fo as f:
        for d in data:
            f.write(encoder(d))


# -*- coding: utf-8 -*-
"""
author SparkByExamples.com
"""

import pyspark
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName('SparkByExamples.com').getOrCreate()

simpleData = (("James", "Sales", 3000), \
    ("Michael", "Sales", 4600),  \
    ("Robert", "Sales", 4100),   \
    ("Maria", "Finance", 3000),  \
    ("James", "Sales", 3000),    \
    ("Scott", "Finance", 3300),  \
    ("Jen", "Finance", 3900),    \
    ("Jeff", "Marketing", 3000), \
    ("Kumar", "Marketing", 2000),\
    ("Saif", "Sales", 4100) \
  )

columns= ["employee_name", "department", "salary"]

df = spark.createDataFrame(data = simpleData, schema = columns)

df.printSchema()
df.show(truncate=False)

from pyspark.sql.window import Window
from pyspark.sql.functions import row_number
windowSpec  = Window.partitionBy("department").orderBy("salary")

df.withColumn("row_number",row_number().over(windowSpec)) \
    .show(truncate=False)

from pyspark.sql.functions import rank
df.withColumn("rank",rank().over(windowSpec)) \
    .show()

from pyspark.sql.functions import dense_rank
df.withColumn("dense_rank",dense_rank().over(windowSpec)) \
    .show()

from pyspark.sql.functions import percent_rank
df.withColumn("percent_rank",percent_rank().over(windowSpec)) \
    .show()

from pyspark.sql.functions import ntile
df.withColumn("ntile",ntile(2).over(windowSpec)) \
    .show()

from pyspark.sql.functions import cume_dist
df.withColumn("cume_dist",cume_dist().over(windowSpec)) \
   .show()

from pyspark.sql.functions import lag
df.withColumn("lag",lag("salary",2).over(windowSpec)) \
      .show()

from pyspark.sql.functions import lead
df.withColumn("lead",lead("salary",2).over(windowSpec)) \
    .show()

windowSpecAgg  = Window.partitionBy("department")
from pyspark.sql.functions import col,avg,sum,min,max,row_number
df.withColumn("row",row_number().over(windowSpec)) \
  .withColumn("avg", avg(col("salary")).over(windowSpecAgg)) \
  .withColumn("sum", sum(col("salary")).over(windowSpecAgg)) \
  .withColumn("min", min(col("salary")).over(windowSpecAgg)) \
  .withColumn("max", max(col("salary")).over(windowSpecAgg)) \
  .where(col("row")==1).select("department","avg","sum","min","max") \
  .show()


from datetime import datetime, date
from person_class import Person

# Employee (наследуемся от Person) (добавляются свойства: должность, опыт работы, зарплата)
# ** (только для продвинутых) Можете в конструкторе проверить, что в опыт работы и зарплата не отрицательные 😊
# Реализовать новые методы:
# возвращает должность с приставкой, которая зависит от опыта работы: Junior — менее 3 лет, Middle — от 3 до 6 лет,
# Senior — больше 6 лет.
# Т.е. метод должен вернуть позицию с приставкой Junior/Middle/Senior <position>.
# Если, например у вас объект имел должность “programmer” с опытом 2 года, метод должен вернуть “Junior programmer”
# метод, который увеличивает зарплату на сумму, которую вы передаёте аргументом.

class Employee(Person):
    """full_name= str must be two words name and surname like 'Ivan Durak', raise ValueError if not\n
        birth_date= datetime.datetime.date obj , year must be in range 1900<year<current_year,
        raise ValueError if not\n
        position='' position str\n
        experience=0 years of experience int raise ValueError if <0\n
        salary=0 current salary of employee int raise ValueError if <0"""

    def __init__(self, full_name='', birth_date=date(datetime.now().year, datetime.now().month, datetime.now().day),
                 position='', experience=0, salary=0):
        super().__init__(full_name, birth_date)
        self._position = position
        if experience >= 0:
            self.experience = experience
        else:
            raise ValueError(f'experience={experience} can not be less 0')
        if salary >= 0:
            self.salary = salary
        else:
            raise ValueError(f'experience={salary} can not be less 0')

    def full_position(self) -> str:
        """return str of full position based on experience and position\n
        0..2 Junior; 3..6 Middle; 6 and more Senior"""
        status = ("Junior" if self.experience < 3 else
                  "Middle" if 3 <= self.experience < 6 else
                  "Senior")
        return f'{status} {self._position}'

    def change_salary(self, delta=0):
        """change salary of employee to delta\n
        delta=0 must be int, can be minus
        but
        delta in minus can not be more salary raise ValueError
        """
        if self.salary + delta >= 0:
            self.salary += delta
        else:
            raise ValueError(f'delta={delta} , sum of salary={self.salary} and delta can\'t be less 0')

    def __str__(self):
        return f'{super().__str__()}, {self._position}, {self.experience}, {self.salary}'

if __name__ == '__main__':
    per = Employee('Ivan Durak', date(1985, 10, 27), 'programmer', 5, 2500)
    print(per)


"Report Generation Framework"

# -------------------------------------------------------------------------
#
# standard python modules
#
# -------------------------------------------------------------------------
from ...const import GRAMPS_LOCALE as glocale

_ = glocale.translation.gettext
import os

# -------------------------------------------------------------------------
#
# Constants
#
# -------------------------------------------------------------------------

# Report categories
from .. import (
    CATEGORY_TEXT,
    CATEGORY_DRAW,
    CATEGORY_CODE,
    CATEGORY_WEB,
    CATEGORY_BOOK,
    CATEGORY_GRAPHVIZ,
    CATEGORY_TREE,
)

standalone_categories = {
    CATEGORY_TEXT: ("RepText", _("Text Reports")),
    CATEGORY_DRAW: ("RepGraph", _("Graphical Reports")),
    CATEGORY_CODE: ("RepCode", _("Code Generators")),
    CATEGORY_WEB: ("RepWeb", _("Web Pages")),
    CATEGORY_BOOK: ("RepBook", _("Books")),
    CATEGORY_GRAPHVIZ: ("Graphs", _("Graphs")),
    CATEGORY_TREE: ("Trees", _("Trees")),
}
book_categories = {
    CATEGORY_TEXT: _("Text"),
    CATEGORY_DRAW: _("Graphics"),
}


import statsmodels.api as sm

# In[4]:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()

# In[5]:

url = 'https://en.wikipedia.org/wiki/Estimates_of_historical_world_population'
dataset = pd.read_html(url, header = 0)

# In[6]:

dataset = dataset[2]

# In[7]:

dataset.head()

# In[8]:

dataset.to_excel('World_Population_Estimate.xlsx')

# In[9]:

dataset_for_analysis = dataset[['Year', 'United States Census Bureau (2017)[29]']]

# In[10]:

dataset_for_analysis.head()

# In[11]:

dataset_for_analysis = dataset_for_analysis.dropna()

# In[12]:

dataset_for_analysis.describe()

# ## Data Exploration

# In[13]:

y = dataset_for_analysis['United States Census Bureau (2017)[29]'] # Defining the independent and dependent variables
x1 = dataset_for_analysis['Year']

# In[16]:

fig, ax = plt.subplots(figsize = (14,7))
plt.scatter(x1,y)
plt.title('World Population', fontsize=45)
plt.xlabel('Year', fontsize=40)
plt.ylabel('Census', fontsize=40)
plt.show()

# ## Regression Model

# In[28]:

y = dataset_for_analysis['United States Census Bureau (2017)[29]'] # Defining the independent and dependent variables
x1 = dataset_for_analysis['Year']

# ### Using Ordinary Least Squares

# In[29]:

x = sm.add_constant(x1)
results = sm.OLS(y,x).fit()
results.summary()

# ## Explanation of table
# ## With our R- squared value of 0.997, this shows our model explains the variability of the data to a large extent

# In[15]:

fig, ax = plt.subplots(figsize = (14,8))
plt.scatter(x1,y)
yhat = 75290000*x1 - 144500000000 # census = 75290000 * x1 + (-144500000000)
fig = plt.plot(x1, yhat, lw=4, c='yellow', label = 'regression line')
plt.title('World Population Growth', fontsize=45)
plt.xlabel('Year', fontsize=40)
plt.ylabel('Census', fontsize=40)
plt.show()

#
# # Interpretation of Regression Analysis
#
# ## From the analysis, we calculated the values for our constants in the regression equation:
# ### yhat = -144500000000 + 75290000 * x1
# ### Where;
# ### x1 = Year
# ### yhat = Census
# ## This equation can be use to predict the World's population
#

# In[ ]:


import cv2 as cv
import numpy as np

points = []   # store four points coordinate
img = cv.imread('Resources/rotate.jpg')

def getpoints(event, x, y, flags, param):
    if event == cv.EVENT_LBUTTONDOWN:
        cv.circle(img, (x, y), 3, (255, 0, 0), -1)
        points.append([x, y])
        print(points)
        if len(points) == 4:
            getperspective()
    #cv.imshow('image', img)

def getperspective():
    width = points[1][0] - points[0][0]   # subtract 0_index_first_value from 1_index_first_value
    height = points[2][1] - points[0][1]  # points[0][1] = index 0 & 2 nd value take from points list
    pts1 = np.float32([points[0:4]])
    pts2 = np.float32([[0, 0], [width, 0], [0, height], [width, height]])
    matrix = cv.getPerspectiveTransform(pts1, pts2)
    wp_img = cv.warpPerspective(img, matrix, (width, height))
    cv.imshow('output', wp_img)

while True:
    cv.imshow('image', img)
    cv.setMouseCallback('image', getpoints)
    if cv.waitKey(1) & 0xff == ord('q'):
        break

    elif cv.waitKey(1) & 0xff == ord('r'):
        img = cv.imread('Resources/rotate.jpg')
        points = []
        cv.imshow('image', img)
        cv.setMouseCallback('image', getpoints)
    else:
        continue


import common, itertools
def solve():
	for n in itertools.count(1):
		if (divisorCount(n) + 1) // 2 > 1000:
			return str(n)

def divisorCount(n):
	count = 1
	end = common.sqrt(n)
	for i in itertools.count(2):
		if i > end:
			break
		if n % i == 0:
			j = 0
			while True:
				n //= i
				j += 1
				if n % i != 0:
					break
			count *= j * 2 + 1
			end = common.sqrt(n)
	if n != 1:
		count *= 3
	return count

if __name__ == "__main__":
	print(solve())


import sys
sys.stdin = open('input.txt')

N, E = map(int, input().split())
data = list(map(int, input().split()))

# 인접행렬
arr = [[0] * (N+1) for _ in range(N+1)]

for i in range(E):
    arr[data[i*2]][data[i*2+1]] = 1
    arr[data[i*2+1]][data[i*2]] = 1

def DFS(start):
    visited[start] = True
    print(start, visited)

    for next in range(1, N+1):
        if arr[start][next] == 1 and not visited[next]:
            DFS(next)
# 스택을 따로 만들지 않고 재귀함수의 호출을 스택처럼 사용
visited = [False] * (N+1)
DFS(1)


from transformers import AutoTokenizer, AutoModelForTokenClassification
from transformers import pipeline
import statistics
import re
from typing import List, Dict

# TODO: fix entity output from NERPipeline:
# TODO: no ''
# TODO: ammend output that is 'B' and '##ad' - revisit grouped_entities setting.

class NERPipeline(object):
    """
    attributes:
    self.tokenizer AutoTokenizer from_pretrained "APOLLO/bert-base-NER"
    self.model = AutoModelForTokenClassification from_pretrained "APOLLO/bert-base-NER"
    self.nlp transformers pipeline of the tokenizer and model
    self.tokens = []
    """
    def __init__(self):
        self.tokenizer = AutoTokenizer.from_pretrained("APOLLO/bert-base-NER", local_files_only=True)
        self.model = AutoModelForTokenClassification.from_pretrained("APOLLO/bert-base-NER", local_files_only=True)
        self.nlp = pipeline("ner",model=self.model,tokenizer=self.tokenizer)  #, grouped_entities=True)
        self.tokens = []
        self.entities = []

    def flatten(self, lol:List) -> List:
        """
        take any list of lists (of lists), return a single list with all values
        :param lol: List of lists
        :return: a flat list
        """
        if isinstance(lol, list):
            return [a for i in lol for a in self.flatten(i)]
        else:
            return [lol]

    # def _store_tokens(self, txt:str):
    #     """
    #     update list of encoded tokens including start and stop tokens.
    #     """
    #     self.tokens.append(self.tokenizer(txt)['input_ids'])
    def _store_tokens(self, tokens:List):
        """
        store tokens in object attribute
        :param tokens : List of tokens
        :type tokens: list
        :return: None.
        """
        self.tokens.append(tokens)

    def _store_entities(self, entities:List):
        """
        store entites in object attribute
        :param tokens : List of tokens
        :type tokens: list
        :return: None.
        """
        self.entities.append(entities)

    def delete_tokens(self):
        """
        erase collected tokens list
        """
        self.tokens = []

    def delete_entities(self):
        """
        erase collected tokens list
        """
        self.entities = []

    def get_tokens(self, txt:str) -> List:
        """
        :param txt: arbitary str
        :type txt: str
        :return: List of encoded tokens
        :return type: List
        """
        return self.tokenizer(txt)['input_ids']

    def get_decoded_tokens(self) -> List:
        """
        decode tokens to original words
        :return: List [[token_text[], [token_text], ...]
        :return type: List
        """
        decoded_tokens = []
        for tokens in self.tokens:
            for token in tokens:
                decoded_tokens.append(self.tokenizer.decode(token))
        return decoded_tokens

    def get_token_stats(self) -> Dict:
        """
        returns Dict of token statistics
        """
        token_stats={}

        document_lengths = []
        doc_tokens = []
        for tokens in self.tokens:
            document_lengths.append(len(tokens))
            doc_tokens.append(tokens)

        token_stats['total_doc_count'] = len(document_lengths)
        token_stats['total tokens'] = sum(document_lengths)
        token_stats['total unique tokens'] = len(set(self.flatten(doc_tokens)))
        median = statistics.median(document_lengths)
        LQ = statistics.median([x for x in document_lengths if x <= median])
        UQ = statistics.median([x for x in document_lengths if x >= median])
        token_stats['token count median'] = median
        token_stats['token count lower quartile'] = LQ
        token_stats['token count upper quartile'] = UQ
        token_stats['token count IQR'] = UQ-LQ
        return token_stats

    def nerfunc(self, txt):
        ner_res=self.nlp(txt)
        # return list of dicts [ {'word': 'China', 'score': 0.9999999, 'entity': 'B-LOC', index: 45 start: 74 end: 79}, {etc}]
        output=[]
        scores=[]
        types=[]
        tmp=''  #store word to build up sequence.
        s=0  # score tracking
        t=''  # entity types
        counter=1
        # print(f'ner_res: {ner_res}')
        for word_count, rec in enumerate(ner_res):
            # print(f'rec :{rec}')
            if rec['word'][0] == '#':
                tmp+=rec['word'][2:]
                if word_count == len(ner_res)-1:
                    # print(f'final tmp: {tmp}')
                    output.append(tmp)
                    scores.append(s/counter)
                    types.append(t)
                    tmp=rec['word']
                    s=rec['score']
                    if rec['entity']=='B-ORG':
                        t='Organization'
                    if rec['entity']=='B-PER':
                        t='Person'
                    if rec['entity']=='B-LOC':
                        t='Location'
                    if rec['entity']=='B-MISC':
                        t='Miscellaneous'
                continue

            if 'B-' in rec['entity']:
                # print(f'intermediate tmp: {tmp}')
                output.append(tmp)
                scores.append(s/counter)
                types.append(t)
                tmp=rec['word']
                s=rec['score']
                if rec['entity']=='B-ORG':
                    t='Organization'
                if rec['entity']=='B-PER':
                    t='Person'
                if rec['entity']=='B-LOC':
                    t='Location'
                if rec['entity']=='B-MISC':
                    t='Miscellaneous'
            else:
                a=rec['word']
                s+=rec['score']
                if a[0]=='#':
                    a=a[2:]
                    tmp+=a
                    # print(f'# add tmp: {tmp}')
                else:
                    tmp+=' '
                    tmp+=a
                counter+=1
            if word_count == len(ner_res)-1:
                # print(f'final tmp: {tmp}')
                output.append(tmp)
                scores.append(s/counter)
                types.append(t)
                tmp=rec['word']
                s=rec['score']
                if rec['entity']=='B-ORG':
                    t='Organization'
                if rec['entity']=='B-PER':
                    t='Person'
                if rec['entity']=='B-LOC':
                    t='Location'
                if rec['entity']=='B-MISC':
                    t='Miscellaneous'

        return(output,types,scores, self.get_tokens(txt))

    @staticmethod
    def _chunk_out_text(text:str, chunk_size:int = 512) -> List:
        """
        :param text: any string
        :param chunk_size: any positive int
        split up test a list of 0-to-n chunk_size strings and one string with the remaining <chunk_size chunk
        """
        i = 0
        chunks = []
        while i < len(text):
            if i+chunk_size < len(text):
                chunks.append(text[i:i+chunk_size])
            else:
                chunks.append(text[i:len(text)])
            i += chunk_size
        return chunks

    def ner_over_chunks(self, actual_text:str) -> List:
        """
        Take a string of any length, cut it into 512 char sections, run NER on each section then reassemble the
        results into one list.
        :param actual_text: any string - here all concatenated text associated with an incident_id_column_name
        :return: List of three lists [[entities], [entity types], [scores]]
        """
        actual_text = re.sub(r"[|]+", self.tokenizer.sep_token, actual_text)  # aggregated source text is separated by |'s.
        chunks = self._chunk_out_text(actual_text)
        aggregated_results = [[],[],[],[]]
        chunk_ners = []
        for c in chunks:
            # NERPipeline returns 3 value list
            # chunk_ners is a list of three value lists
            res = self.nerfunc(c)
            chunk_ners.append(res)

        for c in chunk_ners:
            for j in range(4):
                aggregated_results[j].extend(c[j])

        entities = aggregated_results[0]
        types = aggregated_results[1]
        scores = aggregated_results[2]
        tokens = aggregated_results[3]

        self._store_entities(entities)

        self._store_tokens(tokens)

        return entities, types, scores

if __name__=="__main__":
    np = NERPipeline()
    texts = [
        "Bucky's a badger. that lives in Madison, WI| Bubbles is a clown"
        ]
    for txt in texts:
        output,types,scores=np.ner_over_chunks(txt)
        print(f'output: {output}')
        print(f'types: {types}')
        print(f'scores: {scores}')
        print(f'bert tokens: {np.tokens}')
        print(f'tokens: {np.get_decoded_tokens()}')
        print(f'token_stats: {np.get_token_stats()}')
        print(f'entities: {np.entities}')


#Class for a WEAPON in CSGO Cases

class Weapon:
	#need at least the weapon name to initialize the object
	#FOR QUALITY
	#4 is battle scarred
	#3 is well worn
	#2 is field tested
	#1 is minimal wear
	#0 is factory new

	#Battle-Scarred— 9.93%
	#Well-Worn— 7.92%
	#Field-Tested— 43.18%
	#Minimal Wear— 24.68%
	#Factory New— 14.71%

	def __init__(self, name_of_weapon = "", skin = "", stattrack = False, condition = -1, buy_price = 0, sell_price = 0):
		self.name_of_weapon = name_of_weapon
		self.skin = skin
		self.stattrack = stattrack
		self.condition = condition
		self.buy_price = float(buy_price)
		self.sell_price = float(sell_price)
		#summation of price at a certain quality * the percent chance of that quality (Expected Value)
		#temp = 0
		quality_value_list = [.1471, .2468, .4118, .0792, .0993]
		#for i in range(5):
		#	temp += sell_price[i] * quality_value_list[i]
		self.estimated_value = float(sell_price) * quality_value_list[condition]

	#changes the odds of getting the weapon.
	def stat_track(self, stattrack):
		if(stattrack):
			self.stattrack = True
		else:
			self.stattrack = False

	#Example:
	#This will be updated with how we want the data.
	#"Name","skin","condition","buy_prive","sell_price", "estimated_value"
	def CSVstructure(self):
		return [self.name_of_weapon,self.skin,self.condition,self.stattrack, self.buy_price,self.sell_price, round(self.estimated_value, 2)]


import cv2
import numpy as np

cap = cv2.VideoCapture(0)  # Webcam Capture

totalNoOfImages = 2
onlyOnce = False
alreadyDetected = [False,False,False,False,False]

while (True):

    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    for i in range(1,totalNoOfImages+1):
        template = cv2.imread('images/pic'+str(i)+'.png', 0)
        w, h = template.shape[::-1]

        if alreadyDetected[i] is False :

            res = cv2.matchTemplate(gray, template, cv2.TM_CCOEFF_NORMED)
            threshold = 0.6

            loc = np.where(res >= threshold)

            for pt in zip(*loc[::-1]):
                top_left = pt
                bottom_right = (top_left[0] + w, top_left[1] + h)
                demo = cv2.rectangle(frame, top_left, bottom_right, (0, 0, 255), 3)
                if i is 1 :
                    cv2.putText(frame, 'Mobile' , (top_left[0], top_left[1] - 10), cv2.FONT_HERSHEY_PLAIN,1.4, (0, 255, 0) , 2)
                elif i is 2 :
                    cv2.putText(frame, 'Vasu', (top_left[0], top_left[1] - 10), cv2.FONT_HERSHEY_PLAIN, 1.4,(0, 255, 0) , 2)

                if demo is not None :
                    if onlyOnce is True :
                        alreadyDetected[i] = True
                    print('Object' , i , 'Found')
                break

    cv2.imshow('Object Tracker', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()


#Manages the knowledge base used to think.
import sys, glob
import time
import aiml

kernel = aiml.Kernel()
for file in glob.glob('ai/*.aiml'):
	kernel.learn(file)

kernel.respond("LOAD AIML B")

while True:
	print("\n" * 100)
	input = input("S> ")
	response = kernel.respond(input)
	print("\n" * 100)
	print(input)
	time.sleep(15)


# -*- coding: utf-8 -*-
# @Project:AID1810
# @Author:biabu
# @Date:2019/3/21 9:47
# @File_name:demo01_eig.py
# @IDE:PyCharm

"""
特征值特征向量
"""
import numpy as np

A = np.mat('1 6 5; 9 7 3; 1 5 6')
print(A)
# 特征值提取
eigvals, eigvecs = np.linalg.eig(A)
print(eigvals, eigvecs, sep='\n')
# 通过特征值与特征向量， 求方阵
S = np.mat(eigvecs) * np.mat(np.diag(eigvals)) * np.mat(eigvecs).I
print(S)

eigvals[1:] = 0
S = np.mat(eigvecs) * np.mat(np.diag(eigvals)) * np.mat(eigvecs).I
print(S)


from django.shortcuts import render, get_object_or_404
from .models import Car
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.http import JsonResponse

# Create your views here.

def cars(request):
    cars = Car.objects.order_by('-created_date')
    paginator = Paginator(cars, 4)
    page = request.GET.get('page')
    paged_cars = paginator.get_page(page)

    title_search = Car.objects.values_list('car_title', flat=True).distinct()
    model_search = Car.objects.values_list('car_model', flat=True).distinct()
    year_search = Car.objects.values_list('year', flat=True).distinct()
    city_search = Car.objects.values_list('city', flat=True).distinct()

    data = {
        'cars': paged_cars,
        'title_search': title_search,
        'model_search': model_search,
        'year_search': year_search,
        'city_search': city_search,
    }
    return render(request, 'cars/cars.html', data)

def car_detail(request, id):
    single_car = get_object_or_404(Car, pk=id)
    data = {
        'single_car': single_car,
    }
    return render(request, 'cars/car_detail.html', data)

def get_json_car_Data(request):
    qs_val = list(Car.objects.values('car_title').distinct())
    return JsonResponse({'data':qs_val})

def get_json_model_data(request, *args, **kwargs):
    selected_car = kwargs.get('car_title')
    obj_models = list(Car.objects.values('car_model').filter(car_title__icontains=selected_car).values().distinct())
    return JsonResponse({'data': obj_models})

def search(request):
    cars = Car.objects.order_by('-created_date')

    title_search = Car.objects.values_list('car_title', flat=True).distinct()
    model_search = Car.objects.values_list('car_model', flat=True).distinct()
    year_search = Car.objects.values_list('year', flat=True).distinct()
    city_search = Car.objects.values_list('city', flat=True).distinct()

    if 'keyword' in request.GET:
        keyword = request.GET['keyword']
        if keyword:
            cars = cars.filter(description__icontains=keyword)

    if 'title' in request.GET:
        title = request.GET['title']
        if title:
            cars = cars.filter(car_title__iexact=title)

    if 'model' in request.GET:
        model = request.GET['model']
        if model:
            cars = cars.filter(car_model__iexact=model)

    if 'location' in request.GET:
        location = request.GET['location']
        if location:
            cars = cars.filter(city__iexact=location)

    if 'year-min' in request.GET:
        yearmin = request.GET['year-min']
        if yearmin:
            cars = cars.filter(year__gte=yearmin)

    if 'year-max' in request.GET:
        yearmax = request.GET['year-max']
        if yearmax:
            cars = cars.filter(year__lte=yearmax)

    if 'min_price' in request.GET:
        min_price = request.GET['min_price']
        max_price = request.GET['max_price']
        if max_price:
           cars = cars.filter(price__gte=min_price, price__lte=max_price)

    data = {
        'cars': cars,
        'title_search': title_search,
        'model_search': model_search,
        'year_search': year_search,
        'city_search': city_search,
    }
    return render(request, 'cars/search.html', data)


acs = {
    'race_pct_white':  {'numerator': 'race_count_white', 'denominator': 'race_count_total'},
    'race_pct_black':  {'numerator': 'race_count_black', 'denominator': 'race_count_total'},
    'race_pct_latino': {'numerator': 'race_count_latino', 'denominator': 'race_count_total'},
    'race_pct_asian':  {'numerator': 'race_count_asian', 'denominator': 'race_count_total'},

    'edu_pct_9th':          {'numerator': 'edu_count_9th', 'denominator': 'edu_count_total'},
    'edu_pct_12th':         {'numerator': 'edu_count_12th', 'denominator': 'edu_count_total'},
    'edu_pct_some_college': {'numerator': 'edu_count_some_college', 'denominator': 'edu_count_total'},
    'edu_pct_college':      {'numerator': 'edu_count_college', 'denominator': 'edu_count_total'},
    'edu_pct_advanced':     {'numerator': 'edu_count_advanced', 'denominator': 'edu_count_total'},

    'families_pct_poverty': {'numerator': 'families_count_poverty', 'denominator': 'families_count_total'},

    'health_pct_uninsured': {'numerator': 'health_count_uninsured', 'denominator': 'health_count'},
    'health_pct_insured_public': {'numerator': 'health_count_insured_public', 'denominator': 'health_count'},
    'health_pct_insured_private': {'numerator': 'health_count_insured_private', 'denominator': 'health_count'},
    'health_pct_minors_uninsured': {'numerator': 'health_minors_count_uninsured', 'denominator': 'health_minors_count'},

    'housing_pct_vacant': {'numerator':'housing_count_vacant', 'denominator':'housing_count'},
    'housing_pct_owner': {'numerator':'housing_count_owner', 'denominator':'housing_count'},
    'housing_pct_renter': {'numerator':'housing_count_renter', 'denominator':'housing_count'},
}

building = {
    'count': {},
    'avg_year_built': {'numerator': 'year_built', 'func':'mean' },
    'pct_pre_1978': {'numerator': (lambda b: b.year_built <= 1978), 'denominator': (lambda b: ~b.year_built.isnull() )},
    'pct_sound': {'numerator': (lambda b: b.bldg_condi == 'SOUND'), 'denominator': (lambda b: ~b.bldg_condi.isnull() )},
    'pct_major': {'numerator': (lambda b: b.bldg_condi == 'NEEDS MAJOR REPAIR'), 'denominator': (lambda b: ~b.bldg_condi.isnull() )},
    'pct_minor': {'numerator': (lambda b: b.bldg_condi == 'NEEDS MINOR REPAIR'), 'denominator': (lambda b: ~b.bldg_condi.isnull() )},
    'pct_uninhabitable': {'numerator': (lambda b: b.bldg_condi == 'UNINHABITABLE'), 'denominator': (lambda b: ~b.bldg_condi.isnull() )},
    'avg_stories': {'numerator': 'stories', 'func': 'mean'},
    'avg_units': {'numerator': 'units', 'func': 'mean'},
    'pct_vacant': {'numerator': 'vacant', 'denominator': 1}
}

assessor = {
    'count': {},
    'pct_residential': {'numerator': 'residential', 'denominator': (lambda a: ~a.residential.isnull() )},
    'avg_residential_total_value': {'numerator': (lambda a: a.total_value.where(a.residential) ), 'func':'mean'},
    'avg_non_residential_total_value': {'numerator': (lambda a: a.total_value.where(~a.residential) ), 'func':'mean'},
    'avg_residential_age' : {'numerator': (lambda a: a.age.where(a.residential) ), 'func':'mean'},
    'avg_non_residential_age' : {'numerator': (lambda a: a.age.where(~a.residential) ), 'func':'mean'}
}

for i in range(10):
    assessor['class_type_' + str(i)] = {'numerator': ( lambda a: a.class_types.apply(lambda c: str(i) in c) ), 'denominator': 1}


import stomp
import time

try:
  conexao = stomp.Connection()
  conexao.connect('','', wait=True)

  conexao.send(body='TESTE', destination ='/queue/DIA-NAMORADOS', idade = 50)
  print('Enviou msg - ')
#  time.sleep(2)
  conexao.disconnect()

except Exception as e:
  print('error')

print('FIM DA EXECUCAO')


"""qtbot should work for testing!"""
from threading import Thread, current_thread, main_thread
from typing import TYPE_CHECKING, Any, Callable, Tuple
from unittest.mock import Mock

import pytest
from typing_extensions import Literal

from psygnal import Signal
from psygnal._signal import _guess_qtsignal_signature

pytest.importorskip("pytestqt")
if TYPE_CHECKING:
    from pytestqt.qtbot import QtBot

def _equals(*val: Any) -> Callable[[Tuple[Any, ...]], bool]:
    def _inner(*other: Any) -> bool:
        return other == val

    return _inner

def test_wait_signals(qtbot: "QtBot") -> None:
    class Emitter:
        sig1 = Signal()
        sig2 = Signal(int)
        sig3 = Signal(int, int)

    e = Emitter()

    with qtbot.waitSignal(e.sig2, check_params_cb=_equals(1)):
        e.sig2.emit(1)

    with qtbot.waitSignal(e.sig3, check_params_cb=_equals(2, 3)):
        e.sig3.emit(2, 3)

    with qtbot.waitSignals([e.sig3], check_params_cbs=[_equals(2, 3)]):
        e.sig3.emit(2, 3)

    signals = [e.sig1, e.sig2, e.sig3, e.sig1]
    checks = [_equals(), _equals(1), _equals(2, 3), _equals()]
    with qtbot.waitSignals(signals, check_params_cbs=checks, order="strict"):
        e.sig1.emit()
        e.sig2.emit(1)
        e.sig3.emit(2, 3)
        e.sig1.emit()

def test_guess_signal_sig(qtbot: "QtBot") -> None:
    from qtpy import QtCore

    class QtObject(QtCore.QObject):
        qsig1 = QtCore.Signal()
        qsig2 = QtCore.Signal(int)
        qsig3 = QtCore.Signal(int, str)

    q_obj = QtObject()
    assert "qsig1()" in _guess_qtsignal_signature(q_obj.qsig1)
    assert "qsig1()" in _guess_qtsignal_signature(q_obj.qsig1.emit)
    assert "qsig2(int)" in _guess_qtsignal_signature(q_obj.qsig2)
    assert "qsig2(int)" in _guess_qtsignal_signature(q_obj.qsig2.emit)
    assert "qsig3(int,QString)" in _guess_qtsignal_signature(q_obj.qsig3)
    assert "qsig3(int,QString)" in _guess_qtsignal_signature(q_obj.qsig3.emit)

def test_connect_qt_signal_instance(qtbot: "QtBot") -> None:
    from qtpy import QtCore

    class Emitter:
        sig1 = Signal()
        sig2 = Signal(int)
        sig3 = Signal(int, int)

    class QtObject(QtCore.QObject):
        qsig1 = QtCore.Signal()
        qsig2 = QtCore.Signal(int)

    q_obj = QtObject()
    e = Emitter()

    # the hard case: signal.emit takes less args than we emit
    def test_receives_1(value: int) -> bool:
        # making sure that qsig2.emit only receives and emits 1 value
        return value == 1

    e.sig3.connect(q_obj.qsig2.emit)
    with qtbot.waitSignal(q_obj.qsig2, check_params_cb=test_receives_1):
        e.sig3.emit(1, 2)  # too many

    # the "standard" cases, where params match
    e.sig1.connect(q_obj.qsig1.emit)
    with qtbot.waitSignal(q_obj.qsig1):
        e.sig1.emit()

    e.sig2.connect(q_obj.qsig2.emit)
    with qtbot.waitSignal(q_obj.qsig2):
        e.sig2.emit(1)

    # the flip case: signal.emit takes more args than we emit
    with pytest.raises(ValueError):
        e.sig1.connect(q_obj.qsig2.emit)
    e.sig1.emit()

@pytest.mark.parametrize("thread", [None, "main"])
def test_q_main_thread_emit(
    thread: Literal["main", None], qtbot: "QtBot", qapp
) -> None:
    """Test using signal.emit(..., queue=True)

    ... and receiving it on the main thread with a QTimer connected to `emit_queued`
    """
    from psygnal.qt import start_emitting_from_queue, stop_emitting_from_queue

    class C:
        sig = Signal(int)

    obj = C()
    mock = Mock()

    @obj.sig.connect(thread=thread)
    def _some_slot(val: int) -> None:
        mock(val)
        assert (current_thread() == main_thread()) == (thread == "main")

    def _emit_from_thread() -> None:
        assert current_thread() != main_thread()
        obj.sig.emit(1)

    with qtbot.waitSignal(obj.sig, timeout=1000):
        t = Thread(target=_emit_from_thread)
        t.start()
        t.join()

    qapp.processEvents()
    if thread is None:
        mock.assert_called_once_with(1)
    else:
        mock.assert_not_called()
        start_emitting_from_queue()
        qapp.processEvents()
        mock.assert_called_once_with(1)

        start_emitting_from_queue(10)  # just for test coverage
        stop_emitting_from_queue()


'''
 @Author    Ray
 @Date      2022-07-25
 @Func      ts片段爬取
 @Version   v1.0
 @Note      无
'''

import os
import time
import copy
import requests
import concurrent.futures

from functools import partial
from misstv.config import crawl_header, sleep_time, worker_num

def scrape(ci, folder_path, download_list, urls):
    os.path.split(urls)
    fileName = urls.split('/')[-1][0:-3]
    saveName = os.path.join(folder_path, fileName + ".mp4")
    if os.path.exists(saveName):
        # 跳过已下载
        download_list.remove(urls)
    else:
        response = requests.get(urls, headers=crawl_header, timeout=100)
        if response.status_code == 200:
            content_ts = response.content
            if ci:
                content_ts = ci.decrypt(content_ts)  # 解碼
            with open(saveName, 'ab') as f:
                f.write(content_ts)
            download_list.remove(urls)
        elif response.status_code == 429:
            time.sleep(sleep_time)
        # 输出进度
        print('\r  -PROCESS: 正在下载 {0}, 剩余 {1} 个, status code: {2} \t'.format(
            urls.split('/')[-1], len(download_list), response.status_code), end='', flush=True)

def crawl(ci, folder_path, download_list):
    round = 0
    while(download_list != []):
        with concurrent.futures.ThreadPoolExecutor(max_workers=worker_num) as executor:
            executor.map(partial(scrape, ci, folder_path,
                                 download_list), download_list)
        round += 1
        print(f', round {round}')

def get_video_file(ci, folder_path, ts_list):
    download_list = copy.deepcopy(ts_list)
    start_time = time.time()
    print(' NOTICE: 开始下载 ' + str(len(download_list)) + ' 份文件, ', end='')
    print('预计等待时间 {0:.2f} 分钟(视影片长度和网络速度而定)'.format(len(download_list) / 120))

    crawl(ci, folder_path, download_list)   #开始爬取

    end_time = time.time()
    print(' NOTICE: 下载成功, 共计 {0:.2f} 分钟'.format((end_time - start_time) / 60))


# reference : https://www.tensorflow.org/tutorials/load_data/csv?hl=zh-tw

import pandas as pd
import numpy as np
import tensorflow as tf
import urllib
import os

np.set_printoptions(precision = 3, suppress = True)

if not os.path.exists('abalone_train.csv'):
    content = urllib.request.urlopen('https://storage.googleapis.com/download.tensorflow.org/data/abalone_train.csv')
    with open('abalone_train.csv', 'w') as f:
        f.write(content.read().decode('utf-8'))

abalone_train = pd.read_csv(
    'abalone_train.csv',
    names=["Length", "Diameter", "Height", "Whole weight", "Shucked weight",
           "Viscera weight", "Shell weight", "Age"])

# print(abalone_train.head())

abalone_feature = abalone_train.copy()
abalone_label = abalone_feature.pop('Age')

# print(abalone_feature)
# print(abalone_label)

model = tf.keras.Sequential([
    tf.keras.layers.Dense(64),
    tf.keras.layers.Dense(1)
])

model.compile(optimizer = 'adam',
              loss = tf.losses.MeanSquaredError())

model.fit(abalone_feature, abalone_label, epochs = 10)


import config
import telebot
import random

from pars import Pars
import time

bot = telebot.TeleBot(config.token)

@bot.message_handler(content_types=["text"])
def repeat_all_messages(message):
    m = bot.send_message(message.chat.id, "обработка... ")
    bot.edit_message_text(chat_id=m.chat.id, message_id=m.message_id, text=f"{m.text} {random.randint(1, 20)}%")

    time.sleep(2)
    bot.edit_message_text(chat_id=m.chat.id, message_id=m.message_id, text=f"{m.text} {random.randint(20, 50)}%")
    # ищем meme png
    id = message.text
    pars = Pars(id)
    pars0 = pars.str1
    bot.edit_message_text(chat_id=m.chat.id, message_id=m.message_id, text=f"{m.text} {random.randint(50, 80)}%")
    par = 'bot.send_media_group(message.chat.id,[' + pars0 + '])'
    bot.edit_message_text(chat_id=m.chat.id, message_id=m.message_id, text=f"{m.text} {random.randint(80, 99)}%")
    # задержка
    time.sleep(3)
    bot.edit_message_text(chat_id=m.chat.id, message_id=m.message_id, text=f"Готово! 100%")
    # кнопки
    m = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)
    btn1 = telebot.types.KeyboardButton("Собака")
    btn2 = telebot.types.KeyboardButton("Кот")
    btn3 = telebot.types.KeyboardButton(message.text)
    m.add(btn1, btn2, btn3)

    # приветствие
    bot.send_message(message.chat.id, text="Привет {0.first_name}!".format(message.from_user), reply_markup=m)
    bot.send_message(message.chat.id, message.text)
    # картинки meme
    if pars0 != 'err':
        #print(pars0)
        try:
            eval(par)
        except telebot.apihelper.ApiTelegramException:
            bot.edit_message_text(chat_id=m.chat.id, message_id=m.message_id, text=f"=( мне бан")
    else:
        bot.send_message(message.chat.id, text="_=( нет meme_", parse_mode="Markdown")
    # картинки meme

if __name__ == '__main__':
     bot.infinity_polling()


from dimension_reduction import Reducer
from feature_selection import Selector
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from math import sqrt
import matplotlib.pyplot as plt

if __name__ == '__main__':
    # reducer = Reducer()
    reducer = Selector()
    input = []
    target = []
    for d in reducer.getLearnData():
        input.append(d[0])
        target.append(d[1][0])

    regressor = LinearRegression()
    regressor.fit(input, target)
    print(regressor.coef_)

    mult = 1#reducer.provider.multiplier

    results = regressor.predict(input)
    print(results)
    w = open('output2_1_s.txt', 'w')
    for i, line in enumerate(results):
        w.write('%f;%f\n' % (target[i]*mult, line*mult))
    w.close()

    input = []
    target = []
    for d in reducer.getTestData():
        input.append(d[0])
        target.append(d[1][0])
    results = regressor.predict(input)
    w = open('output2_2_s.txt', 'w')
    for i, line in enumerate(results):
        w.write('%f;%f\n' % (target[i]*mult, line*mult))
    w.close()
    w = open('linear_mse.txt', 'w')
    w.write('%f;\n' % sqrt(mean_squared_error(target, results)))
    w.close()
    plt.plot(target, 'b', results, 'r')
    plt.ylabel('Reikšmė')
    plt.xlabel('Masyvo elementas')
    plt.title('Multiple linear regression grafikas')
    plt.show()


# coding=utf-8
"""model_1"""
import tensorflow as tf

class Model1(object):
    def __init__(self, num_classes=2, learning_rate=0.0001, bert_size=768, keep_prob=0.9):
        self.num_classes = num_classes
        self.bert_size = bert_size
        self.keep_prob = keep_prob
        self.learning_rate = learning_rate

        self.input_x = tf.placeholder(tf.float32, shape=[None, bert_size], name='input_x')
        self.input_y = tf.placeholder(tf.int64, shape=[None, num_classes], name='input_y')
        self.keep_prob = tf.placeholder(tf.float32, name="keep_prob")

        self.logits = self.inference()
        self.y_predict_val = self.predict()
        self.loss_val = self.loss()
        self.train_op = self.train()
        self.accuracy_val = self.accuracy()
        self.sequence_lengths = tf.placeholder(tf.int32, shape=[None], name="sequence_lengths")

    def inference(self, is_training=True):
        with tf.variable_scope('fc_1', reuse=tf.AUTO_REUSE):
            weights = tf.get_variable(shape=[self.bert_size, self.num_classes],
                                      initializer=tf.random_normal_initializer(), name="w",
                                      trainable=is_training)
            biases = tf.get_variable(shape=[self.num_classes],
                                     initializer=tf.random_normal_initializer(), name="b",
                                     trainable=is_training)
            fc_1_output = tf.nn.xw_plus_b(self.input_x, weights, biases)
            fc_1_drop_out = tf.nn.dropout(fc_1_output, self.keep_prob)
            logits = tf.nn.softmax(fc_1_drop_out)
            return logits

    def predict(self):
        y_predict = tf.argmax(self.logits, axis=1, name="y_pred")
        return y_predict

    def loss(self, l2_lambda=0.0001):
        cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits, labels=self.input_y)
        cross_entropy_mean = tf.reduce_mean(cross_entropy)
        regularization_losses = tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables() if 'bias' not in v.name]) * l2_lambda
        loss = cross_entropy_mean + regularization_losses
        return loss

    def train(self):
        train_op = tf.train.AdamOptimizer(self.learning_rate).minimize(self.loss_val)
        return train_op

    def accuracy(self):
        accuracy = tf.reduce_mean(tf.cast(
            tf.equal(self.y_predict_val, tf.argmax(self.input_y, axis=1)), tf.float32), name="accuracy")
        return accuracy


# start snippet f
import scipy.optimize as optimize
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.collections as mc
from collections import namedtuple

def f(theta):
    L1 = 2
    L2 = np.sqrt(2)
    L3 = np.sqrt(2)
    gamma = np.pi / 2
    p1 = np.sqrt(5)
    p2 = np.sqrt(5)
    p3 = np.sqrt(5)
    x1 = 4
    x2 = 0
    y2 = 4

    A2 = L3 * np.cos(theta) - x1
    B2 = L3 * np.sin(theta)
    A3 = L2 * np.cos(theta + gamma) - x2
    B3 = L2 * np.sin(theta + gamma) - y2

    N1 = B3 * (
        p2 ** 2 - p1 ** 2 - A2 ** 2 - B2 ** 2
    ) - B2 * (p3 ** 2 - p1 ** 2 - A3 ** 2 - B3 ** 2)
    N2 = -A3 * (
        p2 ** 2 - p1 ** 2 - A2 ** 2 - B2 ** 2
    ) + A2 * (p3 ** 2 - p1 ** 2 - A3 ** 2 - B3 ** 2)
    D = 2 * (A2 * B3 - B2 * A3)

    return N1 ** 2 + N2 ** 2 - p1 ** 2 * D ** 2

# end snippet f

Point = namedtuple("Point", ("x", "y"))

class StewartPlatform:
    def __init__(
        self,
        L1=2,
        L2=np.sqrt(2),
        L3=np.sqrt(2),
        gamma=np.pi / 2,
        p1=np.sqrt(5),
        p2=np.sqrt(5),
        p3=np.sqrt(5),
        x1=4,
        x2=0,
        y2=4,
    ):
        self.L1 = L1
        self.L2 = L2
        self.L3 = L3
        self.gamma = gamma
        self.p1 = p1
        self.p2 = p2
        self.p3 = p3
        self.x1 = x1
        self.x2 = x2
        self.y2 = y2

    def f(self, theta):
        A2 = self.L3 * np.cos(theta) - self.x1
        B2 = self.L3 * np.sin(theta)
        A3 = self.L2 * np.cos(theta + self.gamma) - self.x2
        B3 = self.L2 * np.sin(theta + self.gamma) - self.y2

        N1 = B3 * (
            self.p2 ** 2 - self.p1 ** 2 - A2 ** 2 - B2 ** 2
        ) - B2 * (
            self.p3 ** 2 - self.p1 ** 2 - A3 ** 2 - B3 ** 2
        )
        N2 = -A3 * (
            self.p2 ** 2 - self.p1 ** 2 - A2 ** 2 - B2 ** 2
        ) + A2 * (
            self.p3 ** 2 - self.p1 ** 2 - A3 ** 2 - B3 ** 2
        )
        D = 2 * (A2 * B3 - B2 * A3)

        return N1 ** 2 + N2 ** 2 - self.p1 ** 2 * D ** 2

    def platform(self, theta):
        A2 = self.L3 * np.cos(theta) - self.x1
        B2 = self.L3 * np.sin(theta)
        A3 = self.L2 * np.cos(theta + self.gamma) - self.x2
        B3 = self.L2 * np.sin(theta + self.gamma) - self.y2

        N1 = B3 * (
            self.p2 ** 2 - self.p1 ** 2 - A2 ** 2 - B2 ** 2
        ) - B2 * (
            self.p3 ** 2 - self.p1 ** 2 - A3 ** 2 - B3 ** 2
        )
        N2 = -A3 * (
            self.p2 ** 2 - self.p1 ** 2 - A2 ** 2 - B2 ** 2
        ) + A2 * (
            self.p3 ** 2 - self.p1 ** 2 - A3 ** 2 - B3 ** 2
        )
        D = 2 * (A2 * B3 - B2 * A3)

        x = N1 / D
        y = N2 / D

        point_1 = Point(x, y)
        point_2 = Point(
            x + self.L2 * np.cos(theta + self.gamma),
            y + self.L2 * np.sin(theta + self.gamma),
        )
        point_3 = Point(
            x + self.L3 * np.cos(theta),
            y + self.L3 * np.sin(theta),
        )

        return point_1, point_2, point_3

    def draw(self, *thetas, rows=1):
        plt.style.use(
            "https://raw.githubusercontent.com/dhaitz/matplotlib-stylesheets/master/pacoty.mplstyle"
        )
        fig, axs = plt.subplots(rows, len(thetas) // rows)

        A1, A2, A3 = (
            Point(0, 0),
            Point(self.x2, self.y2),
            Point(self.x1, 0),
        )

        try:
            axs = axs.flatten()
        except:
            pass

        for theta, ax in zip(thetas, axs):
            C1, C2, C3 = self.platform(theta)

            lines = [
                (A1, C1),
                (A2, C2),
                (A3, C3),
                (C1, C2),
                (C2, C3),
                (C3, C1),
            ]
            lines = mc.LineCollection(lines)

            ax.add_collection(lines)
            ax.set_aspect("equal", adjustable="box")

            ax.plot(*A1, "o", label="$(0,0)$")
            ax.plot(*A2, "o", label="$(x_2,y_2)$")
            ax.plot(*A3, "o", label="$(x_1,0)$")
            ax.plot(*C1, "o", label="$(x,y)$")
            ax.plot(
                *C2,
                "o",
                label="$(x + L_2 \\cos{\\theta + \\gamma},y_2 + L_2  \\sin{\\theta + \\gamma})$",
            )
            ax.plot(
                *C3,
                "o",
                label="$(x + L_3 \\cos{\\theta},y_2 + L_3  \\sin{\\theta})$",
            )

            ax.autoscale()

        x_lower = min([a.get_xlim()[0] for a in axs])
        x_upper = max([a.get_xlim()[1] for a in axs])
        y_lower = min([a.get_ylim()[0] for a in axs])
        y_upper = max([a.get_ylim()[1] for a in axs])

        for a in axs:
            a.set_xlim((x_lower, x_upper))
            a.set_ylim((y_lower, y_upper))

        plt.show()

    def plot(self, points=[]):
        plt.style.use(
            "https://raw.githubusercontent.com/dhaitz/matplotlib-stylesheets/master/pacoty.mplstyle"
        )
        x = np.linspace(-np.pi, np.pi, 1000)
        plt.plot(x, self.f(x))

        for point in points:
            plt.plot(
                point["x"],
                f(point["x"]),
                point["symbol"],
                markersize=12,
                label=point["label"],
            )

        if points:
            plt.legend()

        plt.show()

def plot():
    plt.style.use(
        "https://raw.githubusercontent.com/dhaitz/matplotlib-stylesheets/master/pacoty.mplstyle"
    )

    # f = system()

    max_x = optimize.fmin(lambda x: -f(x), np.pi)
    root_1 = optimize.bisect(f, -2, 0)
    root_2 = optimize.bisect(f, 0, 2)

    x = np.linspace(-np.pi, np.pi, 1000)
    plt.plot(x, f(x))
    plt.plot(
        root_1,
        f(root_1),
        "*",
        markersize=12,
        label="$R_1 = -\\frac{\\pi}{4}$",
    )
    plt.plot(
        root_2,
        f(root_2),
        "*",
        markersize=12,
        label="$R_2 = \\frac{\\pi}{4}$",
    )
    plt.plot(
        max_x,
        f(max_x),
        "o",
        markersize=12,
        label="$max = \\pi$",
    )

    plt.legend()
    plt.show()

if __name__ == "__main__":
    system = StewartPlatform(
        x1=5,
        x2=0,
        y2=6,
        L1=3,
        L2=3 * np.sqrt(2),
        L3=3,
        gamma=np.pi / 4,
        p1=5,
        p2=5,
        p3=3,
    )

    root_1 = optimize.bisect(system.f, -1, -0.5)
    root_2 = optimize.bisect(system.f, -0.5, 0)
    root_3 = optimize.bisect(system.f, 1, 1.5)
    root_4 = optimize.bisect(system.f, 2, 2.3)

    print(root_4)

    system.plot(
        points=[
            {
                "x": root_1,
                "label": f"$R_1 = {root_1}$",
                "symbol": "*",
            },
            {
                "x": root_2,
                "label": f"$R_2 = {root_2}$",
                "symbol": "*",
            },
            {
                "x": root_3,
                "label": f"$R_3 = {root_3}$",
                "symbol": "*",
            },
            {
                "x": root_4,
                "label": f"$R_4 = {root_4}$",
                "symbol": "*",
            },
        ]
    )

    system.draw(root_1, root_2, root_3, root_4, rows=2)


import turtle as t
from random import randrange
from class_prog import square, vector

food = vector(0, 0)
snake = [vector(10, 0)]
aim = vector(0, -10)
targets = []

def change(x, y):
    aim.x = x
    aim.y = y

def inside(head):
    return -200 < head.x < 200 and -200 < head.y < 200

def move():
    """ To move snake one segment forward. """
    head = snake[-1].copy()
    head.move(aim)
    if not inside(head) or head in snake:
        square(head.x, head.y, 10, "Red")
        t.update()
        return
    snake.append(head)
    if head == food:
        """ Means if snake eats food. """
        print("Snake: ", len(snake))
        food.x = randrange(-15, 15) * 10
        food.y = randrange(-15, 15) * 10
    else:
        snake.pop(0)
    t.clear()
    for body in snake:
        square(body.x, body.y, 10, "Black")
    square(food.x, food.y, 10, "Green")
    t.update()
    t.ontimer(move, 100)

t.setup(420, 420, 370, 0)
t.hideturtle()
t.tracer(False)
t.listen()
t.onkey(lambda: change(10, 0), "Right")
t.onkey(lambda: change(-10, 0), "Left")
t.onkey(lambda: change(0, 10), "Up")
t.onkey(lambda: change(0, -10), "Down")
move()
t.done()


try:
    cantidad_personas = int(input("Ingrese la cantidad de personas: "))
    dias = int(input("Ingrese la cantidad de dias de viaje: "))
except ValueError:
    print("Error: Se ha ingresado un valor que no es valido, solo se ingresa numeros.")
    exit(1)

costo_persona = 125000
monto = costo_persona * cantidad_personas * dias
monto_total = monto + monto * 0.12
print(f"El monto total a pagar por el viaje por {dias} dias con {cantidad_personas} personas y un IVA del 12% es: {round(monto_total, 2)}")