from django.urls import path, include
from accounts import views

urlpatterns = [
    path('employers/list/', views.CompanyListView.as_view(), name="employers-list"),
    path('employer/detail/<str:pk>', views.CompanyDetailView.as_view(), name="employer-detail"),
    path('employers/search/', views.CompanySearchView.as_view(), name="employers-search"),
    path('logout/', views.LogoutRedirectView.as_view(), name='logout'),
    path('login/', views.LoginRedirectView.as_view(), name='login'),
]


import os
import gzip

dir_list = os.listdir("/home/AIWolfPy/pre_logs/gat2017_15")

for dir in dir_list:
    file_list = os.listdir("/home/AIWolfPy/pre_logs/gat2017_15/"+dir)
    for i in range(100):
        file_name = str(i).zfill(3)+".log"
        if file_name not in file_list:
            print("dir: ",dir,"file_name: ",file_name)
            if str(i).zfill(3)+".log.gz" in file_list:
                print("find zip file",str(i).zfill(3)+".log.gz")
                wf = open("/home/AIWolfPy/pre_logs/gat2017_15/"+dir+"/"+str(i).zfill(3)+".log","w")
                wf.write("broken\n")


from .. import *

# 日志地址
LOG_DIR = BASE_DIR.path('logs')

LOGGING = {
    # 版本
    'version': 1,
    # 是否禁止默认配置的记录器
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '\n%(asctime)s %(levelname)s\n'
                      '%(pathname)s\n'
                      'process_id:%(process)d\n'
                      'thread_id:%(thread)d\n'
                      '%(message)s\n',
            'datefmt': '%Y-%m-%d %H:%M:%S'
        }
    },
    # 过滤器
    # 'filters': {
    #     'request_info': {'()': 'apps.common.custom_middleware.DataReCordMiddleware'},
    # },
    'handlers': {
        # 标准输出
        'console': {
            # 'level': 'DEBUG',
            # 'level': 'ERROR',
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            # 'formatter': 'standard'
        },
        # 自定义 handlers，输出到文件
        'requests': {
            'level': 'DEBUG',
            # 时间滚动切分
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': LOG_DIR.path('http.log').__str__(),
            'encoding': 'utf-8',
            'formatter': 'standard',
            # 调用过滤器
            # 'filters': ['request_info'],
            # 每天凌晨切分
            # 'when': 'MIDNIGHT',
            # 保存 30 天
            # 'backupCount': 30,
        },
        # 自定义 handlers，输出到文件
        'event-api': {
            'level': 'DEBUG',
            # 时间滚动切分
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': LOG_DIR.path('event-api.log').__str__(),
            'encoding': 'utf-8',
            'formatter': 'standard',
            # 调用过滤器
            # 'filters': ['request_info'],
            # 每天凌晨切分
            # 'when': 'MIDNIGHT',
            # 保存 30 天
            # 'backupCount': 30,
        },
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level':'DEBUG',
        },
        'django': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': True
        },
        'http': {
            'handlers': ['requests'],
            'level': 'INFO',
            'propagate': False
        },
        'event': {
            'handlers': ['event-api', 'console'],
            'level': 'INFO',
            # 此记录器处理过的消息就不再让 django 记录器再次处理了
            'propagate': False
        },
    }
}


# -*- coding: utf-8 -*-

# Define your spider here
#
# Don't forget to add your parse method
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
""" Correo del orinoco

1. urls of news article:
http://www.correodelorinoco.gob.ve/categoria/categorias/venezuela/nacionales/

2. selectors of DOM elments:
archive > div.spoiler > a.left
archive > div.spoiler > div > h3.subtitle
archive > div.spoiler > div > h2.title
archive > div.spoiler > div > div.meta
archive > div.spoiler > div > p

"""
import scrapy
from VeNews.items import OrinocoItem

orinocoUrl1 = 'http://www.correodelorinoco.gob.ve',
orinocoUrl1 = 'http://www.correodelorinoco.gob.ve',

def checkURL(url):
    file_guid = url.split('/')[-1]
    if file_guid[-3:] != 'pdf':
        url = u'{0}print'.format(url)
    return url

class OrinocosSpiderPage(scrapy.Spider):
    name = "orinocoSpiderPage"
    start_urls = (
        'http://www.correodelorinoco.gob.ve/categoria/categorias/venezuela/nacionales',
        'http://www.correodelorinoco.gob.ve/categoria/categorias/venezuela/caracas',
        'http://www.correodelorinoco.gob.ve/categoria/categorias/venezuela/regiones',
        'http://www.correodelorinoco.gob.ve/categoria/categorias/venezuela/politica',
        'http://www.correodelorinoco.gob.ve/categoria/categorias/opinion/',
        'http://espejo3.correodelorinoco.gob.ve/categoria/categorias/venezuela/impacto/',
        'http://espejo3.correodelorinoco.gob.ve/categoria/categorias/venezuela/poder-popular/',
        'http://espejo3.correodelorinoco.gob.ve/categoria/categorias/venezuela/investigacion/',
        'http://espejo3.correodelorinoco.gob.ve/categoria/categorias/venezuela/alimentacion/',
    )

    def parse(self, response):
        for elm in response.css('div#archive > div.spoiler'):
            """
                Creating a item
            """
            item = OrinocoItem()
            """
                Extracting titles
            """
            item['title'] = elm.css('div > h2.title ::text').extract()
            """
                Extracting href
            """
            urls = elm.css('a.left ::attr(href)').extract()
            urls = [checkURL(url) for url in urls if url]
            item['file_urls'] = urls

            yield item

class OrinocoSpiderPdf(scrapy.Spider):
    name = "orinocoSpiderPdf"
    allowed_domains = ["correodelorinoco.gob.ve"]
    start_urls = (
        'http://www.correodelorinoco.gob.ve/edicion-impresa',
    )

    def start_request(self):
        pass

    def log(self, message, level=3, **kw):
        scrapy.Spider.logger.info('msg')

    def parse(self, response):
        """ parse the table
        for elm in response.css('table > tr > td:nth-child(even)')
        for elm in response.css('table > tr > td:nth-child(even) > img ::attr(src)'):
        for elm in response.css('table > tr > td:nth-child(odd) > p.date1')
        for elm in response.css('table > tr > td:nth-child(odd) > p.date2')
        for elm in response.css('table > tr > td:nth-child(odd) > p.numero')
        for elm in response.css('table > tr > td:nth-child(odd) > p.text')
        for elm in response.css('table > tr > td:nth-child(odd) > p.link:nth-child(even) > a.text ::attr(href)')
        for elm in response.css('table > tr > td:nth-child(odd) > p.link:nth-child(odd) > a.text ::attr(href)')
        """
        for elm in response.css('table > tr'):
            item = OrinocoItem()
            """get even table data, which has images link
            """
            item['image_urls'] = elm.css(
                'td:nth-child(odd) > img.attachment-medium::attr(src)').extract()
            """get other meta data from odd table data
            """
            item['date1'] = elm.css(
                'td:nth-child(even) > p.date1 ::text').extract()
            item['date2'] = elm.css(
                'td:nth-child(even) > p.date2 ::text').extract()
            item['numero'] = elm.css(
                'td:nth-child(even) > p.numero ::text').extract()
            item['texto'] = elm.css(
                'td:nth-child(even) > p.texto ::text').extract()

            urls = elm.css(
                'td:nth-child(even) > p.link > a.text ::attr(href)').extract()
            urls = [checkURL(url) for url in urls if url]
            item['file_urls'] = urls
            yield item

        for next_page in response.css('a.page'):
            """
                if you want to go through all pages, using following code
                next_page_url =  next_page.css('::attr(href)').extract_first()
                yield scrapy.Request(response.urljoin(next_page_url),callback=self.parse)
            """
            pass


from poker.player_actions import *

def cmd(table):
    a = input()
    if a == 'call':
        return call(table)
    elif a == 'bet':
        b = int(input())
        return bet(table, b)
    elif a == 'raise':
        b = int(input())
        return Raise(table, b)
    elif a == 'fold':
        return fold(table)
    elif a == 'all_in':
        return all_in(table)
    elif a == 'check':
        return check(table)
    else:
        return ActionEffect.Input_error

def pp(t1):
    for x in range(len(t1.playerList.List)):
        print(t1.playerList.List[x])

def info(t1):
    pp(t1)
    print()
    print(t1)
    print('\n')

def play(t1):
    while len(t1.playerList) > 1:
        for x in range(4):
            info(t1)
            new_stage = True
            while not t1.finished_stage(new_stage):
                new_stage = False
                c = cmd(t1)
                print(c.name)
                print()
                if c.name == 'OK':
                    if t1.finished_stage():
                        print('but why')
                        break
                    else:
                        print('shit')

                    t1.nextTurn()
                    info(t1)
            print('-------------------------')
            if t1.stage == 3:
                print('SHOWDOWN:')
                winners, decisive = t1.showdown()
                if len(winners) == 1:
                    print('Winner: ' + winners[0].first.user + ' with ' + winners[0].second.HandType.name, end='')
                    if decisive != None:
                        if decisive == 'hight' or decisive == 'kicker':
                            print(' by a ' + decisive, end ='')
                else:
                    print('We have a tie between players: ', end='')
                    for x in winners:
                        print(x.first.user + ' ', end='')
                    print('and the pot is split')
                print('.\n', end='')
                t1.grab_pot(winners)
            else:
                t1.nextStage()
        t1.nextDeal()


# coding=utf-8
from __future__ import unicode_literals
from django.db import models
from administration.models import Profile

