import time
import datetime
import os

import re
from threading import Thread, Lock

import pandas as pd
from openpyxl import load_workbook

def lock_process(func):
    lock = Lock()

    def wrapper(self, *args):
        lock.acquire()
        result = func(self, *args)
        lock.release()
        return result
    return wrapper

def debug(func):
    def wrapper(self, *args):  # 指定一毛一样的参数
        print("[DEBUG]: enter {}()".format(func.__name__))
        return func(self, *args)
    return wrapper  # 返回包装过函数

def get_star_count(morning_star_url):
    import numpy as np
    import requests
    from PIL import Image
    module_path = os.getcwd() + '/src'
    temp_star_url = module_path + '/assets/star/tmp.gif'
    r = requests.get(morning_star_url)
    with open(temp_star_url, "wb") as f:
        f.write(r.content)
    f.close()
    path = module_path + '/assets/star/star'

    # path = './assets/star/star'
    try:
        for i in range(6):
            p1 = np.array(Image.open(path + str(i) + '.gif'))
            p2 = np.array(Image.open(temp_star_url))
            if (p1 == p2).all():
                return i
    except:
        print('morning_star_url', morning_star_url)

def parse_csv(datafile):
    data = []
    with open(datafile, "r") as f:
        header = f.readline().split(",")  # 获取表头
        counter = 0
        for line in f:
            if counter == 10:
                break
            fields = line.split(",")
            entry = {}
            for i, value in enumerate(fields):
                entry[header[i].strip()] = value.strip()  # 用strip方法去除空白
            data.append(entry)
            counter += 1

    return data

def get_quarter_index(input_date):
    year = time.strftime("%Y", time.localtime())
    boundary_date_list = ['03-31', '06-30', '09-30', '12-31']

    input_date_strptime = datetime.datetime.strptime(
        year + '-' + input_date, '%Y-%m-%d')
    index = 1
    for idx in range(len(boundary_date_list)):
        join_date = year + '-' + boundary_date_list[idx]
        season_date_strptime = datetime.datetime.strptime(
            join_date, '%Y-%m-%d')
        if input_date_strptime <= season_date_strptime:
            index = idx + 1
            break
    return index

def get_last_quarter_str(last_index=1):
    last_quarter_time = time.localtime(
        time.time() - last_index * 3 * 30 * 24 * 3600)
    year = time.strftime("%Y", last_quarter_time)
    date = time.strftime("%m-%d", last_quarter_time)
    index = get_quarter_index(date)
    quarter_index_str = year + '-Q' + str(index)
    return quarter_index_str

def get_quarter_date(quarter_index_str):
    year = quarter_index_str.split('-')[0]
    boundary_date_list = ['03-31', '06-30', '09-30', '12-31']
    quarter_index = quarter_index_str.split('-')[1][1:]
    return year + '-' + boundary_date_list[int(quarter_index) - 1]

def fisrt_match_condition_from_list(list, code):
    for item in list:
        stock_code = item.split('-', 1)[0]
        is_exist = code == stock_code
        if is_exist:
            return item

def dict_list_to_list_list(dict_list, key_sort_list):
    tuple_list = []
    for item in dict_list:
        temp_list = []
        for key in key_sort_list:
            temp_list.append(item.get(key))
        tuple_list.append(temp_list)
    return tuple_list

def find_from_list_of_dict(dict_list, match_key, value):
    res = None
    for sub in dict_list:
        if sub[match_key] == value:
            res = sub
            break
    return res

def get_stock_market(stock_code):
    if bool(re.search("^\d{5}$", stock_code)):
        return '港股'
    elif bool(re.search("^\d{6}$", stock_code)) and bool(re.search(
            "^(00(0|1|2|3)\d{3})|(30(0|1)\d{3})|(60(0|1|2|3|5)\d{3})|68(8|9)\d{3}$", stock_code)):
        return 'A股'
    else:
        return '其他'

def update_xlsx_file(path, df_data, sheet_name):
    if os.path.exists(path):
        writer = pd.ExcelWriter(path, engine='openpyxl')
        book = load_workbook(path)
        # 表名重复，删掉，重写
        if sheet_name in book.sheetnames:
            del book[sheet_name]
        if len(book.sheetnames) == 0:
            df_data.to_excel(
                path, sheet_name=sheet_name)
            return
        else:
            writer.book = book
            df_data.to_excel(
                writer, sheet_name=sheet_name)
        writer.save()
        writer.close()
    else:
        df_data.to_excel(
            path, sheet_name=sheet_name)

def bootstrap_thread(target_fn, total, thread_count=2):
    threaders = []
    start_time = time.time()
    # 如果少于10个，只开一个线程
    if total < 10:
        thread_count = 1
    step_num = total / thread_count
    for i in range(thread_count):
        # start = steps[i]['start']
        # end = steps[i]['end']
        start = i * step_num
        end = (i + 1) * step_num
        t = Thread(target=target_fn, args=(int(start), int(end)))
        t.setDaemon(True)
        threaders.append(t)
        t.start()
    for threader in threaders:
        threader.join()
    end_time = time.time()
    print(total, 'run time is %s' % (end_time - start_time))


# -*- coding: utf-8 -*-
import scrapy
from tools.redisTool import RedisTool
from ammmi.items import *
import re

def validateTitle(title):
    rstr = r"[\/\\\:\*\?\"\<\>\|]"  # '/ \ : * ? " < > |'
    new_title = re.sub(rstr, "_", title)  # 替换为下划线
    return new_title

class CosplaySpiderSpider(scrapy.Spider):
    name = 'cosplay_spider'
    base_url = 'https://www.ammmi.com/category/cosplay/page/{0}'
    allowed_domains = ['www.ammmi.com']
    page_index = 1
    page_max = 136
    start_urls = [base_url.format(str(page_index))]
    # redis key and values
    complete_key = 'ammmi:cosplay:complete:urls'
    complete_values = []
    fail_key = 'ammmi:cosplay:fail:urls'
    fail_values = []
    # redis
    client = None
    host = 'localhost'
    port = 6379
    DEBUG = False

    def __init__(self):
        if self.DEBUG:
            self.page_max = 1
        RedisTool.setHost(self.host, self.port)
        self.client = RedisTool()
        self.complete_values = self.client.smembers(self.complete_key)
        self.fail_values = self.client.smembers(self.fail_key)
        self.logger.info('加载{0}:{1} {2}:{3}'.format(self.complete_key,
                                                    self.complete_values[:10:],
                                                    self.fail_key,
                                                    self.fail_values[:10:]))
        super().__init__()

    def close(self, reason):
        self.client.sadd(self.complete_key,
                         self.complete_values)
        self.client.sadd(self.fail_key,
                         self.fail_values)
        self.logger.info('保存{0}\n{1}'.format(self.complete_key, self.fail_key))
        super().close(self, reason)

    def parse(self, response):
        if 'category' in response.url:
            img_urls = []
            img_urls = response.xpath('//div[@class="bt_img mi_ne_kd mrb"]/ul/li/a//@href').extract()
            for url in img_urls:
                yield scrapy.Request(url, callback=self.parse)
            # next page
            if self.page_index <= self.page_max:
                self.page_index += 1
                yield scrapy.Request(self.base_url.format(str(self.page_index)),
                                     callback=self.parse)
        else:
            img_title = 'cosplay'
            title = ''
            img_url = ''
            img_url = response.xpath('//div[@class="yp_context"]//img//@src').extract_first()
            title = response.xpath('//div[@class="yp_context"]//img//@alt').extract_first()
            title = validateTitle(title)
            item = CosplayItem()
            item['img_title'] = img_title
            item['title'] = title
            item['img_url'] = img_url
            yield item


from datetime import datetime

from flask import request
from flask_restful import abort, Resource

class BaseResource(Resource):
    def __init__(self, storage, gossip, myself):
        self.gossip = gossip
        self.storage = storage
        self.myself = myself

    def abort_if_data_not_found(self, name):
        if name not in self.storage:
            abort(404, message=f"No data found for {name} key")

