#!/bin/python3

import sys
import boto3
import re
import time
from botocore.exceptions import ClientError

region = 'ap-northeast-2'
#region = 'us-east-1'
#region = 'ap-northeast-1'
#region = 'eu-west-3'
#region = 'ap-southeast-1'

def insidsplit(description):
    pattern = re.findall('^Created by CreateImage',description)
    if pattern:
        insid = description.split('CreateImage(')[1].split(')')[0]
        return (insid)

def systemTagcheck(tags):
    i = 0
    for a in tags:
        if a['Key'] == 'System':
            i += 1
    return (i)

def CreateTags(tag,snapshotid):
   snapshot = boto3.resource('ec2', region_name=region).Snapshot(snapshotid)
   tag = snapshot.create_tags(Tags=[{'Key':'System','Value':tag}])

def instagcheck(instanceid):
    ec2 = boto3.client('ec2',region_name=region)
    ress = ec2.describe_tags(Filters=[{'Name' : 'resource-id', 'Values': [instanceid]}])
    instag = [i['Value'] for i in ress['Tags'] if i['Key'] == 'System']
    if instag:
        return (instag)

def tagcheckInsert(response):
    ec2 = boto3.client('ec2',region_name=region)
    for a in response['Snapshots']:
        volume = boto3.resource('ec2',region_name=region).Volume(a.get('VolumeId'))
        try:
            instanceid = instagcheck(volume.attachments[0]['InstanceId'])

        except ClientError:
            instanceid = None

        except IndexError:
            instanceid = None

        if instanceid:
            CreateTags(instanceid[0],a.get('SnapshotId'))
            print (("%s Tag를 %s SnapshotID에 입력하였습니다") %(instanceid[0], a.get('SnapshotId')))

def createSnapshotTag():
    ec2 = boto3.client('ec2',region_name=region)
    response = ec2.describe_snapshots(OwnerIds=['self'],MaxResults=500)
    tagcheckInsert(response)

    while True:
        try:
            ntoken = response['NextToken']
            response = ec2.describe_snapshots(OwnerIds=['self'],MaxResults=500,NextToken=ntoken)
            tagcheckInsert(response)

        except KeyError:
            sys.exit()

def amiinscheck(abc):
    ec2 = boto3.client('ec2',region_name=region)
    response = ec2.describe_snapshots(OwnerIds=['self'],SnapshotIds=[abc])

    for i in response['Snapshots']:
        volume = boto3.resource('ec2',region_name=region).Volume(i.get('VolumeId'))
        try:
            return (instagcheck(volume.attachments[0]['InstanceId']))
        except ClientError:
            pass

def amitagcreate():
    ec2 = boto3.client('ec2',region_name=region)
    ec2r = boto3.resource('ec2',region_name=region)
    response = ec2.describe_images(Owners=['self'])

    for i in response['Images']:
        for j in i['BlockDeviceMappings']:
            tag = amiinscheck(j['Ebs']['SnapshotId'])
            if tag:
                img = ec2r.Image(i['ImageId'])
                imgtag = img.create_tags(Tags=[{'Key': 'System', 'Value' : tag[0]}])
                print ("%s 이미지 태그 %s 등록하였습니다." %(i['ImageId'],imgtag))

def enitagcreate(clenv):
    client = boto3.client('ec2',region_name=region)
    client2 = boto3.resource('ec2',region_name=region)
    response = client.describe_network_interfaces()

    for i in response['NetworkInterfaces']:
        try:
            if i['Attachment']:
                p = re.compile('[0-9]{12}')

                if i['Attachment']['InstanceOwnerId'] == 'amazon-rds':
                    tag = rdscheck(i['Groups'])
                    if tag:
                        test1 = client2.NetworkInterface(i['NetworkInterfaceId']).create_tags(Tags=[{'Key' : 'System', 'Value' : tag}])
                        print ("%s eni 태그 %s 등록하였습니다" %(i['NetworkInterfaceId'],tag))

                elif i['Attachment']['InstanceOwnerId'] == 'amazon-elb':
                    tag = elbcheck(i['Groups'])
                    if tag:
                        test1 = client2.NetworkInterface(i['NetworkInterfaceId']).create_tags(Tags=[{'Key' : 'System', 'Value' : tag}])
                        print ("%s eni 태그 %s 등록하였습니다" %(i['NetworkInterfaceId'],tag))

                    else:
                        tag1 = elbcheck2(i['Groups'])
                        if tag1:
                            test1 = client2.NetworkInterface(i['NetworkInterfaceId']).create_tags(Tags=[{'Key' : 'System', 'Value' : tag1}])
                            print ("%s eni 태그 %s 등록하였습니다" %(i['NetworkInterfaceId'],tag1))

                elif p.match(i['Attachment']['InstanceOwnerId']):
                    instag = instagcheck(i['Attachment']['InstanceId'])
                    if instag:
                        test1 = client2.NetworkInterface(i['NetworkInterfaceId']).create_tags(Tags=[{'Key' : 'System', 'Value' : instag[0]}])
                        print ("%s eni 태그 %s 등록하였습니다" %(i['NetworkInterfaceId'],instag[0]))

                else:
                    tag = "Resource-ENI " + clenv
                    test1 = client2.NetworkInterface(i['NetworkInterfaceId']).create_tags(Tags=[{'Key' : 'System', 'Value' : tag}])
                    print ("%s eni 태그 %s 등록하였습니다" %(i['NetworkInterfaceId'],tag))

            else:
                tag = "Resource-ENI " + clenv
                test1 = client2.NetworkInterface(i['NetworkInterfaceId']).create_tags(Tags=[{'Key' : 'System', 'Value' : tag}])
                print ("%s eni 태그 %s 등록하였습니다" %(i['NetworkInterfaceId'],tag))

        except KeyError:
            pass

def test():
    volume = boto3.resource('ec2',region_name=region).Volume('vol-0ff5e76f5dd168d64')
    try:
        instanceid = instagcheck(volume.attachments[0]['InstanceId'])
    except ClientError:
        instanceid = None

    return (instanceid)

def rdscheck(groups):
    ec2 = boto3.client('rds',region_name=region)
    client = ec2.describe_db_instances()
    for i in client['DBInstances']:
        for j in i['VpcSecurityGroups']:
            for group in groups:
                if group['GroupId'] == j['VpcSecurityGroupId']:
                    cl = ec2.list_tags_for_resource(ResourceName=i['DBInstanceArn'])
                    tag = [a['Value'] for a in cl['TagList'] if a['Key'] == 'System']
                    if tag:
                        return (tag[0])

def elbcheck(groups):
    ec2 = boto3.client('elbv2',region_name=region)
    client = ec2.describe_load_balancers()
    for i in client['LoadBalancers']:
        try:
            for j in i['SecurityGroups']:
                for group in groups:
                    if group['GroupId'] == j:
                        cl = ec2.describe_tags(ResourceArns=[i['LoadBalancerArn']])
                        tag = [a['Value'] for a in cl['TagDescriptions'][0]['Tags'] if a['Key'] == 'System']

                        if tag:
                            return (tag[0])
        except KeyError:
            pass

def elbcheck2(groups):
    ec2 = boto3.client('elb',region_name=region)
    client = ec2.describe_load_balancers()
    for i in client['LoadBalancerDescriptions']:
        try:
            for j in i['SecurityGroups']:
                for group in groups:
                    if group['GroupId'] == j:
                        cl = ec2.describe_tags(LoadBalancerNames=[i['LoadBalancerName']])
                        tag = [a['Value'] for a in cl['TagDescriptions'][0]['Tags'] if a['Key'] == 'System']
                        if tag:
                            return (tag[0])
        except KeyError:
            pass

def sgtagging(clenv):
    ec2 = boto3.client('ec2',region_name=region)
    client = ec2.describe_security_groups()

    for i in client['SecurityGroups']:
        if i['GroupName'] == 'default':
            pass
        else:
            try:
                groupname = i['GroupId']
                groupid = {}
                groupid['GroupId'] = groupname
                client2 = boto3.resource('ec2',region_name=region)
                ecins = ec2.describe_instances(Filters=[{'Name':'network-interface.group-id', 'Values':[groupname]}])
                if ecins['Reservations']:
                    for k in ecins['Reservations']:
                        instance = [a['InstanceId'] for a in k['Instances']]
                        if instagcheck(instance[0]):
                            tag = instagcheck(instance[0])[0]
                            if tag:
                                test1 = client2.SecurityGroup(i['GroupId']).create_tags(Tags=[{'Key' : 'System', 'Value' : tag}])
                                print (i['GroupId'],tag)
                else:
                    if rdscheck([groupid]):
                        tag = rdscheck([groupid])
                        if tag:
                            test1 = client2.SecurityGroup(i['GroupId']).create_tags(Tags=[{'Key' : 'System', 'Value' : tag}])
                            print (i['GroupId'],tag)
                    elif elbcheck([groupid]):
                        tag = elbcheck([groupid])
                        if tag:
                            test1 = client2.SecurityGroup(i['GroupId']).create_tags(Tags=[{'Key' : 'System', 'Value' : tag}])
                            print (i['GroupId'],tag)
                    elif elbcheck2([groupid]):
                        tag = elbcheck2([groupid])
                        if tag:
                            test1 = client2.SecurityGroup(i['GroupId']).create_tags(Tags=[{'Key' : 'System', 'Value' : tag}])
                            print (i['GroupId'],tag)
                    else:
                        tag = 'Resource-SG ' + clenv
                        test1 = client2.SecurityGroup(i['GroupId']).create_tags(Tags=[{'Key' : 'System', 'Value' : tag}])
                        print (i['GroupId'],tag)
            except KeyError:
                print (i['GroupId'] + " Key")
                pass

def rdssnapshot():
    ec2 = boto3.client('rds',region_name=region)
    client = ec2.describe_db_snapshots()
    #client3 = ec2.describe_db_cluster_snapshots()
    for i in client['DBSnapshots']:
        if i['DBInstanceIdentifier']:
            if i['DBInstanceIdentifier'] == 'apne2-apprd-newssqure-pg1':
                pass
            else:
                client2 = ec2.describe_db_instances(DBInstanceIdentifier=i['DBInstanceIdentifier'])
                if client2['DBInstances']:
                    resource = client2['DBInstances'][0]['DBInstanceArn']
                    cl = ec2.list_tags_for_resource(ResourceName=resource)
                    tag = [a['Value'] for a in cl['TagList'] if a['Key'] == 'System']
                    if tag:
                        test = ec2.add_tags_to_resource(ResourceName=i['DBSnapshotArn'],Tags=[{'Key' : 'System', 'Value' : tag[0]}])
                        print (i['DBSnapshotArn'], tag[0])
    while True:
        try:
            marker = client['Marker']
            client = ec2.describe_db_snapshots(Marker=marker)
            for i in client['DBSnapshots']:
            #for i in client3['DBClusterSnapshots']:
                if i['DBInstanceIdentifier']:
                    if i['DBInstanceIdentifier'] == 'apne2-apprd-newssqure-pg1':
                        pass
                    else:
                        client2 = ec2.describe_db_instances(DBInstanceIdentifier=i['DBInstanceIdentifier'])
                        if client2['DBInstances']:
                            resource = client2['DBInstances'][0]['DBInstanceArn']
                            cl = ec2.list_tags_for_resource(ResourceName=resource)
                            tag = [a['Value'] for a in cl['TagList'] if a['Key'] == 'System']

                            if tag:
                                test = ec2.add_tags_to_resource(ResourceName=i['DBSnapshotArn'],Tags=[{'Key' : 'System', 'Value' : tag[0]}])
                                print (i['DBSnapshotArn'], tag[0])
        except KeyError:
            sys.exit()