class Venue(models.Model):
    name = models.CharField(max_length=100)
    address = models.TextField(blank=True)
    phone = models.CharField(max_length=20)
    updated = models.DateTimeField(auto_now_add=True)
    updated_by = models.ForeignKey(Profile, related_name='updated_venues', null=True)
    created = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(Profile, related_name='created_venues')

    def create(self, user, force_insert=False, force_update=False, using=None, update_fields=None):
        self.created_by = user
        self.save(force_insert, force_update, using, update_fields)

    def update(self, user, force_insert=False, force_update=False, using=None, update_fields=None):
        self.updated_by = user
        self.save(force_insert, force_update, using, update_fields)

    def __unicode__(self):
        return self.name

    def add_storage_product(self, sp):
        vp = VenueProduct.objects.filter(product_unit__product=sp.product_unit.product,
                                         product_unit__primary=True, venue=self).first()
        if not vp:
            pu = ProductUnit.objects.get(product=sp.product_unit.product, primary=True)
            vp = VenueProduct.objects.create(product_unit=pu, venue=self, quantity=0)
        vp.quantity += sp.quantity / float(sp.product_unit.relation)
        vp.update()

class VenueProduct(models.Model):
    venue = models.ForeignKey(Venue, related_name='products')
    product_unit = models.ForeignKey('ProductUnit', related_name='venues')
    quantity = models.FloatField(default=0)
    updated = models.DateTimeField(auto_now=True)

    def update(self):
        """Function that updates the quantity of product in different units
        """
        units = (self.quantity - VenueProduct.objects.get(pk=self.pk).quantity)/float(self.product_unit.relation)
        for vp in VenueProduct.objects.filter(product_unit__product=self.product_unit.product, venue=self.venue):
            vp.quantity += units * float(vp.product_unit.relation)
            vp.save()

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        """Override of save that stores a log
        """
        VenueProductLog(venue=self.venue, product=self.product_unit, quantity=self.quantity).save()
        super(VenueProduct, self).save(force_insert, force_update, using, update_fields)

    def __unicode__(self):
        return self.product_unit

class VenueProductLog(models.Model):
    venue = models.ForeignKey(Venue, related_name='product_logs')
    product = models.ForeignKey('ProductUnit', related_name='venue_logs')
    quantity = models.IntegerField(default=0)
    created = models.DateTimeField(auto_now_add=True)


from copy import deepcopy

class Judge(object):
    """docstring for Judge"""

    def __init__(self):
        super(Judge, self).__init__()
        self.time = set()  # 存放出发时间
        self.car_No = []  # 存放车辆编号
        self.road_No = []  # 存放道路编号
        self.cross_No = []  # 存放路口编号
        self.car_info = {}  # 存放车辆特征
        self.road_info = {}  # 存放道路特征
        self.cross_info = {}  # 存放路口特征
        self.plan_info = {}  # 存放行车计划
        self.StartTimeBin = {}  # 按照实际出发时间为车辆分桶

    def get_car_info(self, file):
        # car.txt
        # print('get car info, filename is ', file)
        with open(file) as f:
            for line in f.readlines():
                if line[0] == '#':
                    continue
                line = self.convert2list(line)

                [car_id, start, end, speed, planTime] = [int(i) for i in line]
                self.car_No.append(car_id)
                self.car_info[car_id] = Car(car_id,
                                            [start, end, speed, planTime], self.plan_info[car_id])

    def convert2list(self, line):
        line.strip()
        line = line.replace('(', '')
        line = line.replace(')', '')
        return line.split(',')

    def get_road_info(self, file):
        # road.txt
        #        print('get road info, filename is ', file)
        with open(file) as f:
            for line in f.readlines():
                if line[0] == '#':
                    continue
                line = self.convert2list(line)
                [road_id, length, speed, channel, start, end, isDuplex] = [int(i) for i in line]
                self.road_No.append(road_id)
                self.road_info[road_id] = Road(road_id,
                                               [length, speed, channel, start, end, isDuplex])

    def get_cross_info(self, file):
        # cross.txt
        with open(file) as f:
            for line in f.readlines():
                if line[0] == '#':
                    continue
                line = self.convert2list(line)
                [cross_id, roadId1, roadId2, roadId3, roadId4] = [int(i) for i in line]
                self.cross_No.append(cross_id)
                self.cross_info[cross_id] = Cross(cross_id,
                                                  [roadId1, roadId2, roadId3, roadId4])
                # 1，2，3，4代表北、东、南、西

    def parse_Plan_info(self, file):
        # answer.txt
        with open(file) as f:
            for line in f.readlines():
                if line[0] == '#':
                    continue
                line = self.convert2list(line)
                info = [int(i) for i in line]
                # carId,StartTime,RoadId...RoadId
                car_id = info[0]
                StartTime = info[1]

                # 将车辆按出发时间分桶
                if not self.StartTimeBin.get(StartTime):
                    self.StartTimeBin[StartTime] = []
                self.StartTimeBin[StartTime].append(car_id)

                RoadSequence = info[2:]
                self.time.add(StartTime)
                self.plan_info[car_id] = [StartTime] + RoadSequence

class Car(object):
    def __init__(self, _id, _car_info, plan_info):
        [start, end, speed, planTime] = _car_info
        self.id = _id
        self.start = start
        self.end = end
        self.speed = speed
        self.planTime = planTime
        self.StartTime = plan_info[0]  # 记录实际出发时间
        self.RoadSequence = plan_info[1:]  # 记录途径道路顺序
        self.road_index = 0  # 记录当前所处道路在Seq中的位置
        self.road_pos = 0  # 记录在当前道路上的位置
        self.lane = 0  # 记录在当前道路上的车道编号
        self.state = 'wait'  # 当前车辆为等待状态或终止'final'

    def reflush(self):
        # Checked...
        self.state = 'wait'

    def get_road(self, S):
        # Checked...
        road = S.road_info[self.RoadSequence[self.road_index]]
        cross_end = S.cross_info[road.end]
        cross_start = S.cross_info[road.start]
        if road.id != self.RoadSequence[-1]:
            print('Next road', self.RoadSequence[self.road_index + 1],
                  'from {} to {}'.format(S.road_info[self.RoadSequence[self.road_index + 1]].start,
                                         S.road_info[self.RoadSequence[self.road_index + 1]].end))
        else:
            print('This car will reach its destination.')
        print("""Current road {} from {} to {}. \ncross {} linked {}, \ncross {} linked {}.""".format(road.id,
                                                                                cross_start.id,
                                                                                cross_end.id,
                                                                                cross_start.id,
                                                                                cross_start.roads,
                                                                                cross_end.id,
                                                                                cross_end.roads))
        return S.road_info[self.RoadSequence[self.road_index]]

    def PlaceCar_FromGarage(self, S: Judge, dead_stack):
        # Checked...
        road_id = self.RoadSequence[0]
        road = S.road_info[road_id]
        if road.start == self.start:
            lane = road.lane
        elif road.end == self.start:
            lane = road.lane_rev
        v = min(self.speed, road.speed)
        for i in range(road.channel):
            tmp = -1
            for j in range(v):
                if lane[i][j] != 0:
                    if j == 0:
                        break
                    lane[i][j - 1] = self
                    self.lane = i
                    self.road_pos = j - 1
                    self.state = 'final'
                    dead_stack.append(self.id)
                    S.road_info[road_id] = road
                    S.car_info[self.id] = self
                    return dead_stack, S, True
                else:
                    if j >= tmp:
                        # 找到当前道路能到达的最远的空位置
                        tmp = j
            if tmp >= 0:
                lane[i][tmp] = self
                self.lane = i
                self.road_pos = tmp
                self.state = 'final'
                dead_stack.append(self.id)
                S.road_info[road_id] = road
                S.car_info[self.id] = self
                return dead_stack, S, True
        # print('Fail to place the car.', self.id)
        self.planTime += 1
        if S.StartTimeBin:
            S.StartTimeBin[self.planTime].append(self.id)
        else:
            S.StartTimeBin[self.planTime] = [self.id]
        return dead_stack, S, False

    def reachFinal(self, S: Judge):
        # Checked...
        # 车辆到达终点的标记：road_pos = final_road.length， road=final_road
        road = self.RoadSequence[self.road_index]
        if road == self.RoadSequence[-1] and self.road_pos == S.road_info[road].length:
            return True
        return False

