from django.shortcuts import render
import json
from django.http import HttpResponse
from django.http import JsonResponse
from .models import ServerCategorys,ServerPosts,Keywords,Aquestions,Attachments,Centers
from school.models import Schools
from major.models import Majors

# Create your views here.
#服务中心文章列表展示
def serverpostsList(request):
    server_post =ServerPosts .objects.filter(is_status=1)
    context ={'server_post':server_post}
    return render(request,'server/server_posts_list.html',context=context)

#查看服务文章详情
def detailserPos(request):
    ser_pos_id = request.POST.get('ser_pos_id',None)
    ser_posts = ServerPosts.objects.get(id=ser_pos_id)
    return render(request,'server/detail_ser_pos.html',context={'ser_posts':ser_posts})

#添加新服务文章:获取新页面
def addserPos(request):
    ques_school = Schools.objects.filter(is_status=1)
    cateid=ServerCategorys.objects.filter(is_status=1)
    keywords=Keywords.objects.all()
    context = {
        'ques_school': ques_school,
        'cateid': cateid,
        'keywords':keywords
    }
    return render(request, 'server/add_ser_pos.html',context=context)

#添加新服务文章，上传数据，除了标题外，都可不填
def addssserPos(request):
    #获取data的数据
    data = request.POST.get('data', None)
    data = json.loads(data)
    # print(data['post_school'])
    # 判断文章标题是否存在
    info = ServerPosts.objects.filter(post_title=data['post_title'], is_status=1).exists()
    if info:
        return JsonResponse({
            'status': 'fail',
            'message': '该服务文章已存在！',
            'info': ''
        })
    ServerPosts.objects.create(
        post_title=data['post_title'],
        source='舟炬教育' if data['source']=='' else data['source'],
        source_link='http://www.zhoujuedu.com' if data['source_link']=='' else data['source_link'],
        #这几项是外键的id如果不填，会报错，都给个默认值id吧
        #但是major的外键id不填却可以，什么原因呢
        cateid_id='1' if data['cateid']==' ' else data['cateid'],
        keywords_id='8' if data['keywords']==' ' else data['keywords'],
        server_post_school_id='11' if data['server_post_school']==' ' else data['server_post_school'],
        post_content=data['post_content'],
    )
    return JsonResponse({
        'status': 'success',
        'message': '创建成功',
        'info': ''
    })

#删除服务文章，其实是把status变为0
def delserPos(request):
    ser_pos_id=request.GET.get('ser_pos_id')
    ser_posts = ServerPosts.objects.get(id=ser_pos_id)
    context={'ser_posts':ser_posts}
    is_status = 0
    ser_posts.is_status = is_status
    ser_posts.save()
    return render(request, 'server/server_posts_list.html', context=context)

#编辑服务文章:接收数据
def editserPos(request):
    ser_pos_id = request.GET.get('ser_pos_id',None)
    ser_posts = ServerPosts.objects.get(id=ser_pos_id)
    ser_school = Schools.objects.filter(is_status=1).exclude(name=ser_posts.server_post_school.name)
    cateid = ServerCategorys.objects.filter(is_status=1).exclude(server_name=ser_posts.cateid.server_name)
    keywords = Keywords.objects.exclude(key_name=ser_posts.keywords.key_name)
    context = {
        'ser_posts':ser_posts,
        'ser_school':ser_school,
        'cateid':cateid,
        'keywords':keywords
    }
    return render(request,'server/edit_ser_pos.html',context=context)

#编辑服务文章:上传数据
def updateserPos(request):
    # 接收数据
    ser_pos_id = request.POST.get("ser_pos_id",None)

    '''处理数据'''
    data = request.POST.get('data',None)
    data = json.loads(data)

    '''对数据进行处理'''
    pos = ServerPosts.objects.filter(id=ser_pos_id)
    pos.update(**data)

    return HttpResponse(123)

#服务中心分类展示
def serverCates(request):
    server_cates =ServerCategorys .objects.filter(is_status=1)
    context ={'server_cates':server_cates}
    return render(request,'server/server_cates.html',context=context)

#添加服务中心分类:获取新页面
def addserCates(request):
    return render(request, 'server/add_ser_cates.html')

#添加新服务分类：上传数据，名称不允许为空，不允许重复
def addssserCates(request):
    server_name = request.POST.get('server_name')
    # 判断是否存在
    info = ServerCategorys.objects.filter(server_name=server_name).exists()
    if info:  # 如果为true，控制台返回值
        return JsonResponse({
            'status': 'fail',
            'message': '当前分类已存在',#在html写了框，没有用到这个
            'tagid': 'server_name'
        })
    # 如果不存在就增加数据
    ServerCategorys.objects.create(
        server_name=server_name,
    )
    return JsonResponse({
        'status': 'success',
        'message': '创建成功',
        'info': ''
    })

#删除服务分类，其实是把status变为0
def delserCates(request):
    ser_cates_id=request.GET.get('ser_cates_id')
    ser_cates = ServerCategorys.objects.get(id=ser_cates_id)
    context={'ser_cates':ser_cates}
    is_status = 0
    ser_cates.is_status = is_status
    ser_cates.save()
    return render(request, 'server/server_cates.html', context=context)

#编辑服务分类:接收数据
def editserCates(request):
    ser_cates_id = request.GET.get('ser_cates_id',None)
    ser_cates = ServerCategorys.objects.get(id=ser_cates_id)
    context = {
        'ser_cates':ser_cates,
    }
    return render(request,'server/edit_ser_cates.html',context=context)

#编辑服务分类:上传数据
def updateserCates(request):
    # 接收数据
    data = request.POST.get('data', None)
    ser_cateid = request.POST.get("ser_cateid",None)
    data = json.loads(data)
    ser_cates = ServerCategorys.objects.get(id=ser_cateid)

    if data['server_name'] != '':
        ser_cates.server_name = data['server_name']
    ser_cates.save()
    return JsonResponse({
        "status": "success",
        "message": "更改成功",
        "info": ""
    })

#教学中心列表展示
def servercenterList(request):
    center =Centers .objects.filter(is_status=1)
    context ={'center':center}
    return render(request,'server/server_center_list.html',context=context)

#查看教学中心详情
def detailserCenter(request):
    ser_cen_id = request.POST.get('ser_cen_id',None)
    ser_center = Centers.objects.get(id=ser_cen_id)
    return render(request,'server/detail_ser_center.html',context={'ser_center':ser_center})

#添加教学中心:获取新页面
def addserCenter(request):
    return render(request, 'server/add_ser_center.html')

#添加教学中心:上传数据,名称和编号不能为空
def addssserCenter(request):
    cen_name = request.POST.get('cen_name')
    cen_num=request.POST.get('cen_num')
    address = request.POST.get('address',None)
    phone = request.POST.get('phone',None)
    is_direct=request.POST.get('is_direct',None)
    #判断教学中心名称或编号是否存在
    info = Centers.objects.filter(cen_name=cen_name,is_status=1).exists()
    info2 = Centers.objects.filter(cen_num=cen_num,is_status=1).exists()
    # print(info)
    if info or info2:
        return JsonResponse({
            'status': 'fail',
            'message': '教学中心或编号已存在！',#在html写了框，没有用到这个
            'info': ''
        })
    Centers.objects.create(
        cen_name=cen_name,
        cen_num=cen_num,    #因为字段是int，导致如果为空会报错
        address=address,
        phone=phone,
        is_direct=is_direct,
    )
    return JsonResponse({
        'status': 'success',
        'message': '创建成功',
        'info': ''
    })

#删除教学中心，其实是把status变为0
def delserCenter(request):
    ser_center_id=request.GET.get('ser_center_id')
    ser_center = Centers.objects.get(id=ser_center_id)
    context={'ser_center':ser_center}
    is_status = 0
    ser_center.is_status = is_status
    ser_center.save()
    return render(request, 'server/server_center_list.html', context=context)

#编辑教学中心:接收数据
def editserCenter(request):
    ser_center_id = request.GET.get('ser_center_id',None)
    ser_center = Centers.objects.get(id=ser_center_id)
    context = {
        'ser_center':ser_center,
    }
    return render(request,'server/edit_ser_center.html',context=context)

#编辑教学中心:上传数据
def updateserCenter(request):
    # 接收数据
    ser_center_id = request.POST.get("ser_center_id",None)

    '''处理数据'''
    data = request.POST.get('data',None)
    data = json.loads(data)

    '''对数据进行处理'''
    cen = Centers.objects.filter(id=ser_center_id)
    cen.update(**data)

    return HttpResponse(123)

#附件表展示
def serverAtta(request):
    atta =Attachments .objects.filter(is_status=1)
    context ={'atta':atta}
    return render(request,'server/server_atta.html',context=context)

#查看附件详情
def detailserAtta(request):
    ser_atta_id = request.POST.get('ser_atta_id',None)
    ser_atta = Attachments.objects.get(id=ser_atta_id)
    return render(request,'server/detail_ser_atta.html',context={'ser_atta':ser_atta})

#添加附件:获取新页面
def addserAtta(request):
    return render(request, 'server/add_ser_atta.html')

#添加附件:上传数据,都不能为空
def addssserAtta(request):
    atta_name = request.POST.get('atta_name')
    filename=request.POST.get('filename')
    #判断是否存在
    info = Attachments.objects.filter(atta_name=atta_name,filename=filename).exists()
    # print(info)
    if info:
        return JsonResponse({
            'status': 'fail',
            'message': '附件已存在！',#在html写了框，没有用到这个
            'info': ''
        })
    Attachments.objects.create(
        atta_name=atta_name,
        filename=filename,
    )
    return JsonResponse({
        'status': 'success',
        'message': '创建成功',
        'info': ''
    })

#删除附件，其实是把status变为0
def delserAtta(request):
    ser_atta_id=request.GET.get('ser_atta_id')
    ser_atta = Attachments.objects.get(id=ser_atta_id)
    context={'ser_atta':ser_atta}
    is_status = 0
    ser_atta.is_status = is_status
    ser_atta.save()
    return render(request, 'server/server_atta.html', context=context)

#编辑附件:接收数据
def editserAtta(request):
    ser_atta_id = request.GET.get('ser_atta_id',None)
    ser_atta = Attachments.objects.get(id=ser_atta_id)
    context = {
        'ser_atta':ser_atta,
    }
    return render(request,'server/edit_ser_atta.html',context=context)

#编辑附件:上传数据
def updateserAtta(request):
    # 接收数据
    data = request.POST.get('data', None)
    ser_attaid = request.POST.get("ser_attaid",None)
    data = json.loads(data)
    ser_atta = Attachments.objects.get(id=ser_attaid)

    if data['atta_name'] != '':
        ser_atta.atta_name = data['atta_name']
    if data['filename'] != '':
        ser_atta.filename = data['filename']
    ser_atta.save()
    return JsonResponse({
        "status": "success",
        "message": "更改成功",
        "info": ""
    })

#模拟题表展示
def serverAques(request):
    aques =Aquestions .objects.filter(is_status=1)
    context ={'aques':aques}
    return render(request,'server/server_aques.html',context=context)

#查看模拟题附件详情
def detailserAqu(request):
    ser_aqu_id = request.POST.get('ser_aqu_id',None)
    ser_aqu = Aquestions.objects.get(id=ser_aqu_id)
    return render(request,'server/detail_ser_aqu.html',context={'ser_aqu':ser_aqu})

#添加新模拟题:获取新页面,五项都不允许为空
def addserAqu(request):
    que_school = Schools.objects.filter(is_status=1)
    context = {
        'ques_school': que_school,
    }
    return render(request, 'server/add_ser_aqu.html',context=context)

#获取院校id，反向获取到专业信息表的所有院校对应专业id（无重复名称的）
def get_maj(request):
    schid = request.POST.get('schid',None)
    info = Majors.objects.filter(school_id=schid,is_status=1)
    # print(info)
    # list = []
    # for item in info.all():
    #     list.append([item.id,item.major_name])

    lis = []
    lis2=[]
    for ite in info.all():
        if ite.major_name not in lis:
            lis.append(ite.major_name)
    print(lis)
    for i in lis:
        info1 = Majors.objects.filter(major_name=i).first()
        # print(info1.id)
        lis2.append(info1.id)
    print(lis2)
    #接下来就是把列表合并为一个，就可
    listss =[]
    lists = list(zip(lis2, lis))
    for item in lists:
        listss.append([item[0], item[1]])
    return JsonResponse({'data':listss})

#通过专业列表的id，得到专业名，再得到专业名和院校id匹配到的所有层次
def get_lev(request):
    majid = request.POST.get('majid',None)
    school =request.POST.get('school',None)
    # print(school)
    info = Majors.objects.get(id=majid)
    info2 = Majors.objects.filter(major_name=info.major_name,school_id=school,is_status=1)
    # print(info2)
    list = []
    for item in info2.all():
        level = ''
        if item.level == 0:
            level = '高起专'
        elif item.level == 1:
            level = '高起本'
        elif item.level == 2:
            level = '专升本'
        list.append([item.level, level])
    return JsonResponse({'data': list})