class Data(BaseResource):
    """
    Single data entry resource
    """
    def get(self, name):
        self.abort_if_data_not_found(name)
        return self.storage[name]

    def delete(self, name):
        self.abort_if_data_not_found(name)

        timestamp = datetime.utcnow().timestamp()
        author = self.myself

        self.storage.delete(name, author, timestamp)
        # Send update to other cluster nodes
        self.gossip.propagate_data('delete',
            {'author': author, 'timestamp': timestamp}
        )
        return '', 204

    def post(self, name):
        val = request.json['value']
        timestamp = datetime.utcnow().timestamp()
        author = self.myself

        self.storage.set(name, val, author, timestamp)
        # Send update to other cluster nodes
        self.gossip.propagate_data('set',
            {'name': name, 'value': val, 'author': author, 'timestamp': timestamp}
        )
        return {name: val}, 201

class DataHistory(BaseResource):
    def get(self, name):
        self.abort_if_data_not_found(name)
        return self.storage.get_history(name)

class DataSet(BaseResource):
    def get(self):
        """
        Used for data dump.
        """
        return self.storage.dump()

class DataSetHistory(BaseResource):
    def get(self):
        """
        Used for data dump.
        """
        return self.storage.dump_history()

class DataSync(BaseResource):
    def post(self):
        """
        Used for data sync between nodes.
        """
        name = request.json['name']
        value = request.json['value']
        author = request.json['author']
        timestamp = request.json['timestamp']

        self.storage.set(name, value, author, timestamp)
        return {name: value}, 201

    def delete(self):
        name = request.json['name']
        author = request.json['author']
        timestamp = request.json['timestamp']

        self.storage.delete(name, author, timestamp)
        return 200

class Nodes(BaseResource):
    def get(self):
        return {
            'online': list(self.gossip.online_nodes),
            'failed': self.gossip.fail_nodes,
            'offline': list(self.gossip.offline_nodes),
        }

    def post(self):
        node = request.json['node']
        self.gossip.propagate_data('add node', {'node': node})
        self.gossip.add_node(node, 'add node')
        return 200

    def delete(self):
        node = request.json['node']
        self.gossip.remove_node(node, 'rm node')
        return 200

class NodesSync(BaseResource):
    def get(self):
        return {
            'online': list(self.gossip.online_nodes),
            'failed': self.gossip.fail_nodes,
            'offline': list(self.gossip.offline_nodes),
        }

    def post(self):
        node = request.json['node']
        self.gossip.add_node(node, 'add node')
        return 200

    def delete(self):
        node = request.json['node']
        self.gossip.remove_node(node, 'rm node')
        return 200

class Shutdown(BaseResource):
    def post(self):
        self.gossip.denounce_self(self.myself)
        return 'Now you can shutdown the node.'


import time
import paramiko
import threading
import os
import sys
import dateutil.parser
import unicodedata
import sqlite3
import datetime
from flask import Flask, current_app
from flaskr import db
from flaskr.db import get_db

APP_ROOT = os.path.dirname(os.path.abspath(__file__))
APP_STATIC = os.path.join(APP_ROOT, 'static')

threads = []
def updateLive(app, liveInterval, refreshSpeed):
	with app.app_context():
		db = get_db()
		print("Starting live status update.")
		while True:
			macAddressPool = db.execute(
				'SELECT macAddress, lastDetectTime, live, lastAliveTime, timeSpentLive FROM macAddressPool'
			).fetchall()

			for macAddress in macAddressPool:
				mac = macAddress[0]
				live = macAddress[2]

				if live == True:
					currentTime = macAddress[1]
					currentTime = (int(currentTime[:2]) * 60) + int(currentTime[-2:])

					# Get current system time in minutes starting from 0
					date = dateutil.parser.parse(datetime.datetime.now().isoformat())
					systemTime = str(date.time())[0:5]
					systemTime = (int(systemTime[:2]) * 60) + int(systemTime[-2:])

					if abs((currentTime - systemTime)) > liveInterval:
						db.execute('UPDATE macAddressPool SET live=? WHERE macAddress=?', [False, mac])
				db.commit()
			time.sleep(refreshSpeed)

def main(app, liveInterval, refreshSpeed):
	print("Starting Scheduler.")
	t = threading.Thread(target=updateLive, args=(app, liveInterval, refreshSpeed)) #node_combined[0] is ip, [1] is name
	t.dameon = True
	threads.append(t)
	t.start()

if __name__ == "__main__":
	main()


# Create your views here.
from string import letters
from django.shortcuts import render_to_response, get_object_or_404
from models import Entry

def view_entry_list(request):
    ordered_entries = []
    for letter in letters[26:]:
        entries = Entry.live_entries.filter(lemma__istartswith=letter)
        if entries.count():
            ordered_entries.append({letter: entries})
        else:
            ordered_entries.append({letter: None})
    return render_to_response('lexicon_entry_list.html', {
        'entries_list': ordered_entries,
        'locale': request.locale,
        })

def view_edit_entry(request, lemma):
    entry = get_object_or_404(Entry, lemma=lemma)
    return render_to_response('lexicon_edit_entry.html', {
        'entry': entry
        })


from prometheus_client import start_http_server, Summary, Gauge, Counter
import configparser
import os
import time
import sys
import nest

# Gauges
g = {
  'away': Gauge('nest_thermostat_away', 'Away status for entire structure (1=away 0=home 2=unkown)', ['structure']),
  'is_online': Gauge('nest_thermostat_is_online', 'Device connection status with the Nest service', ['structure', 'device']),
  'has_leaf': Gauge('nest_thermostat_has_leaf', 'Displayed when the thermostat is set to an energy-saving temperature', ['structure', 'device']),
  'target_temp': Gauge('nest_thermostat_target_temp', 'Desired temperature', ['structure', 'device']),
  'current_temp': Gauge('nest_thermostat_current_temp', 'Temperature, measured at the device', ['structure', 'device']),
  'humidity': Gauge('nest_thermostat_humidity', 'Humidity, in percent (%) format, measured at the device, rounded to the nearest 5%', ['structure', 'device']),
  'state': Gauge('nest_thermostat_state', 'Indicates whether HVAC system is actively heating, cooling or is off. Use this value to indicate HVAC activity state', ['structure', 'device']),
  'mode': Gauge('nest_thermostat_mode', 'Indicates HVAC system heating/cooling modes, like Heat•Cool for systems with heating and cooling capacity, or Eco Temperatures for energy savings', ['structure', 'device']),
  'time_to_target': Gauge('nest_thermostat_time_to_target', 'The time, in minutes, that it will take for the structure to reach the target temperature', ['structure', 'device']),

}

# Create a metric to track time spent and requests made and exceptions
REQUEST_TIME = Summary('request_processing_seconds', 'Time spent processing request')
REQUEST_EXCEPTIONS = Counter('nest_api_request_exceptions_total', 'Exceptions thrown while calling Nest API')

# Decorate function with metric.
def polling(napi):
    print("%s - Polling!" % time.time())
    with REQUEST_TIME.time():
      with REQUEST_EXCEPTIONS.count_exceptions():
        for structure in napi.structures:
            g['away'].labels(structure.name).set((1 if structure.away == "away" else 0 if structure.away == "home" else 2))
            for device in structure.thermostats:
                g['is_online'].labels(structure.name, device.name).set(device.online)
                g['has_leaf'].labels(structure.name, device.name).set(device.has_leaf)
                g['target_temp'].labels(structure.name, device.name).set(device.target)
                g['current_temp'].labels(structure.name, device.name).set(device.temperature)
                g['humidity'].labels(structure.name, device.name).set(device.humidity)
                g['state'].labels(structure.name, device.name).set((0 if device.hvac_state == "off" else 1))
                g['mode'].labels(structure.name, device.name).set((0 if device.mode == "off" else 1))
                g['time_to_target'].labels(structure.name, device.name).set(''.join(x for x in device.time_to_target if x.isdigit()))