class Road(object):
    def __init__(self, _id, _road_info):
        # Checked...
        [length, speed, channel, start, end, isDuplex] = _road_info
        self.id = _id
        self.length = length
        self.speed = speed
        self.channel = channel
        self.start = start
        self.end = end
        self.isDuplex = isDuplex
        self.lane = [[0 for i in range(self.length)] for i in range(self.channel)]  # 车道用全0矩阵表示
        self.wait_stack = []
        # 处理反向车道
        if self.isDuplex == 1:
            self.lane_rev = [[0 for i in range(self.length)] for i in range(self.channel)]
        else:
            self.lane_rev = []
        # 说明：对于self.lane而言，最前面的表示靠近start cross的位置，最后的表示靠近end cross的位置

    def DriveCar(self, car: Car, dead_stack, S: Judge, reversed=False):
        # 行驶的函数：区分通过路口和不通过路口
        # 规则：通过路口时，优先占据编号小的车道，不通过路口时，保持现有车道
        # 核心规则：在本车道上的行驶距离S2 <= V2 - S1 (V2为此车道限速，S1为前一车道剩余距离)
        # 核心规则决定了本车在速度超过当前车道可行驶距离时， 能不能进入下一车道
        # Checked...
        if self.id == 5009:
            self.lane_id()
        if car.state == 'final':
            return dead_stack, car, False
        #        print('No {} car is drived.'.format(car.id))
        # 调试代码
        # if car.id in [10001, 10009]:
        #     print(self.lane_id())
        #     print('Monitor here', car.get_road(S).id, car.road_pos)
        if not reversed:
            lane = self.lane
            cross_id = self.end
        else:
            assert self.isDuplex, 'Wrong reversed option.'  # 如果输入反向而道路单行，说明输入错误
            lane = self.lane_rev  # 如果是反向行驶，调整self.lane
            cross_id = self.start
        # Case 0，马上到达终点
        if self.id == car.RoadSequence[-1]:
            #            print('The car {} may reach its final.'.format(car.id))
            for j in range(car.road_pos + 1, self.length):
                if lane[car.lane][j] and lane[car.lane][j].state == 'wait':
                    car.state = 'wait'
                    return dead_stack, car, False
                elif lane[car.lane][j] and lane[car.lane][j].state == 'final':
                    lane[car.lane][car.road_pos] = 0
                    car.road_pos = min(car.road_pos + min(self.speed, car.speed), j - 1)
                    lane[car.lane][car.road_pos] = car
                    car.state = 'final'
                    dead_stack.append(car.id)
                    return dead_stack, car, True
                elif j == self.length - 1:
                    lane[car.lane][car.road_pos] = 0
                    if car.road_pos + min(self.speed, car.speed) >= self.length:
                        car.road_pos = self.length
                    else:
                        car.road_pos = car.road_pos + min(self.speed, car.speed)
                        lane[car.lane][car.road_pos] = car
                    car.state = 'final'
                    dead_stack.append(car.id)
                    return dead_stack, car, True
            if car.road_pos == self.length - 1:
                lane[car.lane][car.road_pos] = 0
                car.road_pos = self.length
                car.state = 'final'
                dead_stack.append(car.id)
                return dead_stack, car, True
        else:
            next_Road_id = car.RoadSequence[car.road_index + 1]
            next_Road = S.road_info[next_Road_id]
        #        print(car.id, car.RoadSequence, car.road_index, car.get_road(S).lane_id(), car.state, self.id)
        assert car.RoadSequence[car.road_index] == self.id, 'Car not in this road.'

        # Case1, 若前方有等待行驶的车，自身也不能行驶
        for j in range(self.length - 1, car.road_pos, -1):
            if lane[car.lane][j] and lane[car.lane][j].state == 'wait':
                car.state = 'wait'
                return dead_stack, car, False
        # Case2, 同车道有前车
        for i in range(car.road_pos + 1, self.length):
            if lane[car.lane][i] != 0:  # 找到最近的前车
                lane[car.lane][car.road_pos] = 0
                car.road_pos = min(car.road_pos + min(self.speed, car.speed), i - 1)
                lane[car.lane][car.road_pos] = car
                car.state = 'final'
                dead_stack.append(car.id)
                return dead_stack, car, True
        # Case3, 没有前车且不需要经过路口时，车辆保持车道往前移动
        if car.road_pos + min(self.speed, car.speed) < self.length:
            lane[car.lane][car.road_pos] = 0
            car.road_pos += min(self.speed, car.speed)
            lane[car.lane][car.road_pos] = car
            car.state = 'final'
            dead_stack.append(car.id)
            return dead_stack, car, True
        # Case4, 没有前车，理论上需要经过路口但受到核心规则限制而不能通过(S1 = 车道长度-当前位置-1)
        elif self.length - 1 - car.road_pos >= min(next_Road.speed, car.speed):
            # print('No {} car will pass the cross but get S2 restrict'.format(car.id))
            lane[car.lane][car.road_pos] = 0
            car.road_pos = self.length - 1  # 到达车道最前端
            lane[car.lane][car.road_pos] = car
            car.state = 'final'
            dead_stack.append(car.id)
            return dead_stack, car, True
        # Case5, 没有前车，可以通过路口
        else:
            # print('No {} car will pass the cross.'.format(car.id))
            # print('s1 v2 = ', self.length-1-car.road_pos, min(next_Road.speed, car.speed) )
            car.state = 'wait'
            S.cross_info[cross_id].need_arrange = True
            return dead_stack, car, False

    def lane_id(self):
        if self.isDuplex:
            return [[s.id if s != 0 else 0 for s in self.lane[j]] for j in range(self.channel)], [
                [s.id if s != 0 else 0 for s in self.lane_rev[j]] for j in range(self.channel)]
        else:
            return [[s.id if s != 0 else 0 for s in self.lane[j]] for j in range(self.channel)]

    def passCross(self, dead_stack, S: Judge, reversed=False):
        # 通过路口的逻辑, reversed表示处理该条道路的反向通道
        car_list, rev_car_list = self.WhichCar()
        handled = 0  # 表示有车被调度，用于判断死锁
        if not reversed:
            lane = self.lane
            cross_id = self.end
            todo_list = deepcopy(car_list)
        else:
            assert self.isDuplex == 1, 'Error reversed option for passCross.'
            lane = self.lane_rev
            cross_id = self.start
            todo_list = deepcopy(rev_car_list)
        four_road = S.cross_info[cross_id].roads  # 对于当前路口连接的四条道路
        for car_id in todo_list:
            # if car_id == 18273:
            #     print(0)
            car = S.car_info[car_id]
            lane_prev = car.lane
            if car.state == 'wait':
                # 若到达了最后一条路
                if self.id == car.RoadSequence[-1]:
                    dead_stack, S, signal = self.DriveCar(car, dead_stack, S)
                    if signal:
                        handled = 1
                    return dead_stack, S, handled
                next_road_id = car.RoadSequence[car.road_index + 1]
                next_road = S.road_info[next_road_id]
                # 判断要进入的下一条路是进逆车道或是顺车道
                if next_road.start == cross_id:
                    next_lane = next_road.lane
                elif next_road.end == cross_id:
                    assert next_road.isDuplex, "Next road reversed option false..."
                    next_lane = next_road.lane_rev
                direction = (four_road.index(next_road_id) - four_road.index(self.id)) % 4
                '''-----------------------------------Debuged here'''
                # direction含义：1：左拐，2：直行，3：右拐
                # 若前方没有wait状态的车辆，如果是同一道路直行
                # 此调度发生于DriveCar或者passCross问题后的DriveCar中，不需要额外设计情况
                # 考虑需要通过路口的情况
                # 确定下个位置
                v1 = min(car.speed, self.speed)
                v2 = min(car.speed, next_road.speed)
                s1 = self.length - car.road_pos - 1
                s2 = v2 - s1
                # print('s1, s2, v1, v2, car.id, direction', s1, s2, v1, v2, car.id, direction)
                assert s2 > 0, 'passCross get s2 limited!'
                next_pos = s2 - 1
                flag = 0  # 0表示可通行，1表示不可通行，2表示已经通行完毕
                next_state = 1  # next_state为1表示后续所有的位置都被final的车占据了
                if direction == 2:
                    # 直行到下一条路
                    for i in range(next_road.channel):
                        tmp = -1
                        for j in range(next_pos + 1):
                            if next_lane[i][j] != 0:
                                if next_lane[i][j].state == 'wait':
                                    # 表示前进道路上有等待的车，自己也等待
                                    next_state = 0
                                    flag = 1
                                    break
                                else:
                                    tmp = j - 1
                                    break
                            elif next_lane[i][j] == 0:
                                if j >= tmp:
                                    tmp = j  # tmp记录在最小车道上能到达最远的位置
                        if tmp >= 0:
                            next_state = 0
                            lane[car.lane][car.road_pos] = 0
                            next_lane[i][tmp] = car
                            car.lane = i
                            car.road_pos = tmp
                            car.road_index += 1
                            car.state = 'final'
                            dead_stack.append(car.id)
                            S.car_info[car.id] = car
                            flag = 2
                            break
                        if flag:
                            break
                    # 后面所有可能位置全被final车辆占据，只能走到道路最前端，标为final
                    if next_state:
                        handled = 1
                        lane[car.lane][car.road_pos] = 0
                        car.road_pos = self.length - 1
                        lane[car.lane][car.road_pos] = car
                        car.state = 'final'
                        dead_stack.append(car.id)
                        S.car_info[car.id] = car
                        flag = 2
                    # 已经通行完毕（无论过没过路口），本车道全部需要DriveCar
                    if flag == 2:
                        handled = 1
                        #                        print('{} Success pass cross {}, start DriveCar for rest Car.'.format(car.id, cross_id))
                        # 当成功调度路口后，马上调度这条车道上所有的车。
                        #                        print('After Straightpass the cross, Drive all cars in this lane.')
                        for j in range(self.length - 2, -1, -1):
                            if lane[lane_prev][j]:
                                dead_stack, car, signal = self.DriveCar(lane[lane_prev][j], dead_stack, S, reversed)
                                S.car_info[car.id] = car
                elif direction == 3:
                    # 右拐具有最低的优先级，需要考虑针对目标道路左拐和直行的有无冲突，没有则行车，否则等待下次调度
                    straight_road_id = four_road[(four_road.index(next_road_id) - 2) % 4]
                    left_road_id = four_road[(four_road.index(next_road_id) - 1) % 4]
                    if straight_road_id != -1:
                        straight_road = S.road_info[straight_road_id]
                        straight_car_list, straight_rev_car_list = straight_road.WhichCar()
                    if left_road_id != -1:
                        left_road = S.road_info[left_road_id]
                        left_car_list, left_rev_car_list = left_road.WhichCar()
                    # 处理直行道路是否逆行道路
                    if straight_road_id != -1:
                        if straight_road.end != cross_id:
                            straight_todo_list = deepcopy(straight_rev_car_list)
                        else:
                            straight_todo_list = deepcopy(straight_car_list)
                    else:
                        straight_todo_list = []
                    # 处理左拐道路是否逆行道路
                    if left_road_id != -1:
                        if left_road.end != cross_id:
                            left_todo_list = deepcopy(left_rev_car_list)
                        else:
                            left_todo_list = deepcopy(left_car_list)
                    else:
                        left_todo_list = []
                    # 如果直行道上最高优先级的车辆要去目标道路，flag立起来，本车不能通行。
                    for car_id in straight_todo_list:
                        if S.car_info[car_id].state == 'wait' and S.car_info[car_id].RoadSequence[
                            S.car_info[car_id].road_index + 1] == next_road_id:
                            flag = 1
                            break
                        if S.car_info[car_id].state == 'wait' and S.car_info[car_id].RoadSequence[
                            S.car_info[car_id].road_index + 1] != next_road_id:
                            flag = 0
                            break
                    # 如果直行道上没有，如果左转最高优先级的车辆要去目标道路，flag立起来，本车不能通行。
                    if not flag:
                        for car_id in left_todo_list:
                            if S.car_info[car_id].state == 'wait' and S.car_info[car_id].RoadSequence[
                                S.car_info[car_id].road_index + 1] == next_road_id:
                                flag = 1
                                break
                            if S.car_info[car_id].state == 'wait' and S.car_info[car_id].RoadSequence[
                                S.car_info[car_id].road_index + 1] != next_road_id:
                                flag = 0
                                break
                    if flag == 0:  # 可以右拐
                        for i in range(next_road.channel):
                            tmp = -1
                            for j in range(next_pos + 1):
                                if next_lane[i][j] != 0 and next_lane[i][j].state == 'wait':
                                    # 表示前进道路上有等待的车，自己也等待，后续不能开flag=1
                                    next_state = 0
                                    flag = 1
                                    break
                                elif next_lane[i][j] and next_lane[i][j].state == 'final':
                                    tmp = j - 1  # 最近的一辆final的车，如果能走，走到它后面，如果不能，进入下一个车道
                                    break
                                elif next_lane[i][j] == 0:
                                    if j >= tmp:
                                        tmp = j  # tmp记录在最小车道上车辆能到达的最远的位置
                            if tmp >= 0:
                                next_state = 0
                                lane[car.lane][car.road_pos] = 0
                                next_lane[i][tmp] = car
                                car.lane = i
                                car.road_pos = tmp
                                car.road_index += 1
                                car.state = 'final'
                                dead_stack.append(car.id)
                                S.car_info[car.id] = car
                                flag = 2
                                break
                            if flag:
                                break
                    if next_state:
                        handled = 1
                        lane[car.lane][car.road_pos] = 0
                        lane[car.lane][-1] = car
                        car.road_pos = self.length - 1
                        car.state = 'final'
                        dead_stack.append(car.id)
                        S.car_info[car.id] = car
                        flag = 2
                    if flag == 2:
                        handled = 1
                        # print('{} Success pass cross {}, start DriveCar for rest Car.'.format(car.id, cross_id))
                        # 当成功调度路口后，马上调度这条车道上所有的车。
                        # print('After Rightpass the cross, Drive all cars in this lane.')
                        for j in range(self.length - 1, -1, -1):
                            if lane[lane_prev][j] != 0:
                                dead_stack, car, signal = self.DriveCar(lane[lane_prev][j], dead_stack, S, reversed)
                                S.car_info[car.id] = car
                elif direction == 1:
                    next_state = 1
                    flag = 0  # 若flag为0，表示可正常拐弯
                    # 左拐具有比直行低的优先级，需要考虑针对目标道路直行的有无冲突，没有则行车，否则等待下次调度
                    straight_road_id = four_road[(four_road.index(next_road_id) - 2) % 4]
                    if straight_road_id != -1:
                        straight_road = S.road_info[straight_road_id]
                        straight_car_list, straight_rev_car_list = straight_road.WhichCar()
                    # 处理直行道路是否逆行道路
                    if straight_road_id != -1:
                        if straight_road.end != cross_id:
                            straight_todo_list = straight_rev_car_list
                        else:
                            straight_todo_list = straight_car_list
                    else:
                        straight_todo_list = []
                    # 如果直行道上最高优先级的车辆要去目标道路，flag立起来，本车不能通行。
                    for car_id in straight_todo_list:
                        if S.car_info[car_id].state == 'wait' and S.car_info[car_id].RoadSequence[
                            S.car_info[car_id].road_index + 1] == next_road_id:
                            flag = 1
                            break
                        if S.car_info[car_id].state == 'wait' and S.car_info[car_id].RoadSequence[
                            S.car_info[car_id].road_index + 1] != next_road_id:
                            flag = 0
                            break
                    if flag == 0:  # 可以左拐
                        for i in range(next_road.channel):
                            tmp = -1
                            for j in range(next_pos + 1):
                                if next_lane[i][j] != 0 and next_lane[i][j].state == 'wait':
                                    # 表示前进道路上有等待的车，自己也等待，后续不能开，flag=1
                                    next_state = 0
                                    flag = 1
                                    break
                                elif next_lane[i][j] and next_lane[i][j].state == 'final':
                                    tmp = j - 1  # 最近的一辆final的车
                                    break
                                elif next_lane[i][j] == 0:
                                    if j >= tmp:
                                        tmp = j  # tmp记录在最小车道上车辆能到达的最远的位置
                            if tmp >= 0:
                                next_state = 0
                                lane[car.lane][car.road_pos] = 0
                                next_lane[i][tmp] = car
                                car.lane = i
                                car.road_pos = tmp
                                car.road_index += 1
                                car.state = 'final'
                                dead_stack.append(car.id)
                                S.car_info[car.id] = car
                                flag = 2
                                break
                            if flag:
                                break
                    if next_state:
                        handled = 1
                        lane[car.lane][car.road_pos] = 0
                        lane[car.lane][-1] = car
                        car.road_pos = self.length - 1
                        car.state = 'final'
                        dead_stack.append(car.id)
                        S.car_info[car.id] = car
                        flag = 2
                    if flag == 2:
                        handled = 1
                        #                        print('{} Success pass cross {}, start DriveCar for rest Car.'.format(car.id, cross_id))
                        # 当成功调度路口后，马上调度这条车道上所有的车。
                        #                        print('After Leftpass the cross, Drive all cars in this lane.')
                        for j in range(self.length - 1, -1, -1):
                            if lane[lane_prev][j] != 0:
                                dead_stack, car, signal = self.DriveCar(lane[lane_prev][j], dead_stack, S, reversed)
                                S.car_info[car.id] = car
                if flag == 1:  # 表示未能成功通行，其后的所有车都无法通行。
                    handled = 0
                    return dead_stack, S, handled
            else:
                continue
        return dead_stack, S, handled

    def WhichCar(self):
        # 返回当前道路上所有车辆的编号，按照调度顺序排列
        car_list = []
        rev_car_list = []
        j = self.length - 1
        while j >= 0:
            tmp = []
            for i in range(self.channel):
                if self.lane[i][j]:
                    tmp.append(self.lane[i][j].id)
            car_list += tmp
            j -= 1
        j = self.length - 1
        if self.lane_rev:
            while j >= 0:
                tmp = []
                for i in range(self.channel):
                    if self.lane_rev[i][j]:
                        tmp.append(self.lane_rev[i][j].id)
                rev_car_list += tmp
                j -= 1
        return car_list, rev_car_list