def Alltags():
    client = boto3.resource('ec2',region_name=region)
    Alltags = {}

    for instance in client.instances.filter(MaxResults=500):
        try:
            SystemTag = list(filter(lambda tag: tag['Key'] == 'System', instance.tags))[0]['Value']
            InsTags = list(filter(lambda tag: tag['Key'] == 'System' or tag['Key'] == 'Company' or tag['Key'] == 'Country' or tag['Key'] == 'STAGE', instance.tags))
            Alltags[SystemTag] = InsTags

        except IndexError:
            print (str(instance) + ' IndexError')
            pass

        except TypeError:
            print (str(instance) + ' TypeError')

    return (Alltags)

def volumtagging():
    alltags = Alltags()
    ec2 = boto3.client('ec2',region_name=region)
    volume = ec2.describe_volumes()
    for i in volume['Volumes']:
        if i['State'] == 'in-use':
            ec2res = boto3.resource('ec2',region_name=region)
            try:
                volumeres = [a['Value'] for a in ec2res.Volume(i['VolumeId']).tags if a['Key'] == 'System']
            except TypeError:
                volumeres = None

            if volumeres:
                try:
                    systemcheck = alltags[volumeres[0]]
                except KeyError:
                    print (f"{i['VolumeId']} 볼륨 System 태그 {volumeres[0]} 와 매칭되는 System 키가 없습니다")
                    systemcheck = None

                if systemcheck:
                    ec2res.Volume(i['VolumeId']).create_tags(Tags=systemcheck)

def securitytagging():
    alltags = Alltags()
    ec2 = boto3.client('ec2',region_name=region)
    client = ec2.describe_security_groups()

    for i in client['SecurityGroups']:
        ec2res = boto3.resource('ec2',region_name=region)
        try:
            sgres = [a['Value'] for a in ec2res.SecurityGroup(i['GroupId']).tags if a['Key'] == 'System']

        except TypeError:
            sgres = None

        if sgres:
            try:
                systemcheck = alltags[sgres[0]]

            except KeyError:
                    print (f"{i['GroupId']} SG System 태그 {sgres[0]} 와 매칭되는 System 키가 없습니다")
                    systemcheck = None

            if systemcheck:
                ec2res.SecurityGroup(i['GroupId']).create_tags(Tags=systemcheck)

def networktagging():
    alltags = Alltags()
    ec2 = boto3.client('ec2',region_name=region)
    client = ec2.describe_network_interfaces()

    for i in client['NetworkInterfaces']:
        ec2res = boto3.resource('ec2',region_name=region)
        try:
            netres = [a['Value'] for a in ec2res.NetworkInterface(i['NetworkInterfaceId']).tag_set if a['Key'] == 'System']

        except TypeError:
            netres = None

        if netres:
            try:
                systemcheck = alltags[netres[0]]
            except KeyError:
                    print (f"{i['NetworkInterfaceId']} ENI System 태그 {netres[0]} 와 매칭되는 System 키가 없습니다")
                    systemcheck = None
            if systemcheck:
                ec2res.NetworkInterface(i['NetworkInterfaceId']).create_tags(Tags=systemcheck)

def elbtagging():
    alltags = Alltags()
    ec2 = boto3.client('elb',region_name=region)
    client = ec2.describe_load_balancers()

    for i in client['LoadBalancerDescriptions']:
        try:
            elbres = [a['Value'] for a in ec2.describe_tags(LoadBalancerNames=[i['LoadBalancerName']])['TagDescriptions'][0]['Tags'] if a['Key'] == 'System']

        except TypeError:
            elbres = None

        if elbres:
            try:
                systemcheck = alltags[elbres[0]]

            except KeyError:
                    print (f"{i['LoadBalancerName']} ELB2 System 태그 {elbres[0]} 와 매칭되는 System 키가 없습니다")
                    systemcheck = None

            if systemcheck:
                ec2.add_tags(LoadBalancerNames=[i['LoadBalancerName']],Tags=systemcheck)

def elb2tagging():
    alltags = Alltags()
    ec2 = boto3.client('elbv2',region_name=region)
    client = ec2.describe_load_balancers()

    for i in client['LoadBalancers']:
        try:
            elb2res = [a['Value'] for a in ec2.describe_tags(ResourceArns=[i['LoadBalancerArn']])['TagDescriptions'][0]['Tags'] if a['Key'] == 'System']
        except TypeError:
            elb2res = None

        if elb2res:
            try:
                systemcheck = alltags[elb2res[0]]

            except KeyError:
                    print (f"{i['LoadBalancerArn']} ELB2 System 태그 {elb2res[0]} 와 매칭되는 System 키가 없습니다")
                    systemcheck = None

            if systemcheck:
                ec2.add_tags(ResourceArns=[i['LoadBalancerArn']],Tags=systemcheck)

def apigatewaytagging():
    client = boto3.client('apigateway')
    for i in client.get_rest_apis()['items']:
        apiid = (i['id'])
        arnres = f'arn:aws:apigateway:{region}::/restapis/{apiid}'
        updatetags = client.tag_resource(
            resourceArn=arnres,
            tags={'Company' : 'AP', 'Country' : 'KR', 'Service' : '', 'STAGE' : 'ETC'}
        )

        print (updatetags)

def sagemakertagging():
    sage = boto3.client('sagemaker', region_name='ap-northeast-2')
    train = sage.list_training_jobs(MaxResults=100)
    for i in train['TrainingJobSummaries']:
        resarn = i['TrainingJobArn']
        tags = sage.add_tags(ResourceArn=resarn,Tags=[{'Key' : 'Country', 'Value' : 'KR'},{'Key' : 'Company', 'Value' : 'AP'},{'Key' : 'Sytem', 'Value' : 'DigitalRnD Recsys'},{'Key' : 'STAGE', 'Value' : 'PRD'}])
        print (resarn)
        time.sleep(1)

    while True:
        try:
            check = train['NextToken']
            train2 = sage.list_training_jobs(NextToken=check,MaxResults=100)
            for j in train2['TrainingJobSummaries']:
                resarn2 = j['TrainingJobArn']
                tags2 = sage.add_tags(ResourceArn=resarn2,Tags=[{'Key' : 'Country', 'Value' : 'KR'},{'Key' : 'Company', 'Value' : 'AP'},{'Key' : 'Sytem', 'Value' : 'DigitalRnD Recsys'},{'Key' : 'STAGE', 'Value' : 'PRD'}])
                print (resarn2)
                time.sleep(1)
        except KeyError:
            sys.exit()

def sagemakertagging2():
    sage = boto3.client('sagemaker', region_name='ap-northeast-2')
    train = sage.list_endpoint_configs(MaxResults=100)
    for i in train['EndpointConfigs']:
        resarn = i['EndpointConfigArn']
        tag = sage.add_tags(ResourceArn=resarn,Tags=[{'Key' : 'Country', 'Value' : 'KR'},{'Key' : 'Company', 'Value' : 'AP'},{'Key' : 'Sytem', 'Value' : 'DigitalRnD Recsys'},{'Key' : 'STAGE', 'Value' : 'PRD'}])
        print (resarn)
        time.sleep(1)

def InsTags(instanceid):
    ec2 = boto3.resource('ec2')

    for instance in ec2.instances.filter(InstanceIds=[instanceid]):
        try:
            SystemTag = list(filter(lambda tag: tag['Key'] == 'System', instance.tags))[0]['Value']
            InsTags = list(filter(lambda tag: tag['Key'] == 'System' or tag['Key'] == 'Company' or tag['Key'] == 'Country' or tag['Key'] == 'STAGE', instance.tags))
            return (InsTags)
        except:
            pass

def VolumeTagging():
    ec2 = boto3.client('ec2')
    ec2res = boto3.resource('ec2')
    client = ec2.describe_volumes()

    for i in client['Volumes']:
        if i['State'] == 'in-use':
            # 사용중인 Volume 중에서 System Tag 가 없는 Volume 만 진행
            try:
                tagcheck = [a for a in i['Tags'] if a['Key'] == 'System']
                if tagcheck:
                    pass
                else:
                    instanceid = [b['InstanceId'] for b in i['Attachments']]
                    tag = (InsTags(instanceid[0]))

            # Tag 가 없는 경우
            except KeyError:
                instanceid = [b['InstanceId'] for b in i['Attachments']]
                tag = (InsTags(instanceid[0]))

            if tag:
                ec2res.Volume(i['VolumeId']).create_tags(Tags=tag)
                print (f"{i['VolumeId']} 볼륨에 {tag} 추가 완료하였습니다.")

def ENITagging():
    ec2 = boto3.client('ec2')
    ec2res = boto3.resource('ec2')
    client = ec2.describe_network_interfaces()

    for i in client['NetworkInterfaces']:
        tagcheck = [a for a in i['TagSet'] if a['Key'] == 'System']
        if tagcheck:
            pass
        else:
            print (i)

ENITagging()

#def lambda_handler(event, context):

    #amitagcreate()
    #createSnapshotTag()
    #enitagcreate("APPRD")
    #sgtagging("APPRD")
    #rdssnapshot()

    ### System 기반 Tagging 사용
    #volumtagging()
    #securitytagging()
    #networktagging()
    #elbtagging()
    #elb2tagging()
    #apigatewaytagging()
    #sagemakertagging2()


# 1. Use BFS to construct a graph.
# 2. Use DFS to construct the paths from end to start.
import string
import collections
class Solution(object):
    def findLadders(self, start, end, wordlist):
        """
        :type beginWord: str
        :type endWord: str
        :type wordlist: Set[str]
        :rtype: List[List[int]]
        """
        results = []
        if not wordlist:
            return results

        found = False
        trace = collections.defaultdict(list)
        beginSet = set()
        beginSet.add(start)
        wordlist.add(start)
        wordlist.add(end)

        while beginSet and not found:
            tempSet = set()
            for word in beginSet:
                wordlist.remove(word)
            for word in beginSet:
                for i in xrange(len(word)):
                    for c in string.ascii_lowercase:
                        tmp = word[:i] + c + word[i+1:]
                        if tmp in wordlist:
                            tempSet.add(tmp)
                            trace[tmp].append(word)
                            if tmp == end:
                                found = True
            beginSet = tempSet

        if found:
            self.backTrace(end, start, results, [], trace)
        return results

    def backTrace(self, word, start, results, path, trace):
        if word == start:
            results.append([start] + path)
            return
        if word in trace:
            for pre in trace[word]:
                self.backTrace(pre, start, results, [word] + path, trace)


"""
Example of using the stdpopsim library with msprime.
"""
import msprime

import stdpopsim
from stdpopsim import e_coli

chrom = e_coli.genome.chromosomes["chr"]
#recomb_map = chrom.recombination_map()

model = e_coli.LapierreConstant()
model.debug()

samples=[msprime.Sample(population=0, time=0)]*100

ts = msprime.simulate(
    samples=samples,
    mutation_rate=chrom.default_mutation_rate,
    **model.asdict())
print("simulated:", ts.num_trees, ts.num_sites)
print("mean mut rate", chrom.default_mutation_rate)


# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# NBI API Loader
# ----------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------

# Python modules
from __future__ import absolute_import
import logging
import inspect
import threading
import os
# NOC modules
from noc.config import config
from .base import NBIAPI

logger = logging.getLogger(__name__)
BASE_PREFIX = os.path.join("services", "nbi", "api")