if __name__ == '__main__':
    c = configparser.ConfigParser()
    c.read(os.path.join(os.path.abspath(os.path.dirname(__file__)),'settings.ini'))

    # Setup Nest account
    start_time = time.time()

    napi = nest.Nest(client_id=c['nest']['client_id'], client_secret=c['nest']['client_secret'], access_token_cache_file=os.path.join(os.path.abspath(os.path.dirname(__file__)),c['nest']['access_token_cache_file']))

    resp_time = time.time() - start_time
    sys.stderr.write("Nest API: %0.3fs\n" % resp_time)

    if napi.authorization_required:
      print("Go to " + napi.authorize_url + " to authorize, then enter PIN below")
      if sys.version_info[0] < 3:
        pin = raw_input("PIN: ")
      else:
        pin = input("PIN: ")
      napi.request_token(pin)

    # Start up the server to expose the metrics.
    listen_port = c['general']['port']
    start_http_server(int(listen_port))
    sys.stdout.write("Listening on port " + listen_port + "...\n")

    while True:
        polling(napi)
        time.sleep(int(c['general']['polling_interval']))


import sqlite3

DATABASE = 'data/data.db'

def setup_db():
  """Creates database if it has not already been set up."""
  db = sqlite3.connect(DATABASE)
  cur = db.cursor()

  # Create the table if it doesn't exist.
  cur.execute("CREATE TABLE IF NOT EXISTS mytable(id INTEGER PRIMARY KEY, name TEXT)")
  db.commit()

  # Insert some dummy data if the table is empty.
  cur.execute("SELECT COUNT(*) FROM mytable")
  if cur.fetchall()[0][0] == 0:
    cur.execute('INSERT INTO mytable(name) VALUES("Ian")')
    cur.execute('INSERT INTO mytable(name) VALUES("Tom")')
    cur.execute('INSERT INTO mytable(name) VALUES("Barry")')
    db.commit()

if __name__ == "__main__":
  setup_db()


from pyzbar.pyzbar import decode
from PIL import Image
import pyqrcode
import colorama
from colorama import Fore, Style
colorama.init()

opts = ["encoder", "decoder"]
ForeColor = ["green", "blue"]
ForeColor.sort()
BackColor = ["green", "blue"]
BackColor.sort()
Danger = "WARNING: If the background is not default the QR-Code will not be able to get decoded afterwards" + """
because of the missing transparency"""
def encode():
    Code = input("Input for Code content:\n>> ")
    File = input("Enter output file name:\n>> ")
    print(Fore.GREEN)
    print("Texture colors:" + Fore.LIGHTMAGENTA_EX)
    for i in ForeColor:
        print(i)
    ModuleColor = input("Enter Texture color:\n>> ")
    if ModuleColor == ForeColor[0]:
        print(Fore.MAGENTA + "color >> " + Fore.LIGHTBLUE_EX + ForeColor[0] + Fore.RESET)
        module_color = (0, 0, 255)
    elif ModuleColor == ForeColor[1]:
        print(Fore.MAGENTA + "color >> " + Fore.LIGHTGREEN_EX + ForeColor[1] + Fore.RESET)
        module_color = (0, 255, 0)
    else:
        print(Fore.RED + Style.BRIGHT + "unknown color" + "\n" + Style.RESET_ALL + Fore.LIGHTGREEN_EX + "selecting Default:'black'" + Fore.RESET)
        module_color = (0, 0, 0, 255)
    print(Fore.GREEN)
    print(Fore.LIGHTMAGENTA_EX + "Background colors:" )
    print(Fore.RED + Danger + Fore.RESET + Fore.LIGHTMAGENTA_EX)
    for i in BackColor:
        print(i)
    print("for transparent default background press ENTER")
    BackgroundColor = input("Enter Background color:\n>> ")
    if BackgroundColor == BackColor[0]:
        print(Fore.MAGENTA + "color >> " + Fore.LIGHTBLUE_EX + BackColor[0] + Fore.RESET)
        background = (0, 0, 255)
    elif BackgroundColor == BackColor[1]:
        print(Fore.MAGENTA + "color >> " + Fore.LIGHTGREEN_EX + BackColor[1] + Fore.RESET)
        background = (0, 255, 0)
    else:
        print(Fore.RED + Style.BRIGHT + "unknown color" + "\n" + Style.RESET_ALL + Fore.LIGHTGREEN_EX + "selecting Default:'white'[transparent]" + Fore.RESET)
        background = (255, 255, 255, 255)

    fileformat = str(File) + ".png"
    QR = pyqrcode.create(str(Code))
    QR.png(fileformat, scale=8, module_color=module_color, background=background)
    print(Fore.LIGHTGREEN_EX + "Process finfished" + "\n" + Fore.BLUE +"output file: " + Fore.RED + fileformat + Fore.RESET)

def pic():
    print(Fore.CYAN)
    print("""

     QQQQQQQQQ     RRRRRRRRRRRRRRRRR
   QQ:::::::::QQ   R::::::::::::::::R
 QQ:::::::::::::QQ R::::::RRRRRR:::::R
Q:::::::QQQ:::::::QRR:::::R     R:::::R
Q::::::O   Q::::::Q  R::::R     R:::::R
Q:::::O     Q:::::Q  R::::R     R:::::R
Q:::::O     Q:::::Q  R::::RRRRRR:::::R
Q:::::O     Q:::::Q  R:::::::::::::RR
Q:::::O     Q:::::Q  R::::RRRRRR:::::R
Q:::::O     Q:::::Q  R::::R     R:::::R
Q:::::O  QQQQ:::::Q  R::::R     R:::::R
Q::::::O Q::::::::Q  R::::R     R:::::R
Q:::::::QQ::::::::QRR:::::R     R:::::R
 QQ::::::::::::::Q R::::::R     R:::::R
   QQ:::::::::::Q  R::::::R     R:::::R
     QQQQQQQQ::::QQRRRRRRRR     RRRRRRR
             Q:::::Q
              QQQQQQ

    """)
    print(Fore.MAGENTA)
    print(Style.BRIGHT)
    print("QR operating Options:")
    for option in opts:
        print("'" + option + "'")
    print(Style.NORMAL)
    print(Fore.RESET)

pic()
X = input(">>")
if X == 'encoder':
    encode()
elif X == 'decoder':
    File = input("Enter File Name:\n>> ")
    try:

        content = decode(Image.open(str(File)))

        if content == []:
            print(Fore.RED)
            print("Es wurde keine QR - Information gefunden")
            print(Fore.RESET)
        else:
            print(Fore.GREEN)
            print("Content found:")
            print("QR content:")
            print(content)
            print(Fore.RESET)

    except:
        print(Fore.YELLOW)
        print("File does not exist")
        print(Fore.RESET)

else:
    print(Fore.RED)
    print("unknown command")
    print(Fore.RESET)


from django.contrib import admin, messages
from django.utils.translation import gettext_lazy as _
from django.utils.translation import ngettext

from core.admin import TracingMixinAdmin, make_private, make_public

from . import models

@admin.register(models.Track)
class TrackAdmin(TracingMixinAdmin):
    actions = [make_public, make_private]
    fields = ('name', 'description', 'owner', 'public', 'file')
    list_display = ('id', 'name', 'file', 'owner', 'public', 'entry_created_at', 'entry_updated_at')
    list_display_links = ('id', 'name')
    list_filter = ('public', 'entry_created_at', 'entry_updated_at')
    search_fields = ['id', 'name', 'owner__username']

@admin.register(models.Vote)
class VoteAdmin(TracingMixinAdmin):
    actions = ['make_positive', 'make_negative']
    autocomplete_fields = [
        'user',
    ]
    fields = (
        'user',
        'content_type',
        'object_id',
        'is_positive',
    )
    list_display = (
        '__str__',
        'id',
        'is_positive',
        'user',
        'content_object',
        'entry_created_at',
        'entry_updated_at',
    )
    list_display_links = (
        '__str__',
        'id',
    )
    search_fields = [
        'id__icontains',
        'user__username__icontains',
    ]

    @admin.action(description=_('Mark selected votes as positive'))
    def make_positive(self, request, queryset):
        updated = queryset.update(is_positive=True)
        self.message_user(request, ngettext(
            '%d vote was successfully marked as positive.',
            '%d votes were successfully marked as positive.',
            updated,
        ) % updated, messages.SUCCESS)

    @admin.action(description=_('Mark selected votes as negative'))
    def make_negative(self, request, queryset):
        updated = queryset.update(is_positive=False)
        self.message_user(request, ngettext(
            '%d vote was successfully marked as negative.',
            '%d votes were successfully marked as negative.',
            updated,
        ) % updated, messages.SUCCESS)