#添加模拟题:上传数据,都不能为空
def addssserAqu(request):
    ques_name = request.POST.get('ques_name')
    ques_filename=request.POST.get('ques_filename')
    ques_school = request.POST.get('ques_school')
    ques_major = request.POST.get('ques_major')
    ques_level = request.POST.get('ques_level')  #实际取到的值是0/1/2，并不能传入

    #判断是否存在
    info = Aquestions.objects.filter(ques_name=ques_name,ques_filename=ques_filename,is_status=1).exists()
    # print(info)
    if info or ques_school==' ' or ques_major==' ' or ques_level==' ':
        return JsonResponse({
            'status': 'fail',
            'message': '模拟题已存在或必填项未填写！',#在html写了框，没有用到这个
            'info': ''
        })
    # 专业id获取名称，通过名称和输入框传来的层次值（精确些还需要筛选order_school这个条件），查找到专业的id及其层次id
    mjid = Majors.objects.get(id=ques_major)
    qu_level=Majors.objects.get(major_name=mjid.major_name,level=ques_level,school_id=ques_school)
    # print(qu_level.id,qu_level.major_name)
    Aquestions.objects.create(
        ques_name=ques_name,
        ques_filename=ques_filename,
        ques_school_id=ques_school,
        ques_major_id=ques_major,
        ques_level_id=qu_level.id
    )
    return JsonResponse({
        'status': 'success',
        'message': '创建成功',
        'info': ''
    })

#删除模拟题，其实是把status变为0
def delserAqu(request):
    ser_aqu_id=request.GET.get('ser_aqu_id')
    ser_aqu = Aquestions.objects.get(id=ser_aqu_id)
    context={'ser_aqu':ser_aqu}
    is_status = 0
    ser_aqu.is_status = is_status
    ser_aqu.save()
    return render(request, 'server/server_aques.html', context=context)

#编辑模拟题附件:接收数据
#相同学校，相同专业名，不同层次，使之只显示一次专业名
def editserAqu(request):
    ser_aqu_id = request.GET.get('ser_aqu_id',None)
    ser_aqu = Aquestions.objects.get(id=ser_aqu_id)
    #下拉出的学校和专业列表，不包含is_status=0的，和当前这条数据的学校名和专业名
    ques_school = Schools.objects.filter(is_status=1).exclude(name=ser_aqu.ques_school.name)
    ques_major = Majors.objects.filter(is_status=1).exclude(major_name =ser_aqu.ques_major.major_name)
    majors = Majors.objects.filter(major_name=ser_aqu.ques_major.major_name,school_id=ser_aqu.ques_school.id,is_status=1).exclude(level=ser_aqu.ques_level.level)
    q_mj = Majors.objects.values('major_name').distinct().filter(is_status=1).exclude(major_name =ser_aqu.ques_major.major_name)
    q_mj_lis = []
    for i in q_mj:
        # print(i['major_name'])  #再通过名字和school_id取到符合条件的第一个
        q_mj2 = Majors.objects.filter(major_name=i['major_name'],school_id=ser_aqu.ques_school.id).first()
        if q_mj2 !=None:
            q_mj_lis.append(q_mj2)
    # print(q_mj_lis)
    context = {
        'ser_aqu':ser_aqu,
        'ques_school':ques_school,
        'ques_major':ques_major,
        'q_mj_lis':q_mj_lis,
        'majors':majors,
    }
    return render(request,'server/edit_ser_aqu.html',context=context)

#编辑模拟题附件：上传数据
def updateserAqu(request):
    # 获取数据
    data = request.POST.get('data', None)
    ser_aquid = request.POST.get('ser_aquid', None)

    data = json.loads(data)
    aqu = Aquestions.objects.get(id=ser_aquid)
    if data['ques_school'] != '':
        aqu.ques_school = Schools.objects.get(id=data['ques_school'])
        if data['ques_major'] != '':
            aqu.ques_major = Majors.objects.get(id=data['ques_major'])
            if data['ques_level'] !='':
                #data['ques_level']得到的值其实是0/1/2
                # print(mj.major_name)
                # print(data['ques_level'])
                mj =Majors.objects.get(id=data['ques_major'])
                aqu.ques_level = Majors.objects.get(major_name=mj.major_name,level=data['ques_level'],school_id=data['ques_school'])
                # print(aqu.ques_level)

    if data['ques_name'] != '':
        aqu.ques_name = data['ques_name']

    if data['ques_filename'] != '':
        aqu.ques_filename = data['ques_filename']

    aqu.save()
    return JsonResponse({
        "status": "success",
        "message": "信息更改成功",
        "info": ""
    })

#已删除服务中心文章列表展示
def deldserPos(request):
    server_post =ServerPosts .objects.filter(is_status=0)
    context ={'server_post':server_post}
    return render(request,'server/deld_ser_pos.html',context=context)

#已删除服务中心分类展示
def deldserCates(request):
    server_cates =ServerCategorys .objects.filter(is_status=0)
    context ={'server_cates':server_cates}
    return render(request,'server/deld_ser_cates.html',context=context)

#已删除教学中心列表展示
def deldserCenter(request):
    center =Centers .objects.filter(is_status=0)
    context ={'center':center}
    return render(request,'server/deld_ser_center.html',context=context)

#已删除附件表展示
def deldserAtta(request):
    atta =Attachments .objects.filter(is_status=0)
    context ={'atta':atta}
    return render(request,'server/deld_ser_atta.html',context=context)

#已删除模拟题表展示
def deldserAqu(request):
    aques =Aquestions .objects.filter(is_status=0)
    context ={'aques':aques}
    return render(request,'server/deld_ser_aqu.html',context=context)

#还原服务文章，其实是把status变为1
def posserPos(request):
    ser_pos_id=request.GET.get('ser_pos_id')
    ser_posts = ServerPosts.objects.get(id=ser_pos_id)
    context={'ser_posts':ser_posts}
    is_status = 1
    ser_posts.is_status = is_status
    ser_posts.save()
    return render(request, 'server/deld_ser_pos.html', context=context)

#还原服务分类，其实是把status变为1
def catesserCates(request):
    ser_cates_id=request.GET.get('ser_cates_id')
    ser_cates = ServerCategorys.objects.get(id=ser_cates_id)
    context={'ser_cates':ser_cates}
    is_status = 1
    ser_cates.is_status = is_status
    ser_cates.save()
    return render(request, 'server/deld_ser_cates.html', context=context)

#还原教学中心，其实是把status变为1
def centerserCenter(request):
    ser_center_id=request.GET.get('ser_center_id')
    ser_center = Centers.objects.get(id=ser_center_id)
    context={'ser_center':ser_center}
    is_status = 1
    ser_center.is_status = is_status
    ser_center.save()
    return render(request, 'server/deld_ser_center.html', context=context)

#还原附件，其实是把status变为1
def attaserAtta(request):
    ser_atta_id=request.GET.get('ser_atta_id')
    ser_atta = Attachments.objects.get(id=ser_atta_id)
    context={'ser_atta':ser_atta}
    is_status = 1
    ser_atta.is_status = is_status
    ser_atta.save()
    return render(request, 'server/deld_ser_atta.html', context=context)

#还原模拟题，其实是把status变为1
def aquserAqu(request):
    ser_aqu_id=request.GET.get('ser_aqu_id')
    ser_aqu = Aquestions.objects.get(id=ser_aqu_id)
    context={'ser_aqu':ser_aqu}
    is_status = 1
    ser_aqu.is_status = is_status
    ser_aqu.save()
    return render(request, 'server/deld_ser_aqu.html', context=context)

#永久删除服务文章，删除存在数据库的信息
def delesserPos(request):
    #获取id
    ser_pos_id = request.GET.get('ser_pos_id')
    ser_posts = ServerPosts.objects.get(id=ser_pos_id)
    context = {'ser_posts': ser_posts}
    ServerPosts.objects.get(id=ser_pos_id).delete()
    return render(request,'server/deld_ser_pos.html',context=context)

#永久删除服务分类，删除存在数据库的信息
def delesserCates(request):
    #获取id
    ser_cates_id = request.GET.get('ser_cates_id')
    ser_cates = ServerCategorys.objects.get(id=ser_cates_id)
    context = {'ser_cates': ser_cates}
    ServerCategorys.objects.get(id=ser_cates_id).delete()
    return render(request,'server/deld_ser_cates.html',context=context)

#永久删除教学中心，删除存在数据库的信息
def delesserCenter(request):
    #获取id
    ser_center_id = request.GET.get('ser_center_id')
    ser_center = Centers.objects.get(id=ser_center_id)
    context = {'ser_center': ser_center}
    Centers.objects.get(id=ser_center_id).delete()
    return render(request,'server/deld_ser_center.html',context=context)

#永久删除附件，删除存在数据库的信息
def delesserAtta(request):
    #获取id
    ser_atta_id = request.GET.get('ser_atta_id')
    ser_atta = Attachments.objects.get(id=ser_atta_id)
    context = {'ser_atta': ser_atta}
    Attachments.objects.get(id=ser_atta_id).delete()
    return render(request,'server/deld_ser_atta.html',context=context)

#永久删除模拟题附件，删除存在数据库的信息
def delesserAqu(request):
    #获取id
    ser_aqu_id = request.GET.get('ser_aqu_id')
    ser_aqu = Aquestions.objects.get(id=ser_aqu_id)
    context = {'ser_aqu': ser_aqu}
    Aquestions.objects.get(id=ser_aqu_id).delete()
    return render(request,'server/deld_ser_aqu.html',context=context)


num = int(input())

# DP = [[0] * 3 for _ in range(10**6)]
visited = [[0] * 3 for _ in range(10**6)]

result = 10**6
k = 0
while True:
    k += 1
    cnt = 0
    N = num
    # print('a', N)
    for i in range(10**6):
        if N % 3 == 0 and visited[i][0] == 0:      # 1번 명령어
            N //= 3
            visited[i][0] = 1
        elif N % 2 == 0 and visited[i][1] == 0:    # 2번 명령어
            N //= 2
            visited[i][1] = 1
        elif visited[i][2] == 0:   # 3번 명령어
            N -= 1
            visited[i][2] = 1
        # print('b', N)
        if N == 1:
            cnt = i + 1
            break
        if N == num:
            break
    # print(visited)
    if result > cnt and cnt != 0:
        result = cnt
    # print(i)
    if k > num:
        break
print(result)


#!/usr/bin/python
#coding=utf-8
#用于线程间通信 通过事件标识控制

import threading
from time import sleep,ctime

def wait_for_event(e):
    '''在事件被设置之前,一直等待'''
    print('等待事件开始')

    event_is_set = e.wait()	#事件没有被设置前,一直阻塞
    print('事件set1:%s'%event_is_set)

def wait_for_event_timeout(e,t):
    '''等待一段时间后,进行超时操作'''
    while not e.isSet():
        print('等待超时中')
        event_is_set = e.wait(t)  #等待t秒后,冲破阻塞
        print('事件set2:%s'%event_is_set)
        if event_is_set:
            print('事件被设置')
        else:
            print('事件未被设置')

e = threading.Event()

t1 = threading.Thread(name = 'block',target = wait_for_event,args = (e,))
t1.start()

t2 = threading.Thread(name = 'nonblock',target = wait_for_event_timeout,args = (e,2))
t2.start()

print('10秒后事件将被设置')
sleep(11)
e.set()
print('事件被设置')


import pandas as pd

dict_test = {
    'col1': [1, 2, 3],
    'col2': [4, 5, 6]
}

df_test = pd.DataFrame(dict_test)

df_test.to_excel('item_list.xlsx', index=False, sheet_name='item_list')
print('Process finished')


from __future__ import annotations

import typing
from typing import Any
from typing import cast
from typing import Dict
from typing import Generic
from typing import Iterator
from typing import List
from typing import Mapping
from typing import MutableMapping
from typing import Optional
from typing import overload
from typing import Tuple
from typing import Type
from typing import Union
import weakref

from .attr import _ClsLevelDispatch
from .attr import _EmptyListener
from .attr import _InstanceLevelDispatch
from .attr import _JoinedListener
from .registry import _ET
from .registry import _EventKey
from .. import util
from ..util.typing import Literal

_registrars: MutableMapping[
    str, List[Type[_HasEventsDispatch[Any]]]
] = util.defaultdict(list)

def _is_event_name(name: str) -> bool:
    # _sa_event prefix is special to support internal-only event names.
    # most event names are just plain method names that aren't
    # underscored.

    return (
        not name.startswith("_") and name != "dispatch"
    ) or name.startswith("_sa_event")