class NBIAPILoader(object):
    def __init__(self):
        self.apis = {}  # Load API
        self.lock = threading.Lock()
        self.all_apis = set()

    def get_api(self, name):
        """
        Load API and return NBIAPI instance.
        Returns None when no API found or loading error occured
        """
        with self.lock:
            api = self.apis.get(name)
            if not api:
                logger.info("Loading API %s", name)
                if not self.is_valid_name(name):
                    logger.error("Invalid API name")
                    return None
                for path in config.get_customized_paths(BASE_PREFIX, prefer_custom=True):
                    if not os.path.exists(path):
                        continue
                    if path == BASE_PREFIX:
                        base_name = "noc"
                    else:
                        base_name = "noc.custom"
                    mn = "%s.services.nbi.api.%s" % (base_name, name)
                    try:
                        sm = __import__(mn, {}, {}, "*")
                        for n in dir(sm):
                            o = getattr(sm, n)
                            if (
                                inspect.isclass(o) and
                                issubclass(o, NBIAPI) and
                                o.__module__ == sm.__name__
                            ):
                                api = o
                                break
                        if not api:
                            logger.error("API not found: %s", name)
                    except Exception as e:
                        logger.error("Failed to load API %s: %s", name, e)
                        api = None
                self.apis[name] = api
            return api

    def is_valid_name(self, name):
        return ".." not in name

    def iter_apis(self):
        with self.lock:
            if not self.all_apis:
                self.all_apis = self.find_apis()
        for api in sorted(self.all_apis):
            yield api

    def find_apis(self):
        """
        Scan all available API
        """
        names = set()
        for path in config.get_customized_paths(BASE_PREFIX, prefer_custom=True):
            if not os.path.exists(path):
                continue
            for fn in os.listdir(path):
                if fn.startswith("_") or not fn.endswith(".py"):
                    continue
                names.add(fn[:-3])
        return names

# Create singleton object
loader = NBIAPILoader()


import turtle

def main():
    wn = turtle.Screen()
    wn.bgcolor("lightgreen")
    wn.title("Hello, Tess!")

    tess = turtle.Turtle()
    tess.color("blue")
    tess.pensize(3)

    tess.forward(50)
    tess.left(120)
    tess.forward(50)

    wn.mainloop()

if __name__ == '__main__':
    main()


'''
Created on Jun 30, 2015

@author: Luiz fernando
'''

from wiringx86 import GPIOEdison as GPIO;
import time;

gpio=GPIO(debug=False);

pin=13;

gpio.pinMode(pin,gpio.OUTPUT);
turnON=0;
try:
    while (True):

        turnON=input('on or off (1 or 0): ');
        if turnON ==1:
            gpio.digitalWrite(pin,gpio.HIGH);

        elif turnON==0:
            gpio.digitalWrite(pin,gpio.LOW);
        else:
            return;
        print (turnON);

        time.sleep(1);

except KeyboardInterrupt:
    print('cleaning up and exiting');
    gpio.cleanup();


'''
使用类方法来实现多个构造器
'''

import time

class Date:
	def __init__(self, year, month, day):
		self.year = year
		self.month = month
		self.day = day

	@classmethod
	def today(cls):
		t = time.localtime()
		return cls(t.tm_year, t.tm_mon, t.tm_mday)

a = Date(2021, 2, 2)
b = Date.today()
print(b)


#!/usr/bin/env python2
import BaseHTTPServer
import mimetypes
import os
import SimpleHTTPServer
import subprocess
import urllib
import urlparse

class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
	def do_GET(self):
		try:
			self.path=self.path.split('?')
			query_str='?'.join(self.path[1:])
			if len(query_str)>0:
				query_str='?'+query_str
			if query_str=='?get_frame':
				self.send_response(200)
				self.send_header('Content-type','application/json')
				self.end_headers()
				self.wfile.write(json.dumps(last_frame))
				self.wfile.close()
				return
			self.path=self.path[0]
			if len(self.path)>0 and self.path[-1]=='/':
				self.path+='index.html'
			cwd=os.getcwd()+'/web/'
			self.path=os.path.abspath(cwd+self.path)
			if self.path.find(cwd)!=0 or not os.path.isfile(self.path):
				self.send_response(404)
				self.end_headers()
				return
			file=open(self.path,'r')
			self.send_response(200)
			mime=mimetypes.guess_type(self.path)
			if len(mime)>0:
				mime=mime[0]
			else:
				mime='text/plain'
			print(mime+' '+self.path)
			self.send_header('Content-type',mime)
			self.end_headers()
			self.wfile.write(file.read())
			self.wfile.close()
		except Exception as error:
			print(error)
			self.send_response(401)

	def do_POST(self):
		try:
			query_str=urlparse.urlparse(self.path).query

			for query in query_str.split('&'):
				try:
					query=query.split('=')

					if len(query)>1:
						key=query[0]
						val=urllib.unquote(query[1]).lower()
						valid=['ipfw','iptables','netsh','pf','ipf','ufw','wipfw']
						if key=='def':
							file=open('wofgen/rules.wof','r')
							self.send_response(200)
							self.send_header('Content-type','text/plain')
							self.end_headers()
							self.wfile.write(file.read())
							self.wfile.close()
						elif key!='wof' or val not in valid:
							self.send_response(400)
						else:
							data_len=int(self.headers.getheader('content-length',0))
							if data_len>100000:
								data_len=100000
							data=self.rfile.read(data_len)
							cmd=['wofgen/bin/wofgen_'+val]
							p=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)
							out,err=p.communicate(data)
							err=err.split('\n')
							errmsg=''
							for ii in range(0,len(err)):
								if err[ii].lower().startswith('error'):
									errmsg=err[ii]
									break
							if len(errmsg)>0:
								out=errmsg
							self.send_response(200)
							self.send_header('Content-type','text/plain')
							self.end_headers()
							self.wfile.write(out)
							self.wfile.close()
				except:
					pass
		except:
			pass

try:
	Handler=MyHandler
	server=BaseHTTPServer.HTTPServer(('127.0.0.1',8080),MyHandler)
	server.serve_forever()
except:
	pass


from time import sleep
from airflow.models import Variable
from airflow.hooks.base_hook import BaseHook
from googleapiclient import discovery
from slack_message import slack_message
import requests
import json

def get_project_id():
    apiurl = "http://metadata.google.internal/computeMetadata/v1/project/project-id"
    response = requests.get(apiurl, headers={"Metadata-Flavor": "Google"})
    response.raise_for_status()
    return response.text

def instance_group_manager_info(project_id, instance_group):
    service = discovery.build('compute', 'v1')
    request = service.instanceGroupManagers().get(project=project_id, zone=instance_group['zone'], instanceGroupManager=instance_group['name'])
    return request.execute()

def instance_group_info(project_id, instance_group):
    service = discovery.build('compute', 'v1')
    request = service.instanceGroups().get(project=project_id, zone=instance_group['zone'], instanceGroup=instance_group['name'])
    return request.execute()

def list_managed_instances(instance_group):
    project_id = get_project_id()
    service = discovery.build("compute", "v1")
    page_token = None
    instances = []
    while True:
        request = service.instanceGroupManagers().listManagedInstances(project=project_id, zone=instance_group["zone"], instanceGroupManager=instance_group["name"], pageToken=page_token, maxResults=20)
        ret = request.execute()
        if not ret:
            return instances
        instances += [r["instance"] for r in ret['managedInstances']]
        page_token = ret.get("nextPageToken", None)
        if not page_token:
            break

    return instances

def get_instance_property(instance_group, instance, key):
    project_id = get_project_id()
    service = discovery.build("compute", "v1")
    request = service.instances().get(project=project_id, zone=instance_group['zone'], instance=instance)
    ret = request.execute()
    return ret[key]

def delete_instances(ig, instances):
    project_id = get_project_id()
    request_body = {
        "instances": instances,
        "skipInstancesOnValidationError": True,
    }
    service = discovery.build('compute', 'v1')
    request = service.instanceGroupManagers().deleteInstances(project=project_id, zone=ig["zone"], instanceGroupManager=ig["name"], body=request_body)
    ret = request.execute()
    print(ret)

def get_cluster_target_size(project_id, instance_groups):
    total_size = 0
    for ig in instance_groups:
        info = instance_group_manager_info(project_id, ig)
        total_size += info['targetSize']
    return total_size

def get_cluster_size(project_id, instance_groups):
    total_size = 0
    for ig in instance_groups:
        info = instance_group_info(project_id, ig)
        total_size += info['size']
    return total_size

def reset_cluster(key, initial_size):
    try:
        project_id = get_project_id()
        cluster_info = json.loads(BaseHook.get_connection("InstanceGroups").extra)
    except:
        slack_message(":exclamation:Failed to load the cluster information from connection {}".format("InstanceGroups"))
        slack_message(":exclamation:Cannot reset cluster {}".format(key))
        return

    if key not in cluster_info:
        slack_message(":exclamation:Cannot find the cluster information for key {}".format(key))
        slack_message(":exclamation:Cannot reset cluster {}".format(key))
        return

    total_size = get_cluster_target_size(project_id, cluster_info[key])

    try:
        target_sizes = Variable.get("cluster_target_size", deserialize_json=True)
        target_size = target_sizes[key]
        total_size = target_size
    except:
        slack_message(":information_source: Cannot obtain the target size of cluster {}".format(key))

    slack_message(":information_source:Start reseting {} instances in cluster {}".format(total_size, key))
    ramp_down_cluster(key, 0)
    slack_message(":information_source:Reduce the number of instances to 0, wait 5 min to spin them up again")
    sleep(300)
    ramp_up_cluster(key, initial_size, total_size)
    slack_message(":information_source:{} instances in cluster {} restarted".format(total_size, key))

def resize_instance_group(instance_group, size):
    project_id = get_project_id()

    total_size = get_cluster_target_size(project_id, instance_group)

    max_size = 0
    for ig in instance_group:
        max_size += ig['max_size']

    if size > max_size:
        slack_message(":information_source:Limit the number of instances to {} instead of {}".format(max_size, size))

    downsize = False
    if size < total_size:
        downsize = True

    target_size = size
    for ig in instance_group:
        info_group_manager = instance_group_manager_info(project_id, ig)
        info_group = instance_group_info(project_id, ig)
        ig_size = min(target_size, ig['max_size'])
        if ig_size < info_group["size"] and not downsize:
            continue
        if info_group_manager["targetSize"] > info_group["size"]:
            ig_size = min(ig_size, info_group["size"]+1)
        service = discovery.build('compute', 'v1')
        request = service.instanceGroupManagers().resize(project=project_id, zone=ig['zone'], instanceGroupManager=ig['name'], size=ig_size)
        response = request.execute()
        print(json.dumps(response, indent=2))
        slack_message(":information_source: resize instance group {} to {} instances".format(ig['name'], ig_size), notification=True)
        target_size -= ig_size
        if not downsize and target_size == 0:
            break
        if downsize and target_size <= 0:
            target_size = 0
        sleep(30)

    return min(size, max_size)

def ramp_up_cluster(key, initial_size, total_size):
    try:
        target_sizes = Variable.get("cluster_target_size", deserialize_json=True)
        target_sizes[key] = total_size
        Variable.set("cluster_target_size", target_sizes, serialize_json=True)
        slack_message(":information_source: ramping up cluster {} to {} instances, starting from {} instances".format(key, total_size, min(initial_size, total_size)))
        increase_instance_group_size(key, min(initial_size, total_size))
    except:
        increase_instance_group_size(key, total_size)

def ramp_down_cluster(key, total_size):
    try:
        target_sizes = Variable.get("cluster_target_size", deserialize_json=True)
        target_sizes[key] = total_size
        Variable.set("cluster_target_size", target_sizes, serialize_json=True)
        reduce_instance_group_size(key, total_size)
    except:
        reduce_instance_group_size(key, total_size)