import cv2

cap = cv2.VideoCapture(0)

while True:
    _, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (5, 5), 0)
    edge = cv2.Canny(blur, 10, 70)
    _, mask = cv2.threshold(edge, 70, 255, cv2.THRESH_BINARY)
    # cv2.imshow("original", frame)
    # cv2.imshow("gray", gray)
    # cv2.imshow("blur", blur)
    # cv2.imshow("edge", edge)
    cv2.imshow("mask", mask)
    if cv2.waitKey(1) == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()


"""
Author: Xiaoran Xu
BU: xiaorxu
CS506 - Extra Credit
"""

from collections import defaultdict
from math import inf
import random
import csv
import math

def point_avg(points):
    """
    Accepts a list of points, each with the same number of dimensions.
    (points can have more dimensions than 2)

    Returns a new point which is the center of all the points.
    """

    #https://stackoverflow.com/questions/3223043/how-do-i-sum-the-columns-in-2d-list
    sum_pts = [sum(x) for x in zip(*points)]
    return [col_sum /len(points) for col_sum in sum_pts]

def update_centers(data_set, assignments):
    """
    Accepts a dataset and a list of assignments; the indexes
    of both lists correspond to each other.
    Compute the center for each of the assigned groups.
    Return `k` centers in a list
    """

    cluster_points = {}
    for point, assignment in zip(data_set, assignments):
        if not assignment in cluster_points.keys():
            cluster_points[assignment] = []
        cluster_points[assignment].append(point)

    centers = []
    for k in cluster_points.keys():
        centers.append(point_avg(cluster_points[k]))

    return centers

def assign_points(data_points, centers):
    """
    """
    assignments = []
    for point in data_points:
        shortest = inf  # positive infinity
        shortest_index = 0
        for i in range(len(centers)):
            val = distance(point, centers[i])
            if val < shortest:
                shortest = val
                shortest_index = i
        assignments.append(shortest_index)
    return assignments

def distance(a, b):
    """
    Returns the Euclidean distance between a and b
    """
    temp = 0
    for i,j in zip(a,b):
        temp += (i-j)**2
    return math.sqrt(temp)

def generate_k(data_set, k):
    """
    Given `data_set`, which is an array of arrays,
    return a random set of k points from the data_set
    """
    return random.sample(data_set, k)

def get_list_from_dataset_file(dataset_file):
    data = []
    with open(dataset_file, newline = '') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            data.append([int(r) for r in row])
    return data

def cost_function(clustering):
    cost = 0
    for k,points in clustering.items():
        center = point_avg(points)
        for point in points:
            cost += distance(center, point)
    return cost

def k_means(dataset_file, k):
    dataset = get_list_from_dataset_file(dataset_file)
    k_points = generate_k(dataset, k)
    assignments = assign_points(dataset, k_points)
    old_assignments = None
    while assignments != old_assignments:
        new_centers = update_centers(dataset, assignments)
        old_assignments = assignments
        assignments = assign_points(dataset, new_centers)
    clustering = defaultdict(list)
    for assignment, point in zip(assignments, dataset):
        clustering[assignment].append(point)
    return clustering


import numpy as np
from collections import deque
import cv2 as cv

def main():
    fourcc = cv.VideoWriter_fourcc(*'MJPG')
    out = cv.VideoWriter('data/output.avi',fourcc, 20.0, (1280, 720))

    cap = cv.VideoCapture(0)
     # wait for static background
    fback = wait_for_static_background(cap)
    while(1):

        _, frame = cap.read()
        frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
        if frame is None:
            break
        newframe = cv.absdiff(frame, fback)
        _, newframe = cv.threshold(newframe, 5, 255, cv.THRESH_TOZERO)

        circles = cv.HoughCircles(newframe, cv.HOUGH_GRADIENT, 1, 1000,
                               param1=100, param2=30,
                               minRadius=1, maxRadius=250)

        _, contours, _ = cv.findContours(np.copy(newframe), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)

        newframe = resize_frame_to_out(newframe)
        newframe = cv.cvtColor(newframe, cv.COLOR_GRAY2BGR)
        if circles is not None:
            circles = np.uint16(np.around(circles))
            for i in circles[0,:]:
                # draw the outer circle
                cv.circle(newframe,(i[0],i[1]),i[2],(0,255,0),2)
                # draw the center of the circle
                cv.circle(newframe,(i[0],i[1]),2,(0,0,255),3)

            # find largest contour
            main_contour_i = 0
            for i in range(len(contours)):
                if len(contours[main_contour_i]) < len(contours[i]):
                    main_contour_i = i

            # find backbone subset
            backbone = []
            main_contour = contours[main_contour_i]
            top_pixel_i = 0
            for i in range(len(main_contour)):
                if main_contour[i][0][1] < main_contour[top_pixel_i][0][1]: # y coord
                    top_pixel_i = i

            backbone = main_contour[top_pixel_i:500]
            cv.polylines(newframe, backbone, True, (0, 0, 255), thickness=5)
            # out.write(newframe)
        else:
            cv.putText(newframe, "READY", (400, 400), cv.FONT_HERSHEY_SIMPLEX, 3, (0, 0, 200))
        cv.imshow("frame", newframe)
        k = cv.waitKey(30) & 0xff
        if k == 27:
            break

    cap.release()
    cv.destroyAllWindows()

def wait_for_static_background(cap):
    frames_count = 10
    frames_accamulator = deque(maxlen=frames_count)
    while (1):
        _, frame = cap.read()
        frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
        if len(frames_accamulator) == frames_count:
            diff_s = 0
            for prev_frame in frames_accamulator:
                diff = cv.absdiff(frame, prev_frame)
                _, diff = cv.threshold(diff, 35, 255, cv.THRESH_TOZERO)
                diff_s += cv.sumElems(diff)[0]
            print(diff_s)
            if diff_s < 3000:
                print("Static captured")
                return frame
        cv.imshow("frame", frame)
        k = cv.waitKey(30) & 0xff
        if k == 27:
            break
        frames_accamulator.append(frame)

def resize_frame_to_work(frame):
    W_HEIGHT = 720
    W_WIDTH = W_HEIGHT * 16 // 9
    return cv.resize(frame, (W_WIDTH, W_HEIGHT), cv.INTER_AREA)

def resize_frame_to_out(frame):
    O_HEIGHT = 720
    O_WIDTH = 1280
    return cv.resize(frame, (O_WIDTH, O_HEIGHT), cv.INTER_AREA)

def prepare_frame(frame):
    frame = resize_frame_to_work(frame)

    return frame

def draw_pixel(x, y):
    cv.circle(newframe,(x, y),2,(0,0,255),3)

if __name__ == '__main__':
    main()


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

"""
Name: web_server.py
Author: fengdi
Datetime: 19:10 2019-07-15
Description:

"""

import socket
import re
import time
import mini_frame
import multiprocessing

# 定义TCP服务器地址
HOST = ""
PORT = 7890
server_addr = (HOST, PORT)