class _UnpickleDispatch:
    """Serializable callable that re-generates an instance of
    :class:`_Dispatch` given a particular :class:`.Events` subclass.

    """

    def __call__(self, _instance_cls: Type[_ET]) -> _Dispatch[_ET]:
        for cls in _instance_cls.__mro__:
            if "dispatch" in cls.__dict__:
                return cast(
                    "_Dispatch[_ET]", cls.__dict__["dispatch"].dispatch
                )._for_class(_instance_cls)
        else:
            raise AttributeError("No class with a 'dispatch' member present.")

class _DispatchCommon(Generic[_ET]):
    __slots__ = ()

    _instance_cls: Optional[Type[_ET]]

    def _join(self, other: _DispatchCommon[_ET]) -> _JoinedDispatcher[_ET]:
        raise NotImplementedError()

    def __getattr__(self, name: str) -> _InstanceLevelDispatch[_ET]:
        raise NotImplementedError()

    @property
    def _events(self) -> Type[_HasEventsDispatch[_ET]]:
        raise NotImplementedError()

class _Dispatch(_DispatchCommon[_ET]):
    """Mirror the event listening definitions of an Events class with
    listener collections.

    Classes which define a "dispatch" member will return a
    non-instantiated :class:`._Dispatch` subclass when the member
    is accessed at the class level.  When the "dispatch" member is
    accessed at the instance level of its owner, an instance
    of the :class:`._Dispatch` class is returned.

    A :class:`._Dispatch` class is generated for each :class:`.Events`
    class defined, by the :meth:`._HasEventsDispatch._create_dispatcher_class`
    method.  The original :class:`.Events` classes remain untouched.
    This decouples the construction of :class:`.Events` subclasses from
    the implementation used by the event internals, and allows
    inspecting tools like Sphinx to work in an unsurprising
    way against the public API.

    """

    # "active_history" is an ORM case we add here.   ideally a better
    # system would be in place for ad-hoc attributes.
    __slots__ = "_parent", "_instance_cls", "__dict__", "_empty_listeners"

    _active_history: bool

    _empty_listener_reg: MutableMapping[
        Type[_ET], Dict[str, _EmptyListener[_ET]]
    ] = weakref.WeakKeyDictionary()

    _empty_listeners: Dict[str, _EmptyListener[_ET]]

    _event_names: List[str]

    _instance_cls: Optional[Type[_ET]]

    _joined_dispatch_cls: Type[_JoinedDispatcher[_ET]]

    _events: Type[_HasEventsDispatch[_ET]]
    """reference back to the Events class.

    Bidirectional against _HasEventsDispatch.dispatch

    """

    def __init__(
        self,
        parent: Optional[_Dispatch[_ET]],
        instance_cls: Optional[Type[_ET]] = None,
    ):
        self._parent = parent
        self._instance_cls = instance_cls

        if instance_cls:
            assert parent is not None
            try:
                self._empty_listeners = self._empty_listener_reg[instance_cls]
            except KeyError:
                self._empty_listeners = self._empty_listener_reg[
                    instance_cls
                ] = {
                    ls.name: _EmptyListener(ls, instance_cls)
                    for ls in parent._event_descriptors
                }
        else:
            self._empty_listeners = {}

    def __getattr__(self, name: str) -> _InstanceLevelDispatch[_ET]:
        # Assign EmptyListeners as attributes on demand
        # to reduce startup time for new dispatch objects.
        try:
            ls = self._empty_listeners[name]
        except KeyError:
            raise AttributeError(name)
        else:
            setattr(self, ls.name, ls)
            return ls

    @property
    def _event_descriptors(self) -> Iterator[_ClsLevelDispatch[_ET]]:
        for k in self._event_names:
            # Yield _ClsLevelDispatch related
            # to relevant event name.
            yield getattr(self, k)

    def _listen(self, event_key: _EventKey[_ET], **kw: Any) -> None:
        return self._events._listen(event_key, **kw)

    def _for_class(self, instance_cls: Type[_ET]) -> _Dispatch[_ET]:
        return self.__class__(self, instance_cls)

    def _for_instance(self, instance: _ET) -> _Dispatch[_ET]:
        instance_cls = instance.__class__
        return self._for_class(instance_cls)

    def _join(self, other: _DispatchCommon[_ET]) -> _JoinedDispatcher[_ET]:
        """Create a 'join' of this :class:`._Dispatch` and another.

        This new dispatcher will dispatch events to both
        :class:`._Dispatch` objects.

        """
        if "_joined_dispatch_cls" not in self.__class__.__dict__:
            cls = type(
                "Joined%s" % self.__class__.__name__,
                (_JoinedDispatcher,),
                {"__slots__": self._event_names},
            )
            self.__class__._joined_dispatch_cls = cls
        return self._joined_dispatch_cls(self, other)

    def __reduce__(self) -> Union[str, Tuple[Any, ...]]:
        return _UnpickleDispatch(), (self._instance_cls,)

    def _update(
        self, other: _Dispatch[_ET], only_propagate: bool = True
    ) -> None:
        """Populate from the listeners in another :class:`_Dispatch`
        object."""
        for ls in other._event_descriptors:
            if isinstance(ls, _EmptyListener):
                continue
            getattr(self, ls.name).for_modify(self)._update(
                ls, only_propagate=only_propagate
            )

    def _clear(self) -> None:
        for ls in self._event_descriptors:
            ls.for_modify(self).clear()

def _remove_dispatcher(cls: Type[_HasEventsDispatch[_ET]]) -> None:
    for k in cls.dispatch._event_names:
        _registrars[k].remove(cls)
        if not _registrars[k]:
            del _registrars[k]

class _HasEventsDispatch(Generic[_ET]):
    _dispatch_target: Optional[Type[_ET]]
    """class which will receive the .dispatch collection"""

    dispatch: _Dispatch[_ET]
    """reference back to the _Dispatch class.

    Bidirectional against _Dispatch._events

    """

    if typing.TYPE_CHECKING:

        def __getattr__(self, name: str) -> _InstanceLevelDispatch[_ET]:
            ...

    def __init_subclass__(cls) -> None:
        """Intercept new Event subclasses and create associated _Dispatch
        classes."""

        cls._create_dispatcher_class(cls.__name__, cls.__bases__, cls.__dict__)

    @classmethod
    def _accept_with(
        cls, target: Union[_ET, Type[_ET]], identifier: str
    ) -> Optional[Union[_ET, Type[_ET]]]:
        raise NotImplementedError()

    @classmethod
    def _listen(
        cls,
        event_key: _EventKey[_ET],
        *,
        propagate: bool = False,
        insert: bool = False,
        named: bool = False,
        asyncio: bool = False,
    ) -> None:
        raise NotImplementedError()

    @staticmethod
    def _set_dispatch(
        klass: Type[_HasEventsDispatch[_ET]],
        dispatch_cls: Type[_Dispatch[_ET]],
    ) -> _Dispatch[_ET]:
        # This allows an Events subclass to define additional utility
        # methods made available to the target via
        # "self.dispatch._events.<utilitymethod>"
        # @staticmethod to allow easy "super" calls while in a metaclass
        # constructor.
        klass.dispatch = dispatch_cls(None)
        dispatch_cls._events = klass
        return klass.dispatch

    @classmethod
    def _create_dispatcher_class(
        cls, classname: str, bases: Tuple[type, ...], dict_: Mapping[str, Any]
    ) -> None:
        """Create a :class:`._Dispatch` class corresponding to an
        :class:`.Events` class."""

        # there's all kinds of ways to do this,
        # i.e. make a Dispatch class that shares the '_listen' method
        # of the Event class, this is the straight monkeypatch.
        if hasattr(cls, "dispatch"):
            dispatch_base = cls.dispatch.__class__
        else:
            dispatch_base = _Dispatch

        event_names = [k for k in dict_ if _is_event_name(k)]
        dispatch_cls = cast(
            "Type[_Dispatch[_ET]]",
            type(
                "%sDispatch" % classname,
                (dispatch_base,),
                {"__slots__": event_names},
            ),
        )

        dispatch_cls._event_names = event_names
        dispatch_inst = cls._set_dispatch(cls, dispatch_cls)
        for k in dispatch_cls._event_names:
            setattr(dispatch_inst, k, _ClsLevelDispatch(cls, dict_[k]))
            _registrars[k].append(cls)

        for super_ in dispatch_cls.__bases__:
            if issubclass(super_, _Dispatch) and super_ is not _Dispatch:
                for ls in super_._events.dispatch._event_descriptors:
                    setattr(dispatch_inst, ls.name, ls)
                    dispatch_cls._event_names.append(ls.name)

        if getattr(cls, "_dispatch_target", None):
            dispatch_target_cls = cls._dispatch_target
            assert dispatch_target_cls is not None
            if (
                hasattr(dispatch_target_cls, "__slots__")
                and "_slots_dispatch" in dispatch_target_cls.__slots__
            ):
                dispatch_target_cls.dispatch = slots_dispatcher(cls)
            else:
                dispatch_target_cls.dispatch = dispatcher(cls)

class Events(_HasEventsDispatch[_ET]):
    """Define event listening functions for a particular target type."""

    @classmethod
    def _accept_with(
        cls, target: Union[_ET, Type[_ET]], identifier: str
    ) -> Optional[Union[_ET, Type[_ET]]]:
        def dispatch_is(*types: Type[Any]) -> bool:
            return all(isinstance(target.dispatch, t) for t in types)

        def dispatch_parent_is(t: Type[Any]) -> bool:
            return isinstance(
                cast("_JoinedDispatcher[_ET]", target.dispatch).parent, t
            )

        # Mapper, ClassManager, Session override this to
        # also accept classes, scoped_sessions, sessionmakers, etc.
        if hasattr(target, "dispatch"):
            if (
                dispatch_is(cls.dispatch.__class__)
                or dispatch_is(type, cls.dispatch.__class__)
                or (
                    dispatch_is(_JoinedDispatcher)
                    and dispatch_parent_is(cls.dispatch.__class__)
                )
            ):
                return target

        return None

    @classmethod
    def _listen(
        cls,
        event_key: _EventKey[_ET],
        *,
        propagate: bool = False,
        insert: bool = False,
        named: bool = False,
        asyncio: bool = False,
    ) -> None:
        event_key.base_listen(
            propagate=propagate, insert=insert, named=named, asyncio=asyncio
        )

    @classmethod
    def _remove(cls, event_key: _EventKey[_ET]) -> None:
        event_key.remove()

    @classmethod
    def _clear(cls) -> None:
        cls.dispatch._clear()

class _JoinedDispatcher(_DispatchCommon[_ET]):
    """Represent a connection between two _Dispatch objects."""

    __slots__ = "local", "parent", "_instance_cls"

    local: _DispatchCommon[_ET]
    parent: _DispatchCommon[_ET]
    _instance_cls: Optional[Type[_ET]]

    def __init__(
        self, local: _DispatchCommon[_ET], parent: _DispatchCommon[_ET]
    ):
        self.local = local
        self.parent = parent
        self._instance_cls = self.local._instance_cls

    def __getattr__(self, name: str) -> _JoinedListener[_ET]:
        # Assign _JoinedListeners as attributes on demand
        # to reduce startup time for new dispatch objects.
        ls = getattr(self.local, name)
        jl = _JoinedListener(self.parent, ls.name, ls)
        setattr(self, ls.name, jl)
        return jl

    def _listen(self, event_key: _EventKey[_ET], **kw: Any) -> None:
        return self.parent._listen(event_key, **kw)

    @property
    def _events(self) -> Type[_HasEventsDispatch[_ET]]:
        return self.parent._events

class dispatcher(Generic[_ET]):
    """Descriptor used by target classes to
    deliver the _Dispatch class at the class level
    and produce new _Dispatch instances for target
    instances.

    """

    def __init__(self, events: Type[_HasEventsDispatch[_ET]]):
        self.dispatch = events.dispatch
        self.events = events

    @overload
    def __get__(
        self, obj: Literal[None], cls: Type[Any]
    ) -> Type[_Dispatch[_ET]]:
        ...

    @overload
    def __get__(self, obj: Any, cls: Type[Any]) -> _DispatchCommon[_ET]:
        ...

    def __get__(self, obj: Any, cls: Type[Any]) -> Any:
        if obj is None:
            return self.dispatch

        disp = self.dispatch._for_instance(obj)
        try:
            obj.__dict__["dispatch"] = disp
        except AttributeError as ae:
            raise TypeError(
                "target %r doesn't have __dict__, should it be "
                "defining _slots_dispatch?" % (obj,)
            ) from ae
        return disp

class slots_dispatcher(dispatcher[_ET]):
    def __get__(self, obj: Any, cls: Type[Any]) -> Any:
        if obj is None:
            return self.dispatch

        if hasattr(obj, "_slots_dispatch"):
            return obj._slots_dispatch

        disp = self.dispatch._for_instance(obj)
        obj._slots_dispatch = disp
        return disp


import json
import torch
from SAC.Agent import AgentV2