class Cross(object):
    """docstring for Cross"""

    def __init__(self, _id: int, cross_info: list):
        super(Cross, self).__init__()
        self.id = _id
        self.roads = sorted(cross_info)  # 存放连接该路口的四条路的编号
        self.need_arrange = False  # 是否需要调度

    def crossArrange(self, dead_stack, S: Judge):
        # 此处是调度各个路口的逻辑
        handled = 0
        for road_id in self.roads:
            if road_id == -1:
                continue
            else:
                road = S.road_info[road_id]
                if road.end == self.id:  # 出路口道路
                    dead_stack, S, tmp = road.passCross(dead_stack, S)
                elif road.start == self.id and road.isDuplex:  # 双向车道出路口
                    # print('process rev road, id is {}'.format(road_id))
                    dead_stack, S, tmp = road.passCross(dead_stack, S, reversed=True)
            handled |= tmp
        return dead_stack, S, handled

    def get_lane_and_car(self, S):
        for road_id in self.roads:
            if road_id != -1:
                road = S.road_info[road_id]
                print(road.id)
                print(road.lane_id())
                print('Next Road...')
        return 0


from django.core.management.base import BaseCommand
from tqdm import tqdm

from conditions.models import ConditionSet

class Command(BaseCommand):

    def handle(self, *args, **options):

        all_conditionsets = ConditionSet.objects.all()

        for conditionset in tqdm(all_conditionsets):

            # Re-generate the systematic name
            conditions_list = [(u'%s' % condition) for condition in
                               conditionset.conditions.order_by('type__tags__order', 'type__chebi_name',
                                                                'type__pubchem_name', 'type__name').all()]
            conditionset.systematic_name = u'%s' % ", ".join(conditions_list)

            conditionset.display_name = conditionset.systematic_name
            if conditionset.common_name:
                conditionset.display_name = conditionset.common_name

            conditionset.save()

        self.stdout.write('Successfully updated %d conditionsets.' % all_conditionsets.count())


# uncompyle6 version 3.7.4
# Python bytecode 2.6 (62161)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /home/uittenbroek/Projects/buildout-nuffic/src/collective.newrelic/collective/newrelic/patches/newrelic_transaction.py
# Compiled at: 2013-12-24 05:41:42
from collective.newrelic.utils import logger
from newrelic.api.transaction import Transaction
original__init__ = Transaction.__init__
original__exit__ = Transaction.__exit__

def patched__init__(self, *args, **kwargs):
    original__init__(self, *args, **kwargs)
    self._transaction_id = id(self)

Transaction.__init__ = patched__init__
logger.info('Patched newrelic.api.transaction:Transaction.__init__ to add _transaction_id')