# TCP服务器类
class Wsgiserver(object):

    def __init__(self, addr):
        """
        创建tcp服务器对象，绑定地址，开启监听
        :param addr: TCP服务器地址
        """
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server_socket.bind(addr)
        self.server_socket.listen(128)

    def server_forever(self):
        """
        循环处理客户端连接
        :return:
        """
        while True:
            tmp_socket, addr = self.server_socket.accept()
            t1 = multiprocessing.Process(target=self.handler_req, args=(tmp_socket, ))
            t1.start()
            tmp_socket.close()
        self.server_socket.close()

    # 定义请求处理函数
    def handler_req(self, client_socket):
        """
        对客户端请求进行处理，返回需求数据
        :param client_socket: 临时套接字，与一个客户端通信
        :return: 返回请求资源，未找到返回404
        """

        # 长连接方式：接收请求数据
        while True:
            try:
                recv_data = client_socket.recv(1024).decode("utf-8")
                print(recv_data)
            except Exception as ret:
                print(">" * 50, ret)
                client_socket.close()
                return

            # 判断浏览器是否关闭
            if not recv_data:
                client_socket.close()
                return

            # 从请求数据内提取请求文件名
            request_lines = recv_data.splitlines()
            ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0])

            file_name = ""
            if ret:
                file_name = ret.group(1)
                if file_name == "/":
                    file_name = "/index.html"

            if not file_name.endswith('.py'):
                # 根据请求文件名打开文件读取,返回文件内容给客户端
                try:
                    f = open("./html" + file_name, "rb")
                except FileNotFoundError:
                    response_body = "------file not found------"

                    response_header = "HTTP/1.1 404 not found\r\n"
                    response_header += "Content-Length: %d\r\n" % (len(response_body))
                    response_header += "\r\n"

                    response = response_header + response_body
                    client_socket.send(response.encode("utf-8"))
                else:
                    html_content = f.read()
                    f.close()
                    response_body = html_content

                    response_header = "HTTP/1.1 200 OK\r\n"
                    response_header += "Content-Length: %d\r\n" % (len(response_body))
                    response_header += "\r\n"

                    response = response_header.encode("utf-8") + response_body
                    client_socket.send(response)
            else:
                env = dict()
                response_body = mini_frame.application(env, self.set_response_header)

                response_header = "HTTP/1.1 %s\r\n" % self.status
                response_header += "Content-Length: %d\r\n" % (len(response_body.encode("utf-8")))

                for temp in self.headers:
                    response_header += "%s:%s\r\n" % (temp[0], temp[1])

                response_header += "\r\n"

                response = response_header + response_body
                client_socket.send(response.encode("utf-8"))

        client_socket.close()

    def set_response_header(self, status, headers):
        self.status = status
        self.headers = headers

def main():
    """
    主函数，控制整体
    :return:
    """
    myserver = Wsgiserver(server_addr)
    print("server running on port %s" % PORT)
    myserver.server_forever()

if __name__ == '__main__':
    main()


from django import forms

class IFriendlyForm(forms.Form):
	CHOICES = (
		('U6', 'U6'),
		('U7', 'U7'),
    	('U8', 'U8'),
    	('U9', 'U9'),
    	('U10', 'U10'),
    	('U11', 'U11'),
    	('U12', 'U12'),
    	('U13', 'U13'),
        ('U14', 'U14(IP)'),
    	('U15', 'U15'),
    	('U17', 'U17'),
    )
	leeftijd = forms.ChoiceField(choices=CHOICES, required=True, label='Leeftijd')
	datum = forms.CharField(label='datum', widget=forms.TextInput())


import os
import re
from bs4 import BeautifulSoup
import requests
from pathos.multiprocessing import ProcessPool as Pool

def get_index(id):
    i = 0
    url = 'http://www.513mj.com/index.php/video/play/id/{id}'.format(id=id)
    url_origin = 'http://v.51feetv.com'
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'lxml')
    path = soup.select('.F img')[0]['data-original']
    path = re.match('(.*/)',path).group(1)
    title = soup.select('.F .mt6')[0].get_text().strip().replace(' ','')
    local_path = '/Users/wang/movie/' + title
    mkdir(local_path)
    path = path + 'index.m3u8'
    index = requests.get(path)
    m3_path = parseM3u8(index.text)
    for line in m3_path:
        m3u8_name = re.search('/ppvod(.*?.m3u8)',line).group(1)
        ts_m3u8 = requests.get(url_origin+line)
        m3u8_path = local_path + m3u8_name
        with open(m3u8_path,'wb') as f:
            f.write(ts_m3u8.content)
        modify_m3u8(m3u8_path,local_path,url_origin)
        ts_path = parseM3u8(ts_m3u8.text)
        groups = [url_origin+ts for ts in ts_path]
        paths = [local_path] * len(groups)
        i = [i for i in range(0,len(groups)+1)]
        lens = [len(groups)] * len(groups)
        pool = Pool(4)
        pool.map(get_ts, groups,paths, i, lens)
    # combine(local_path, title)
        combine2(local_path,title,m3u8_path)

def parseM3u8(content):
    if "#EXTM3U" not in content:
        raise BaseException("非M3U8的链接")

    if "EXT-X-STREAM-INF" in content:  # 第一层
        file_line = content.split("\n")
        for line in file_line:
            if '.m3u8' in line:
                yield line

    if '#EXT-X-DISCONTINUITY' in content:
        file_line = content.split("\n")
        for line in file_line:
            if '.js' in line:
                yield line

def mkdir(path):
    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")

    isExists = os.path.exists(path)

    if not isExists:
        os.makedirs(path)
        print('创建成功')
    else:
        print('目录已存在')

def modify_m3u8(m3u8_path, path, url):
    i = 0
    with open(m3u8_path,'r') as f:
        lines =f.readlines()
    with open(m3u8_path,'w') as f_w:
        for line in lines:
            if '#EXT-X-KEY:METHOD=AES-128,' in line:
                old = re.search('URI="(.*)"',line).group(1)
                url = url + old
                response = requests.get(url)
                key_path = path+'/key.key'
                with open(key_path,'wb') as f:
                    f.write(response.content)
                new = '"{path}"'.format(path=key_path)
                line = '#EXT-X-KEY:METHOD=AES-128,URI=' + new + '\n'
                # re.sub('URI="(.*)"','{path}'.format(path=path+'/key.key'),line)
            if '#EXTINF:15,' in line:
                continue
            if 'http://v.51feetv.com/b.ts' in line:
                continue
            if '.js' in line:
                line = path + '/sp{i}.ts'.format(i=i) + '\n'
                i += 1
            f_w.write(line)

def get_ts(url, path, i, total):
    response = requests.get(url)
    path = path + '/sp{i}.ts'.format(i=i)
    with open(path,'wb') as f:
        f.write(response.content)
    print('下载完成 %s/%s' %(i,total))
# print(response.content)

def combine(path, title):
    exec_str = r'find ' + path + ' -name' + r' *.mp4 ' + '-exec rm -rf {} \\;'
    os.system(exec_str)
    ts = []
    lists = os.listdir(path)
    for file in lists:
        if file.endswith('.ts'):
            ts.append(file)
    ts.sort(key=lambda x:int(x[2:-3]))
    try:
        print("开始组合资源...")
        exec_str = 'cd {path} && ffmpeg -i'.format(path=path) + ' ' + '"concat:'
        for i in ts:
            exec_str = exec_str + i +'|'
        exec_str = exec_str[:-1] + '" -c copy ' + title +'.mp4'
        os.system(exec_str)  # 使用cmd命令将资源整合
        exec_str = r'find ' + path + ' -name' + r' *.ts ' + '-exec rm -rf {} \\;'
        os.system(exec_str)  # 删除原来的文件
    except:
        print("资源组合失败")
    else:
        print("资源组合成功!")

def combine2(path, title, m3u8_path):
    exec_str = r'find ' + path + ' -name' + r' *.mp4 ' + '-exec rm -rf {} \\;'
    os.system(exec_str)
    try:
        print("开始组合资源...")
        exec_str = 'ffmpeg -allowed_extensions ALL -i {m3u8} -c copy '.format(m3u8=m3u8_path) + path + '/{name}.mp4'.format(name=title)
        print(exec_str)
        os.system(exec_str)  # 使用cmd命令将资源整合
        exec_str = r'find ' + path + ' -name' + r' *.ts ' + '-exec rm -rf {} \\;'
        os.system(exec_str)  # 删除原来的文件
        os.remove(m3u8_path)

    except:
        print("资源组合失败")
    else:
        print("资源组合成功!")

if __name__ == '__main__':
    ids = input('输入ID: ')
    ids = ids.split(",")
    for id in ids:
        get_index(id)


import requests
import datetime as dt

from requests.models import Response

USERNAME = "whzd"
TOKEN = "verysecretcodeomg"
PIXELA_URL = "https://pixe.la/v1/users/"
GRAPH_ID = "graph1"

# Create a user
user_parameters = {
    "token": "verysecretcodeomg",
    "username": "whzd",
    "agreeTermsOfService": "yes",
    "notMinor": "yes"
}

# response = requests.post(url=PIXELA_URL, json=user_parameters)
# print(response.text)