def increase_instance_group_size(key, size):
    try:
        project_id = get_project_id()
        cluster_info = json.loads(BaseHook.get_connection("InstanceGroups").extra)
    except:
        slack_message(":exclamation:Failed to load the cluster information from connection {}".format("InstanceGroups"))
        slack_message(":exclamation:Cannot increase the size of the cluster to {} instances".format(size))
        return

    if key not in cluster_info:
        slack_message(":exclamation:Cannot find the cluster information for key {}".format(key))
        slack_message(":exclamation:Cannot increase the size of the cluster to {} instances".format(size))
        return

    total_size = get_cluster_target_size(project_id, cluster_info[key])
    if total_size > size:
        slack_message(":arrow_up: No need to scale up the cluster ({} instances requested, {} instances running)".format(size, total_size))
        return
    else:
        real_size = resize_instance_group(cluster_info[key], size)
        slack_message(":arrow_up: Scale up cluster {} to {} instances".format(key, real_size))

def reduce_instance_group_size(key, size):
    try:
        project_id = get_project_id()
        cluster_info = json.loads(BaseHook.get_connection("InstanceGroups").extra)
    except:
        slack_message(":exclamation:Failed to load the cluster information from connection {}".format("InstanceGroups"))
        slack_message(":exclamation:Cannot reduce the size of the cluster to {} instances".format(size))
        return

    if key not in cluster_info:
        slack_message(":exclamation:Cannot find the cluster information for key {}".format(key))
        slack_message(":exclamation:Cannot reduce the size of the cluster to {} instances".format(size))
        return

    total_size = get_cluster_target_size(project_id, cluster_info[key])
    if total_size < size:
        slack_message(":arrow_down: No need to scale down the cluster ({} instances requested, {} instances running)".format(size, total_size))
        return
    else:
        real_size = resize_instance_group(cluster_info[key], size)
        slack_message(":arrow_down: Scale down cluster {} to {} instances, sleep for one minute to let it stablize".format(key, real_size))
        sleep(60)

def cluster_status(name, cluster):
    project_id = get_project_id()
    current_size = get_cluster_size(project_id, cluster)
    requested_size = get_cluster_target_size(project_id, cluster)
    stable = True
    if requested_size > 0:
        slack_message(":information_source: status of cluster {}: {} out of {} instances up and running".format(name, current_size, requested_size), notification=True)

    if (requested_size - current_size) > 0.1 * requested_size:
        slack_message(":exclamation: cluster {} is still stabilizing, {} of {} instances created".format(name, current_size, requested_size))
        stable = False

    return stable, requested_size

def collect_resource_metrics(start_time, end_time):
    import pendulum
    from google.cloud import monitoring_v3

    project_id = get_project_id()
    cluster_info = json.loads(BaseHook.get_connection("InstanceGroups").extra)

    resources = {}

    for k in cluster_info:
        resources |= {ig['name'] : {} for ig in cluster_info[k]}

    alignment_period = 60

    client = monitoring_v3.MetricServiceClient()
    project_name = f"projects/{project_id}"

    interval = monitoring_v3.TimeInterval(
        {
            "end_time": {"seconds": int(end_time.timestamp()), "nanos": 0},
            "start_time": {"seconds": int(start_time.timestamp()), "nanos": 0},
        }
    )
    aggregation_sum = monitoring_v3.Aggregation(
        {
            # Use SUM for DELTA metrics
            "alignment_period": {"seconds": alignment_period},
            "per_series_aligner": monitoring_v3.Aggregation.Aligner.ALIGN_SUM,
            "cross_series_reducer": monitoring_v3.Aggregation.Reducer.REDUCE_SUM,
            "group_by_fields": ["metadata.user_labels.vmrole", "metadata.user_labels.location", "metadata.system_labels.instance_group"],
        }
    )

    aggregation_sum_gcs = monitoring_v3.Aggregation(
        {
            # Use SUM for DELTA metrics
            "alignment_period": {"seconds": alignment_period},
            "per_series_aligner": monitoring_v3.Aggregation.Aligner.ALIGN_SUM,
            "cross_series_reducer": monitoring_v3.Aggregation.Reducer.REDUCE_SUM,
            "group_by_fields": ["metric.label.method", "resource.label.bucket_name"],
        }
    )

    aggregation_mean = monitoring_v3.Aggregation(
        {
            # SUM over series so we can average by uptime
            "alignment_period": {"seconds": alignment_period},
            "per_series_aligner": monitoring_v3.Aggregation.Aligner.ALIGN_MEAN,
            "cross_series_reducer": monitoring_v3.Aggregation.Reducer.REDUCE_SUM,
            "group_by_fields": ["metadata.user_labels.vmrole", "metadata.user_labels.location", "metadata.system_labels.instance_group"],
        }
    )

    def query_metric(metric, aggregation):
        try:
            return client.list_time_series(
               request={
                   "name": project_name,
                   "filter": f'metric.type = "{metric}"',
                   "interval": interval,
                   "view": monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL,
                   "aggregation": aggregation,
               }
            )
        except:
            print(f"Cannot fetch metric {metric}")
            return []

    for result in query_metric("compute.googleapis.com/instance/uptime", aggregation_sum):
        group_name = result.metadata.system_labels.fields['instance_group'].string_value
        if group_name in resources:
            resources[group_name]["uptime"] = pendulum.duration(seconds=sum(p.value.double_value for p in result.points))

    for result in query_metric("compute.googleapis.com/instance/cpu/usage_time", aggregation_sum):
        group_name = result.metadata.system_labels.fields['instance_group'].string_value
        if group_name in resources and "uptime" in resources[group_name]:
            resources[group_name]["cputime"] = pendulum.duration(seconds=sum(p.value.double_value for p in result.points))
            resources[group_name]["cpu_utilization"] = resources[group_name]["cputime"].total_seconds()/resources[group_name]["uptime"].total_seconds()*100

    for result in query_metric("compute.googleapis.com/instance/network/received_bytes_count", aggregation_sum):
        group_name = result.metadata.system_labels.fields['instance_group'].string_value
        if group_name in resources and "uptime" in resources[group_name]:
            resources[group_name]["received_bytes"] = sum(p.value.int64_value for p in result.points)

    for result in query_metric("compute.googleapis.com/instance/network/sent_bytes_count", aggregation_sum):
        group_name = result.metadata.system_labels.fields['instance_group'].string_value
        if group_name in resources and "uptime" in resources[group_name]:
            resources[group_name]["sent_bytes"] = sum(p.value.int64_value for p in result.points)

    for result in query_metric("custom.googleapis.com/instance/gpu/utilization", aggregation_mean):
        group_name = result.metadata.system_labels.fields['instance_group'].string_value
        if group_name in resources and "uptime" in resources[group_name]:
            resources[group_name]["gputime"] = pendulum.duration(seconds=sum(p.value.double_value*alignment_period/100 for p in result.points))
            resources[group_name]["gpu_utilization"] = resources[group_name]["gputime"].total_seconds()/resources[group_name]["uptime"].total_seconds()*100

    buckets = Variable.get("gcs_buckets", deserialize_json=True, default_var=[])
    resources["GCS"] = {}

    for result in query_metric("storage.googleapis.com/api/request_count", aggregation_sum_gcs):
        bucket = result.resource.labels['bucket_name']
        if bucket in buckets:
            if bucket not in resources["GCS"]:
                resources["GCS"][bucket] = {}

            resources["GCS"][bucket][result.metric.labels['method']] = resources["GCS"][bucket].get(result.metric.labels['method'], 0) + sum(p.value.int64_value for p in result.points)

    return resources


import sys
import pandas as pd
import random

df=pd.read_csv('mcq.csv',usecols=['Name','Symbol'])
#creating separate lists for name ans symbol
name=df['Name'].tolist()
symbol=df['Symbol'].tolist()
#creating a dictionary where question is the key and answer is its value
ori_dict={name[i]:[symbol[i]] for i in range(len(name))}
final_dict={}

#creating a choices dictionary and editing it to create questions and their choices

for i in name:
    for j in symbol:
        choices=random.sample(symbol,2)
        break
    final_dict[i]=choices
#print final_dict
result={key: value + final_dict[key] for key,value in ori_dict.items()}
#print(result)
#code to replace duplicate choices of a question
for i,j in result.items():
    if (j[0]==j[1])|(j[0]==j[2]):
        j[0]=random.choice( [x for x in symbol if (x!=j[1])&(x!=j[2])])
        #print(j)

for i in result.values():
    random.shuffle(i)
    #print(i)
#printing question paper
print("You can only print one question paper set at a time")

while(1):

    print("\nEnter 1 to view a question paper: ")
    ch=int(input())
    print("\n")

    if ch==1:

        temp_n=random.sample(result.keys(),20)
        #print(temp_n)
        temp_s=[result[k] for k in temp_n]
        #print(temp_s)

        for i in range(20):
            print(str(i+1)+". What is the symbol of "+temp_n[i]+"?")
            print("A."+temp_s[i][0]+" B."+temp_s[i][1]+" C."+temp_s[i][2]+"\n")

        print("Answer key for the above question paper:\n")

        for i in temp_n:
            x=temp_n.index(i)+1
            if (ori_dict[i][0]==result[i][0]):
                print(str(x)+".A")

            elif (ori_dict[i][0]==result[i][1]):
                print(str(x)+".B")

            elif (ori_dict[i][0]==result[i][2]):
                print(str(x)+".C")

    else:
        print("Try Again!")
        sys.exit(1)


# Ying Dang and Derek Rhodehamel
# CSE 415 A, Spring 2016
# Homework 4: Option B

# COMPLETE
# Klotski is a game represented by 1x1, 1x2, and 2x1 tiles followed by a single 2x2 tile
# in a 4x5 board with two 1x1 squares left empty.

# The goal of the game is to manuever the tiles by "swapping" with the empty spaces
# in such a way that the 2x2 block is located at the center bottom in order to remove that
# tile in the "exit" opening at the center bottom of the board.

#<INITIAL_STATE>
GOAL_BLOCK = 'A'
CREATE_INITIAL_STATE = lambda : ["B", "A", "A", "C",
                                 "B", "A", "A", "C",
                                 "D", "E", "E", "F",
                                 "D", "G", "H", "F",
                                 "I", "_", "_", "J"]
"""
CREATE_INITIAL_STATE = lambda : ["E", "E", "_", "H",
                                 "B", "G", "_", "C",
                                 "B", "A", "A", "C",
                                 "D", "A", "A", "F",
                                 "D", "I", "J", "F"]"""
#</INITIAL_STATE>

# class for a piece
# represented by it's id = ALPHA_CHAR
#                      x = top left starting x
#                      y = top left starting y
#                      w = how wide to the right
#                      h = how long to the bottom
# defining can move precond
class Piece:
    # constructor
    def __init__(self, id, x, y, w, h):
        self.id = id
        self.x = x
        self.y = y
        self.w = w
        self.h = h

    # string representation of the piece
    def __str__(self):
        return self.id + " " + str(int(self.x)) + " " + str(int(self.y)) \
        + " " + str(int(self.w)) + " " + str(int(self.h))

    # precond defining whether or not this piece can move in a certain
    # direction given a current state
    def can_move(self, state, direction):
        w = int(self.w)
        h = int(self.h)
        x = int(self.x)
        y = int(self.y)
        try:
            move = 1
            if direction == 1 or direction == 2:
                move = -1
            if direction == 0:
                move += w - 1
            if direction == 3:
                move += h - 1
            if direction % 2 == 0:
                for i in range(h):
                    if 0 <= x + move < 4:
                        if state[4*(y + i) + x + move] != "_":
                            return False
                    else:
                        return False
            else:
                for i in range(w):
                    if 0 <= y + move < 5:
                        if state[4*(y + move) + (x + i)] != "_":
                            return False
                    else:
                        return False
            return True

        except (Exception) as e:
            print(e)