def patched__exit__(self, *args, **kwargs):
    if self._transaction_id != id(self):
        logger.exception(('Checking my id: {0}  against {1}').format(self._transaction_id, id(self)))
        return
    original__exit__(self, *args, **kwargs)

Transaction.__exit__ = patched__exit__
logger.info('Patched newrelic.api.transaction:Transaction.__exit__ to check _transaction_id')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 22 18:31:58 2020

@author: gossn
"""

import numpy as np

#%% outofRangeDetection
def outofRangeDetection(array,rmin=np.nan,rmax=np.nan):
    '''
    Parameters
    ----------
    array : NumPy array or masked array. Dim (N,) or (N,1).
        Input array.
    rmin : float, optional
        Minimum acceptable value. Values below will be flagged as 'out of range'. The default is np.nan (no threshold applied).
    rmax : TYPE, optional
        Maximum acceptable value. Values above will be flagged as 'out of range'. The default is np.nan (no threshold applied).

    Returns
    -------
    rangeFlag. NumPy array of booleans. Flag indicating values out of range.
    '''
    # Example
    array = np.array([np.nan,1000,2.4,1.5,2,300,4,5,6000])
    mask0 = np.array([0     ,0   ,0  ,0  ,0,0  ,0,0,1   ])
    array = np.ma.array(array,mask=mask0)
    rmin=0;rmax=30
    rangeFlag = outofRangeDetection(array,rmin=0,rmax=10)

    arrayVal   = np.ma.getdata(array)
    rangeFlag = np.zeros(arrayVal.shape,dtype=bool)
    if not np.isnan(rmin):
        rangeFlag = (rangeFlag)|(arrayVal<rmin)
    if not np.isnan(rmax):
        rangeFlag = (rangeFlag)|(arrayVal>rmax)
    return rangeFlag
#%% statsArray
def statsArray(array):
    '''
    Parameters
    ----------
    array : NumPy array or masked array. Dim (N,) or (N,1)
        Computes main statistics of unmasked elements of array.
    Returns
    -------
    stats, dictionary with statistics.

    '''
    # Example:
    # array = np.array([np.nan,1000,2.4,1.5,2,300,4,5,2,7,6000])
    # mask0 = np.array([0     ,0   ,0  ,0  ,0,0  ,0,0,0,0,1   ])
    # array = np.ma.array(array,mask=mask0)
    # stats = statsArray(array)

    arrayVal   = np.ma.getdata(array)
    mask = np.ma.getmask(array)

    valid = (~mask)&(~np.isnan(arrayVal))
    arrayValid = np.ma.getdata(array[valid])

    stats = {}

    stats['N']      = len(array)
    stats['Nvalid'] = len(arrayValid)

    stats['Mean']   = np.mean(arrayValid)
    stats['Std']    = np.std( arrayValid)
    stats['CV']     = stats['Std']/stats['Mean']

    # Compute quartiles 1,2,3:
    for q,qfrac in zip([1,2,3],[0.25,0.50,0.75]):
        if len(arrayValid)>0:
            stats['Q' + str(q)] = np.quantile(arrayValid,qfrac)
        else:
            stats['Q' + str(q)] = np.nan

    stats['IQR']    = stats['Q3'] - stats['Q1']
    stats['sIQR']   = stats['IQR']/2
    stats['CV_R']   = (20/27)*(stats['IQR']/stats['Q2'])

    return stats
#%% outlierDetection
def outlierDetection(array,mode='iqr'):
    '''
    Parameters
    ----------
    array : NumPy array or masked array. Dim (N,) or (N,1)
    mode  : string, optional. Indicates the method to compute the presence of outliers. The default is 'iqr'.

    Returns
    -------
    outFlag. NumPy array of booleans. Flag indicating outliers. Does not include previously masked values.
    stats. Dictionary with statistics, computed over the non-masked and non-outlier values of the array.
    '''
    # Example
    # array = np.array([np.nan,100000,2.4,1.5,2,300,4,5,6000])
    # mask0 = np.array([0     ,0     ,0  ,0  ,0,0  ,0,0,1   ])
    # array = np.ma.array(array,mask=mask0)
    # outFlag,stats = outlierDetection(array,mode='s3vt')

    stats = statsArray(array)

    arrayVal   = np.ma.getdata(array)
    mask = np.ma.getmask(array)

    if mode == 'iqr':
        outFlag = (arrayVal<(stats['Q1']-1.5*stats['IQR']))|(arrayVal>(stats['Q3']+1.5*stats['IQR']))
    elif mode == 's3vt':
        outFlag = np.abs(arrayVal-stats['Mean']) > 1.5*stats['Std']
    elif mode == 's3vt-r':
        outFlag = np.abs(arrayVal-stats['Q2'  ]) > 10/9*stats['IQR']
    else:
        TypeError

    outFlag = (outFlag)&(~mask)
    stats = statsArray(np.ma.array(array,mask=(mask)|(outFlag)))

    return outFlag,stats
#%% qcArray
def qcArray(array,mode='default'):
    '''
    Parameters
    ----------
    array : NumPy array or masked array. Dim (N,) or (N,1)
    mode : string, optional. Decides which mode to apply. The default is 'default'.
        if mode == 'default':
            Reject negative values. No maximum threshold applied
            Uses S3VT-R mode to detect outliers

    Returns
    -------
    rangeFlag. NumPy array of booleans. Flag indicating values out of range.
    outFlag. NumPy array of booleans. Flag indicating outliers. Does not include previously masked values.
    stats. Dictionary with statistics, computed over the non-masked and non-outlier values of the array.
    '''
    # Example
    # array = np.array([np.nan,1000,2.4,1.5,2,300,4,5,6000,-10])
    # mask0 = np.array([0     ,0   ,0  ,0  ,0,0  ,0,0,1   ,0  ])
    # array = np.ma.array(array,mask=mask0)
    # rangeFlag,outFlag,stats = qcArray(array)

    if mode == 'default':
        '''
        Reject negative values. No maximum threshold applied
        Uses S3VT-R mode to detect outliers
        '''
        rmin=0; rmax=np.nan; mode='s3vt-r'

        rangeFlag = outofRangeDetection(array,rmin=rmin,rmax=rmax)
        array = np.ma.array(array,mask=np.ma.getmask(array)|rangeFlag)

        outFlag,stats = outlierDetection(array,mode=mode)

    return rangeFlag,outFlag,stats


import sys
import urllib.request
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5 import uic
import sensing
import time
import matplotlib.pyplot as plt
from gasLeakage import *
import pandas as pd
import datetime

form_class = uic.loadUiType("sensor.ui")[0]

class WindowClass(QMainWindow, form_class) :
    def __init__(self) :
        super().__init__()
        self.setupUi(self)

        self.btn_1.clicked.connect(self.button1Function)

    def button1Function(self) :

        count =0
        temp = []
        temp2 = []
        gas = gasLeakage()

        while True:
            getData = gas.getSensorData()
            gas.controlFan(getData)

            print("[DEBUG] Smoke Sensor Value = %u"%(getData))

            data = [[datetime.datetime.now(), getData]]
            submission = pd.DataFrame(data)
            submission.to_csv('./Gas_DataSet.csv', header = False, mode = 'a', index = False)
            time.sleep(0.5)
            temp.append(getData)
            temp2.append(str(getData))
            count +=1
            if count >= 15:
                break

        auth = 0
        for element in temp:
            if element >= 200:
                auth = 1

        if auth == 1:
            self.textBrowser_2.setPlainText("위험상황입니다.")
        else:
            self.textBrowser_2.setPlainText("정상입니다.")
        self.textBrowser_3.setPlainText("정상입니다.")

        view = self.listView
        model = QStandardItemModel()
        for f in temp2:
            model.appendRow(QStandardItem(f))
        view.setModel(model)

        plt.plot(temp, color='red')
        plt.xlabel("Time")
        plt.ylabel("Gas_data")
        plt.draw()
        fig = plt.gcf()
        fig.set_figwidth(320/fig.dpi)
        fig.set_figheight(240/fig.dpi)
        fig.savefig("myfile.png")

        self.qPixmapFileVar = QPixmap()
        self.qPixmapFileVar.load("myfile.png")
        self.qPixmapFileVar = self.qPixmapFileVar.scaled(320,240)
        self.lbl_picture.setPixmap(self.qPixmapFileVar)

if __name__ == "__main__" :
    app = QApplication(sys.argv)
    myWindow = WindowClass()
    myWindow.show()
    app.exec_()


import time

import RPi.GPIO as GPIO

from nrf24 import NRF24

class Connection:
    WRITING_PIPE = [0xf0, 0xf0, 0xf0, 0xf0, 0xe1]
    READING_PIPE = [0xf0, 0xf0, 0xf0, 0xf0, 0xd2]
    BUS = 0
    CHIP = 0
    CE_PIN = 25
    IRQ_PIN = 18
    RADIO_RETRY_DELAY = 15
    RADIO_RETRY_COUNT = 15
    RADIO_CHANNEL = 0x4c
    RADIO_PAYLOAD_SIZE = 32
    PACKET_AVAILABLE_TIMEOUT = 1 / 1000.0

    def __init__(self):
        GPIO.setmode(GPIO.BCM)
        self._radio = NRF24()

    def radio_setup(self):
        self._radio.begin(self.BUS, self.CHIP, self.CE_PIN, self.IRQ_PIN)
        self._radio.setRetries(self.RADIO_RETRY_DELAY, self.RADIO_RETRY_COUNT)
        self._radio.setPayloadSize(self.RADIO_PAYLOAD_SIZE)
        self._radio.setChannel(self.RADIO_CHANNEL)
        self._radio.setDataRate(NRF24.BR_250KBPS)
        self._radio.setPALevel(NRF24.PA_MAX)
        self._radio.setAutoAck(1)
        self._radio.openWritingPipe(self.WRITING_PIPE)
        self._radio.openReadingPipe(1, self.READING_PIPE)
        self._radio.enableDynamicPayloads()
        self._radio.startListening()

    def get_packet(self):
        while not self._radio.available([0], True):
            time.sleep(self.PACKET_AVAILABLE_TIMEOUT)
        rec_buffer = []
        self._radio.read(rec_buffer, self._radio.getDynamicPayloadSize())
        return rec_buffer


import pygame
from engine import *
import random
from collections import deque

class SnakeController(Behaviour):
    def on_start(self):
        self.speed = 0.15
        self.moveDir = Vector2(1, 0)
        self.head = Head("snakeHead", 1)
        self.head.instantiate(self.gameObject, pos=Vector2(0, 0))
        self.tail = Tail("snakeTail", 0.5)
        self.tail.instantiate(self.gameObject, pos=Vector2(0, 0))
        self.length = 22
        self.food = Food("food", -1)
        self.food.instantiate(self.gameObject.getRoot())
        self.eat()

    def eat(self):
        self.length += 1
        scene = self.gameObject.getRoot()
        foodSize = self.food.getComponent(BoxTexture).size
        _x = foodSize[0] / 2 + random.random() * (scene.screen.get_rect().width - foodSize[0])
        _y = foodSize[0] / 2 + random.random() * (scene.screen.get_rect().height - foodSize[1])
        self.food.transform.pos = Vector2(_x, _y)

    def on_keydown(self, key, mod, unicode, scancode):
        newMoveDir = self.moveDir
        if key in [pygame.K_w, pygame.K_UP]:
            newMoveDir = Vector2(0, -1)
        elif key in [pygame.K_s, pygame.K_DOWN]:
            newMoveDir = Vector2(0, 1)
        elif key in [pygame.K_a, pygame.K_LEFT]:
            newMoveDir = Vector2(-1, 0)
        elif key in [pygame.K_d, pygame.K_RIGHT]:
            newMoveDir = Vector2(1, 0)
        if newMoveDir @ self.moveDir == 0:
            return
        self.moveDir = newMoveDir

    def on_tick(self, scene):
        tr = self.head.transform
        tr.pos += self.moveDir * self.speed * scene.clock.get_time()
        tr.pos = tr.parent.fromAbsolute(tr.getAbsolutePosition().clamp(scene.screen.get_rect()))
        self.tail.addTrail(tr.pos, self.moveDir)
        # TODO: Collider Component
        headCollider = self.head.getComponent(BoxCollider)
        foodCollider = self.food.getComponent(BoxCollider)
        if Collider.collide(headCollider, foodCollider):
            self.eat()
        tailCollider = self.tail.getComponent(TailCollider)
        if Collider.collide(headCollider, tailCollider):
            print("Dead!")
            self.gameObject.getRoot().stop()

class Head(GameObject):
    def __init__(self, name=None, zIndex=0):
        super().__init__(name)
        self.addComponent(BoxTexture, (32, 32), (255, 255, 255), zIndex=zIndex, offset=(-16, -16))
        self.addComponent(BoxCollider, (32, 32), offset=(-16, -16))

class Food(GameObject):
    def __init__(self, name=None, zIndex=0):
        super().__init__(name)
        self.addComponent(BoxTexture, (16, 16), (255, 0, 0), zIndex=zIndex, offset=(-8, -8))
        self.addComponent(BoxCollider, (16, 16), offset=(-8, -8))

class TailCollider(Collider):
    def __init__(self, gameObject, width):
        super().__init__(gameObject)
        self.width = width

    def _collide(self, other):
        if isinstance(other, BoxCollider):
            otherRect = other.getRect()
            trail = self.gameObject.getTrail(self.width)
            #print(trail)
            if not self.gameObject.trail[0][1]:
                trail = trail[1:]
            if len(self.gameObject.trail) >= 2 and not self.gameObject.trail[1][1]:
                trail = trail[1:]
            for rect in trail:
                if otherRect.colliderect(rect):
                    return True
            return False
        return NotImplemented

class TailTexture(Texture):
    def __init__(self, gameObject, width, color, zIndex=0):
        super().__init__(gameObject, zIndex=zIndex)
        self.color = color
        self.width = width

    def on_draw(self, drawBuf):
        for rect in self.gameObject.getTrail(self.width):
            self.draw(drawBuf, self.color, rect)

class Tail(GameObject):
    def __init__(self, name=None, zIndex=0):
        super().__init__(name)
        self.trail = deque()
        self.addComponent(TailTexture, 32, (0, 255, 0), zIndex=zIndex)
        self.addComponent(TailCollider, 32)

    def addTrail(self, pos, moveDir):
        gap = False
        if len(self.trail) >= 2:
            lastDir = self.trail[-1][0] - self.trail[-2][0]
            curDir = pos - self.trail[-1][0]
            if curDir * moveDir < 0:
                gap = True
            elif curDir * lastDir > 0:
                self.trail.pop()
        self.trail.append((pos, gap))
        # !Clear
        if len(self.trail) >= 10 ** 4:
            self.trail.popleft()

    def getTrail(self, width):
        trail = list(self.trail)[::-1]
        res = []
        rem = self.getParent().getComponent(SnakeController).length * 32
        for i in range(1, len(trail)):
            prevPoint = trail[i - 1][0]
            curPoint = trail[i][0]
            if trail[i - 1][1]:
                continue
            segLen = abs(curPoint - prevPoint)
            rem -= segLen
            dir = (curPoint - prevPoint).normalize()
            radius = dir.rotate90() * (width / 2)
            if rem <= 0:
                r0 = prevPoint - radius - dir * 16
                r1 = curPoint + dir * rem + radius + dir * 16
                rect = Vector2.rect(r0, r1)
                res.append(rect)
                break
            r0 = prevPoint - radius - dir * 16
            r1 = curPoint + radius + dir * 16
            rect = Vector2.rect(r0, r1)
            res.append(rect)
        return res

def main():
    pygame.init()
    size = 800, 600

    scene = Scene(size=size, bgColor=(0, 0, 0))
    snake = GameObject()
    snake.addComponent(SnakeController)
    snake.instantiate(scene)
    scene.run()

try:
    main()
finally:
    pygame.quit()


"""
Title:       Automated Data Acquisition Script
Description: Example
Comments:    Message termination for all instruments is set to '\n'