# Create a graph
graph_parameters = {
    "id": "graph1",
    "name": "Meditation Graph",
    "unit": "minutes",
    "type": "int",
    "color": "sora"
}

headers = {
    "X-USER-TOKEN": TOKEN
}

# response = requests.post(url=f"{PIXELA_URL}whzd/graphs", json=graph_parameters, headers=headers)
# print(response.text)

# Create a pixel
pixel_parameters = {
    # "date": str(dt.date.today()).replace("-", ""),
    "date": dt.datetime.now().strftime("%Y%m%d"),
    "quantity": "5"
}

# response = requests.post(url=f"{PIXELA_URL}{USERNAME}/graphs/{GRAPH_ID}", json=pixel_parameters, headers=headers)
# response.raise_for_status()
# print(response.json())

date = dt.datetime.now().strftime("%Y%m%d")

# Update a pixel
# response = requests.put(url=f"{PIXELA_URL}{USERNAME}/graphs/{GRAPH_ID}/{date}", json={"quantity": "10"}, headers=headers)
# print(response.json())

# Delete a pixel
response = requests.delete(url=f"{PIXELA_URL}{USERNAME}/graphs/{GRAPH_ID}/{date}", headers=headers)
print(response.json())


import MAUS
import sys
import os
import numpy
import scipy.stats
import argparse

PARTICLE_ID_MAP = { -13 : 2, 13 : -2 }

if __name__ == "__main__" :
  parser = argparse.ArgumentParser("KDE Sampler")

  parser.add_argument( "data_file", help="An icool03 type beam file of particles to perform the resampling")

  parser.add_argument( "-N", "--number_particles", default=100, help="Number of particles to generate" )

  parser.add_argument( "-O", "--output_filename", default="resampled_beam", help="Output File Name" )

  parser.add_argument( "-D", "--output_directory", default="./", help="Output Directory" )

  parser.add_argument( "-P", "--particle_id", default=-13, type=int, help="Specify the PID of the beam to produce (Geant4 notation)" )

  namespace = parser.parse_args()

  vectors = None
  weights = None

  vectors = numpy.loadtxt(namespace.data_file, delimiter=' ', usecols=(6, 7, 8, 9, 10, 11), skiprows=2)
  weights = numpy.loadtxt(namespace.data_file, delimiter=' ', usecols=(5), skiprows=2)

#  kernel = scipy.stats.gaussian_kde(numpy.transpose(vectors), weights=weights)
  kernel = scipy.stats.gaussian_kde(numpy.transpose(vectors))

  outfilename = os.path.join(namespace.output_directory, namespace.output_filename)+".txt"
  with open( outfilename, "w" ) as outfile :

    outfile.write( "Custom Input file\n" )
    outfile.write( "0. 0. 0. 0. 0. 0. 0. 0.\n" )

    for count in range( namespace.number_particles ) :
      particle = kernel.resample(1)
#      print particle

      # 0  : Event Number
      value_1 = 1 # Particle Number
      value_2 = PARTICLE_ID_MAP[namespace.particle_id] # Particle ID
      value_3 = 0 # Status
      value_4 = 0.0 # Time
      value_5 = 0.0 # Local Weight
      value_6 = float(particle[0]) # x [m]
      value_7 = float(particle[1]) # y [m]
      value_8 = float(particle[2]) # z [m]
      value_9 = float(particle[3]) # px [GeV/c]
      value_10 = float(particle[4]) # py [GeV/c]
      value_11 = float(particle[5]) # pz [GeV/c]
      value_12 = 0 # sx
      value_13 = 0 # sy
      value_14 = 0 # sz

      outfile.write( str( count ) + ' ' +\
                     str( value_1 ) + ' ' + \
                     str( value_2 ) + ' ' + \
                     str( value_3 ) + ' ' + \
                     str( value_4 ) + ' ' +\
                     str( value_5 ) + ' ' +\
                     str( value_6 ) + ' ' +\
                     str( value_7 ) + ' ' +\
                     str( value_8 ) + ' ' +\
                     str( value_9 ) + ' ' +\
                     str( value_10 ) + ' ' +\
                     str( value_11 ) + ' ' +\
                     str( value_12 ) + ' ' +\
                     str( value_13 ) + ' ' +\
                     str( value_14 ) + '\n' )


"""Tests for letsencrypt_apache.parser."""
import os
import shutil
import sys
import unittest

import augeas
import mock
import zope.component

from letsencrypt import errors
from letsencrypt.display import util as display_util

from letsencrypt_apache.tests import util

class ApacheParserTest(util.ApacheTest):
    """Apache Parser Test."""

    def setUp(self):
        super(ApacheParserTest, self).setUp()

        zope.component.provideUtility(display_util.FileDisplay(sys.stdout))

        from letsencrypt_apache.parser import ApacheParser
        self.aug = augeas.Augeas(flags=augeas.Augeas.NONE)
        self.parser = ApacheParser(self.aug, self.config_path, self.ssl_options)

    def tearDown(self):
        shutil.rmtree(self.temp_dir)
        shutil.rmtree(self.config_dir)
        shutil.rmtree(self.work_dir)

    def test_root_normalized(self):
        from letsencrypt_apache.parser import ApacheParser
        path = os.path.join(self.temp_dir, "debian_apache_2_4/////"
                            "two_vhost_80/../two_vhost_80/apache2")
        parser = ApacheParser(self.aug, path, None)
        self.assertEqual(parser.root, self.config_path)

    def test_root_absolute(self):
        from letsencrypt_apache.parser import ApacheParser
        parser = ApacheParser(self.aug, os.path.relpath(self.config_path), None)
        self.assertEqual(parser.root, self.config_path)

    def test_root_no_trailing_slash(self):
        from letsencrypt_apache.parser import ApacheParser
        parser = ApacheParser(self.aug, self.config_path + os.path.sep, None)
        self.assertEqual(parser.root, self.config_path)

    def test_parse_file(self):
        """Test parse_file.

        letsencrypt.conf is chosen as the test file as it will not be
        included during the normal course of execution.

        """
        file_path = os.path.join(
            self.config_path, "sites-available", "letsencrypt.conf")

        self.parser._parse_file(file_path)  # pylint: disable=protected-access

        # search for the httpd incl
        matches = self.parser.aug.match(
            "/augeas/load/Httpd/incl [. ='%s']" % file_path)

        self.assertTrue(matches)

    def test_find_dir(self):
        from letsencrypt_apache.parser import case_i
        test = self.parser.find_dir(case_i("Listen"), "443")
        # This will only look in enabled hosts
        test2 = self.parser.find_dir(case_i("documentroot"))
        self.assertEqual(len(test), 2)
        self.assertEqual(len(test2), 3)

    def test_add_dir(self):
        aug_default = "/files" + self.parser.loc["default"]
        self.parser.add_dir(aug_default, "AddDirective", "test")

        self.assertTrue(
            self.parser.find_dir("AddDirective", "test", aug_default))

        self.parser.add_dir(aug_default, "AddList", ["1", "2", "3", "4"])
        matches = self.parser.find_dir("AddList", None, aug_default)
        for i, match in enumerate(matches):
            self.assertEqual(self.parser.aug.get(match), str(i + 1))

    def test_add_dir_to_ifmodssl(self):
        """test add_dir_to_ifmodssl.

        Path must be valid before attempting to add to augeas

        """
        from letsencrypt_apache.parser import get_aug_path
        self.parser.add_dir_to_ifmodssl(
            get_aug_path(self.parser.loc["default"]),
            "FakeDirective", "123")

        matches = self.parser.find_dir("FakeDirective", "123")

        self.assertEqual(len(matches), 1)
        self.assertTrue("IfModule" in matches[0])

    def test_get_aug_path(self):
        from letsencrypt_apache.parser import get_aug_path
        self.assertEqual("/files/etc/apache", get_aug_path("/etc/apache"))

    def test_set_locations(self):
        with mock.patch("letsencrypt_apache.parser.os.path") as mock_path:

            mock_path.isfile.return_value = False

            # pylint: disable=protected-access
            self.assertRaises(errors.PluginError,
                              self.parser._set_locations, self.ssl_options)

            mock_path.isfile.side_effect = [True, False, False]

            # pylint: disable=protected-access
            results = self.parser._set_locations(self.ssl_options)

            self.assertEqual(results["default"], results["listen"])
            self.assertEqual(results["default"], results["name"])