# returns a message when the goal is reached
def goal_message(s):
    return "Solved the Klotski puzzle, champ!"

# Performs an appropriately deep copy of a state,
# for use by operators in creating new states.
def copy_state(s):
    new_state = list(s)
    return new_state

# determines whether or not the two states are indentical by value
def DEEP_EQUALS(s1, s2):
    for i in range(len(s1)):
        if s1[i] != s2[i]:
            return False
    return True

# string representation of the state of the game as shown:
# A B B C
# A B B C
# D E E F
# D G H F
# I _ _ J
def DESCRIBE_STATE(state):
    result = ""
    for row in range(5):
        result = result + "   "
        for col in range (4):
            result = result + (str(state[4 * row + col]) + " ")
        result = result + "\n"
    return result

# hashes the current state given such that all states
# are guaranteed to be unique
def HASHCODE(state):
    return DESCRIBE_STATE(state)

class Operator:
    def __init__(self, name, precond, state_transf):
        self.name = name
        self.precond = precond
        self.state_transf = state_transf

    def is_applicable(self, s):
        return self.precond(s)

    def apply(self, s):
        return self.state_transf(s)

# moves a tile in the given direction in the current state given
# and returns that new state
def move(s, tile, dir):
    '''Assuming it's legal to make the move, this computes
     the new state resulting from moving the a tile to an available
     location'''
    new_state = copy_state(s)

    curr_index = tile.y * 4 + tile.x
    for width in range(tile.w):
        for height in range(tile.h):
            tile_index = int(curr_index + width + height * 4)

            if dir == 3:
                new_state[tile_index + 4] = s[tile_index]
                if height == 0:
                    new_state[tile_index] = "_"

            elif dir == 1:
                new_state[tile_index - 4] = s[tile_index]
                if height == tile.h - 1:
                    new_state[tile_index] = "_"

            elif dir == 0:
                new_state[tile_index + 1] = s[tile_index]
                if width == 0 :
                    new_state[tile_index] = "_"

            else:
                new_state[tile_index - 1] = s[tile_index]
                if width == tile.w - 1:
                    new_state[tile_index] = "_"

    return new_state

# determines whether or not the state is a goal state
# implying that 2x2 square is on the center bottom
def goal_test(state):
    return state[13] == GOAL_BLOCK and state[14] == GOAL_BLOCK and \
           state[17] == GOAL_BLOCK and state[18] == GOAL_BLOCK

# translate a numerical direction into the corresponding
# compass direction in the following format:
#    1
# 2     0
#    3
# on the condition that only 0 - 3 is passed in
def translate_dir(num):
    dir = ''
    if num == 0:
        dir = 'east'
    elif num == 1:
        dir = 'north'
    elif num == 2:
        dir = 'west'
    else:
        dir = 'south'
    return dir

# returns the can_move function of the given piece in a
# direction relative to the state
def can_move(s, piece, direction):
    return piece.can_move(s, direction)

# creates a list of all possible combinations of tiles to
# direction = (0, 1, 2, 3) and returns it
def combo_list():
    ls = []
    for tile in sorted(list(set(CREATE_INITIAL_STATE()) - set(['_']))):
        for i in range(4):
            ls.append((tile, i))
    return ls

# makes a piece object given a tile and the state locating that tile
# and returns it
def make_piece(state, tile):
    index = state.index(tile)
    curr_col = index % 4
    curr_row = int(index / 4)

    shape = [1,1]
    if state[(index + 1)%len(state)] == state[index]:
        shape[0] += 1
    if state[(index + 4)%len(state)] == state[index]:
        shape[1] += 1
    return Piece(state[index], curr_col, curr_row, shape[0], shape[1])

#<OPERATORS>
OPERATORS = [Operator("Move tile " + str(tile) + " to the " + str(translate_dir(direction)),
                      lambda s, p=tile, q=direction: can_move(s, make_piece(s, p), q),
                      lambda s, p=tile, q=direction: move(s, make_piece(s, p), q))
             for (tile, direction) in combo_list()]
#</OPERATORS>

#<GOAL_TEST> (optional)
GOAL_TEST = lambda s: goal_test(s)
#</GOAL_TEST>

#<GOAL_MESSAGE_FUNCTION> (optional)
GOAL_MESSAGE_FUNCTION = lambda s: goal_message(s)
#</GOAL_MESSAGE_FUNCTION>

# totals up the number of tile square beneath the goal block
# including whether or not the empty spaces are adjacent
# and returns that value
def h_custom(s):
    goal_y = int(s.index(GOAL_BLOCK) / 4) + 1
    total = 0
    empty_index = int(s.index('_'))
    if ((empty_index+1)%4 != 0 and s[(empty_index+1)%4] != '_') \
            or (s[(empty_index + 4) % 20] != '_'):
        total += 2

    for key in sorted(set(s) - set(['_'])):
        piece = make_piece(s, key)
        if (piece.y > goal_y):
            total += piece.w * piece.h
    return int(total)

#<HEURISTICS>
HEURISTICS = {'h_custom':h_custom}
#</HEURISTICS>

# <STATE_VIS>
def render_state(s):
    return DESCRIBE_STATE(s)
# </STATE_VIS>


# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""

import abc

from mako import parsetree
from mako.ast import PythonFragment

from .exceptions import ForbiddenMakoTemplateException

class MakoNodeCodeExtractor:
    @abc.abstractmethod
    def extract(self, node):
        """
        处理 Mako Lexer 分割出来的 code 对象，返回需要检测的 python 代码，返回 None 表示该节点不需要处理

        :param node: mako parsetree node
        :return: 需要处理的代码，或 None
        """
        raise NotImplementedError()

class StrictMakoNodeCodeExtractor(MakoNodeCodeExtractor):
    def extract(self, node):
        if isinstance(node, parsetree.Code) or isinstance(node, parsetree.Expression):
            return node.text
        elif isinstance(node, parsetree.ControlLine):
            if node.isend:
                return None
            return PythonFragment(node.text).code
        elif isinstance(node, parsetree.Text):
            return None
        else:
            raise ForbiddenMakoTemplateException(
                "不支持[{}]节点".format(node.__class__.__name__)
            )


# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.db import models

class Patient(models.Model):
    name = models.CharField(max_length=1000,null=True)
    age = models.DateField(null=True)

class MedicalHistory(models.Model):
    patient = models.ForeignKey(Patient,on_delete=models.CASCADE)
    description = models.CharField(max_length=1000)

class Contact(models.Model):
	patient = models.ForeignKey(Patient,on_delete=models.CASCADE)
	phonenumber = models.CharField(max_length=11)


# encoding: utf-8
import sys
import os
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] [%(levelname)s]:: %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    # filename='testRe.log',
                    # filemode='w'
                    )

fp = open('allUrl.txt', 'r')
lines = fp.readlines()
urls = []
for line in lines:
    line = line.split(':::')
    # logging.debug(line[0])
    # logging.debug(line[1])
    urls.append([line[0].strip(), line[1].strip()])

for url in urls:
    logging.info(url[0] + url[1].decode('gbk'))


class Solution(object):
    def twoSum(self, numbers, target):
        """

        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """

        target_dict = dict()

        for x, y in enumerate(numbers, 1):
            _target = target - y
            if _target not in target_dict:
                target_dict[y] = x
            else:
                return [target_dict.get(_target), x]

def main():
    solution = Solution()
    ret = solution.twoSum([2, 7, 11, 15], 9)
    print(ret)

if __name__ == '__main__':
    main()


p, q = int(input()), int(input())

count = 0

for i in range(p, q+1):
    s = str(i**2)
    l = len(s)
    a = 0
    if l > 1:
        a = int(s[:int(l/2)])
    b = int(s[int(l/2):])
    if (a+b == i):
        count += 1
        print(i, end=' ')

if not count:
    print("INVALID RANGE")


"""
Take (gzipped) input MAF file(s) and write fasta files, for one non-focal species,
with the same coordinates as the focal species. Capital letters in the non-focal
species' fasta files represent standard 5' -> 3' direction of nucleotides. Lower-
case letters represent the reverse synteny of the 5' -> 3' strand (necessary
when 5'/3' context is required, eg. when defining CpG sites). Run once for each
non-focal alignment required (because this program eats up a lot of RAM by keeping
the new data in memory)
"""

import argparse, gzip, sys, Bio, csv, glob, string, copy
from Bio import SeqIO, AlignIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import generic_dna

parser = argparse.ArgumentParser(description="""make reference sequences populated by outgroup alleles using
                                                pairwise alignments in MAF format""")

parser.add_argument('MAF_file_directory', help='the directories with the MAF format files in from EBI')
parser.add_argument('reference_fai_file', help='the index for the reference file, in fasta format - to get the chromosome lengths')
parser.add_argument('reference_species', help='the name of the species that you want to get an outgroup alignment FOR, as defined in the MAF file(s)')
parser.add_argument('outgroup_species', help='the name of the species that you want to get outgroup alleles FROM, as defined in the MAF file(s)')

args = parser.parse_args()

# arguments specified on the command line:
reference_file_index = args.reference_fai_file
ref_species = args.reference_species
out_species = args.outgroup_species
MAFdir = args.MAF_file_directory

# initiate an empty dict:
reference_dict = dict()

# read in the index file and fill the dictionary above with the contig lengths
with open(reference_file_index, 'r') as f:
    textreader = csv.reader(f, delimiter='\t', quoting=csv.QUOTE_NONE)
    for line in textreader:
        if not line[0] in reference_dict:
            reference_dict[line[0]] = line[1]

# make a dict of empty contigs, each the length of the original ref sequence's, for the non-focal species
contigs = {name: ['.'] * int(length) for (name, length) in reference_dict.items()}