if __name__ == "__main__":
    jsonFilePath = "./cfg/RealTrain.json"

    with open(jsonFilePath) as file:
        json_dict = json.load(file)
        agentDict = json_dict['Agent']

    x = AgentV2(agentDict)

    rstate = torch.zeros((32, 8))
    lidarpt = torch.zeros((32, 1, 360))
    image = torch.zeros((32, 1, 96, 96))

    y = x.forward((rstate, lidarpt, image))
    print("here")


from IPython import display
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from gym.envs.mujoco import *
from envs.hopper_env import HopperModEnv
from envs.cheetah_env import CheetahModEnv
import numpy as np
import copy
import gym
from scipy.io import loadmat
from scipy.io import savemat
import moviepy.editor as mpy
from simulators import *
from rot_utils import *
import seaborn as sns
sns.set_style('darkgrid')
import warnings
warnings.filterwarnings('ignore')
from part_a import lqr_infinite_horizon

# implement linearization about a point
def linearize_dynamics(f, x_ref, u_ref, dt, my_eps, x_ref_tplus1=None):
    """
    f : dynamics simulator
    my_eps : delta for forward and backward differences you'll need
    NOTE: please use centered finite differences!

    x(:,t+1) - x_ref  approximately = A*( x(:,t)-x_ref ) + B* ( u(:,t) - u_ref ) + c
    If we pick x_ref and u_ref to constitute a fixed point, then c == 0

    For part (b), you do not need to use the optional argument (nor c).
    For part (d), you'll have to revisit and modify this function
        --at this point, you'll want to use the optional argument and the resulting c.

    return: A, B, c
    """

    if x_ref_tplus1 is not None:
        x_ref_next = x_ref_tplus1
    else:
        x_ref_next = x_ref

    dx, du = x_ref.shape[0], u_ref.shape[0]
    A, B = np.zeros((dx, dx)), np.zeros((dx, du))

    """YOUR CODE HERE"""
    for i in range(dx):
        delta_x = np.zeros((dx,))
        delta_x[i] = my_eps
        f_x_forward = f(x_ref + delta_x, u_ref, dt)
        f_x_backward = f(x_ref - delta_x, u_ref, dt)
        f_derivatives = (f_x_forward - f_x_backward) / (2 * my_eps)
        A[:, i] = f_derivatives

    for j in range(du):
        delta_u = np.zeros((du,))
        delta_u[j] = my_eps
        f_x_forward = f(x_ref, u_ref + delta_u, dt)
        f_x_backward = f(x_ref, u_ref - delta_u, dt)
        f_derivatives = (f_x_forward - f_x_backward) / (2 * my_eps)
        B[:, j] = f_derivatives

    """YOUR CODE ENDS HERE"""

    c = f(x_ref, u_ref, dt) - x_ref_next
    if x_ref_tplus1 is not None:
        A = np.hstack([A, c.reshape(-1,1)])
        A = np.vstack([A, np.zeros(A.shape[1])])
        A[-1,-1] = 1
        B = np.vstack([B, np.zeros(B.shape[1])])

    if len(B.shape) == 1:
        return A, B.reshape(-1, 1), c
    return A, B, c