if __name__ == "__main__":
    unittest.main()  # pragma: no cover


#-*- coding: UTF-8 -*-
#!/usr/bin/env python
#
import os
import sys
import optparse
from replay_kinect_bone_data import draw
from matlab_cp2tform import get_similarity_transform_for_cv2
import cv2
import numpy as np
#from builtins import input
try:
   input = raw_input
except NameError:
   pass

JointType_SpineBase = 0
JointType_SpineMid = 1
JointType_Neck = 2
JointType_Head = 3
JointType_ShoulderLeft = 4
JointType_ElbowLeft = 5
JointType_WristLeft = 6
JointType_HandLeft = 7
JointType_ShoulderRight = 8
JointType_ElbowRight = 9
JointType_WristRight = 10
JointType_HandRight = 11
JointType_HipLeft = 12
JointType_KneeLeft = 13
JointType_AnkleLeft=14
JointType_FootLeft = 15
JointType_HipRight = 16
JointType_KneeRight = 17
JointType_AnkleRight=18
JointType_FootRight = 19
JointType_SpineShoulder = 20
JointType_HandTipLeft = 21
JointType_ThumbLeft = 22
JointType_HandTipRight = 23
JointType_ThumbRight = 24
Frame_Num=25

skeletons = []
skeletons_lines = []
value_threshold = 0.09
line_threshold = 6
skeleton_threshold = 6
candidates=[]
op_flag = False
def alignment(src_img, src_pts):
    # ref_pts = [[30.2946, 51.6963], [65.5318, 51.5014],
    #            [48.0252, 71.7366], [33.5493, 92.3655], [62.7299, 92.2041]]
    ref_pts = [[48.0252, 20.6963],[38,30],[48.0252, 60.7366]]

    crop_size = (96, 112)
    src_pts = np.array(src_pts).reshape(3, 2)

    s = np.array(src_pts).astype(np.float32)
    r = np.array(ref_pts).astype(np.float32)

    tfm = get_similarity_transform_for_cv2(s, r)
    bone_img = cv2.warpAffine(src_img, tfm, crop_size)
    return bone_img
def save_skeleton_video(video_path, start=0, end=10**10, subject_lines=[],num=0):
    write=True
    avi = os.path.join(video_path, "bgr.avi")
    txt = os.path.join(video_path, "kinect color.txt")
    f = open(txt, encoding='utf-8')  # ,encoding='utf-8'
    lines = f.readlines()
    dict = {}
    line_num = 0
    for i in range(len(lines)):
        line_num = line_num + 1
        line = lines[i].split(' ')[0:-1]
        # use color frame as the key in the dict
        if (int(line[1]) not in dict):
            dict[int(line[1])] = []
        values = []
        pre_i = 0
        # there are two frame numbers in a line
        for i in line[2:]:
            try:
                i = float(i)
                values.append(i)
                pre_i = i
            except:
                values.append(pre_i)
        values.append(int(line[0]))
        values.append(line_num)
        dict[int(line[1])].append(values)

    cap = cv2.VideoCapture(avi)
    fg=0#fg是当前帧数
    while 1:
        fg+=1
        ret, copy = cap.read()

        if(fg<start):
            continue
        if(fg>end):
            break
        if (not copy is None):
            if (fg in dict):
                tmp = len(dict[fg])
                skeletons = []
                for j in range(tmp):
                    if (dict[fg][j][Frame_Num * 2] == dict[fg][0][Frame_Num * 2]):
                        jointArr = [[0, 0] for _ in range(26)]
                        for k in range(26):
                            for l in range(2):
                                if l == 0:
                                    jointArr[k][0] = dict[fg][j][k * 2 + l]
                                else:
                                    jointArr[k][1] = dict[fg][j][k * 2 + l]
                        skeletons.append(jointArr)

                if len(skeletons) > 0:
                    bones=[]
                    for jointArr in skeletons:
                        x = []
                        y = []
                        for point in jointArr:
                            x.append(int(point[0]))
                            y.append(int(point[1]))
                        x = sorted(x)
                        y = sorted(y)

                        if jointArr[25][1] in subject_lines:
                            if(x[1]-20<0):
                                x[1]=5
                            if(x[-2]+20>960):
                                x[-2]=954
                            if(y[1]-50<0):
                                y[1]=30
                            if(y[-2]+50>540):
                                y[-2]=509
                            bones.append(jointArr[JointType_Head])
                            bones.append(jointArr[JointType_ShoulderLeft])
                            bones.append(jointArr[JointType_SpineBase])
                            try:
                                copy[:, 0:x[1] - 20] = 0
                                copy[:, x[-2] + 20:960] = 0
                                copy[0:y[1] - 50, :] = 0
                                copy[y[-2] + 50:540, :] = 0
                                res=alignment(copy,bones)
                                res=cv2.flip(res,1)
                                cv2.imshow("replay", res)
                                if write:
                                    dir_name=dest_dir+'/ali_img/'
                                    if not os.path.exists(dir_name):
                                        os.mkdir(dir_name)
                                    dir_name=dir_name+'/'+str(num)
                                    if not os.path.exists(dir_name):
                                        os.mkdir(dir_name)
                                    cv2.imwrite(dir_name+"/"+str(fg)+".jpg",res)
                                    print(dir_name+"/"+str(fg)+".jpg",res)
                            except:
                                continue
            if cv2.waitKey(50) & 0xFF == ord('e'):
                break
    cap.release()
    cv2.destroyAllWindows()

def generate_dest_file_name(src_file):
    path_list = src_file.split(os.sep)
    return "%s_%s" % (path_list[-2], "bone")

def create_destination_dir(dir):
    if not dir:
        print(("The output directory doesn't exist: %s" % dir))
        dir = os.path.join(os.path.dirname(src_file),"cleaned")
        print(("Use the source directory as destination directory: %s" % dir))
    if not os.path.isdir(dir):
        os.makedirs(dir)
    return dir

def get_patient_dir(filepath):
    path_list = filepath.split(os.sep)
    patient_dir = ""
    try:
        patient_dir = path_list[-4]
    except IndexError:
        pass
    return patient_dir

def load_and_clean_kinect_bone_data(src_file):
    if not os.path.exists(src_file):
        raise SystemExit("The source file doesn't exist : %s" % src_file)
    # read data from file line by line
    line_num = 1
    with open(src_file, "r") as sf:
        for line in sf:
            append_line_to_skeletons(line.strip(), line_num)
            line_num = line_num + 1
    print(("total lines: %d" % line_num))

def append_line_to_skeletons(line, line_num):
    print(("processing the line %d" % line_num))
    values = line.split(' ')
    try:
        v1 = int(values[0])
    except ValueError:
        v1 = float(values[0])
    try:
        v2 = int(values[1])
    except ValueError:
        v2 = float(values[1])

    if not skeletons:
        # the raw data doesn't have frame number
        if not isinstance(v1, int) or v1 == 0:
            values.insert(0, line_num)
        if not isinstance(v2, int) or v2 == 0:
            values.insert(1, line_num)
        print(("insert the line %d to the empty skeletons" % line_num))
        skeletons.append([values])
        skeletons_lines.append([line_num])
    else:
        # the raw data has frame number (After P29)
        if isinstance(v1, int) and v1 != 0:
            # the raw data has 2 frame number (After P40)
            if isinstance(v2, int) and v2 != 0:
                pass
            # the raw data has 1 frame number (P30 to P40)
            else:
                values.insert(1, v1)
        # the raw data doesn't have frame number (P1 to P29)
        else:
            values.insert(0, line_num)
            values.insert(1, line_num)

        processed = False
        for i in range (1, skeleton_threshold + 1):
            try:
                diff_frames = abs(int(skeletons[-i][-1][0]) - int(values[0]))
                if ( diff_frames >=1 and diff_frames <=6 ) and ( abs(float(skeletons[-i][-1][2]) - float(values[2])) <= value_threshold ) :
                    print(("insert the line %d to the skeleton[%d]" % (line_num, len(skeletons)-i+1)))
                    skeletons[-i].append(values)
                    skeletons_lines[-i].append(line_num)
                    processed = True
                    break
            except IndexError as ie:
                print(("the line %d does not match to the last 6 skeletons" % line_num))

        if not processed:
            print(("insert the line %d as a new skeleton" % line_num))
            skeletons.append([values])
            skeletons_lines.append([line_num])
            processed = True