i=0
for MAFFILE in glob.glob(MAFdir + '*maf.gz'):

    # this bit is specific to the 1000 genomes maf filenames that I've made, and I
    # include it as a sanity check: get the chromosome of the ref sequence from the filename
    # filename format: # Compara.6_primates_EPO.chr1_1.maf.gz
    # chr_check = MAFFILE.split('/')[-1].split('.')[2].split('_')[0].split('chr')[1]

    with gzip.open(MAFFILE, mode = 'rt') as f:
        for multiple_alignment in AlignIO.parse(f, "maf"):
            nogap = None
            contig = None
            strt = None
            stp = None
            in_strand = None
            out_strand = None
            contig_check = True

            # First thing: There may be paralogs in the multiple alignment.
            # eg. the focal species' sequence may map to another part of its own genome
            # OR the focal species' sequence may map to multiple regions in the outgroup species' genome
            # In either of these cases, ignore this record?
            # So this is all the species in the record:
            spps = [seqrec.id.split('.')[0] for seqrec in multiple_alignment]
            # and if there is not only one of each of the in- and outgroup, then skip this multiple alignment record:
            if len([x for x in spps if x == ref_species]) != 1:
                continue
                # print(spps)
            if len([x for x in spps if x == out_species]) != 1:
                continue
                # print(spps)

            # now go through the records one by one, and do the relevant things if
            # it's an ingroup or an outgroup record

            # for the ingroup:
            for seqrec in multiple_alignment:
                if seqrec.id.split('.')[0] == ref_species:
                    # check that the contig actually exists in the reference file
                    contig = ('.').join(seqrec.id.split('.')[1:])
                    if not contig in contigs:
                        contig_check = False
                        continue

                    # # This bit is specific to the primate alignment that I used for
                    # # Peters sfs methods paper:
                    # # check the chromosome is the one we're expecting:
                    # if seqrec.id.split('.')[1] != chr_check:
                    #     print('chromosome from the filename doesn\'t match the chromosome in the seq record for the ingroup')
                    #     sys.exit()

                    # get the strand that the ingroup sequence is on, because this affects whether we need to reverse complement
                    # the outgroup sequence, and affects the coordinates
                    in_strand = int(copy.copy(seqrec.annotations['strand']))

                    # first, the coordinates:
                    if in_strand < 0:
                        strt = seqrec.annotations['srcSize'] - (seqrec.annotations['start'] + seqrec.annotations['size'])
                        stp = seqrec.annotations['srcSize'] - seqrec.annotations['start']
                        nogap = copy.copy([i for i, item in enumerate(seqrec.seq.reverse_complement()) if item != '-'])
                    if in_strand > 0:
                        strt = seqrec.annotations['start']
                        stp = strt + seqrec.annotations['size']
                        nogap = copy.copy([i for i, item in enumerate(seqrec.seq) if item != '-'])

                    # print(len(nogap))
                    # print(stp - strt)
                    # print()

            if not contig_check:
                continue

            # for the outgroup:
            for seqrec in multiple_alignment:
                if seqrec.id.split('.')[0] == out_species:
                    # this is the strand that the outgroup sequence is on:
                    out_strand = int(copy.copy(seqrec.annotations['strand']))

                    # now carry out the following logic:
                    # if in_strand == out_strand: sequence should be uppercase, because synteny is the same in the in- and outgroups; else sequence should be lowercase
                    # if in_strand < 0: sequence should be reverse complemented to get the alleles that match the human reference sequence
                    tempSeq1 = seqrec.seq

                    if in_strand == out_strand:
                        tempSeq2 = tempSeq1.upper()
                    if in_strand != out_strand:
                        tempSeq2 = tempSeq1.lower()

                    if in_strand < 0:
                        mySeq = tempSeq2.reverse_complement()
                    if in_strand > 0:
                        mySeq = tempSeq2

                    # this is the outgroup sequence for positions which aren't gaps in the ingroup sequence:
                    seq_nogaps = [mySeq[i] for i in nogap]

                    contigs[contig][strt:stp] = seq_nogaps

# there may be gaps in the new reference where there are deletions in the ingroup,
# so replace these with missing data:
for c in contigs.values():
    for idx, item in enumerate(c):
        if item == '-':
            c[idx] = '.'

# Now save the new reference a file

# Make a SeqRecord object with all the sequences in it, by concatenating them
# and assigning their contig names.
new_reference = [SeqRecord(Seq(''.join(s), generic_dna), id = c, description = '') for c, s in contigs.items()]

# Write the record above (with a wrap of 60 characters):
filename = ref_species + '_' + out_species + '_alleles.fa'
Bio.SeqIO.write(new_reference, filename, 'fasta')


"""GUI for viewing shapelab's shader compilation logs.
"""

import sys
from pathlib import Path
import argparse

from PyQt5.QtCore import Qt, QFileSystemWatcher, pyqtSlot
from PyQt5.QtWidgets import QTextEdit, QApplication, QWidget, QVBoxLayout, QLabel

class LogsWindow(QWidget):
    def __init__(self, vert_file=None, frag_file=None,
                 link_file=None, parent=None):
        super(LogsWindow, self).__init__(parent)

        self.vert_file = vert_file
        self.frag_file = frag_file
        self.link_file = link_file

        files = [str(file) for file in [vert_file, frag_file, link_file]
                 if file is not None]
        self.fs_watcher = QFileSystemWatcher(files)
        self.fs_watcher.fileChanged.connect(self.file_changed)
        self.fs_watcher.directoryChanged.connect(self.dir_changed)

        self.vert_log = QTextEdit(self)
        self.frag_log = QTextEdit(self)
        self.link_log = QTextEdit(self)

        layout = QVBoxLayout()
        layout.addWidget(QLabel("Vertex shader log: "))
        layout.addWidget(self.vert_log)

        layout.addWidget(QLabel("Fragment shader log: "))
        layout.addWidget(self.frag_log)

        layout.addWidget(QLabel("Link log: "))
        layout.addWidget(self.link_log)

        self.setLayout(layout)

        self._update_text(self.vert_file, self.vert_log)
        self._update_text(self.frag_file, self.frag_log)
        self._update_text(self.link_file, self.link_log)

    @pyqtSlot(str)
    def file_changed(self, path):
        path = Path(path)
        edit = {
            self.vert_file: self.vert_log,
            self.frag_file: self.frag_log,
            self.link_file: self.link_log,
        }

        if path in edit:
            self._update_text(path, edit[path])

    @pyqtSlot(str)
    def dir_changed(self, path):
        print(path)

    def _update_text(self, path, text_edit):
        with open(path, 'r') as file:
            text = '\n'.join(file.readlines())
        text_edit.setText(text)

def _main():
    parser = argparse.ArgumentParser()
    parser.add_argument("shader_stem")

    args = parser.parse_args()
    app = QApplication([])

    vert_file = Path(args.shader_stem).with_suffix(".vert.out")
    frag_file = Path(args.shader_stem).with_suffix(".frag.out")
    link_file = Path(args.shader_stem).with_suffix(".vert.link")

    window = LogsWindow(vert_file=vert_file, frag_file=frag_file,
                        link_file=link_file)
    window.show()

    sys.exit(app.exec_())

if __name__ == '__main__':
    _main()


#####################################################################################################
# Name: Kristopher Carroll
# CSCE A351
# Assignment 1
#####################################################################################################

#########################################################################
#                         **** RESOURCE DUMP ***
#------------------------------------------------------------------------
# General Procedure:
#   https://www.geeksforgeeks.org/theory-of-computation-conversion-from-nfa-to-dfa/
#   https://math.stackexchange.com/questions/1478718/union-of-two-non-deterministic-finite-automata
#   https://www.tutorialspoint.com/automata_theory/ndfa_to_dfa_conversion.htm
#   http://condor.depaul.edu/glancast/444class/docs/nfa2dfa.html
#
# Implementation Examples:
#   https://github.com/caleb531/automata/blob/master/automata/fa
#   http://www.nightmare.com/rushing/python/nfa.py
#   https://stackoverflow.com/questions/35272592/how-are-finite-automata-implemented-in-code
#   http://www-bcf.usc.edu/~breichar/teaching/2011cs360/NFAtoDFA.py
#   https://github.com/handylim/E-NFA-to-DFA-Converter
#
# Regular Expression Procedure:
#   https://swtch.com/~rsc/regexp/regexp1.html
#
# Testing:
#   https://cyberzhg.github.io/toolbox/nfa2dfa (regex to NFA generator)
#
#########################################################################

######################################
# A model of a DFA:
#   DFA = (Q, sigma, delta, q0, F)
#       Q = set of all states in DFA
#       sigma = alphabet recognized by DFA
#       delta = transition dictionary to process state transitions
#       q0 = starting state
#       F = accepted state(s)
#   This DFA accepts words with any number of zeroes or 0 or more '0'
#   followed by '10' followed by 0 or more '1', followed by '01', followed by 0
#   or more '0'
#   Ex: "00000000000" or "000101111111101" or "100100000000"
#       but not "11111" or "0101010101"
#   https://stackoverflow.com/questions/35272592/how-are-finite-automata-implemented-in-code
#######################################
Q = {'0', '1', '2'}
sigma = {'0', '1'}
delta = {'0':{
            '0':{'0'}, '1':{'1'}},
         '1':{
             '0':{'2'}, '1':{'0'}},
         '2':{
             '0':{'1'}, '1':{'2'}}
        }
q0 = {'0'}
F = {'0'}

dfa = (Q, sigma, delta, q0, F)

######################################
# A model of an NFA:
#   NFA = (Q, sigma, delta, q0, F)
#       Q = set of all states in the NFA
#       sigma = alphabet recognized by DFA
#       delta = transition dictionary to process tate transitions
#       q0 = starting state
#       F = accepted state(s)
# Modeled from example NFA found in online textbook (Maheshwari & Smid) p. 45
#######################################
Q = {'1', '2', '3'}
sigma = {'a', 'b'}
delta = {'1':{
            'a':{'3'}, 'b':{}, None: {'2'}},
         '2':{
            'a':{'1'}, 'b':{}, None: {}},
         '3':{
             'a':{'2'}, 'b':{'2','3'}, None: {}}
         }
q0 = {'1'}
F = {'2'}
nfa = (Q, sigma, delta, q0, F)

#######################################
# Another NFA modeled from https://www.geeksforgeeks.org/theory-of-computation-conversion-from-nfa-to-dfa/
# Accepts any string that ends in 'ab'
#######################################
Q = {'0', '1', '2'}
sigma = {'a', 'b'}
delta = {'0':{
            'a':{'0', '1'},'b':{'0'}, None: {}},
         '1':{
            'a':{}, 'b':{'2'}, None: {}},
         '2':{
             'a':{}, 'b':{}, None: {}}
        }
q0 = {'0'}
F = {'2'}
nfa2 = (Q, sigma, delta, q0, F)

#######################################
# Same NFA as above but changed Q to be 'a', 'b' and 'c' states for union and concat testing
# Accepts strings ending in 'ab'
#######################################
Q = {'a', 'b', 'c'}
sigma = {'a', 'b'}
delta = {'a':{
            'a':{'a', 'b'},'b':{'a'}, None: {}},
         'b':{
            'a':{}, 'b':{'c'}, None: {}},
         'c':{
             'a':{}, 'b':{}, None: {}}
        }
q0 = {'a'}
F = {'c'}
nfa2b = (Q, sigma, delta, q0, F)

######################################
# A third NFA modeled from http://condor.depaul.edu/glancast/444class/docs/nfa2dfa.html
# Accepts strings 'a', 'aa', 'aba' and 'abb' only
######################################
Q = {'1', '2', '3', '4', '5'}
sigma = {'a', 'b'}
delta = {'1':{
            'a':{'3'}, 'b':{}, None:{'2'}},
         '2':{
             'a':{'4', '5'}, 'b':{}, None:{}},
         '3':{
             'a':{}, 'b':{'4'}, None: {}},
         '4':{
             'a':{'5'}, 'b':{'5'}, None:{}},
         '5':{
             'a':{}, 'b':{}, None:{}}
         }
q0 = {'1'}
F = {'5'}

nfa3 = (Q, sigma, delta, q0, F)
####################################################
# Function: dfa_accept
# Inputs: 5-tuple (Q, sigma, delta, q0, F) representing a DFA matching the structure seen in the example DFA above
#         String of the word to be tested for the DFA
# Outputs: Boolean value representing if the DFA accepts the word
# Purpose: Test DFAs with words for accept or reject
####################################################
# Modeled on dfa_accept() provided by Dr. Lauter for assignment
def dfa_accept(dfa, word):
    (Q, sigma, delta, q0, F) = dfa
    q = next(iter(q0))

    if q not in Q: # if start state not in Q, reject
        return False
    # Process transitions
    for input in word:
        if input not in sigma: # if input isn't in alphabet, reject
            return False
        try:
            q = next(iter(delta[q][input]))
            if q not in Q: # if state returned not in Q, reject
                return False
        except:
            return False

    if q in F:
        return True
    return False