# take an environment and find the infinite horizon controller for the linearized system
def lqr_nonlinear(config):
    env = config['env']
    f = config['f']
    dt = 0.1  # we work with discrete time
    my_eps = 0.01  # finite difference for numerical differentiation

    # load in our reference points
    x_ref, u_ref = config['x_ref'], config['u_ref']

    # linearize
    A, B, c = linearize_dynamics(f, x_ref, u_ref, dt, my_eps)
    print('A shape: ', A.shape, 'B shape: ', B.shape)
    dx, du = A.shape[0], B.shape[1]
    Q, R = np.eye(dx), np.eye(du) * 2

    # solve for the linearized system
    K_inf, P_inf = lqr_infinite_horizon(A, B, Q, R)  # you implemented in part (a)

    # recognize the simulation code from part (a)? modify it to use your controller at each timestep
    def simulate(K_inf, f, x_ref, u_ref, dt, n_starting_states, T, noise=None):
        for s in np.arange(n_starting_states):
            x, u = np.zeros((K_inf.shape[1], T + 1)), np.zeros((K_inf.shape[0], T + 1))
            x[:, 0] = starting_states[:, s]
            for t in np.arange(T):
                """YOUR CODE HERE"""
                u[:, t] = u_ref + K_inf @ (x[:, t] - x_ref)
                """YOUR CODE ENDS HERE"""
                x[:, t + 1] = f(x[:, t], u[:, t], dt)
                if "p_val" in config.keys():
                    perturbation_values = config["p_val"]
                    perturb = perturbation_values[t // (T // len(perturbation_values))]
                    x[:, t + 1] = f(x[:, t], u[:, t], dt, rollout=True, perturb=perturb)
                if env is not None:
                    if t % 5 == 0:
                        plt.clf()
                        plt.axis('off')
                        plt.grid(b=None)
                        plt.imshow(env.render(mode='rgb_array', width=256, height=256))
                        plt.title("Perturbation Magnitude {}".format(perturb))
                        display.clear_output(wait=True)
                        display.display(plt.gcf())

                if noise is not None:
                    x[:, t + 1] += noise[:, t]
            if env is not None:
                plt.clf()

            plt.plot(x.T[:-1], linewidth=.6)
            plt.plot(np.squeeze(u.T[:-1]) / 10.0, linewidth=.7, linestyle='--')  # scaling for clarity
            if 'legend' in config.keys():
                config['legend'].append('u')
                plt.legend(config['legend'])
            else:
                legend_elements = [Line2D([0], [0], label='x'), Line2D([0], [0], linestyle='--', label='u')]
                plt.legend(handles=legend_elements)
            plt.xlabel('time')
            plt.title(config["exp_name"])
            plt.show()

    # now let's simulate and see what happens for a few different starting states
    starting_states = config['ss']
    n_starting_states = starting_states.shape[1]
    T = config['steps']  # simulating for T steps
    simulate(K_inf, f, x_ref, u_ref, dt, n_starting_states, T)
    if 'noise' in config.keys():
        # and now in the presence of noise
        noise_id = config['noise']
        noise_loaded = loadmat("mats/" + noise_id + ".mat")[noise_id]
        simulate(K_inf, f, x_ref, u_ref, dt, n_starting_states, noise_loaded.shape[1], noise=noise_loaded)

if __name__ == "__main__":

    runCartPole = 1
    runHelicopter = 0
    runHopper = 0
    if runCartPole:
        # Find the infinite horizon controller for the linearized version of the cartpole balancing problem
        cartpole_config = {
            'f': sim_cartpole,
            'exp_name': "Cartpole-Balancing",
            'env': None,
            'steps': 500,
            'x_ref': np.array([0, np.pi, 0, 0]),
            'u_ref': np.array([0]),
            'legend':['x', 'theta', 'xdot', 'thetadot'],
            'ss': np.array([[0, 0, 0, 10, 50],
                            [9*np.pi/10, 3*np.pi/4, np.pi/2, 0, 0],
                            [0, 0, 0, 0, 0],
                            [0, 0, 0, 0, 0]]), #ss = starting states
            'noise': 'p_b_w',
        }
        lqr_nonlinear(cartpole_config)

    if runHelicopter:
        # Find the infinite horizon controller for the linearized version of the hovering copter
        # Just run the cell below to generate plots using the code you wrote for cartpole!
        x_ref, u_ref = np.zeros(12), np.zeros(4)
        x_ref[9] = np.arcsin(3.0 / (5 * 9.81))
        u_ref[3] = 9.81 * 5 * np.cos(x_ref[9]) / 137.5
        heli_config = {
            'f': sim_heli,
            'env': None,
            'exp_name': "Helicopter-Hovering",
            'steps': 200,
            'x_ref': x_ref,
            'u_ref': u_ref,
            'ss': loadmat("mats/p_c_heli_starting_states.mat")["heli_starting_states"],  # ss = starting states
            'noise': 'p_c_w',
        }
        lqr_nonlinear(heli_config)

    if runHopper:
        env = HopperModEnv()
        x_ref, u_ref = np.zeros(11), np.zeros(env.action_space.sample().shape[0])
        hopper_config = {
            'env': env,
            'f': env.f_sim,
            'exp_name': "Perturbed Hopper",
            'steps': 500,
            'x_ref': x_ref,
            'u_ref': u_ref,
            'ss': np.array([[np.concatenate([env.init_qpos[1:], env.init_qvel])]]),
            'p_val': [0, .1, 1, 10]
        }
        lqr_nonlinear(hopper_config)


from typing import List

class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:
        n = len(nums)
        if n == 0 or 1 not in nums:
            return 1
        i = 0
        while i < n:
            idx = nums[i] - 1
            if 0 <= idx < n and nums[idx] != nums[i]:
                nums[i], nums[idx] = nums[idx], nums[i]
            else:
                i += 1
        for i in range(n):
            if nums[i] != i + 1:
                return i + 1
        return n + 1


# File : fileName.py
# Author : your name
# Saibt Id : your saibt id
# Description : Assignment 2   place assignment description here . . .
# This is my own work as defined by the University ’s
# Academic Misconduct pol icy .

# Function length() - get the length of given list, return the length
def length(my_list):
	counter = 0
	for i in my_list:
		counter += 1
	return counter

# Function to_string() - parse list to string, return a string
def to_string(my_list, sep=', '):
	if length(my_list) == 0:
		return ""
	output = ""
	for i in range(length(my_list)-1):
		output = output + str(my_list[i]) + sep
	output = output + str(my_list[length(my_list)-1])
	return output

# Function count() - count the occurence of specified char in list
def count(my_list, value):
	counter = 0
	for item in my_list:
		if item == value:
			counter +=1
	return counter

# Function find() - find the value in the list , return index of the value
def find(my_list, value):
	for index in range(length(my_list)):
		if my_list[index] == value:
			return index
	return -1

# Function insert_value() - insert a value into list, return a new list
def insert_value(my_list, value, insert_position):
	lst_length = length(my_list)
	# if insert position less than 0
	if insert_position <=0:
		return [value] + my_list
	# if insert position greater than the length
	if insert_position >= lst_length:
		return my_list + [value]
	array = []
	for i in range(0, insert_position):
		array.append(my_list[i])
	array.append(value)
	for i in range(insert_position, lst_length):
		array.append(my_list[i])
	return array

# Function remove_value() - remove a value in the specified index, return the new list
def remove_value(my_list, remove_position):
	lst_length = length(my_list)
	result = []
	# if remvoe position less than 0
	if remove_position <= 0:
		for i in range(1, lst_length):
			result.append(my_list[i])
		return result
	# if remove position great than length
	if remove_position >= lst_length:
		for i in range(0, lst_length-1):
			result.append(my_list[i])
		return result

	for i in range(0, remove_position):
		result.append(my_list[i])
	for i in range(remove_position+1, lst_length):
		result.append(my_list[i])
	return result


"""Remove order in shop product and replace with the unwieldy row/column again :/

Revision ID: 4f786f3c132b
Revises: 2d4ea6b57d6e
Create Date: 2016-03-20 07:11:09.422825

"""

# revision identifiers, used by Alembic.
revision = '4f786f3c132b'
down_revision = '2d4ea6b57d6e'

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('Shop_product', sa.Column('column', sa.Integer(), nullable=True))
    op.add_column('Shop_product', sa.Column('row', sa.Integer(), nullable=True))
    op.drop_column('Shop_product', 'order')
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('permission', 'user_id',
               existing_type=mysql.INTEGER(display_width=11),
               nullable=False)
    op.add_column('Shop_product', sa.Column('order', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True))
    op.drop_column('Shop_product', 'row')
    op.drop_column('Shop_product', 'column')
    op.create_table('backup_Class_description',
    sa.Column('description_id', mysql.INTEGER(display_width=11), server_default=sa.text(u"'0'"), autoincrement=False, nullable=False),
    sa.Column('order', mysql.SMALLINT(display_width=5, unsigned=True), autoincrement=False, nullable=False),
    sa.Column('title', mysql.VARCHAR(length=255), nullable=False),
    sa.Column('abbr', mysql.VARCHAR(length=255), nullable=False),
    sa.Column('description', mysql.LONGTEXT(), nullable=False),
    sa.Column('menu', mysql.LONGTEXT(), nullable=False),
    sa.Column('knife_level', mysql.VARCHAR(length=1), nullable=False),
    sa.Column('veggie_level', mysql.VARCHAR(length=1), nullable=False),
    sa.Column('dairy_level', mysql.VARCHAR(length=1), nullable=False),
    sa.Column('wheat_level', mysql.VARCHAR(length=1), nullable=False),
    sa.Column('cost_override', mysql.SMALLINT(display_width=5, unsigned=True), autoincrement=False, nullable=True),
    sa.Column('wine', mysql.VARCHAR(length=255), nullable=False),
    mysql_default_charset=u'latin1',
    mysql_engine=u'InnoDB'
    )
    op.create_table('gift_certificate',
    sa.Column('certificate_id', mysql.INTEGER(display_width=11), nullable=False),
    sa.Column('campus_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),
    sa.Column('created', mysql.DATETIME(), nullable=True),
    sa.Column('sender_name', mysql.VARCHAR(length=100), nullable=True),
    sa.Column('sender_email', mysql.VARCHAR(length=75), nullable=True),
    sa.Column('sender_phone', mysql.VARCHAR(length=20), nullable=True),
    sa.Column('amount_to_give', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),
    sa.Column('recipient_name', mysql.VARCHAR(length=100), nullable=True),
    sa.Column('recipient_email', mysql.VARCHAR(length=75), nullable=True),
    sa.Column('message', mysql.TEXT(), nullable=True),
    sa.Column('giftcard', mysql.TINYINT(display_width=1), autoincrement=False, nullable=True),
    sa.Column('date_sent', sa.DATE(), nullable=True),
    sa.Column('name_on_envelope', mysql.VARCHAR(length=255), nullable=True),
    sa.Column('street_address', mysql.VARCHAR(length=255), nullable=True),
    sa.Column('city', mysql.VARCHAR(length=100), nullable=True),
    sa.Column('state', mysql.VARCHAR(length=2), nullable=True),
    sa.Column('zip_code', mysql.VARCHAR(length=10), nullable=True),
    sa.Column('code', mysql.VARCHAR(length=10), nullable=True),
    sa.Column('creditcard_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),
    sa.Column('paid_with', mysql.VARCHAR(length=10), nullable=True),
    sa.Column('expiration_date', sa.DATE(), nullable=True),
    sa.ForeignKeyConstraint(['campus_id'], [u'Class_campus.campus_id'], name=u'gift_certificate_ibfk_1'),
    sa.PrimaryKeyConstraint('certificate_id'),
    mysql_default_charset=u'latin1',
    mysql_engine=u'InnoDB'
    )
    op.drop_table('forgot_password_links')
    ### end Alembic commands ###


import csv, json
from geojson import Feature, FeatureCollection, Point

features = []
with open('../data2.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    next(reader,None)
    for row in reader:
        # print(row[0])
        latitude, longitude = map(float, (row[1], row[0]))
        features.append(
            Feature(
                geometry = Point((longitude, latitude)),
                properties = {
                    'Unique_Squirrel_ID': row[2],
                }
            )
        )

collection = FeatureCollection(features)
with open("../map/static/map/GeoObs3.geojson", "w") as f:
    f.write('%s' % collection)


# 3

print('Члены ряда, подходящие под условие:\n')

print('-' * 30)

cnt = int(input('Кол-во чисел: '))

arr = []

c = 0

eps = float(input('Точность: '))

def factorial(a):
	n = 1
	while a > 1:
		n *= a
		a -= 1

	return n

while True:
	c += 1

	num = int(input('{} Число: '.format(c)))
	arr.append(num)

	if c == cnt:
		break

k = 0

print('')

for i in range(len(arr)):
	el = arr[i]
	num = (10**el) / factorial(el)

	if i > 0:
		pel = arr[i-1]
		if abs(el - pel) < eps:
			k += 1
			print('{}. {}'.format(k, num))
	else:
		if el < eps:
			k += 1
			print('{}. {}'.format(k, num))

print('\nИх количество: {}'.format(k))


import os
import logbook
import gossip

from .project import get_project
# from .celery_utils import celery_app

_logger = logbook.Logger(__name__)

_cached_app = None

_building = False

def build_app(*, use_cached=False, config_overrides=None):
    from flask import Flask

    global _cached_app  # pylint: disable=global-statement
    global _building    # pylint: disable=global-statement
    if use_cached and _cached_app is not None:
        return _cached_app

    if config_overrides is None:
        config_overrides = {}

    if os.environ.get('COB_TESTING'):
        config_overrides.update({'TESTING': True})

    if _building:
        raise RuntimeError('Attempted to create an app while an app was already being initialized!')

    _building = True
    try:
        proj = get_project()
        _logger.debug('Starting app {.name}...', proj)
        _cached_app = Flask(get_project().name, static_folder=None, template_folder=None)
        _cached_app.config.update(config_overrides)
        proj.configure_app(_cached_app)
        gossip.trigger_with_tags('cob.after_configure_app', {'app': _cached_app})
        _logger.trace('URL map: {}', _cached_app.url_map)
        return _cached_app
    finally:
        _building = False


# CPE 101-01
# LAB 8: File i/o
# Name: Tyler Baxter
# Section: 03

# main function that runs the code
# none -> none
def main():
    file_r = open('std_info.txt', 'r')
    lst = read_file(file_r)
    file_w = open('student_avg.txt', 'w')
    write_average(file_w, write_file(lst, file_w))

# reads the file and puts the values into a list
# text file -> nested list
def read_file(file_r):
    lst = file_r.readlines()
    lst_new = []
    for i in range(len(lst)):
        x = lst[i].split()
        lst_new.append([])
        lst_new[i].append(x[0] + " " + x[1])
        lst_new[i].append(x[2])
        lst_new[i].append(float(x[3]))
    file_r.close()
    return lst_new

# writes the information from the old file as well class averages on the new file
# text file, text file -> list
def write_file(in_file, out_file):
    ee_avg = cpe_avg = total_avg = ee_cnt = cpe_cnt = total_cnt = 0
    for i in range(len(in_file)):
        out_file.write(str(in_file[i][0]) + ' ' + str(in_file[i][1]) + ' ' + str(in_file[i][2]) + '\n')
        if in_file[i][1] == "EE":
            ee_avg += in_file[i][2]
            total_avg += in_file[i][2]
            ee_cnt += 1
        elif in_file[i][1] == "CPE":
            cpe_avg += in_file[i][2]
            total_avg += in_file[i][2]
            cpe_cnt += 1
        else:
            total_avg += in_file[i][2]
        total_cnt += 1
    return [ee_avg, ee_cnt, cpe_avg, cpe_cnt, total_avg, total_cnt]

# this function computes and prints the averages to the new text file
# text file, list -> none
def write_average(out_file, averages):
    out_file.write('....' + '\n')
    out_file.write("EE average = " + str(averages[0] / averages[1]) + '\n')
    out_file.write("CPE average = " + str(averages[2] / averages[3]) + '\n')
    out_file.write("Total average = " + str(averages[4] / averages[5]) + '\n')
    out_file.close()

if __name__ == '__main__':
    main()


#reverse a number

num=input("Enter the number :")

length=len(num)

numrev=""

for i in range(0,length):
    numrev=numrev+num[length-1-i]

numrev=int(numrev)

print(f"\nThe reverse of {num} is {numrev}")


# hcm/util/file_utils.py
"""File utilities. """
import os
import sys
import logging
import pandas as pd

logger = logging.getLogger(__name__)
pd.set_option('display.width', 1000)

def days_suffix(obs_period):
    return obs_period.replace('-', '_').replace(' ', '_')

def progress(count, total, status=''):
    bar_len = 60
    filled_len = int(round(bar_len * count / float(total)))
    percents = round(100.0 * count / float(total), 1)
    bar = '=' * filled_len + '-' * (bar_len - filled_len)
    sys.stdout.write('[{}] {}{} ...{}\r'.format(bar, percents, '%', status))
    sys.stdout.flush()  # As suggested by Rom Ruben (see: http://stackoverflow.com/questions/3173320/text-progress
    #  #  -bar-in-the-console/27871113#comment50529068_27871113)

def dataroot():
    return "/data/HCM/"

def datadir(exp_name):  # day=None):
    """ TODO: Move this to the data field. """
    daydir = ""
    other_exp = ["2cD1A2aCRE", "2cD1A2aCRE2", "2CFast", "1ASTRESS", "Stress_HCMe1r1", "CORTTREAT", "HiFat2", "HiFat1"]
    if exp_name in other_exp:
        datadir_parent = ""
        data_dir = exp_name
    # if day is not None: daydir = "D%d" % (day + 1)
    # elif exp_name.startswith("SS_Data_051905_FV"):
    #     datadir, expround = self.name.split(":")
    #     datadir_parent = "EventFiles/EventFiles_SSe1r%s" % expround
    #     date = (self.start + datetime.timedelta(days=day)).strftime("%m%d%Y")
    #     daydir = "%se1r%sd%s" % (date, expround, day + 1)
    elif exp_name == "StrainSurvey":
        datadir_parent = ""
        data_dir = "SS_Data_051905_FV"
    elif exp_name.startswith("WR"):
        datadir_parent = "WR"
        data_dir = exp_name
    else:
        raise ValueError("Unknown experiment: {}".format(exp_name))
    return os.path.join(dataroot(), "Experiments", datadir_parent, data_dir, daydir)

def hcm_dir():
    dir_parent, sub_dir = None, None
    if os.uname()[1] == "giorgios-MacBook-Pro.local":
        dir_parent = "/Users/go"
        sub_dir = "Projects/HomeCageMonitoring/"
    return os.path.join(dir_parent, sub_dir)

def repo_dir():
    return os.path.join(hcm_dir(), "hcm2")

def find_files(path, ext='npy'):
    """ returns a generator over filenames in path """
    return (os.path.join(dirpath, f) for dirpath, _, files in os.walk(path) for f in sorted(files) if
            f.endswith('.{}'.format(ext)))

def mouseday_label_from_filename(fname, ext="npy"):
    stripped = fname.strip('.{}'.format(ext)).split('/')
    exp_name, akind, qty, md_label = [stripped[x] for x in [6, 7, -2, -1]]
    one, group, two, mouse, day = md_label.split('_')
    return group, mouse, int(day[1:])

# # kinda old
# # # EVENTS
# def create_df_from_series_data(experiment, dfs, days, ignore=False):
#     df = pd.DataFrame(dfs).T
#     df = df.reset_index().rename(index=str, columns={'level_0': 'group', 'level_1': 'mouse', 'level_2': 'day'})
#     df = df[df['day'].isin(days)]
#     if ignore:
#         # ignored = list() or experiment.ignored
#         df = remove_ignored_from_dataframe(experiment, df)
#     df = set_df_indices(df, experiment, index=['group', 'mouse', 'day'])
#     return df
#

# def load_ingestion_events_dataframe(experiment, days=(), ev_type='F', ignore=False):
#     path_to_npy1 = path_to_binary(experiment, subdir=os.path.join('preprocessing', '{}_timeset'.format(ev_type)))
#     print "loading {} event data from npy:\n{}".format(ev_type, path_to_npy1)
#     tot = len(list(find_files(path_to_npy1, ext='npy')))
#     dfs1, dfs2 = dict(), dict()
#     # durations
#     for cnt, fname in enumerate(find_files(path_to_npy1, ext='npy')):
#         vals = np.load(fname)
#         if len(vals):
#             dur, = np.diff(vals).T
#             interdur = vals[1:, 0] - vals[:-1, 1]
#         else:
#             dur, interdur = list(), list()
#
#         index = mouseday_label_from_filename(fname)
#         dfs1[index] = pd.Series(dur)
#         dfs2[index] = pd.Series(interdur)
#         progress(cnt, tot)
#
#     df1 = create_df_from_series_data(experiment, dfs1, days, ignore)
#     df2 = create_df_from_series_data(experiment, dfs2, days, ignore)
#
#     # Feeding and Licking Coeff
#     coeff_name = 'FC' if ev_type == 'F' else "LC"
#     path_to_npy2 = path_to_binary(experiment, subdir=os.path.join('preprocessing', coeff_name))
#     print "loading {} data from npy:\n{}".format(coeff_name, path_to_npy2)
#     tot = len(list(find_files(path_to_npy2, ext='npy')))
#     dfs3 = dict()
#     for cnt, fname in enumerate(find_files(path_to_npy2, ext='npy')):
#         vals = np.load(fname).tolist()
#         index = mouseday_label_from_filename(fname)
#         dfs3[index] = pd.Series(vals)
#         progress(cnt, tot)
#
#     df3 = create_df_from_series_data(experiment, dfs3, days, ignore) * 1000  # to mg/s
#     return df1, df2, df3
#
#
# @utils.timing
# def load_locomotion_events_dataframe(experiment, days=(), ignore=False):
#     keys = ['delta_t', 'idx_timestamps_out_hb', 'idx_timestamps_at_hb', 'velocity', 'distance']
#     print "loading timestamp data from npy:\n{}".format(keys)
#     dfs_list = [dict() for _ in range(9)]
#     tot = len(list(experiment.mousedays))
#     for cnt, md in enumerate(experiment.mousedays):
#         if md.day in days:
#             delta_t, idx_out, idx_at, vel, dist = [load_preprocessing_data(md, keys=[key])['preprocessing'][key]
#                                                    for key in keys]
#             dfs_list[0][md.label] = pd.Series(delta_t)
#             dfs_list[1][md.label] = pd.Series(vel)
#             dfs_list[2][md.label] = pd.Series(dist)
#             dfs_list[3][md.label] = pd.Series(delta_t[idx_out])
#             dfs_list[4][md.label] = pd.Series(vel[idx_out])
#             dfs_list[5][md.label] = pd.Series(dist[idx_out])  # todo: REWRITE
#             dfs_list[6][md.label] = pd.Series(delta_t[idx_at])
#             dfs_list[7][md.label] = pd.Series(vel[idx_at])
#             dfs_list[8][md.label] = pd.Series(dist[idx_at])
#             progress(cnt, tot)
#             cnt += 1
#
#     return [create_df_from_series_data(experiment, dfs, days, ignore) for dfs in dfs_list]


# -*- coding: utf-8 -*-
'''
    :codeauthor: :email:`Rahul Handay <rahulha@saltstack.com>`
'''

# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import (
    MagicMock,
    patch,
    NO_MOCK,
    NO_MOCK_REASON
)

ensure_in_syspath('../../')

# Import Salt Libs
from salt.modules import oracle
import os

# Globals
oracle.__salt__ = {}
oracle.cx_Oracle = object()

@skipIf(NO_MOCK, NO_MOCK_REASON)
class OracleTestCase(TestCase):
    '''
    Test cases for salt.modules.oracle
    '''
    def test_run_query(self):
        '''
        Test for Run SQL query and return result
        '''
        with patch.object(oracle, '_connect', MagicMock()) as mock_connect:
            mock_connect.cursor.execute.fetchall.return_value = True
            with patch.object(oracle, 'show_dbs', MagicMock()):
                self.assertTrue(oracle.run_query('db', 'query'))

    def test_show_dbs(self):
        '''
        Test for Show databases configuration from pillar. Filter by `*args`
        '''
        with patch.dict(oracle.__salt__, {'pillar.get':
                                          MagicMock(return_value='a')}):
            self.assertDictEqual(oracle.show_dbs('A', 'B'),
                                 {'A': 'a', 'B': 'a'})

            self.assertEqual(oracle.show_dbs(), 'a')

    def test_version(self):
        '''
        Test for Server Version (select banner  from v$version)
        '''
        with patch.dict(oracle.__salt__, {'pillar.get':
                                          MagicMock(return_value='a')}):
            with patch.object(oracle, 'run_query', return_value='A'):
                self.assertDictEqual(oracle.version(), {})

    def test_client_version(self):
        '''
        Test for Oracle Client Version
        '''
        with patch.object(oracle, 'cx_Oracle',
                          MagicMock(side_effect=MagicMock())):
            self.assertEqual(oracle.client_version(), '')

    def test_show_pillar(self):
        '''
        Test for Show Pillar segment oracle.*
        '''
        with patch.dict(oracle.__salt__, {'pillar.get':
                                          MagicMock(return_value='a')}):
            self.assertEqual(oracle.show_pillar('item'), 'a')

    def test_show_env(self):
        '''
        Test for Show Environment used by Oracle Client
        '''
        with patch.object(os, 'environ',
                          return_value={'PATH': 'PATH',
                                        'ORACLE_HOME': 'ORACLE_HOME',
                                        'TNS_ADMIN': 'TNS_ADMIN',
                                        'NLS_LANG': 'NLS_LANG'}):
            self.assertDictEqual(oracle.show_env(), {})

if __name__ == '__main__':
    from integration import run_tests
    run_tests(OracleTestCase, needs_daemon=False)


import os
import sys
from dataclasses import dataclass

from src.logger import logging
from src.exception import CustomException
from src.utils import save_object, evaluate_model

from sklearn.ensemble import AdaBoostRegressor, GradientBoostingRegressor, RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
from sklearn.neighbors import KNeighborsRegressor
from sklearn.tree import DecisionTreeRegressor
from xgboost import XGBRegressor

@dataclass
class ModelTrainerConfig:
    trained_model_file_path = os.path.join('artifacts','model.pkl')

class ModelTrainer:
    def __init__(self):
        self.model_trainer_config = ModelTrainerConfig()

    def initiate_model_trainer(self, train_arr, test_arr, preprocessor_path=None):
        try:

            # separate the target variable in the train and test arrays
            logging.info('Splitting training and testing input data')
            X_train, y_train, X_test, y_test = (
                train_arr[:,:-1],
                train_arr[:,-1],
                test_arr[:,:-1],
                test_arr[:,-1],
            )

            # a list of models to experiment with
            models = {
                "Random Forest": RandomForestRegressor(),
                "Decision Tree": DecisionTreeRegressor(),
                "Gradient Boosting": GradientBoostingRegressor(),
                "Linear Regression": LinearRegression(),
                "K-Neighbours Regressor": KNeighborsRegressor(),
                "XGBRegressor": XGBRegressor(),
                "AdaBoost Regressor": AdaBoostRegressor(),
            }

            model_report:dict = evaluate_model(x_train=X_train, y_train=y_train, x_test=X_test,
                                                y_test=y_test, models=models)

            ## to get the best model score from dict
            best_model_score = max(sorted(model_report.values()))

            ## to get best model froom dict
            best_model_name = list(model_report.keys())[
                list(model_report.values()).index(best_model_score)
            ]

            best_model = models[best_model_name]

            if best_model_score < 0.6:
                raise CustomException('No best Model Found!!!')
            logging.info('Found best model on both training and test data')

            save_object(file_path=self.model_trainer_config.trained_model_file_path,
                            obj=best_model)

            return (best_model, best_model_name, best_model_score)

        except Exception as e:
            raise CustomException(e, sys)


class Student:
    def __init__(self, name: str, age: int = 0, country: str = 'France') -> None:
        self.name = name
        self.age = age
        self.country = country

    def __str__(self):
        return f'Hello! My name is {self.name}. I am {self.age} years old. I am from {self.country}.'

    def print_data(self) -> None:
        print(f'Hello! My name is {self.name}. I am {self.age} years old. I am from {self.country}.')

first_student = Student(name ='Nick', age=20, country= 'USA')
second_student = Student('Kate', 19, 'Ukraine')
third_student = Student('Al', age=54)

print(first_student)
print(second_student)
print(third_student)


from typing import Iterable
from minecraft_launch.modules.interface.iresource import IResource
from minecraft_launch.modules.models.launch.game_core import GameCore
from minecraft_launch.modules.utils.extend_util import ExtendUtil

class ResourceInstaller():
    max_download_threads: int = 64

    def __init__(self, game_core: GameCore) -> None:
        self.game_core: GameCore = game_core
        self.failed_resouces: list[IResource] = []

    def get_file_resources(self) -> Iterable[IResource]:
        if(self.game_core.client_file != None):
            yield self.game_core.client_file

    async def get_assets_resources_async(self):
        if(not(ExtendUtil.verify(self.game_core.assets_index_file.file_info, self.game_core.assets_index_file.size) or\
            ExtendUtil.verify(self.game_core.assets_index_file.file_info, self.game_core.assets_index_file.check_sum))):
            ...


"""Functions for various pipeline use cases.

Author: Seth Axen
E-mail: seth.axen@gmail.com
"""
from .config.params import params_to_sections_dict
from .conformer.util import mol_from_smiles, mol_from_sdf, mol_to_sdf
from .conformer.generate import generate_conformers
from .fingerprint.generate import fprints_dict_from_mol

def params_to_dicts(params):
    """Get params dicts for pipeline functions from INI format params file."""
    sections_dict = params_to_sections_dict(params, auto=True)

    # preproc_params will eventually be returned separately, when there's a
    # pipeline function for protonation
    preproc_params = sections_dict.get("preprocessing", {})
    confgen_params = sections_dict.get("conformer_generation", {})
    confgen_params.update(preproc_params)
    fprint_params = sections_dict.get("fingerprinting", {})
    return confgen_params, fprint_params

def confs_from_smiles(smiles, name, confgen_params={}, save=False):
    """Generate conformations of molecule from SMILES string."""
    mol = mol_from_smiles(smiles, name)
    confgen_result = generate_conformers(
        mol, name, save=save, **confgen_params
    )
    mol = confgen_result[0]
    return mol

def sdf_from_smiles(
    smiles, name, confgen_params={}, out_file=None, out_ext=".sdf.bz2"
):
    """Generate conformations from SMILES string and save to SDF file."""
    mol = confs_from_smiles(
        smiles, name, confgen_params=confgen_params, save=False
    )
    if out_file is None:
        out_file = name + out_ext
    mol_to_sdf(mol, out_file)

def fprints_from_fprints_dict(fprints_dict, level=-1):
    """Get fingerprint at `level` from dict of level to fingerprint."""
    fprints_list = fprints_dict.get(
        level, fprints_dict[max(fprints_dict.keys())]
    )
    return fprints_list

def fprints_from_mol(mol, fprint_params={}, save=False):
    """Generate fingerprints for all `first` conformers in mol."""
    fprints_dict = fprints_dict_from_mol(mol, save=save, **fprint_params)
    level = fprint_params.get("level", -1)
    fprints_list = fprints_from_fprints_dict(fprints_dict, level=level)
    return fprints_list

def fprints_from_smiles(
    smiles, name, confgen_params={}, fprint_params={}, save=False
):
    """Generate conformers and fingerprints from a SMILES string."""
    if save is False and "first" not in confgen_params:
        confgen_params["first"] = fprint_params.get("first", -1)
    mol = confs_from_smiles(
        smiles, name, confgen_params=confgen_params, save=save
    )
    fprints_list = fprints_from_mol(
        mol, fprint_params=fprint_params, save=save
    )
    return fprints_list

def fprints_from_sdf(sdf_file, fprint_params={}, save=False):
    """Generate fingerprints from conformers in an SDF file."""
    mol = mol_from_sdf(sdf_file)
    fprints_list = fprints_from_mol(
        mol, fprint_params=fprint_params, save=save
    )
    return fprints_list


import numpy as np
import rdkit.Chem as Chem
from rdkit import DataStructs
from rdkit.Chem import rdMolDescriptors
import copy

class CandidatePool():
    def __init__(self,
                 candidate_pool_size=50):
        self.candidate_pool_size = candidate_pool_size
        self.pool = []

    def _calculate_softmax(self, pool_life_time):
        exp_sum = 0
        for i in pool_life_time:
            exp_sum += np.exp(i)
        res = [i/exp_sum for i in pool_life_time]
        return res

    def get_length(self):
        return len(self.pool)

    def add_molecule(self, molecule):
        pool_length = len(self.pool)
        if pool_length < self.candidate_pool_size:
            self.pool.append(molecule)
        elif pool_length == self.candidate_pool_size:
            pool_life_time = [i.pool_life_time for i in self.pool if i.prior_flag == False]
            sorted_life_time = np.argsort(pool_life_time)
            index = sorted_life_time[0]
            self.pool.pop(index)
            molecule.pool_life_time = 0
            self.pool.append(molecule)

    def _smilarity_between_two_smiles(self, smi1, smi2):
        mol1, mol2 = Chem.MolFromSmiles(smi1), Chem.MolFromSmiles(smi2)

        vec1 = rdMolDescriptors.GetMorganFingerprintAsBitVect(mol1, 4, nBits=512)
        vec2 = rdMolDescriptors.GetMorganFingerprintAsBitVect(mol2, 4, nBits=512)

        tani = DataStructs.TanimotoSimilarity(vec1, vec2)
        return tani

    def _calculate_similarity(self, molecule):
        similarity = []
        for i in self.pool:
            similarity.append(self._smilarity_between_two_smiles(molecule.smiles, i.smiles))
        return similarity

    def extract_molecules(self, molecule_list):
        res_mols = []
        length = len(molecule_list)
        if length > len(self.pool):
            res_mols = self.pool
            return res_mols
        else:
            for mol in molecule_list:
                similarity = self._calculate_similarity(mol)
                max_index = np.argmax(similarity)
                self.pool[max_index].pool_life_time = 0
                res_mols.append(self.pool[max_index])
                self.pool.pop(max_index)
            return res_mols

    def unload_molecules(self, num_molecules):
        pool = self.pool
        pool = sorted(pool, key=lambda x: x.pool_life_time, reverse=True)
        temp_mols = pool[:num_molecules]
        for i in range(num_molecules):
            pool.pop(0)
        return temp_mols

    def update_candidate_pool(self):
        for molecule in self.pool:
            molecule.pool_life_time += 1

from a_molecule import *

if __name__ == '__main__':
    candidate_pool = CandidatePool()

    smiles_pool = ['C']

    for i in range(10):
        smiles_pool.append(smiles_pool[-1]+'C')

    for i in range(10):
        candidate_pool.add_molecule(Molecule(smiles_pool[i]))

    standard_mol = Molecule(smiles_pool[-1])
    print(len(candidate_pool.pool))
    print(candidate_pool.extract_molecules([standard_mol])[0].smiles)


from tkinter import *
from tkinter import messagebox
from tkinter import PhotoImage

def boton_aceptar():
    # Segunda ventana
    ventana2 = Tk()
    ventana2.geometry("320x320")
    ventana2.title("¿Edad actual que tienes?")
    ventana2.config(bg="Slategray2")
    ventana2.resizable(0, 0)

    Label1v2 = Label(text="Selecciona tù rango de edad")

    Label1v2.config(fg="gray30", bg="cadetblue1", font=("Comic Sans MS",22))
    def edad_3_a_5_años():
        ventana3 = Tk()
        ventana3.geometry("1000x650")
        ventana3.title("Accediste a los ejercicios de la edad de 3 a 5 años")
        ventana3.config(bg="SkyBlue2")
        ventana3.resizable(0, 0)
        texto_niños= Label(ventana3, text= "\n--Ejercicios para niños de 3 a 5 años--\n\n En esta edad pueden realiar los siquientes tipos de ejercicios:\n\n Baloncesto\n\nFutbol\n\n Baile\n\n")
        texto_niños.config(bg="SkyBlue2",fg="Black", font=("Comic Sans MS",20))
        texto_niños.place(x=50,y=5,width=900,height=500)
    def edad_6_a_11_años():
        ventana3 = Tk()
        ventana3.geometry("1000x650")
        ventana3.title("Accediste a los ejercicios de la edad de 6 a 11 años")
        ventana3.config(bg="SkyBlue2")
        ventana3.resizable(0, 0)
        texto_niños= Label(ventana3, text= "\n--Ejercicios para niños de 6 a 11 años--\n\n En esta edad pueden realiar los siquientes tipos de ejercicios:\n\nAtletismo\n\n Baloncesto\n\nFutbol\n\nTae Kwon Do o Judo\n\n")
        texto_niños.config(bg="SkyBlue2",fg="Black", font=("Comic Sans MS",20))
        texto_niños.place(x=50,y=5,width=900,height=500)
    def edad_12_a_19_años():
        ventana3 = Tk()
        ventana3.geometry("1000x650")
        ventana3.title("Accediste a los ejercicios de la edad de 12 a 19 años")
        ventana3.config(bg="SkyBlue2")
        ventana3.resizable(0, 0)
        texto_niños= Label(ventana3, text= "\n--Ejercicios para jovenes  de 12 a 19 años--\n\n se empieza con el calentamiento:Salto de tijera, estiramiento de brazo,\ntrotar,Saltos con cuerda.\n\n Ya cuando se ha calentado el cuerpo sequimos con:\n Flexiones con inclinaciòn(12 Repeticiones)\n Flexiones con brazos abiertos(8 R ) Flexiones con apoyo de rodilla(12 R)\n Crunch Abdominales(10 R),Twits Ruso(7 R),Elevaciones de piernas(12 R)\n\nPara terminar con la rutina diaria: \nEstiramiento de cobra(60 s), Estiramiento\n de pecho(80 s).\n\n Ademas otros ejercicios podria ser el:\n Atletismo, Ciclismo,Futbol,Nataciòn\n\n")
        texto_niños.config(bg="SkyBlue2",fg="Black", font=("Comic Sans MS",19))
        texto_niños.place(x=50,y=5,width=900,height=500)
    def edad_20_a_26_años():
        ventana3 = Tk()
        ventana3.geometry("1000x650")
        ventana3.title("Accediste a los ejercicios de la edad de 19 a 26 años")
        ventana3.config(bg="SkyBlue2")
        ventana3.resizable(0, 0)
        texto_niños= Label(ventana3, text= "\n--Ejercicios para personas adultos de 20 a 26 años--\n\n En esta edad pueden realiar los siquientes tipos de ejercicios:\n\n Iniciamos con el calentamiento:\n Salto de tijera(40 s),Trotar(60 s),Saltar Laso(120 s),Rotaciones \nde Brazo(20 R) \n\nDespues de haber calentado:\nAbdominales(30 R), Cruch de bicicleta(24 R),Butt britge(18 R)\n Abdominales en V(18 R),Burpees(12 R), Flexiones en Diamante(16 R)\nFlexiones con Inclinacion(20 R)\n\nPara concluir con la rutina:Estiramiento de Hombros(30 s)\n Estiramiento de cobra(30 s), Estiramiento de pecho(30 s)")
        texto_niños.config(bg="SkyBlue2",fg="Black", font=("Comic Sans MS",20))
        texto_niños.place(x=0,y=5,width=1000,height=650)
    # Imagen que aparece en la entrada de los botones

    # Imagen que aparece en la entrada de los botones

    # Botón para acceder a la edad de 3 a 5 años
    boton_niños3_5=Button(ventana2,text="3-5",command=edad_3_a_5_años)
    # Ubicació para el botón para edades de 3 a 5 años
    boton_niños3_5.pack(pady=15)
    boton_niños3_5.config(width=14,height=2)

    # Botón para acceder a la edad de 6 a 11 años
    boton_niños6_11=Button(ventana2,text="6-11",command=edad_6_a_11_años)

    # Ubicació para el botón para edades de 6 a 11 años
    boton_niños6_11.pack(pady=15)
    boton_niños6_11.config(width=14,height=2)

    # Botón para acceder a la edad de 12 a 19 años
    boton_niños12_19=Button(ventana2,text="12-19",command=edad_12_a_19_años)
    # Ubicació para el botón para edades de 12 a 19 años
    boton_niños12_19.pack(pady=15)
    boton_niños12_19.config(width=14,height=2)

    # Botón para acceder a la edad de 20 a 26 años
    boton_niños20_26=Button(ventana2,text="20-26",command=edad_20_a_26_años)
    # Ubicació para el botón para edades de 20 a 26 años
    boton_niños20_26.pack(pady=15)
    boton_niños20_26.config(width=14,height=2)

# Ventana principal
root = Tk()
root.geometry("650x490")
root.title("Vida Saludable")
root.config(bg="cadetblue1")
root.resizable(False, False)

# Texto indicativo en forma de Label
Label1 = Label(text="Digite sus datos para continuar")
Label2 = Label(text="Nombre")
Label3 = Label(text="Peso(kilogramos)")
Label4 = Label(text="Altura(centímetros)")

#Configuración de los Label; tipo, tamaño y color de letra
Label1.config(fg="gray30", bg="cadetblue1", font=("Comic Sans MS",22))
Label2.config(fg="gray30", bg="cadetblue1", font=("Comic Sans MS",22))
Label3.config(fg="gray30", bg="cadetblue1", font=("Comic Sans MS",22))
Label4.config(fg="gray30", bg="cadetblue1", font=("Comic Sans MS",22))

# Ubicación de los Label
Label1.place(x=100, y=40)
Label2.place(x=40, y=150)
Label3.place(x=40, y=230)
Label4.place(x=40, y=310)

# Entradas de texto
entrada1 = Entry() #"Nombre"
entrada2 = Entry() #"Peso(kilogramos)"
entrada3 = Entry() #"Altura(centímetros)"

#Foco de digitar texto en los entry
entrada1.focus_set()

#Configuración de las entradas; tipo, tamaño y color de letra
entrada1.config(bg="turquoise1", fg="steel blue", font=("Comic Sans MS",22))
entrada2.config(bg="turquoise1", fg="steel blue", font=("Comic Sans MS",22))
entrada3.config(bg="turquoise1", fg="steel blue", font=("Comic Sans MS",22))

# Ubicación de las entradas de texto y ajustes de tamaños de las mismas
entrada1.place(x=350, y=150, width=260,height=40)
entrada2.place(x=350, y=230, width=260,height=40)
entrada3.place(x=350, y=310, width=260,height=40)

# Botón de aceptar

boton_aceptar = Button(text="Aceptar",command=boton_aceptar)

# Ubicación del Botón aceptar
boton_aceptar.place(x=275,y=410, width=100,height=40)

root.mainloop()


from flask import current_app
from marshmallow import Schema, ValidationError, fields, validates_schema
from marshmallow.validate import Length

class CreateTaskSchema(Schema):
    title = fields.Str(
        required=True,
        validate=Length(min=1),
    )
    description = fields.Str(required=True, validate=Length(max=128))
    user_id = fields.Str(required=True, validate=Length(equal=14))

    @validates_schema
    def validate_user_id(self, data, **kwargs):
        board = current_app.config["DB_CONN"]["factwise"]["board"].find_one({"name": data.get("title", "")})
        if data.get("user_id") not in current_app.config["DB_CONN"]["factwise"]["team"].distinct(
            "users.user_id", {"team_id": board.get("team_id")}
        ):
            raise ValidationError("user_id not belong to the team to whom the board is assigned")
        if data.get("title") not in current_app.config["DB_CONN"]["factwise"]["board"].distinct("name"):
            raise ValidationError("Board not available for the requested title")


import graph_tool.topology as topology
from graph_tool.all import *
import numpy as np

class gt_Graph(Graph):

    def __init__(self):
        Graph.__init__(self)
        self.cnodes = []
        self.dedges = {}

    @staticmethod
    def get_comps(G):
        labels, _ = topology.label_components(G)

        labels = labels.a
        nc = np.max(labels) + 1

        comps = [[] for _ in range(nc)]

        [comps[labels[i]].append(i) for i in range(len(labels))]
        return comps

    #Add N vertex
    @staticmethod
    def gr_add_vertex(G,N):
        G.add_vertex(N)
        for i in range(N):
            G.dedges[i] = set()

    @staticmethod
    def gr_add_one_vertex(G):
        G.add_vertex()
        i = G.num_vertices()-1
        G.dedges[i] = set()

    @staticmethod
    def gr_add_edge(G,i,j):
        G.add_edge(i,j)
        # if i not in G.dedges:
        #     G.dedges[i] = set()

        G.dedges[i].add(j)

    @staticmethod
    def gr_add_edge_list(G,l):
        G.add_edge_list(l)
        for e in l:
            i,j = e
            G.dedges[i].add(j)


import numpy as np
import scipy.spatial
import itertools

from sklearn import metrics

def rand_score( X, labels_true, labels_pred ):
     correct = 0
     total = 0

     arr2 = []
     opop = len(X)
     for i in range(opop):
         arr2.append( i )

     for index_combo in itertools.combinations(arr2, 2):
          index1 = index_combo[0]
          index2 = index_combo[1]

          same_class = (labels_true[index1] == labels_true[index2])
          same_cluster = (labels_pred[index1] == labels_pred[index2])

          if same_class and same_cluster:
              correct += 1
          elif not same_class and not same_cluster:
              correct += 1

          total += 1

     return float(correct) / total

def cluster_centroids(data, clusters, k):
    return np.array([data[ clusters==i ].mean( axis = 0 ) for i in range(k)]) # Compute the mean of data[ i ] where i is set column wise

def kmeans(X, initial_centroids, max_iters):
     eval_mat = []
     clusters = []

     k = len(initial_centroids)

     opop = X.shape[1]-1
     label_true = np.copy(X[:, opop])
     Y =  np.copy(X[:, range(0, opop)])

     try:
         label_true = label_true.astype(np.int)
         label_true = label_true - 1
     except ValueError:
         qq = set(label_true)
         len1 = len(qq)
         for i in range(len1):
            ele1 = qq.pop()
            for j in range( len(X) ):
                if( label_true[j]==ele1 ):
                    label_true[j] = str(i)

     label_true = label_true.astype(np.int)
     Y = Y.astype(np.float)

     centroids = initial_centroids
     for i in range(max_iters):
         # Squared distances between each point and each centroid
        sqdists = scipy.spatial.distance.cdist(Y, centroids, 'sqeuclidean')  # n*k matrix of squared distance, in each row distance of point from each of the centroid is stored

        # Index of the closest centroid to each data point
        clusters = np.argmin(sqdists, axis = 1)                                 # For example np.argmin(a, axis=0) returns the index of the minimum value in each of the columns

        # Finding new centroids
        new_centroids = cluster_centroids(Y, clusters, k)

        # break early if new_centroids = centroids
        if np.array_equal(new_centroids, centroids):
            break

        centroids = new_centroids

     # Normalized Mutual Information(MI)
     nmi = metrics.normalized_mutual_info_score(label_true, clusters)

     # Adjusted Mutual Information(AMI)
     ami = metrics.adjusted_mutual_info_score(label_true, clusters)

     # Rand index(RI)
     ri = rand_score(Y, label_true, clusters)

     # Adjusted Rand index(ARI)
     ari = metrics.adjusted_rand_score(label_true, clusters)

     eval_mat.append( nmi )
     eval_mat.append( ami )
     eval_mat.append( ri )
     eval_mat.append( ari )

     return new_centroids, eval_mat


from bs4 import BeautifulSoup
import requests
import xlsxwriter

base_trade_url = 'https://www.realmeye.com/offers-by/'

pots = {
    2793: "Life Potion",
    2592: "Defense Potion",
    2591: "Attack Potion",
    2593: "Speed Potion",
    2636: "Dexterity Potion",
    2613: "Wisdom Potion",
    2612: "Vitality Potion",
    2794: "Mana Potion"
}
rev_pots = {v: k for k, v in pots.items()}

# In terms of Speed Pots ETA
pot_values = {
    "Life Potion": 8,
    "Defense Potion": 3,
    "Attack Potion": 3,
    "Speed Potion": 1,
    "Dexterity Potion": 1,
    "Wisdom Potion": 1.2,
    "Vitality Potion": 2,
    "Mana Potion": 5,
}

class Item:
    def __init__(self, item_id, qty):
        self.item_id = item_id
        self.qty = int(qty[1:])
        if item_id in pots.keys():
            self.name = pots[item_id]
            self.worth = self.qty * pot_values[self.name]
        else:
            self.name = 'OTHER_ITEM'
            self.worth = 0

    def __str__(self):
        return f'{self.qty} {self.name}'

class Trade:
    def __init__(self, selling_items, buying_items, qty, added, author, seen, server):
        self.selling_items = selling_items
        self.buying_items = buying_items
        self.qty = qty
        self.added = added
        self.author = author
        self.seen = seen
        self.server = server
        self.selling_worth = sum([i.worth for i in selling_items])
        self.buying_worth = sum(i.worth for i in buying_items)

def getBuyingList(id):
    buying_spd_pots_url = f'https://www.realmeye.com/offers-to/buy/{id}/pots'
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}
    r = requests.get(buying_spd_pots_url, headers=headers)
    soup = BeautifulSoup(r.content, 'html.parser')

    tbl = soup.find("table", id="g").find("tbody")
    raw_trades = tbl.findAll("tr")

    trades_list = []

    for trade in raw_trades:
        trade_attributes = trade.findAll('td')

        selling_list = trade_attributes[0].findAll('span', {'class': 'item-static'})
        buying_list = trade_attributes[1].findAll('span', {'class': 'item-static'})

        selling_itms = []
        for itm in selling_list:
            data_id = int(itm.find('span', {'class': 'item'})['data-item'])
            data_qt = itm.find('span', {'class': 'item-quantity-static'}).text
            temp_item = Item(data_id, data_qt)
            selling_itms.append(temp_item)

        buying_itms = []
        for itm in buying_list:
            data_id = int(itm.find('span', {'class': 'item'})['data-item'])
            data_qt = itm.find('span', {'class': 'item-quantity-static'}).text
            buying_itms.append(Item(data_id, data_qt))

        trade_qty = trade_attributes[2].find('span')
        trade_added = trade_attributes[3].find('span').text
        trade_author = trade_attributes[5].find('a').text
        trade_seen = trade_attributes[6].find('span')
        trade_server = trade_attributes[7].find('abbr')
        if trade_server is not None:
            trade_server = trade_server.text

        trades_list.append(Trade(selling_itms, buying_itms, trade_qty, trade_added, trade_author, trade_seen, trade_server))
    return trades_list

col_headers = [
    {'header': 'USER'},
    {'header': 'SERVER'},
    {'header': 'SELLING'},
    {'header': 'BUYING'},
    {'header': 'SELLING WORTH'},
    {'header': 'BUYING WORTH'},
    {'header': 'DIFFERENCE'},
]

trades_file = open('trades.txt', 'w')
workbook = xlsxwriter.Workbook('Trades.xlsx')
worksheet = workbook.add_worksheet()

data = []
for pot_type in pots.values():
    trades_list = getBuyingList(rev_pots[pot_type])

    for trade in trades_list:
        buying_items_string = ''
        for item in trade.buying_items:
            if item.name == 'OTHER_ITEM':
                continue
            buying_items_string += f'{item}, '

        selling_items_string = ''
        for item in trade.selling_items:
            if item.name == 'OTHER_ITEM':
                continue
            selling_items_string += f'{item}, '

        user_url = f'{base_trade_url}{trade.author}'
        excel_hyperlink = f'=HYPERLINK(\"{user_url}\",\"{trade.author}\")'

        data.append([excel_hyperlink, trade.server, selling_items_string, buying_items_string, trade.selling_worth,
                     trade.buying_worth, trade.selling_worth - trade.buying_worth])

        printing_string = f'{trade.author}({trade.server}) has {selling_items_string}and wants {buying_items_string}'
        print(printing_string)
        trades_file.write(printing_string + '\n')

worksheet.add_table(0, 0, len(data), len(col_headers) - 1, {'data': data, 'columns': col_headers})
trades_file.close()
workbook.close()


class Solution:
    def closeStrings(self, word1: str, word2: str) -> bool:
        if set(word1) != set(word2):
            return False

        word_one_cnt = Counter(word1)
        word_two_cnt = Counter(word2)
        return Counter(word_one_cnt.values()) == Counter(word_two_cnt.values())


from pyspark.sql import SparkSession
import numpy as np
import pandas as pd
import gc
from pyspark.ml.feature import StringIndexer, VectorIndexer, VectorAssembler
from pyspark.sql.functions import col
from pyspark.sql.types import StringType,BooleanType,DateType,DoubleType
from pyspark.ml import Pipeline
from pyspark.ml.classification import DecisionTreeClassifier
from pyspark.ml.evaluation import MulticlassClassificationEvaluator

def init_spark():
  sql = SparkSession.builder\
    .appName("hdfs_ICU-stays-pred_LR")\
    .getOrCreate()
  sc = sql.sparkContext
  return sql,sc

# i dati utilizzati sono di physionet.org challenge 2012 sono però in un formato diverso dunque c'è una prima fase di reshaping per renderlo nel formato a noi più
#congeniale, nel seguente programma viene saltata questa fase di preprocessing utilizzando un dato già presente e preprocessato da kaggle
#se venisse richiesto quà trovi come fare il pre-processing e tutto https://www.kaggle.com/code/msafi04/predict-icu-mortality-shap/notebook oppure
# fai una prima fase in panda e poi converti un un dataframe Spark

file = "hdfs://namenode:9000/user/root/input/Applications/Data/icu_mortality_train.csv"

sql,sc = init_spark()

#lavoriamo con panda per il momento
df = sql.read.load(file,format = "csv", inferSchema="true", sep=",", header="true").toPandas()
df = df.replace([-1.0, np.inf, -np.inf], np.nan)
df['age_group'] = pd.cut(df['Age'], bins = 9, labels = ['<20', '20s', '30s', '40s', '50s', '60s', '70s', '80s', '90s'])

df['Height'] = df['Height'].fillna(df['Height'].median())
df['Weight'] = df['Weight'].fillna(df['Weight'].median())
df['bmi'] = df.apply(lambda x: round((x['Weight'] / (x['Height'] ** 2)) * 10000, 2), axis = 1)
df['bmi_group'] = pd.cut(df['bmi'], bins = [df['bmi'].min(), 18.5, 24.9, 29.9, df['bmi'].max()], labels = ['Underweight', 'Healthy', 'Overweight', 'Obesity'])

del df['bmi']
gc.collect()

cat_features = ['Gender', 'ICUType', 'age_group', 'bmi_group']
num_features = [c for c in df.columns if c not in cat_features]
num_features = [c for c in num_features if c not in ['RecordID', 'In-hospital_death']]
cat_features, num_features

#lavoriamo con dataframe panda per poi passare ad un dataframe spark
df_0 = df[df['In-hospital_death'] == 0].copy()
df_1 = df[df['In-hospital_death'] == 1].copy()
#Impute Numerical Features with mean value
df_0[num_features] = df_0[num_features].fillna(df_0[num_features].mean())
df_1[num_features] = df_1[num_features].fillna(df_1[num_features].mean())

#Impute Categorical Features with most frequent value
for col in cat_features:
    df_0[col] = df_0[col].fillna(df_0[col].value_counts().index[0])
    df_1[col] = df_1[col].fillna(df_1[col].value_counts().index[0])

#concat both df, shuffle and reset index
df = pd.concat([df_0, df_1], axis = 0).sample(frac = 1).reset_index(drop = True)

#print(cat_features, num_features)

data = sql.createDataFrame(df)

#anzichè fare il label casta ad integer i valori in string e poi abilità la pipeline di sotto

indexer = StringIndexer(inputCol="age_group", outputCol="age_label")
indexer.fit(data).transform(data)
temp_sdf = indexer.fit(data).transform(data)
data = temp_sdf.withColumn("age_group", temp_sdf["age_label"].cast("integer"))

indexer = StringIndexer(inputCol="bmi_group", outputCol="bmi_label")
indexer.fit(data).transform(data)
temp_sdf = indexer.fit(data).transform(data)
data = temp_sdf.withColumn("bmi_group", temp_sdf["bmi_label"].cast("integer"))

feature = VectorAssembler(inputCols = data.drop('In-hospital_death').columns, outputCol='features')
feature_vector = feature.transform(data)

feat_lab_df = feature_vector.select(['features', 'In-hospital_death'])
train, test = feat_lab_df.randomSplit([0.8, 0.2])

from pyspark.ml.classification import LogisticRegression
from pyspark.ml.tuning import ParamGridBuilder, TrainValidationSplit
from pyspark.mllib.evaluation import BinaryClassificationMetrics as metric

lr = LogisticRegression(labelCol='In-hospital_death')

paramGrid = ParamGridBuilder().addGrid(lr. regParam, (0.01, 0.1))\
                              .addGrid(lr.maxIter, (5, 10))\
                              .addGrid(lr.tol, (1e-4, 1e-5))\
                              .addGrid(lr.elasticNetParam, (0.25, 0.75))\
                              .build()

tvs = TrainValidationSplit(estimator=lr,
                           estimatorParamMaps=paramGrid,
                           evaluator=MulticlassClassificationEvaluator(labelCol='In-hospital_death'),
                           trainRatio=0.8)

lr_model = tvs.fit(train)
lr_model_pred = lr_model.transform(test)

lr_model_pred.show(3)
lr_model_pred.printSchema()

results = lr_model_pred.select(['probability', 'In-hospital_death'])

results.show(10)

results_collect = results.collect()
results_list = [(float(i[0][0]), 1.0-float(i[1])) for i in results_collect]
scoreAndLabels = sc.parallelize(results_list)

metrics = metric(scoreAndLabels)
lr_acc = round(MulticlassClassificationEvaluator(labelCol='In-hospital_death', metricName='accuracy').evaluate(lr_model_pred), 4)
lr_prec = round(MulticlassClassificationEvaluator(labelCol='In-hospital_death', metricName='weightedPrecision').evaluate(lr_model_pred), 4)
lr_roc = round(metrics.areaUnderROC, 4)

lr_dict = {'Accuracy': lr_acc, 'Precision': lr_prec, 'ROC Score': lr_roc}
print(lr_dict)


#!/usr/bin/env python
#coding:utf-8
"""
  Author:   --<v1ll4n>
  Purpose: Test ZSRPS
  Created: 07/19/17
"""

import unittest
import time

from vikitx.core.proto import zsrps
from vikitx.core.workpool import task

########################################################################
class ZSRPSTester(unittest.TestCase):
    """"""

    #----------------------------------------------------------------------
    def test_1_start_server(self):
        """"""
        def print_result(_, result):
            print(result)

        svr = zsrps.ZSRPSServer('server')
        _t = task.Task(svr.send_action, 'client', 'asdfasdfsadfasdf')
        _t.call_later(5, print_result)
        svr.start(port=7000)

        time.sleep(3)
        #client = svr.get_available_client()[0]
        #scope = svr.get_scope(client)
        #assert isinstance(scope, dict)
        #svr.send_action(client_id='client', content='tetsetststs')
        #svr.join()

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


#pylint: disable=no-member
import tcod
from random import randint
from game_messages import Message

class Brute:
    def take_turn(self, target, fov_map, game_map, entities):
        results=[]
        monster=self.owner
        if tcod.map_is_in_fov(fov_map, monster.x, monster.y):
            if monster.distance_to(target)>=2:
                monster.move_astar(target, entities, game_map)
            elif target.combatant.health>0:
                results.extend(monster.combatant.attack_physical(target))
        return results

class ConfusedLad:
    def __init__(self, prev_ai, nof_turns=5):
        self.prev_ai=prev_ai
        self.nof_turns=nof_turns

    def take_turn(self, target, fov_map, game_map, entities):
        results=[]
        if self.nof_turns:
            dx=self.owner.x+randint(-1, 1)
            dy=self.owner.y+randint(-1, 1)
            if dx!=self.owner.x and dy!=self.owner.y:
                self.owner.move_towards(dx, dy, game_map, entities)
            self.nof_turns-=1
        else:
            self.owner.ai=self.prev_ai
            results.append({'message': Message('The {0} regains self-control.'.format(self.owner.name), tcod.red)})
        return results


from LinkedList import LinkedList
from LinkedListHelper import CreateLinkedList
def isIdentical(head1,head2):
    while head1 and head2:
        if head1.val != head2.val:
            return False
        head1 = head1.next
        head2 = head2.next
    if not head1 and not head2:
        return True
    return False
def main():
    l1 = LinkedList()
    l2 = LinkedList()
    CreateLinkedList(l1)
    CreateLinkedList(l2)
    print("Is identical : ",isIdentical(l1.head , l2.head))
if __name__ == "__main__":
    main()