def print_out_skeletons():
    print(("There are %d skeletons in this file" % len(skeletons)))
    i = 0
    global candidates
    for skeleton in skeletons:
        i = i + 1
        if len(skeleton) < 20 or len(skeleton) > 250:
            continue
        candidates.append(i)
        print("===========================================")
        print(("The %d skeleton \n Start from %d to %d, total %d frames(lines)" % (i, int(skeleton[0][0]), int(skeleton[-1][0]), len(skeleton))))
        print((skeleton[0]))
        print("......")
        print((skeleton[-1]))
        print("===========================================")

op_flg = False
def showAvi(dict):
    global candidates
    src=os.path.dirname(src_file)
    num=''
    print(("Skeletons Candidate Set:", candidates))
    if(len(candidates)==0):
        print("Set is Empty.")
        print("## All process completely, Exit")
        exit(0)
    else:
        while(num==''):
            if op_flg:
                num = candidates[0]
            else:
                num = input("Input Skeleton num / e To exit:")
    if (num == "e"):
        exit(0)

    if num != '':
        try:
            num = int(num)
            start = int(skeletons[num - 1][0][1])
            end = int(skeletons[num - 1][-1][1])
            draw(src, start, end, skeletons_lines[num-1],dict)
            confirm = input("Save %d? ((y-->save)/(n-->don't save)/(e-->exit)/(enter or others-->pass)):" % num)
            if confirm == 'y':
                save_skeleton_to_file(num)
                # save_skeleton_video(src,start, end, skeletons_lines[num-1],num)
                candidates.remove(num)
            if confirm=='n':
                candidates.remove(num)
            if confirm == 'e':
                exit(0)
        except ValueError as ve:
           print(("Unknow options [%s] please check your input" % num))
        showAvi(dict)

def print_options_to_user():
    print("Please input the options: (no [])")
    print("     Input [numbers] to save the skeletons: e.g. 1 for the skeleton 1 or 1,2,3 for the skeletons of 1, 2, 3")
    print("     Input [skeletons] or [s] to show the skeletons information: e.g. skeletons or s")
    print("     Input [avi] or [a] to watch movie with bone:e.g. avi or a")
    print("     Input [help] or [h] to show this message again: e.g. help or h")
    print("     Input [exit] or [q] to exit the program: e.g. exit or q")

def handle_user_input(input):
    if input == "skeletons" or input == "s":
        print_out_skeletons()
    elif input == "help" or input == "h":
        print_options_to_user()
    elif input == "e" or input == "q":
        pass
    elif input=="avi" or input=="a":
        showAvi()
    else:
        numbers_str = input.strip().split(',')
        numbers = []
        try:
            for num_str in numbers_str:
                if num_str:
                    numbers.append(int(num_str))
        except ValueError:
            print(("Unknow options [%s] please check your input" % input))
            return

        if len(numbers) > 0:
            for num in numbers:
                save_skeleton_to_file(num)

def save_skeleton_to_file(num):
    try:
        #src_file_name = os.path.splitext(os.path.basename(src_file))[0]
        skeleton_file_name = "%s_%d.txt" % (dest_file_name, num)
        skeleton_file = os.path.join(dest_dir, skeleton_file_name)
        skeletons[num-1]
        with open(skeleton_file, "w") as sf:
            for item in skeletons[num-1]:
                sf.write("%s\n" % " ".join(map(str,item)))
        print(("saved skeleton %d to file: %s" % (num, skeleton_file)))
    except IndexError as ie:
        print(("Failed: %d is not found in skeletons" % num))

#---------------
# Main Script
#---------------
def main():
    usage = "Usage: %prog [options] args"
    parser = optparse.OptionParser(usage)
    parser.add_option("-s", "--source", dest="source", default="", help="The source directory of raw data")
    parser.add_option("-d", "--destination", dest="destination", default="", help="The output directory for cleaned data")
    (opts, extra) = parser.parse_args()

    # Verify the arguments
    if len(sys.argv) == 1:
        parser.error("No argument has been provided. \nTry --help to get more details.")

    if not os.path.exists(opts.source):
        raise SystemExit("The given source file doesn't exist : %s" % opts.source)

    kinect_bone_file = os.path.join(opts.source, "kinect bone.txt")
    kinect_bgr_file = os.path.join(opts.source, "bgr.avi")

    if not os.path.isfile(kinect_bone_file):
        raise SystemExit("The file 'kinect bone.txt' doesn't exist in : %s" % opts.source)
    if not os.path.isfile(kinect_bgr_file):
        raise SystemExit("The file 'bgr.avi' doesn't exist in : %s" % opts.source)

    global src_file
    src_file = kinect_bone_file
    global dest_file_name
    dest_file_name = generate_dest_file_name(src_file)
    global dest_dir
    dest_dir = create_destination_dir(opts.destination)

    load_and_clean_kinect_bone_data(kinect_bone_file) # save cleaned to skeletons

    print_out_skeletons()

    inputs = ""
    print_options_to_user()
    # 直接进入符合骨架条件的视频

    '''
    copy from replay
    '''
    video_path = os.path.dirname(src_file)
    if not os.path.exists(video_path):
        raise SystemExit("The video path doesn't exist : %s" % video_path)
    avi = os.path.join(video_path, "bgr.avi")
    txt = os.path.join(video_path, "kinect color.txt")
    f=open(txt, encoding='utf-8') #,encoding='utf-8'
    lines=f.readlines()
    dict={}
    line_num = 0
    for i in range(len(lines)):
        line_num = line_num + 1
        line=lines[i].split(' ')[0:-1]
        # use color frame as the key in the dict
        if(int(line[1]) not in dict):
            dict[int(line[1])]=[]
        values = []
        pre_i = 0
        # there are two frame numbers in a line
        for i in line[2:]:
            try:
                i = float(i)
                values.append(i)
                pre_i = i
            except:
                values.append(pre_i)
        values.append(int(line[0]))
        values.append(line_num)
        dict[int(line[1])].append(values)
    '''
    end
    '''

    showAvi(dict)
    while inputs != "exit" and inputs != "q":
        inputs = input("Enter your option: ")
        if inputs:
            handle_user_input(inputs)
        else:
            print("Nothing has been input")

    print("Exit the program.")

if __name__ == '__main__':
    main()


from flask import Flask, request, Response, render_template, jsonify
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import os
import matplotlib.pyplot as plt
import numpy as np
import io
app = Flask(__name__)
positions =[]

#
@app.route('/')
def index():
	return render_template('index.html')

@app.route('/plot.png', methods=['GET'])
def plot_png():
    try:
      fig = create_figure1(positions[-1], positions[-2])
      output = io.BytesIO()
      FigureCanvas(fig).print_png(output)
      return Response(output.getvalue(), mimetype='image/png')
    except:
      fig = create_figure1(positions[-1], positions[-2])
      output = io.BytesIO()
      FigureCanvas(fig).print_png(output)
      return Response(output.getvalue(), mimetype='image/png')

@app.route('/plot.png', methods=['POST'])
def plot_pngp():
    x = request.get_json()
    positions.extend(x)
    return 'done'

def create_figure():
    fig = Figure()
    axis = fig.add_subplot(1, 1, 1)
    xs = np.linspace(-2*np.pi, 2*np.pi, 100)
    ys = np.sin(xs)
    axis.plot(xs, ys)
    return fig

def create_figure1(x, y):
    fig = Figure()
    axis = fig.add_subplot(1, 1, 1)
    xs = np.linspace(int(x)*np.pi, int(y)*np.pi, 100)
    ys = np.sin(xs)
    ns = np.cos(xs)
    axis.plot(xs, ns)
    axis.plot(xs, ys)
    return fig

app.run(debug=True)