####################################################
# Function: set_to_string
# Inputs: A set
# Outputs: String representation of the elements in the set, separated by ', '
# Purpose: Convert set elements to strings to be used for dictionary keys for delta transitions
####################################################
def set_to_string(set):
    set_string = ""
    set_list = list(set)
    set_list.sort()
    if len(set_list) > 1:
        for i in range(len(set_list)):
            set_string = set_string + str(set_list[i])
            if i < len(set_list) - 1:
                set_string = set_string + ", "
        return set_string
    elif len(set_list) == 1:
        return next(iter(set))

# http://www.nightmare.com/rushing/python/nfa.py
####################################################
# Function: epsilon_closure
# Inputs: Dictionary representing the delta function of an NFA
#         A set containing an element representing a state in the NFA
# Outputs: The set containing all elements in the epsilon-closure of the input set
# Purpose: Find the epsilon-closures of states for use in conversion from an NFA to a DFA
####################################################
def epsilon_closure(delta, state):
    # Get the states that can be epsilon transitioned to
    e_moves = delta[set_to_string(state)][None]

    # No epsilon transitions, return the set containing only the state
    if len(e_moves) == 0:
        return set(state)
    # Epsilon transitions possible
    else:
        r = set() # empty set that will hold all states in the closure
        r = r.union(state) # add the input state to closure
        # for every state that can be epsilon-transitioned to, get their epsilon closures to add to the overall closure
        for s in e_moves:
            r = r.union(epsilon_closure(delta, set(s)))
        return r
####################################################
# Function: convert_nfa_to_dfa
# Inputs: 5-tuple (Q, sigma, delta, q0, F) representing an NFA matching the structure seen in examples above
# Outputs: 5-tuple (Q, sigma, delta, q0, F) representing the DFA that accepts the same language as the input NFA
# Purpose: Convert an NFA into the corresponding DFA that accepts the same language, with minimization
####################################################
def convert_nfa_to_dfa(nfa):
    (nfa_Q, nfa_sigma, nfa_delta, nfa_q0, nfa_F) = nfa

    q0 = {set_to_string(epsilon_closure(nfa_delta, nfa_q0))} # q0 of DFA should be the epsilon closure of the NFA's q0
    Q = set()
    Q = Q.union(q0) # Add q0 to Q
    delta = {}
    F = set()
    sigma = nfa_sigma

    # Establish a stack to process states that are possible to be transitioned to, starting with q0
    stack = []
    stack.append(set_to_string(epsilon_closure(nfa_delta, nfa_q0)))
    # Continue while there are more states to be checked
    while len(stack) > 0:
        r = set([x.strip() for x in stack.pop().split(',')]) # get composite state as new possible state for DFA
        r_string = set_to_string(r) # get string representation of states
        delta[r_string] = {} # establish transition dictionary for associated state
        # check transitions for every letter in sigma to define delta transitions
        for input in sigma:
            transfer_states = set() # establish empty set for adding all transitions possible
            # for every individual state in composite state
            for split_state in r:
                r_epsilon = epsilon_closure(nfa_delta, {split_state}) # get epsilon closure of individual state
                # add states possible to be transitioned to for every state in epsilon closure
                for state in r_epsilon:
                    transfer_states = transfer_states.union(nfa_delta[set_to_string({state})][input])
            states_string = set_to_string(transfer_states) # convert transition states into string representing a composite state possible for DFA
            if states_string is None: # No states can be transitioned to
                delta[r_string][input] = {} # define no transitions
            else:
                delta[r_string][input] = {states_string} # add composite state as transition to r with input letter checked
            if states_string in Q or len(transfer_states) == 0: # If new state found already in Q or no state found, continue
                continue
            # else, add the newly found state to DFA's Q and the stack to be checked
            Q.add(states_string)
            stack.append(states_string)
    # Check all composite states found to see if they contain a state found in the input NFA's F
    for r in Q:
        r_set = set([x.strip() for x in r.split(',')])
        try: # simple handling for composite states vs. single states
            for state in r_set:
                if state in nfa_F:
                    F.add(r)
                    break
        except: # composite state contains only a single state, check it
            if r in nfa_F:
                F.add(r)

    dfa = (Q, sigma, delta, q0, F)
    return dfa

# TODO: Finish logic to ensure all states in Q2 are converted to unique state names not found in Q1
def unique_states(nfa1, nfa2):
    (Q1, sigma1, delta1, q01, F1) = nfa1
    (Q2, sigma2, delta2, q02, F2) = nfa1

    intersection = Q1.intersection(Q2)
    if len(intersection) > 0:
        return

####################################################
# Function: nfa_union
# Inputs: Two 5-tuples (Q, sigma, delta, q0, F) representing NFAs matching structure in examples above
# Outputs: 5-tuple (Q, sigma, delta, q0, F) representing the NFA that accepts the union of the language of the input NFAs
# Purpose: Produce an NFA that accepts the union of the languages of two input NFAs
####################################################
def nfa_union(nfa1, nfa2):
    (Q1, sigma1, delta1, q01, F1) = nfa1
    (Q2, sigma2, delta2, q02, F2) = nfa2
    unique_states(nfa1, nfa2) # check to see if nfa1 and nfa2 have unique state names, convert one of them if they don't
    q0 = {'-1'} # create new starting state
    Q = q0.union(Q1).union(Q2) # new Q should be the union of Q1 and Q2 with our new start state
    sigma = sigma1.union(sigma2) # new sigma should be the union of sigma1 and sigma2
    delta = {} # establish empty delta for defining programmatically
    F = F1.union(F2) # new F should be the union of F1 and F2

    # Check every state in new Q
    for state in Q:
        delta[state] = {} # establish transition dictionary for state
        if state == '-1': # new start state, create epsilon transitions
            delta[state][None] = q01.union(q02)
        # define transitions for every letter in new sigma
        for input in sigma:
            if state in Q1: # we're in a state from nfa1, define transition with delta1 for input and epsilon
                delta[state][input] = delta1[state][input]
                delta[state][None] = delta1[state][None]
            elif state in Q2: # we're in a state from nfa2, define transition with delta2 for input and epsilon
                delta[state][input] = delta2[state][input]
                delta[state][None] = delta2[state][None]
            else: # add transition definitions for new start state
                delta[state][input] = {}

    nfa = (Q, sigma, delta, q0, F)
    return nfa
####################################################
# Function: nfa_concat
# Inputs: Two 5-tuples (Q, sigma, delta, q0, F) representing NFAs matching structure in examples above
# Outputs: 5-tuple (Q, sigma, delta, q0, F) representing the NFA that accepts the concatenation of the language of the input NFAs
# Purpose: Produce an NFA that accepts the concatenation of the languages of two input NFAs
####################################################
def nfa_concat(nfa1, nfa2):
    (Q1, sigma1, delta1, q01, F1) = nfa1
    (Q2, sigma2, delta2, q02, F2) = nfa2
    Q = Q1.union(Q2) # new Q should be the union of Q1 and Q2
    sigma = sigma1.union(sigma2) # new sigma should be the union of sigma1 and sigma2
    delta = {} # create blank transition dictionary
    q0 = q01 # start state is nfa1's start state
    F = F2 # new F should be the states in F2

    # Check every state in new Q for transitions
    for state in Q:
        delta[state] = {}
        # define transitions for every letter in sigma
        for input in sigma:
            if state in Q1: # we're in a state from Q1, define transitions using delta1 for input and epsilon
                delta[state][input] = delta1[state][input]
                delta[state][None] = delta1[state][None]
            elif state in Q2: # we're in a state from Q1, define transitions using delta2 for input and epsilon
                delta[state][input] = delta2[state][input]
                delta[state][None] = delta2[state][None]
            else: # error state, shouldn't be reachable but define empty transition anyway
                delta[state][input] = {}
        # if the state was in F1, define an epsilon transition to q02 but keep other epsilon transitions defined
        if state in F1:
            delta[state][None] = q02.union(delta[state][None])
    nfa = (Q, sigma, delta, q0, F)
    return nfa
####################################################
# Function: nfa_star
# Inputs: 5-tuple (Q, sigma, delta, q0, F) representing NFA matching structure in examples above
# Outputs: 5-tuple (Q, sigma, delta, q0, F) representing the NFA that accepts the star of the language of the input NFA
# Purpose: Produce an NFA that accepts the star of the language of input NFA
####################################################
def nfa_star(nfa1):
    (Q1, sigma1, delta1, q01, F1) = nfa1
    q0 = {'-1'}
    Q = q0.union(Q1)
    sigma = sigma1
    delta = {}
    F = F1.union(q0)

    for state in Q:
        delta[state] = {}
        for input in sigma:
            if state in Q1:
                delta[state][input] = delta1[state][input]
                delta[state][None] = delta1[state][None]
            else:
                delta[state][input] = {}
                delta[state][None] = {}
        if state == '-1' or state in F1:
            delta[state][None] = q01.union(delta[state][None])

    nfa = (Q, sigma, delta, q0, F)
    return nfa

# TODO: Finish this - currently incomplete and not used for testing.
def reg_ex_to_nfa(regex):
    Q = set()
    sigma = set()
    q0 = set()
    delta = {}
    F = set()

    operators = ['*', '|'] # TODO: add support for '(' and ')' parsing (stacks)
    for char in regex:
        if char not in operators:
            if char not in sigma:
                sigma.add(char)
####################################################
# Function: regex_accept
# Inputs: string representing the regular expression and a string representing the word to be checked from NFA representing regular expression
# Outputs: boolean representing whether the word is accepted by the NFA representing the regular expression
# Purpose: Check whether the NFA produced by the regular expression accepts the input word
####################################################
def regex_accept(regex, word):
    nfa = reg_ex_to_nfa(regex) # get NFA converted from regex
    dfa = convert_nfa_to_dfa(nfa) # get DFA converted from NFA
    return dfa_accept(dfa, word) # return whether the DFA accepts the word

# Testing DFA
print(dfa_accept(dfa, "00000000000"))
print(dfa_accept(dfa, "11111111111"))

# Outputting converted DFA from NFA
new_dfa = convert_nfa_to_dfa(nfa)
(newQ, newSigma, newDelta, newq0, newF) = new_dfa
print("Returned DFA is as follows:")
print("\tQ:", newQ)
print("\tSigma:", newSigma)
print("\tDelta:", newDelta)
print("\tq0:", newq0)
print("\tF:", newF)

# Testing NFA conversions
print("Testing nfa1 with accepted string:",dfa_accept(convert_nfa_to_dfa(nfa), "abbbbbbbbbbb"))
print("Testing nfa1 with rejected string:",dfa_accept(convert_nfa_to_dfa(nfa), "bbbbbbbbbbbb"))
print("Testing nfa2 with accepted string:",dfa_accept(convert_nfa_to_dfa(nfa2), "aaaaaaaaaaab"))
print("Testing nfa2 with rejected string:",dfa_accept(convert_nfa_to_dfa(nfa2), "aaaaaaaaaaaba"))
print("Testing nfa3 with accepted string:",dfa_accept(convert_nfa_to_dfa(nfa3), "abb"))
print("Testing nfa3 with rejected string:",dfa_accept(convert_nfa_to_dfa(nfa3), "abba"))

# Testing NFA union
print("Testing nfa1 union nfa2b with accepted string:", dfa_accept(convert_nfa_to_dfa(nfa_union(nfa, nfa2b)), "abbbbbbbbbbb"))
print("Testing nfa1 union nfa2b with second accepted string:", dfa_accept(convert_nfa_to_dfa(nfa_union(nfa, nfa2b)), "bbbbbbbbbbbab"))
print("Testing nfa1 union nfa2b with rejected string:", dfa_accept(convert_nfa_to_dfa(nfa_union(nfa, nfa2b)), "111111111"))