Author: fkyburz
"""
import numpy as np
import time
from ntbvisa import *

__version__ = '0.0'

__author__ = 'Falk Kyburz'
__license__ = 'None'
__status__ = 'Development'
__date__ = '2017-07-28'

# File name for the raw results file (.pickle, .mat)
filename = 'Transformer'

# Fill in primary and secondary inductance
L_prim = 1224e-6
L_sek = 924.2e-6

# Set DMM names
dmm_pri_name = 'TCPIP::mmies010::INSTR'
dmm_sek_name = 'TCPIP::mmies011::INSTR'
gen_name = 'TCPIP::fgies002::INSTR'

# AWG Config
gen_config = ['OUTP1:LOAD INF',
              'SOUR1:FUNC SIN',
              'SOUR1:FREQ 10000',
              'SOUR1:VOLT 1 VRMS',
              'SOUR1:VOLT:OFFS 0'
              ]

# DMM Config
dmm_config = ['CONF:VOLT:AC 1',
              'SAMP:COUN 5000']

def dcload_config(instr):
    instr.setRemoteControl()
    instr.setFunction('fixed')
    instr.setMode('cc')
    instr.setMaxPower(500)
    instr.setMaxCurrent(2)
    instr.setMaxVoltage(500)

def main():

    #     list_resources()

    # Keysight AWG
    gen = NTBResource(gen_name, gen_config)
    # Keysight DMM
    dmm_pri = NTBResource(dmm_pri_name, dmm_config)
    # Keysight DMM
    dmm_sek = NTBResource(dmm_sek_name, dmm_config)
    # ITECH Load
    load = NTBResourceDCLoad('COM6', 4800, 0, dcload_config)

    # Put instruments in setup
    setup = NTBSetup([gen, dmm_pri, dmm_sek, load])

    # Turn on gen
    gen.write('OUTP1 ON')
    gen.write('INIT1:CONT ON')

    # Turn on load
    load.turnLoadOn()
    time.sleep(2)
    load.turnLoadOff()

    setup.close_all()

if __name__ == "__main__":
    main()


import struct
import datetime

# File Download
CMD_START_FILE_DOWNLOAD = 0x40
CMD_GET_FILE_METADATA = 0x41
CMD_GET_FILE_DOWNLOAD_STATUS = 0x42
CMD_CANCEL_FILE_DOWNLOAD = 0x43
CMD_GET_FILE_DATA = 0x44

class FileMixins(object):

    def start_file_download(self, fileid):
        """Start file download

        :param integer fileid:
            FileID of start to download, must be 1 to 5.

        """

        if isinstance(fileid, list):
            # for Compatibility
            fileid = fileid[0]

        self.execute_command(CMD_START_FILE_DOWNLOAD, [fileid, 0x00])

    def get_file_metadata(self):
        """Get file metadata

        :return: Dict of file metadata (status, filesize, timestamp, checksum).
        :rtype: dict
        """

        response = self.execute_command(CMD_GET_FILE_METADATA)
        return {
            "status": response[0],
            "size": struct.unpack("<i", struct.pack("4B", *response[1:5]))[0],
            "timestamp": struct.unpack("<q", struct.pack("8B", *response[5:13]))[0],
            "checksum": response[13:17],
        }

    def get_file_download_status(self):
        """Get file download status

        :return: Dict of download status and received datasize.
        :rtype: dict
        """

        response = self.execute_command(CMD_GET_FILE_DOWNLOAD_STATUS)
        return {
            "status": response[0],
            "size": struct.unpack("<i", struct.pack("4B", *response[1:5]))[0],
        }

    def cancel_file_download(self):
        """Cancel file download"""

        self.execute_command(CMD_CANCEL_FILE_DOWNLOAD)

    def get_file_data(self, rsize):
        """Get file data

        :param integer rsize:
            Max receive size, must be 1 to 255.

        :return: Part of data
        :rtype: list
        """

        is_old_style = False

        if isinstance(rsize, list):
            rsize = rsize[0]
            is_old_style = True

        if rsize <= 0 or rsize > 255:
            raise ValueError("Invalid rsize %d", rsize)

        response = self.execute_command(CMD_GET_FILE_DATA, [rsize])
        if is_old_style:
            return {
                "data": response[0:]
            }
        return response


#!/usr/bin/env python

# Imports, sorted alphabetically.

# Python packages
from ConfigParser import NoSectionError, NoOptionError
import argparse
from binascii import hexlify
import datetime
import os
import random
import time

# Third-party packages
import pyglet
# Disable error checking for increased performance
pyglet.options['debug_gl'] = False
from pyglet.gl import *

# Modules from this project
from controllers import *
import globals as G
from timer import Timer

class InvalidChoice(Exception):
    pass

def get_or_update_config(section, option, default_value, conv=str, choices=()):
    try:
        if conv is bool:
            user_value = G.config.getboolean(section, option)
        else:
            user_value = conv(G.config.get(section, option))
    except NoSectionError:
        G.config.add_section(section)
    except NoOptionError:
        pass
    else:
        # If the option is already set:
        if choices and user_value not in choices:
            raise InvalidChoice('%s.%s must be in %s' %
                                (section, option, repr(tuple(choices))))
        return user_value
    G.config.set(section, option, str(default_value))
    return default_value

class InvalidKey(Exception):
    pass

def get_key(key_name):
    key_code = getattr(pyglet.window.key, key_name, None)
    if key_code is None:
        # Handles cases like pyglet.window.key._1
        key_code = getattr(pyglet.window.key, '_' + key_name, None)
        if key_code is None:
            raise InvalidKey('%s is not a valid key.' % key_name)
    return key_code

def initialize_config():
    #
    # General
    #

    general = 'General'

    G.DEBUG = get_or_update_config(
        general, 'debug', G.DEBUG, conv=bool)

    get_or_update_config(
        general, 'save_mode', G.SAVE_MODE, choices=G.SAVE_MODES)

    #
    # Graphics
    #

    graphics = 'Graphics'

    G.FULLSCREEN = get_or_update_config(
        graphics, 'fullscreen', G.FULLSCREEN, conv=bool)
    G.WINDOW_WIDTH = get_or_update_config(
        graphics, 'width', G.WINDOW_WIDTH, conv=int)
    G.WINDOW_HEIGHT = get_or_update_config(
        graphics, 'height', G.WINDOW_HEIGHT, conv=int)

    G.DRAW_DISTANCE_CHOICE = get_or_update_config(
        graphics, 'draw_distance', G.DRAW_DISTANCE_CHOICE,
        choices=G.DRAW_DISTANCE_CHOICES)
    G.DRAW_DISTANCE = G.DRAW_DISTANCE_CHOICES[G.DRAW_DISTANCE_CHOICE]

    G.FOG_ENABLED = get_or_update_config(
        graphics, 'fog_enabled', G.FOG_ENABLED, conv=bool)

    G.MOTION_BLUR = get_or_update_config(
        graphics, 'motion_blur', G.MOTION_BLUR, conv=bool)

    #
    # World
    #

    world = 'World'

    # TODO: This setting must be removed when terrain generation will improve.
    get_or_update_config(world, 'size', 64, conv=int)

    #
    # Controls
    #

    controls = 'Controls'

    # Adds missing keys to configuration file and converts to pyglet keys.
    for control, default_key_name in G.KEY_BINDINGS.items():
        key_name = get_or_update_config(controls, control, default_key_name)
        try:
            pyglet_key = get_key(key_name)
        except InvalidKey:
            pyglet_key = get_key(default_key_name)
            G.config.set(controls, control, default_key_name)
        setattr(G, control.upper() + '_KEY', pyglet_key)

    #
    # Save config file
    #

    with open(G.config_file, 'wb') as handle:
        G.config.write(handle)

class Window(pyglet.window.Window):
    def __init__(self, **kwargs):
        kwargs.update(
            caption=G.APP_NAME,
        )
        super(Window, self).__init__(
            G.WINDOW_WIDTH, G.WINDOW_HEIGHT, **kwargs)
        self.exclusive = False
        self.reticle = None
        self.controller = None
        controller = MainMenuController(self)
        self.switch_controller(controller)
        if G.FULLSCREEN:
            self.set_fullscreen()
        pyglet.clock.schedule_interval(self.update, 1.0 / G.MAX_FPS)

    def set_exclusive_mouse(self, exclusive):
        super(Window, self).set_exclusive_mouse(exclusive)
        self.exclusive = exclusive

    def update(self, dt):
        self.controller.update(dt)

    def switch_controller(self, new_controller):
        if self.controller:
            self.controller.pop_handlers()
        self.controller = new_controller
        self.controller.push_handlers()

    def on_key_press(self, symbol, modifiers):
        if self.exclusive:
            if symbol == G.ESCAPE_KEY and not self.fullscreen:
                self.set_exclusive_mouse(False)
            elif symbol == key.Q and self.fullscreen:  # FIXME: Better fullscreen mode.
                pyglet.app.exit()  # for fullscreen

    def on_draw(self):
        if self.exclusive:
            self.reticle.draw(GL_LINES)
            if G.MOTION_BLUR:
                glAccum(GL_MULT, 0.65)
                glAccum(GL_ACCUM, 0.35)
                glAccum(GL_RETURN, 1.0)

    def on_resize(self, width, height):
        if self.reticle:
            self.reticle.delete()
        x, y = width / 2, height / 2
        n = 10
        self.reticle = pyglet.graphics.vertex_list(
            4,
            ('v2i', (x - n, y, x + n, y, x, y - n, x, y + n))
        )

def main(options):
    G.GAME_MODE = options.game_mode
    G.SAVE_FILENAME = options.save
    G.DISABLE_SAVE = options.disable_save
    for name, val in options._get_kwargs():
        setattr(G.LAUNCH_OPTIONS, name, val)

    G.TERRAIN_CHOICE = options.terrain
    G.TERRAIN = G.TERRAIN_CHOICES[options.terrain]

    G.FLAT_MODE = options.flat

    if options.fast:
        G.TIME_RATE /= 20

    seed = options.seed
    if seed is None:
        # Generates pseudo-random number.
        try:
            seed = long(hexlify(os.urandom(16)), 16)
        except NotImplementedError:
            import time
            seed = long(time.time() * 256)  # use fractional seconds
        # Then convert it to a string so all seeds have the same type.
        seed = str(seed)

        print('Random seed: ' + seed)

    random.seed(seed)

    with open(os.path.join(G.game_dir, 'seeds.txt'), 'a') as seeds:
        seeds.write(datetime.datetime.now().strftime(
            'Seed used the %d %m %Y at %H:%M:%S\n'))
        seeds.write('%s\n\n' % seed)

    # try:
        # window_config = Config(sample_buffers=1, samples=4) #, depth_size=8)  #, double_buffer=True) #TODO Break anti-aliasing/multisampling into an explicit menu option
        # window = Window(resizable=True, config=window_config)
    # except pyglet.window.NoSuchConfigException:
    window = Window(resizable=True, vsync=False)

    G.main_timer = Timer()
    pyglet.clock.schedule_interval(G.main_timer.schedule, G.TIMER_INTERVAL)
    pyglet.app.run()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Play a Python made Minecraft clone.')

    game_group = parser.add_argument_group('Game options')
    game_group.add_argument("--terrain", choices=G.TERRAIN_CHOICES, default=G.DEFAULT_TERRAIN_CHOICE)
    game_group.add_argument("--flat", action="store_true", default=False, help="Generate a flat world.")
    game_group.add_argument("--fast", action="store_true", default=False, help="Makes time progress faster then normal.")
    game_group.add_argument("--game-mode", choices=G.GAME_MODE_CHOICES, default=G.GAME_MODE)

    save_group = parser.add_argument_group('Save options')
    save_group.add_argument("--disable-auto-save", action="store_false", default=True, help="Do not save world on exit.")
    save_group.add_argument("--save", default=G.SAVE_FILENAME, help="Type a name for the world to be saved as.")
    save_group.add_argument("--disable-save", action="store_false", default=True, help="Disables saving.")

    parser.add_argument("--seed", default=None)

    options = parser.parse_args()
    initialize_config()
    main(options)


"""Discrete MLP QFunction."""
import tensorflow as tf

from garage.misc.overrides import overrides
from garage.tf.core.mlp import mlp
from garage.tf.q_functions import QFunction

class DiscreteMLPQFunction(QFunction):
    """
    Discrete MLP Function class.

    This class implements a Q-value network. It predicts Q-value based on the
    input state and action. It uses an MLP to fit the function Q(s, a).
    """

    def __init__(self,
                 env_spec,
                 hidden_sizes=(32, 32),
                 hidden_nonlinearity=tf.nn.relu,
                 output_nonlinearity=None,
                 layer_norm=False):
        """
        Initialize class with multiple attributes.

        Args:
            env_spec: environment specification
            hidden_sizes: A list of numbers of hidden units
                for all hidden layers.
            hidden_nonlinearity: An activation shared by all fc layers.
            output_nonlinearity: An activation used by the output layer.
            layer_norm: A bool to indicate whether to perform
                layer normalization or not.
        """
        super(DiscreteMLPQFunction, self).__init__()

        self._action_dim = env_spec.action_space.flat_dim
        self._hidden_sizes = hidden_sizes
        self._hidden_nonlinearity = hidden_nonlinearity
        self._output_nonlinearity = output_nonlinearity
        self._layer_norm = layer_norm

    @overrides
    def build_net(self, name, input):
        """
        Set up q network based on class attributes.

        Args:
            name: Network variable scope.
            input: Input tf.placeholder to the network.
        """
        return mlp(
            input_var=input,
            output_dim=self._action_dim,
            hidden_sizes=self._hidden_sizes,
            name=name,
            hidden_nonlinearity=self._hidden_nonlinearity,
            output_nonlinearity=self._output_nonlinearity,
            layer_normalization=self._layer_norm)


# @Author: Tushar Agarwal(tusharcoder) <tushar>
# @Date:   2017-06-13T10:05:29+05:30
# @Email:  tamyworld@gmail.com
# @Filename: models.py
# @Last modified by:   tushar
# @Last modified time: 2017-06-13T12:11:46+05:30

from django.db import models
from django.contrib.auth.models import User
from .app_settings import PROFILE_CHANGABLE_FIELDS
# Create your models here.

class UserProfile(models.Model):
    """
    Model to store the user profile
    """
    user = models.ForeignKey(User)
    name = models.CharField(max_length=100)
    emp_id = models.CharField(max_length=10)
    address = models.TextField(max_length=500)
    pan_no= models.CharField(max_length=12)
    position= models.CharField(max_length=20)

    def __str__(self):
        """
        return the string representation of the model
        """
        return self.name

    def updateProfile(self,**kwargs):
        """
        model to save the UserProfile
        """
        fields_to_change = set(kwargs.keys()).intersection(PROFILE_CHANGABLE_FIELDS)
        for field in fields_to_change:
            setattr(self,field,kwargs.get(field)[0])
        self.save()
        return True

class Project(models.Model):
    """Model to store the Projet details"""
    name=models.CharField(max_length=100)
    description=models.CharField(max_length=500)
    def __str__(self):
        """return the string representation of the MOdel Project"""
        return self.name

class WorkType(models.Model):
    """Model to store the type"""
    name=models.CharField(max_length=100)
    def __str__(self):
        """return the string representation of the MOdel Project"""
        return self.name

class Task(models.Model):
    """Model to store the task assigned to the user"""
    name=models.CharField(max_length=100)
    description=models.CharField(max_length=500)
    starttime=models.DateTimeField()
    endtime=models.DateTimeField()
    project=models.ForeignKey(Project)
    worktype=models.ForeignKey(WorkType)
    assigned_by=models.ForeignKey(User)
    is_approved = models.BooleanField(default=False)

    def __str__(self):
        return self.name


# -*- coding: utf-8 -*-
"""
functions to use GEE within Qgis python script
"""
import ee

import ee_plugin.utils

def addLayer(image: ee.Image, visParams=None, name='untitled', shown=True, opacity=1.0):
    """
        Mimique addLayer GEE function

        Uses:
            >>> from ee_plugin import Map
            >>> Map.addLayer(.....)
    """
    if not isinstance(image, ee.Image):
        err_str = "\n\nThe image argument in 'addLayer' function must be a 'ee.Image' instance."
        raise AttributeError(err_str)

    if visParams:
        image = image.visualize(**visParams)

    ee_plugin.utils.add_or_update_ee_image_layer(image, name, shown, opacity)


# -*- coding: utf-8 -*-
"""
Created on Tue Jun 11 11:18:58 2019
@author: Harish Julapalli
"""

import os
import nltk
from nltk.corpus import RegexpTokenizer as regextoken
import matplotlib.pyplot as plt
nltk.download('averaged_perceptron_tagger')

os.chdir("E:\\Python\\NLP\\")

def read_files(path, review_list):
    os.chdir(path)
    entries = os.listdir(path)
    for entry in entries:
        with open(entry,'r') as input:
            review_list.append(input.read())
    return review_list

positive_reviews_true = []
positive_reviews_true = read_files("E:\\Python\\NLP\\op_spam_v1.4\\pos_tru", positive_reviews_true)

positive_reviews_dec = []
positive_reviews_dec = read_files("E:\\Python\\NLP\\op_spam_v1.4\\pos_dec", positive_reviews_dec)

negative_reviews_true = []
negative_reviews_true = read_files("E:\\Python\\NLP\\op_spam_v1.4\\neg_tru", negative_reviews_true)

negative_reviews_dec = []
negative_reviews_dec = read_files("E:\\Python\\NLP\\op_spam_v1.4\\neg_dec", negative_reviews_dec)

#POSITIVE REVIEWS
def pos_tagger(review_list):
    tokenizer = regextoken(r'\w+')
    for review in review_list:
        words = tokenizer.tokenize(review)
        pos = nltk.pos_tag(words)
    print(pos)

pos_tagger(positive_reviews_true)


def backtrack(candidates, target, solutionSet, runningSum, candidateSolution):
    if(runningSum > target):
        return
    elif(runningSum == target):
        #if candidateSolution not in solutionSet:
        #    solutionSet.append(candidateSolution)
        newKey = ""
        for i in candidateSolution:
            newKey += str(i)
        if newKey not in solutionSet:
            solutionSet[newKey] = [elem for elem in candidateSolution]
            solutionSet[newKey].sort()
    else:
        for j in range(0,len(candidates),1):
            candidateSolution.append(candidates[j])
            runningSum += candidates[j]
            backtrack(candidates, target, solutionSet, runningSum, candidateSolution)
            candidateSolution.pop()
            runningSum -= candidates[j]

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        solutionSet = []
        solutionDict = {}
        backtrack(candidates, target, solutionDict, 0, [])
        #print(solutionDict)
        #print(len(solutionDict.keys()))
        for key in solutionDict:
            #tmp = solutionDict[key].sort()
            if solutionDict[key] not in solutionSet:
                solutionSet.append(solutionDict[key])
        return solutionSet


from typing import List

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def make_tree(nodes: List[int]) -> List[TreeNode]:
    v = []
    for n in nodes:
        v.append(TreeNode(n) if n is not None else None)

    size = len(v) - 1
    for i in range(len(v)):
        n = 2 * i + 1
        if n > size:
            break

        if v[i] is not None:
            v[i].left = v[n]
            n += 1
            if n > size:
                break
            v[i].right = v[n]

    return v


from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import FeatureUnion
from sklearn.pipeline import Pipeline
from sklearn.svm import SVC
import re

class SectionSelector(BaseEstimator, TransformerMixin):
    '''
        used by scikit, calculates all of the html specific stats i generate
    '''
    def __init__(self, sec='body'):
        self.sec = sec
        self.funcs = {'body': self.joinBodies,
                      'head': self.joinHeads
        }

    def fit(self, x, y=None):
        return self

    def transform(self, data):
        return self.funcs[self.sec](data)

    def joinBodies(self, data):
        print(data)
        r =  ''.join([self.stripWhiteSpace(r) for p in data.iterPages()
                        for r in re.findall("<body>(.*)</body>", p, flags=re.DOTALL)
                        if r])
        print(r)
        return r

    def joinHeads(self):
        pass

    def stripWhiteSpace(self, page):
        return ''.join(page.split())

pipeline = Pipeline([
    ('union', FeatureUnion(
        transformer_list=[

            # Pipeline for pulling features from the post's subject line
            ('body_tag_counter', Pipeline([
                ('body_tags', SectionSelector(sec='body')),
                ('bpdy_tag_features', TfidfVectorizer(analyzer='word',
                                                      lowercase=True,
                                                      token_pattern="<(.+)?\s")),
            ])),

        ],

        # weight components in FeatureUnion
        transformer_weights={
        },
    )),

    # Use a SVC classifier on the combined features
    ('svc', SVC(kernel='linear')),
])


import os
import sys

def my_function(one, two,
                three, four,
                five, six):
    print("Hello world")

def second_function(): #two blank lines between functions
    print("Second function")

my_list = [1, 2,
           3, 4,
           5, 6]

my_list[2]

x = 3*52 + 7*2 #lower priority operation with spaces

check = True

if check is True:
    print('This is true')


import tkinter as tk
from PIL import Image, ImageTk
from game_sim import decode_table
from game_sim import encodeCards

root = tk.Tk()
root.geometry('600x400+0+0')

alice_frame = tk.Frame(root, bg="#000000")
alice_frame.place(relx=0.5, rely=1, relwidth=1, relheight=0.3, anchor="s")

# import card pictures
cards = {}
for color_int, color_str in decode_table["colors"].items():
    for value_int, value_str in decode_table["values"].items():
        card_id = (color_int, value_int)
        path = "../card_images/"+color_str.lower()+"_"+value_str.lower()+".png"

        image = Image.open(path).resize((106,142))

        image = ImageTk.PhotoImage(image)
        cards[card_id] = image

bob_frame = tk.Frame(root, bg="#000000")
bob_frame.place(relx=0.5, rely=0, relwidth=1, relheight=0.3, anchor="n")

example_card = tk.Button(bob_frame, image=cards[(0,11)])
example_card.place(relx=0.5, rely=0, relwidth=0.2, relheight=1, anchor="n")

# frame = tk.Frame(root, bg='#00ff00', bd=5)
# frame.place(relx=0.5, rely=0.5 , relwidth=0.5, relheight=0.5)

# button = tk.Button(frame)
# button.place(relx=0.5, relheight=1, relwidth=0.3)

# canvas = tk.Canvas(root, width=40, height=60, bg='#00ff00')
# canvas.place(relx=0, rely=0)
# canvas.create_line(0, 50, 50, 50 )

root.mainloop()