# Testing NFA concat
print("Testing nfa2 concat nfa2b with accepted string:", dfa_accept(convert_nfa_to_dfa(nfa_concat(nfa2, nfa2b)),"aaaaaaaaaaab" + "bbbbbbbbbbbab"))
print("Testing nfa2 concat nfa2b with rejected string:", dfa_accept(convert_nfa_to_dfa(nfa_concat(nfa2, nfa2b)),"aaaaaaaaaabb" + "bbbbbbbbbbbbb"))

# Testing NFA star
print("Testing nfa3 star with accepted string:", dfa_accept(convert_nfa_to_dfa(nfa_star(nfa3)), "abaaba"))
print("Testing nfa3 star with empty string:", dfa_accept(convert_nfa_to_dfa(nfa_star(nfa3)), ""))
print("Testing nfa3 star with rejected string:", dfa_accept(convert_nfa_to_dfa(nfa_star(nfa3)), "abbb"))

######################################
# Woo's NFA
#
######################################
Q = {'1', '2', '3', '4', '5'}
sigma = {'a', 'b'}
delta = {'1':{
            'a':{'3'}, 'b':{'4'}, None:{'2'}},
         '2':{
             'a':{}, 'b':{}, None:{'3'}},
         '3':{
             'a':{}, 'b':{'2', '5'}, None: {}},
         '4':{
             'a':{'1', '3'}, 'b':{'3'}, None:{'5'}},
         '5':{
             'a':{'3'}, 'b':{}, None:{}}
         }
q0 = {'1'}
F = {'2'}

nfa_woo = (Q, sigma, delta, q0, F)

print("Testing nfa_woo to determine returned DFA...")
new_dfa = convert_nfa_to_dfa(nfa_woo)
(newQ, newSigma, newDelta, newq0, newF) = new_dfa
print("Returned DFA is as follows:")
print("\tQ:", newQ)
print("\tSigma:", newSigma)
print("\tDelta:", newDelta)
print("\tq0:", newq0)
print("\tF:", newF)


import tkinter as tk
from tkinter import scrolledtext, INSERT
import re
from tkinter import filedialog, messagebox

taxa = []
sequences = []

def main():
    master_window = tk.Tk()
    master_window.geometry("800x400")
    master_window.title("FastoPhy")

    # Parent widget for the buttons
    buttons_frame = tk.Frame(master_window)
    buttons_frame.grid(row=0, column=0, sticky = tk.W + tk.E) # creating a grid (West, East)

    # Buttons in parent widget
    btn_fasta = tk.Button(buttons_frame, text="FASTA file to Phyllip file", command = initializing)
    btn_fasta.grid(row=0, column=0, padx=10, pady=10)

    # Parent widget for console log
    console_frame = tk.LabelFrame(master_window, text="Console log", padx =10, pady =10)
    console_frame.grid(row=1, column=0, columnspan=3, padx=10, pady=10, sticky=tk.W + tk.E + tk.N + tk.S)

    master_window.columnconfigure(0, weight=1)
    master_window.rowconfigure(1, weight=1)

    console_frame.rowconfigure(0, weight=1)
    console_frame.columnconfigure(0, weight=1)

    # Console log without text
    console_log = scrolledtext.ScrolledText(console_frame, width=40, height=10)
    console_log.grid(row=0, column=0, sticky=tk.W + tk.E + tk.N + tk.S)
    console_log.tag_configure("centered", justify="left")
    console_log.insert(INSERT, "------------ FastoPhy v0.3.1, a software to convert FASTA file in Phyllip file ------------\n")
    console_log.insert(INSERT, "Please, click on top button to input FASTA file and iniate the conversion.\n")

    master_window.mainloop()

def ask_for_continue():
    check = messagebox.askyesno(title= 'Fas to Phy',
                                message= 'Do you want input another FASTA file to convert to Phyllip file?')
    return check

def choosing_fasta_file():
    local = filedialog.askopenfilename(title = "Choose a FASTA file ('.fas', '.fasta', '.fna', 'ffn', 'faa', '.frn')",
                                       filetypes = [('FASTA file', ('.fas', '.fasta', '.fna', 'ffn', 'faa', '.frn')),
                                                    ('all files', '.*')])
    return local

def initializing():
    check = True
    while check:
        fasta_file = choosing_fasta_file()
        extracting_data_from_fasta_file(fasta_file)
        phy_file = choosing_local_and_name_to_phy_file()
        writing_data_from_fasta_to_phy_file(phy_file)
        check = ask_for_continue()

def extracting_data_from_fasta_file(fasta_file):
    with open(fasta_file, mode = 'r') as fasta_data:
        content = fasta_data.readlines()
        for item in content:
            if content.index(item) == 0 or content.index(item) % 2 == 0:
                item = cleaning_taxon_name_from_fasta_to_phy(item)
                taxa.append(item.strip())
            else:
                sequences.append(item.strip())
        testing_number_of_taxa_and_sequence()
    print(f'{len(taxa)} taxa found, {len(sequences)} sequences found(number of sites: {len(sequences[0])})')

def cleaning_taxon_name_from_fasta_to_phy(taxon_name):
    pattern = ">"
    taxon_name = re.sub(pattern, '', taxon_name)
    return taxon_name

def testing_number_of_taxa_and_sequence():
    number_of_taxa = len(taxa)
    number_of_sequences = len(sequences)
    if (number_of_taxa == number_of_sequences):
        print('OK!')
    else:
        ValueError('Number of taxa and sequence do not match. Check the pattern of your .fasta or .fas file.')

def choosing_local_and_name_to_phy_file():
    local = filedialog.asksaveasfilename(title="Choose a local to save your converted Phyllip file ('.phy'):",
                                         filetypes=[('Phyllip file (.phy)', '.phy'), ('all files', '.*')],
                                         defaultextension='.phy',
                                         initialfile='converted')
    return local

def writing_data_from_fasta_to_phy_file(phy_file):
    with open(phy_file, mode = 'w') as output_file:
        output_file.write(f'{len(taxa)} {len(sequences[0])}\n')
        for taxon in taxa:
            output_file.write(f'{taxon} {sequences[taxa.index(taxon)]}\n')
    taxa.clear()
    sequences.clear()
    print('FASTA file converted sucessfully to Phyllip file!')

if __name__ == '__main__':
    main()


#!/usr/bin/python
#python 2.7 is used
import urllib
import re
import json
import sqlite3

connection = sqlite3.connect("database.db") #Sets the Database whom to connect to

cursor = connection.cursor()                # Connect to the Database

# Open a file
fo = open("data.html", "r+")
str = fo.read();

int1 = str.find('list:[')   # Findet die Position im Dokument wo die ID Freundesliste beginnt
print(int1)
int1 += 7                  # Weil sonst "list:[" auch noch in der Liste dabei ist die wir einlesen

int2 = str.find('],shortProfiles')
print(int2)

# Calc how many char. for reading
new = int2-int1

#Read in the ID's from the html file
fo.seek(int1, 0);           #Spring an die Postion der Variable int1
data = fo.read(new);        # String wo die ID's gespeichert sind
#print(data)

splitdata = data.split("\",\"")         # Auslesen der ID's aus den json format

print(splitdata)

friends = len(splitdata)/2  #Anzahl der Freunde
print(friends)
listAnz = len(splitdata)    #Anzahl der Elemente in der Liste

IDs = []                    #Hier werden die Freunde IDs gespeichert

for i in range(0, listAnz): # start, stop

    id, check = splitdata[i].split("-")
    if check is "2":
        IDs.append(id)
        print(id)
        cursor.execute("INSERT INTO Scanned VALUES (?, NULL, NULL, NULL);", (id,))
        #sql_command = "INSERT INTO Scanned VALUES (" + id + ",NULL ,NULL,NULL);"
        #cursor.execute(sql_command)

print(IDs)

connection.commit()
connection.close()

AnzIDs = len(IDs)

abgleich = -1
print(abgleich)

downloadlist = []

for i in range(0, AnzIDs): # start, stop
    #print("%s: %s  " % (i, newlist[i]))
    url = "https://graph.facebook.com/" + IDs[i] + "?fields=picture.width(720).height(720)"
    print(AnzIDs - i)
    response = urllib.urlopen(url)
    data = response.read()      # a `bytes` object
    text = data.decode('utf-8') # a `str`; this step can't be used if data is binary
    search = "error"
    check = text.find(search)  # search the term "error"
                                # Wenn nichts gefunden wird check=-1
    if check is abgleich:
        resp_dict = json.loads(text)
        mitgabe = "" + resp_dict['picture']['data']['url'] + "#" + IDs[i] + ""
        downloadlist.append(mitgabe)

downlen = len(downloadlist)

Fehler = friends - downlen
print("Fehler: %s  " % (Fehler))

for i in range(0, downlen): # start, stop
    print(downloadlist[i])
    url, id = downloadlist[i].split("#")

    urllib.urlretrieve(url, "" + id + ".jpg")

# Close opend file
fo.close()
connection.commit()
connection.close()


#!/usr/bin/env python3
#

from threading import Thread
import time

def sayhi(name):
    time.sleep(2)
    print('%s say hello' % name)

if __name__ == '__main__':
    t = Thread(target=sayhi, args=('alice',))
    t.setDaemon(True)  # 必须在t.start()之前设置，此处用法为setDaemon(True)，进程中是daemon=True
    t.start()

    print('主线程')
    print(t.is_alive())


import os
import time
import cv2

import denoising.dpsr.dpsr as dpsr
from config.config import cfg

def main(video_name):

    # -- get the video path
    video_path = os.path.join(cfg.PATH.VIDEO, video_name)

    # -- check the video type(video or cam)
    if video_name is None:
        print('There is no video or the path is incorrect.')
        return
    videoCapture = cv2.VideoCapture(video_path)
    if not videoCapture.isOpened():
        print('Cannot open the video.')
        videoCapture.release()
        return

    # -- cv2 info
    (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
    if int(major_ver) < 3:
        fps = videoCapture.get(cv2.cv.CV_CAP_PROP_FPS)
        fourcc = cv2.cv.CV_FOURCC('M', 'P', '4', 'V')
    else:
        fh = int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT))
        fw = int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH))
        fps = videoCapture.get(cv2.CAP_PROP_FPS)
        fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', 'V')

    print(fw, fh, fps)

    # -- instance for video writer
    videoWriter = cv2.VideoWriter(os.path.join(cfg.PATH.SAVEV, video_name), fourcc, fps, (int(fw/2), int(fh/2)))

    # -- instance for the dpsr model
    dpsr_model = dpsr.DPSR(
                cfg.PATH.WEIGHT,
                noise_level=cfg.IMG.NOISE,
                n_channels=cfg.IMG.CHANNEL,
                upscale=cfg.MODEL.UPSCALE,
                act_mode=cfg.MODEL.ACT,
                upsample_mode=cfg.MODEL.UPSAMPLE,
                method=cfg.MODEL.EXCUTE)

    # -- process
    while True:

        # -- capture the video frame
        _, frame = videoCapture.read()

        # -- check the video frame
        if frame is None:
            break

        start_time = time.time()

        # -- denoise the image
        h, w = frame.shape[:2]
        #frame = cv2.resize(frame, (int(w/2), int(h/2)))
        frame = dpsr_model.denoising(frame)

        denoising_time = time.time() - start_time

        # -- process the res
        print('denoising time in ', denoising_time, 's')
        cv2.imshow('video', frame)
        videoWriter.write(frame)

        c = cv2.waitKey(1)
        if c == 27:
            break

    videoCapture.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main('vlc-record-2019-09-09-19h37m43s-rtsp___192.168.1.88_554_main-.mp4')