# -*- coding: utf-8 -*-
# @Author: JinZhang
# @Date:   2019-05-16 18:33:42
# @Last Modified by:   JinZhang
# @Last Modified time: 2019-05-17 16:32:03

import wx;
import random, math;
from enum import Enum, unique;
from datetime import datetime;

from _Global import _GG;
from function.base import *;

@unique
class Direction(Enum):
	LEFT = 0;
	TOP = 1;
	RIGHT = 2;
	BOTTOM = 3;

class TetrisViewUI(wx.Panel):
	"""docstring for TetrisViewUI"""
	def __init__(self, parent, id = -1, curPath = "", viewCtr = None, params = {}):
		self.initParams(params);
		super(TetrisViewUI, self).__init__(parent, id, pos = self.__params["pos"], size = self.__params["size"], style = self.__params["style"]);
		self._className_ = TetrisViewUI.__name__;
		self._curPath = curPath;
		self.__viewCtr = viewCtr;
		self.init();
		self.createTimer();
		self.SetBackgroundColour(self.__params["bgColour"]);

	def __del__(self):
		self.__dest__();

	def __dest__(self):
		if not hasattr(self, "_unloaded_"):
			self._unloaded_ = True;
			self.__unload__();

	def __unload__(self):
		self.stopAllTimer(isDestroy = True); # 停止定时器

	def init(self):
		self.__playing = False; # 游戏进行中的标记
		self.__isSpeedUp = False; # 升速的标记位
		self.__timeDuration = 400; # 每次移动的时间
		self.__fixedItemMatrix = []; # 已固定的方块矩阵
		self.__movingItemList = []; # 移动中的方块列表
		self.__nextItemMtList = [];
		self.__setNextItemMtList__();
		self.__initFixedItemMatrix__();

	def initParams(self, params):
		# 初始化参数
		self.__params = {
			"pos" : (0,0),
			"size" : (360,360),
			"style" : wx.BORDER_NONE,
			"bgColour" : wx.Colour(255,255,255),
			"matrix" : (36,36),
			"squareColour" : wx.Colour(0,0,0),
			"onSetNext" : None,
			"onEliminate" : None,
			"onGameOver" : None,
		};
		for k,v in params.items():
			self.__params[k] = v;

	def getCtr(self):
		return self.__viewCtr;

	def initView(self):
		self.createControls(); # 创建控件
		self.initViewLayout(); # 初始化布局

	def createControls(self):
		# self.getCtr().createCtrByKey("key", self._curPath + "***View"); # , parent = self, params = {}
		pass;

	def initViewLayout(self):
		pass;

	def updateView(self, data):
		pass;

	def stopAllTimer(self, isDestroy = False):
		self.stopTimer();
		if isDestroy:
			_GG("TimerManager").deleteTimer(self.__timer);

	def __setNextItemMtList__(self):
		curItemMtList = self.__nextItemMtList;
		col = int(self.__params["matrix"][1]/2);
		self.__nextItemMtList = self.getCtr().getMovingItemPosList((0, 0));
		if callable(self.__params.get("onSetNext", None)):
			self.__params["onSetNext"](self.__nextItemMtList);
		for itemMt in self.__nextItemMtList:
			itemMt[1] += col;
		return curItemMtList;

	# 初始化固定方块矩阵
	def __initFixedItemMatrix__(self):
		for i in range(self.__params["matrix"][0]):
			fixedItemList = [];
			for j in range(self.__params["matrix"][1]):
				fixedItemList.append(None);
			self.__fixedItemMatrix.append(fixedItemList); # 已固定的方块矩阵

	def createTimer(self):
		self.__timer = _GG("TimerManager").createTimer(self, callback = self.onTimer);
		self.__curTimer = datetime.now();

	def startTimer(self):
		self.__timer.Start(self.__timeDuration);

	def stopTimer(self):
		if self.__timer.IsRunning():
			self.__timer.Stop();

	def onTimer(self, event = None):
		self.moveItemList();
		if self.__isSpeedUp:
			self.startTimer();
			self.__isSpeedUp = False;
		self.checkToFocusSelf(); # 检测是否重新对焦自己

	def getItemSize(self):
		rows, cols = self.__params["matrix"][0], self.__params["matrix"][1];
		return wx.Size(self.__params["size"][0]/cols, self.__params["size"][1]/rows);

	def createItem(self):
		return wx.Panel(self, size = self.getItemSize(), style = wx.BORDER_THEME);

	def moveItem(self, item, row, col):
		itemSize = self.getItemSize();
		item.Move(col*itemSize.x, row*itemSize.y);
		item.m_mt = (row, col);

	# 移动方块
	def moveItemList(self, direction = Direction.BOTTOM):
		if self.__playing:
			if self.checkDirection(direction):
				for item in self.__movingItemList:
					row, col = item.m_mt;
					if direction == Direction.BOTTOM:
						row+=1;
					elif direction == Direction.LEFT:
						col-=1;
					elif direction == Direction.RIGHT:
						col+=1;
					self.moveItem(item, row, col);
			elif direction == Direction.BOTTOM:
				if not self.checkGameOver():
					self.setFixedItemMatrix();
					self.eliminateSquares();
					self.createMovingItemList();

	# 创建移动方块
	def createMovingItemList(self):
		self.__movingItemList = [];
		itemMtList = self.__setNextItemMtList__();
		for itemMt in itemMtList:
			item = self.createItem();
			item.SetBackgroundColour(self.__params["squareColour"]);
			self.moveItem(item, *itemMt);
			self.__movingItemList.append(item);

	# 设置固定方块
	def setFixedItemMatrix(self, itemList = []):
		if len(itemList) == 0:
			itemList = self.__movingItemList;
			self.__movingItemList = [];
		for item in itemList:
			row, col = item.m_mt;
			if row > 0:
				self.__fixedItemMatrix[row][col] = item;

	# 检测方向
	def checkDirection(self, direction):
		if direction in [Direction.LEFT, Direction.TOP, Direction.RIGHT, Direction.BOTTOM]:
			for item in self.__movingItemList:
				row, col = item.m_mt;
				if direction == Direction.BOTTOM:
					row+=1;
				elif direction == Direction.LEFT:
					col-=1;
				elif direction == Direction.RIGHT:
					col+=1;
				rows, cols = self.__params["matrix"][0], self.__params["matrix"][1];
				if row >= rows or col < 0 or col >= cols:
					return False;
				elif row >= 0 and self.__fixedItemMatrix[row][col]:
					return False;
			return True;
		return False;

	# 消除方块
	def eliminateSquares(self):
		eliminateCount = 0;
		rows, cols = self.__params["matrix"][0], self.__params["matrix"][1];
		# 逐行消除
		for i in range(rows-1, -1, -1):
			squareCount = 0;
			for j in range(cols):
				if self.__fixedItemMatrix[i][j]:
					squareCount += 1;
			if squareCount > 0:
				if squareCount == cols:
					for j in range(cols):
						if self.__fixedItemMatrix[i][j]:
							self.__fixedItemMatrix[i][j].Destroy();
							self.__fixedItemMatrix[i][j] = None;
					eliminateCount += 1;
				elif eliminateCount > 0:
					for j in range(cols):
						if self.__fixedItemMatrix[i][j]:
							self.moveItem(self.__fixedItemMatrix[i][j], i+eliminateCount, j);
							self.__fixedItemMatrix[i][j], self.__fixedItemMatrix[i+eliminateCount][j] = None, self.__fixedItemMatrix[i][j];
			else:
				# 若该行不存在方块，则跳出该循环
				break;
		if callable(self.__params.get("onEliminate", None)):
			self.__params["onEliminate"](eliminateCount);

	# 旋转方块
	def rotateItemList(self):
		if self.__playing and len(self.__movingItemList) > 0:
			# 获取Item的移动数据
			newItemMtList = [];
			centerRow, centerCol = self.__movingItemList[1].m_mt;
			angle = -math.pi/2;
			sinVal, cosVal = int(math.sin(angle)), int(math.cos(angle));
			rows, cols = self.__params["matrix"][0], self.__params["matrix"][1];
			for item in self.__movingItemList:
				row, col = item.m_mt;
				newRow = centerRow + (row - centerRow) * cosVal - (col - centerCol) * sinVal;
				newCol = centerCol + (col - centerCol) * cosVal + (row - centerRow) * sinVal;
				if newRow >= rows or newCol < 0 or newCol >= cols:
					return
				elif newRow >= 0 and self.__fixedItemMatrix[newRow][newCol]:
					return
				newItemMtList.append((item, newRow, newCol));
			# 移动Item
			for itemMt in newItemMtList:
				self.moveItem(*itemMt);

	def checkGameOver(self):
		for item in self.__movingItemList:
			if item.m_mt[0] <= 0:
				self.onGameOver();
				return True;
		return False;

	def onGameOver(self):
		self.stopTimer();
		if callable(self.__params.get("onGameOver", None)):
			self.__params["onGameOver"]();
		msgDialog = wx.MessageDialog(self, "游戏结束！", "游戏结束", style = wx.OK|wx.ICON_INFORMATION);
		msgDialog.ShowModal();
		# 停止游戏并清除界面
		self.stopGame();

	def resetFixedItemMt(self):
		for items in self.__fixedItemMatrix:
			for i in range(len(items)):
				if items[i]:
					items[i].Destroy();
					items[i] = None;

	def resetMovingItemList(self):
		for item in self.__movingItemList:
			item.Destroy();
		self.__movingItemList = [];

	def startGame(self, event = None):
		if not self.__playing:
			self.createMovingItemList();
			self.__playing = True;
		if not self.__timer.IsRunning():
			self.startTimer();

	def pauseGame(self, event = None):
		if self.__playing:
			self.stopTimer();

	def isPlaying(self):
		return self.__playing;

	def isRunningTimer(self):
		return self.__timer.IsRunning();

	def stopGame(self, event = None):
		self.stopTimer();
		self.resetFixedItemMt();
		self.resetMovingItemList();
		self.init();

	def toSpeedUp(self, rate = 0.8):
		self.__timeDuration = self.__timeDuration * rate;
		self.__isSpeedUp = True;

	def checkToFocusSelf(self):
		nowTime = datetime.now();
		diffDataTime = nowTime - self.__curTimer;
		diffSeconds = diffDataTime.seconds;
		if diffSeconds >= 1:
			self.SetFocusFromKbd(); # 时间回调时，
			self.__curTimer = nowTime;


# round함수는 round_half_even 방식을 택한다.
# 사사오입 원칙
# 반올림할 자리의 수가 5이면 반올림 할 때
# 앞자리의 숫자가 짝수면 내림, 홀수면 올림 한다.
# round(4.5) // 4 (짝수->내림)
# round(3.5) // 4 (홀수->올림)

n = int(input())
score = list(map(int, input().split()))
avarage = round(sum(score)/n)
ans = []
min = 2147000000
for idx, x in enumerate(score):
    tmp = abs(avarage - score[idx])
    if tmp < min:
        min = tmp
        tmp_score = x
        res = idx + 1
    elif tmp == min:
        if x > tmp_score:
            tmp_score = x
            res = idx + 1

print(avarage, res)


import json
import uuid

def create_chat(user, name, short_desc, long_desc, scenario, origin, id, chat, image):

    with open("data.json", "a") as file:  # Use "a" mode to append to the file
        post = {
            'user': user,
            'name': name,
            'short_desc': short_desc,
            'long_desc': long_desc,
            'dialouge': scenario,
            'origin': origin,
            'id': id,
            'chat':chat,
            'image':image
        }

        json.dump(post, file)
        file.write('\n')

def load_chats():
    posts = []
    with open('data.json', 'r') as file:
        for line in file:
            post = json.loads(line)
            posts.append(post)

        return posts

def get_chat(id):

    results = []

    data = load_chats()
    for post in data:
        if post['id'] == id:
             results.append(post)

    return results


import threading
import time
import random

class Phil(threading.Thread):
    def __init__(self, forks, n):
        threading.Thread.__init__(self)
        self.forks = forks
        self.n = n
    def fork(self, dir):
        if dir == 'left':
            return self.forks[self.n]
        else:
            return self.forks[(self.n + 1) % 5]
    def fork_ord(self):
        if random.random() < 0.5:
            take1, take2 = 'left', 'right'
        else:
            take1, take2 = 'right', 'left'
        if random.random() < 0.5:
            put1, put2 = 'left', 'right'
        else:
            put1, put2 = 'right', 'left'
        return (take1, take2, put1, put2)
    def run(self):
        for i in range(100):
            print('Philosopher', self.n, 'thinks', i, 'th iteration')
            #time.sleep(random.random())
            take1, take2, put1, put2 = self.fork_ord()
            print('Philosopher', self.n, 'takes', take1, 'fork', i, 'th iteration')
            self.fork(take1).acquire()
            #time.sleep(random.random())
            print('Philosopher', self.n, 'takes', take2, 'fork', i, 'th iteration')
            self.fork(take2).acquire()
            print('Philosopher', self.n, 'eats', i, 'th iteration')
            #time.sleep(random.random())
            print('Philosopher', self.n, 'puts down', put1, 'fork', i, 'th iteration')
            self.fork(put1).release()
            #time.sleep(random.random())
            print('Philosopher', self.n, 'puts down', put2, 'fork', i, 'th iteration')
            self.fork(put2).release()

forks = [threading.Semaphore(1) for i in range(5)]
phils = [Phil(forks, i) for i in range(5)]

for t in phils:
    t.start()

for t in phils:
    t.join()


#!/usr/bin/env python3

import numpy as np
from pandas import read_csv
import math
import matplotlib.pyplot as mplt

original_file = 'lbm'
filtered_files = [ ['unfiltered'],\
	['Gaussian-0.5', 'Gaussian-1', 'Gaussian-1.5', 'Gaussian-2', 'Gaussian-2.5', 'Gaussian-3', 'Gaussian-3.5', 'Gaussian-4', 'Gaussian-4.5', 'Gaussian-5'], \
	['POD-20-1', 'POD-35-1', 'POD-50-1', 'POD-65-1', 'POD-80-1'],\
	['POD-20-2', 'POD-35-2', 'POD-50-2', 'POD-65-2', 'POD-80-2'],\
	['POD-20-3', 'POD-35-3', 'POD-50-3', 'POD-65-3', 'POD-80-3'],\
	['NLM_0.1', 'NLM_1', 'NLM_10', 'NLM_100', 'NLM_1000', 'NLM_10000'] ]

#get analytical data
original_data = read_csv(original_file+'.csv', delimiter=';', usecols=[0,1,2], names=['t', 'x', 'y'], index_col=None)
#truncate offset (80)
original_data = original_data.loc[original_data['t'].isin(range(80,1000))]

MSE_x = []
MSE_y = []

#for each filter type
for f in filtered_files:
	filter_data = [read_csv(file+'.csv', delimiter=';', usecols=[0,1,2,3,7,8,9,10], \
	names=['t','x','y','z','m','px','py','pz'], index_col=None) for file in f]

	#edge case: 'unfiltered' does not need MSE lists, cf. 'MSE_{x,y}_unfiltered' below.
	if(f != ['unfiltered']):
		#new MSE lists for this filter type
		MSE_x.append([])
		MSE_y.append([])

	#for each instance of that filter type
	for i in range(len(filter_data)):

		rows = filter_data[i]

		#truncate offset (80)
		rows = rows.loc[rows['t'].isin(range(80,1000))]

		#select cell 129
		rows = rows.loc[rows['x'] == 3]
		rows = rows.loc[rows['y'] == 3]
		rows = rows.loc[rows['z'] == 3]

		#get momenta & mass
		filtered_px = np.array(rows['px'])
		filtered_py = np.array(rows['py'])
		filtered_m = np.array(rows['m'])

		#compute velocity
		filtered_velx = filtered_px / filtered_m
		filtered_vely = filtered_py / filtered_m

		#compute MSE in x,y dirs
		diff_x = np.array(original_data['x']) - filtered_velx
		diff_y = np.array(original_data['y']) - filtered_vely

		#edge case: 'unfiltered' is not sampled in different ways, it has a "constant" MSE.
		if(f == ['unfiltered']):
			MSE_x_unfiltered = np.dot(diff_x, diff_x) / diff_x.size
			MSE_y_unfiltered = np.dot(diff_x, diff_x) / diff_x.size
		else:

			MSE_x[-1].append(np.dot(diff_x, diff_x) / diff_x.size)
			MSE_y[-1].append(np.dot(diff_y, diff_y) / diff_y.size)

			print(f[i] + ': MSE (vel x) = ' + str(MSE_x[-1][-1]))
			print(f[i] + ': MSE (vel y) = ' + str(MSE_y[-1][-1]))

def plot_mses(file_location, tested_parameter, x_axis, f_index):
	mplt.style.use('seaborn')
	print(MSE_y[f_index])
	fig, ax = mplt.subplots(1,2)

	ax[0].plot(x_axis, MSE_x[f_index], '-', label = file_location, color='blue')
	ax[0].plot(x_axis, [MSE_x_unfiltered] * len(x_axis), '-', label = 'unfiltered', color='red')

	ax[1].plot(x_axis, MSE_y[f_index], '-', label = file_location, color='blue')
	ax[1].plot(x_axis, [MSE_y_unfiltered] * len(x_axis), '-', label = 'unfiltered', color='red')

	#labeling
	ax[0].set_ylabel('MSE of x velocity')
	ax[1].set_ylabel('MSE of y velocity')
	ax[0].set_xlabel(tested_parameter)
	ax[1].set_xlabel(tested_parameter)

	fig.tight_layout()
	ax[0].set_yscale('log', basey=2)
	ax[1].set_yscale('log', basey=2)

	#ax[1].set_yticks([0.002,0.003,0.004,0.005])

	file_location = file_location + ".png"
	mplt.savefig(file_location)

print(MSE_x)

plot_mses('Gaussian', 'sigma', [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5], 0)
plot_mses('POD-1', 'tws', [20, 35, 50, 65, 80], 1)
plot_mses('POD-2', 'tws', [20, 35, 50, 65, 80], 2)
plot_mses('POD-3', 'tws', [20, 35, 50, 65, 80], 3)
plot_mses('NLM', 'sigma² = h²', ['0.1', '1', '10', '100', '1000', '10000'], 4)


from flask import Flask, render_template, flash, jsonify, send_from_directory, request, redirect, url_for
import os
import subprocess
import requests
import connections

# Local module imports
from user_management import manage_users, fetch_users, delete_user, get_user_details
from ssh_management import generate_ssh_key, get_keys, delete_key, get_private_key
from network_operations import network_info, network_data, get_lsof_status, get_ss_status, get_client_command

app = Flask(__name__, static_folder="static", template_folder="static")
app.secret_key = "supersecretkey"  # Ideally, this should be in a config or environment variable

# Register routes
app.add_url_rule('/', 'index', lambda: render_template('index.html'))

# user routes
app.add_url_rule('/users', 'manage_users', manage_users, methods=['GET', 'POST'])
app.add_url_rule('/fetch-users', 'fetch_users', fetch_users)
app.add_url_rule('/delete-user', 'delete_user', delete_user, methods=['POST'])

# key-manager routes
#app.add_url_rule('/get_all_users', 'get_all_users', get_all_users, methods=['GET'])
app.add_url_rule('/api/users', 'api_users', connections.fetch_users)
app.add_url_rule('/key-manager', 'key_manager', lambda: send_from_directory('static', 'key-manager.html'))
app.add_url_rule('/static/<path:path>', 'serve_static', lambda path: send_from_directory('static', path))
app.add_url_rule('/generate_ssh_key/<username>', 'generate_ssh_key', generate_ssh_key, methods=['POST'])
app.add_url_rule('/get_keys', 'get_keys', get_keys, methods=['GET'])
app.add_url_rule('/delete_key', 'delete_key', delete_key, methods=['POST'])
app.add_url_rule('/get_private_key/<username>/<filename>', 'get_private_key', get_private_key, methods=['GET'])

# network-info routes
app.add_url_rule('/network-info', 'network_info', network_info)
app.add_url_rule('/network-data', 'network_data', network_data)
app.add_url_rule('/api/lsof/<port>', 'get_lsof_status', get_lsof_status)
app.add_url_rule('/api/ss/<port>', 'get_ss_status', get_ss_status)
app.add_url_rule('/api/client-command', 'get_client_command', get_client_command)

# SSH Connection Manager routes
app.add_url_rule('/connections', 'connection_manager', lambda: send_from_directory('static', 'connections.html'))
app.add_url_rule('/api/users', 'api_users', connections.fetch_users)
app.add_url_rule('/api/certs/<username>', 'api_certs', connections.fetch_certs_for_user)
app.add_url_rule('/api/lsof', 'api_lsof', connections.run_lsof, methods=['POST'])
app.add_url_rule('/api/ss', 'api_ss', connections.run_ss, methods=['POST'])
app.add_url_rule('/api/client-command', 'api_client_command', connections.build_client_command, methods=['POST'])

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80, debug=True)


import requests
from zipfile import ZipFile
import os
import pandas as pd

def get_dataset(path, filename, url):
    response = requests.get(url)
    zip_path = os.path.join(path, filename)
    with open(zip_path, "wb") as file:
        file.write(response.content)
    return zip_path

def unzip_dataset(zip_path, destination_path):
    with ZipFile(zip_path, "r") as file:
        file.extractall(destination_path)

def create_dataset(path):
    df = pd.read_csv(path, sep="\t", index_col=0)
    df = df.rename(columns={'lenght_diff': 'length_diff'})
    return df

def filter_dataset(df, toxicity_threshold, non_toxicity_threshold):
    df_ref_tox = df[(df['ref_tox'] > toxicity_threshold) & (df['trn_tox'] < non_toxicity_threshold)]
    df_ref_tox = df_ref_tox.rename(columns={'reference': 'toxic', 'translation': 'non-toxic', 'ref_tox':'toxic_metric', 'trn_tox':'non-toxic_metric'})
    df_trn_tox = df[(df['ref_tox'] < non_toxicity_threshold) & (df['trn_tox'] > toxicity_threshold)]
    df_trn_tox = df_trn_tox.rename(columns={'reference': 'non-toxic', 'translation': 'toxic', 'ref_tox':'non-toxic_metric', 'trn_tox':'toxic_metric'})
    df_trn_tox = df_trn_tox[['toxic', 'non-toxic', 'similarity', 'length_diff', 'toxic_metric', 'non-toxic_metric']]
    df_united = pd.concat([df_ref_tox, df_trn_tox])
    df_final = df_united[['toxic', 'non-toxic']]
    return df_final

def create_train_val_test(df, seed):
    df.to_csv("./data/raw/suitable.csv")
    train = df.sample(10000, random_state=seed)
    val = df.drop(train.index).sample(1000, random_state=seed)
    test = df.drop(train.index).drop(val.index).sample(1000, random_state=seed)
    train.to_csv("./data/raw/train.csv")
    val.to_csv("./data/raw/val.csv")
    test.to_csv("./data/raw/test.csv")

URL = "https://github.com/skoltech-nlp/detox/releases/download/emnlp2021/filtered_paranmt.zip"
PATH = os.path.abspath("data/raw/")
SEED = 177013
archive_path = get_dataset(PATH, "archive.zip", URL)
unzip_dataset(archive_path, PATH)
dataset = create_dataset(os.path.abspath("data/raw/filtered.tsv"))
filtered_dataset = filter_dataset(dataset, 0.95, 0.05)
create_train_val_test(filtered_dataset, SEED)


from __future__ import print_function
from string import Template
import argparse
import sys
import os
import shutil
from collections import namedtuple

# python2 only module, use subprocess for python3
import commands
import socket

BIN_NAME = "dmc_mac"
FOLDER_NAME = "bin"  # the location inside MEI tempfolder where the binary has to be kept
LABEL = "storage-dmc"  # used to start the service
AGENT_FILE_LOCATION = "/Library/LaunchDaemons/{}.plist".format(LABEL)

REMOTE_FILE_LOCATION = "~/.dmc_service"
TEMPLATE = \
    """
        <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
        <plist version="1.0">
        <dict>
        <key>Label</key>
        <string>${LABEL}</string>
        <key>Program</key>
        <string>${location}/${bin_name}</string>
        <key>ProgramArguments</key>
        <array>
        <string>${location}/${bin_name}</string>
        <string>--logLevel</string>
        <string>${logLevel}</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>WorkingDirectory</key>
        <string>${location}</string>
        <key>StandardOutPath</key>
        <string>${location}/${bin_name}.stdout</string>
        <key>StandardErrorPath</key>
        <string>${location}/${bin_name}.stderr</string>
        <key>KeepAlive</key>
        <dict>
        <key>Crashed</key>
        <true/>
        </dict>
        </dict>
        </plist>
        """

# Define function to import external files when using PyInstaller.
def resource_path():
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
        print(base_path)
    except Exception:
        base_path = os.path.abspath(".")

    return base_path

# for dev purposes
def parse_arguments():
    parser = argparse.ArgumentParser(description="A script to install and start dmc service")

    parser.add_argument('--logLevel', type=str, nargs=1, default=["INFO"],
                        choices=('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'),
                        help='LogLevel can be CRITICAL/ERROR/WARNING/INFO/DEBUG')

    parser.add_argument('action', type=str, nargs='?', choices=('start', 'stop', 'restart'),
                        default="start", help='To start, stop or restart the DMC service')

    return parser.parse_args()

def start_service(args):
    base_location = resource_path()
    tpl = Template(TEMPLATE)

    current_binary_location = os.path.expanduser(os.path.join(base_location, FOLDER_NAME, BIN_NAME))
    remote_binary_location = os.path.expanduser(REMOTE_FILE_LOCATION)

    try:
        os.makedirs(remote_binary_location)
    except OSError as e:
        if e.errno == 17:
            print("DMC service is already running.")
            print("Please try 'restart' option to restart DMC service with command.")
            print("Usage: ./dmc_mac_service [start|stop|restart]")
        else:
            print(e.strerror)
        sys.exit(2)
    except Exception as e:
        print("Technical error. Please contact administrator.")
        print(e)
        sys.exit(2)

    remote_binary_location_file = os.path.join(remote_binary_location, BIN_NAME)
    try:
        agent_service_file = open(os.path.expanduser(AGENT_FILE_LOCATION), "w")
        agent_service_file.write(tpl.safe_substitute(
            location=remote_binary_location, LABEL=LABEL, bin_name=BIN_NAME, logLevel=args.logLevel[0]))
        agent_service_file.flush()
    except Exception as e:
        print("Cannot open the service file at", AGENT_FILE_LOCATION, file=sys.stderr)
        print(e)
        sys.exit(2)

    # using copy2 to copy the binary file (with metadata intact)
    # to the user specified location
    try:
        shutil.copy2(current_binary_location, remote_binary_location_file)
    except IOError as e:
        if e.errno == 26:
            print("DMC service is already running.")
            print("Please try 'restart' option to restart DMC service with command.")
            print("Usage: ./dmc_mac_service [start|stop|restart]")
        else:
            print(e.strerror)
        sys.exit(2)
    except Exception as e:
        print("Technical error. Please contact administrator.")
        print(e)
        sys.exit(2)

    print(commands.getoutput("launchctl load -w {}".format(AGENT_FILE_LOCATION)))
    print(commands.getoutput("launchctl start {}".format(LABEL)))
    print("DMC service started")

def stop_service():
    commands.getoutput("launchctl stop {}".format(AGENT_FILE_LOCATION))
    commands.getoutput("launchctl unload {}".format(AGENT_FILE_LOCATION))
    commands.getoutput("rm -rf {}".format(AGENT_FILE_LOCATION))
    commands.getoutput("rm -rf {}".format(REMOTE_FILE_LOCATION))
    print("DMC service stopped")

def tryPort(port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = False
    try:
        sock.bind(("0.0.0.0", port))
        result = True
    except:
        print("Port 8080 is already in use")
    sock.close()
    return result

if __name__ == "__main__":
    args = parse_arguments()

    if not os.geteuid() == 0:
        print("This command must be run as root user.")
        sys.exit(2)

    if args.action in ('start', 'restart') and not tryPort(8080):
        sys.exit(2)

    if args.action == 'stop':
        stop_service()
    elif args.action == 'start':
        start_service(args)
    elif args.action == 'restart':
        stop_service()
        start_service(args)


from trackers.siamrpn import SiamRPN
from trackers.meta_siamrpn import MetaSiamRPN
from trackers.grad_siamrpn import GradSiamRPN

trackers={
    'SiamRPN': SiamRPN,
    'MetaSiamRPN': MetaSiamRPN,
    'GradSiamRPN': GradSiamRPN
}
def get_tracker(tracker_name,*args):
    return trackers[tracker_name](*args)


# Write a program to reverse a number

# Path: sessionWorks\Day3\reversNum.py

temp = num = eval(input("Enter a number: "))
rev = 0

while temp> 0:
    rev = rev*10 + temp%10
    temp = temp//10

print("Reverse of", num, "is", rev)


from dataclasses import asdict, dataclass, field
from datetime import datetime
from typing import Any

from homeassistant.util import dt as dtutil

@dataclass
class HistoricalState:
    state: Any
    dt: datetime
    attributes: dict[str, Any] = field(default_factory=dict)

    def asdict(self):
        return asdict(self)

    def as_value_and_timestamp(self):
        if not self.dt.tzinfo:
            raise ValueError(f"{self}.dt is missing tzinfo")

        utc = dtutil.as_utc(self.dt)
        ts = dtutil.utc_to_timestamp(utc)
        return self.state, ts


import sys
import scipy
import scipy.sparse as sparse
import numpy as np
import numpy.linalg as linalg
import scipy.linalg as sclinalg
from sklearn.cluster import KMeans

EVEC_SMOOTH = 9

def getUnweightedLaplacianEigsDense(W):
    """
    Get eigenvectors of the unweighted Laplacian
    Parameters
    ----------
    W: ndarray(N, N)
        A symmetric similarity matrix that has nonnegative entries everywhere

    Returns
    -------
    v: ndarray(N, N)
        A matrix of eigenvectors
    """
    D = scipy.sparse.dia_matrix((W.sum(1).flatten(), 0), W.shape).toarray()
    L = D - W
    try:
        _, v = linalg.eigh(L)
    except:
        return np.zeros_like(W)
    return v

def getSymmetricLaplacianEigsDense(W):
    """
    Get eigenvectors of the weighted symmetric Laplacian
    Parameters
    ----------
    W: ndarray(N, N)
        A symmetric similarity matrix that has nonnegative entries everywhere

    Returns
    -------
    v: ndarray(N, N)
        A matrix of eigenvectors
    """
    D = scipy.sparse.dia_matrix((W.sum(1).flatten(), 0), W.shape).toarray()
    L = D - W
    SqrtD = np.sqrt(D)
    SqrtD[SqrtD == 0] = 1.0
    DInvSqrt = 1/SqrtD
    LSym = DInvSqrt.dot(L.dot(DInvSqrt))
    try:
        _, v = linalg.eigh(LSym)
    except:
        return np.zeros_like(W)
    return v

def getRandomWalkLaplacianEigsDense(W):
    """
    Get eigenvectors of the random walk Laplacian by solving
    the generalized eigenvalue problem
    L*u = lam*D*u
    Parameters
    ----------
    W: ndarray(N, N)
        A symmetric similarity matrix that has nonnegative entries everywhere

    Returns
    -------
    v: ndarray(N, N)
        A matrix of eigenvectors
    """
    D = scipy.sparse.dia_matrix((W.sum(1).flatten(), 0), W.shape).toarray()
    L = D - W
    try:
        _, v = sclinalg.eigh(L, D)
    except:
        return np.zeros_like(W)
    return v

def spectralClusterSequential(v, dim, times, rownorm=False):
    """
    Given Laplacian eigenvectors associated with a time series, perform
    spectral clustering, and return a compressed representation of
    the clusters, merging adjacent points with the same label into one cluster
    Parameters
    ----------
    v: ndarray(N, k)
        A matrix of eigenvectors, excluding the zeroeth
    dim: int
        Dimension of spectral clustering, <= k
    times: ndarray(N)
        Time in seconds of each row of the eigenvector matrix
    rownorm: boolean
        Whether to normalize each row (if using symmetric Laplacian)

    Returns
    -------
    labels: ndarray(N)
        Cluster membership for each point
    intervals_hier: ndarray (N, 2)
        Intervals (in seconds) of annotations
    labels_hier: list(strings)
        Corresponding segment labels for annotations
    """
    assert dim <= v.shape[1]
    x = np.array(v[:, 0:dim])
    if EVEC_SMOOTH > 0:
        x = scipy.ndimage.median_filter(x, size=(EVEC_SMOOTH, 1))
    if rownorm:
        norms = np.sqrt(np.sum(x**2, 1))
        norms[norms == 0] = 1
        x /= norms[:, None]
    labels = KMeans(n_clusters = dim, n_init=50, max_iter=500).fit(x).labels_
    splits = np.where(np.abs(labels[1::]-labels[0:-1]) > 0)[0]+1
    splits = np.concatenate(([0], splits, [labels.size]))
    # Handle edge case with small audio
    splits[splits >= times.size] = times.size
    if np.sum(splits == times.size) > 1:
        splits = np.unique(splits)
    groups = np.split(labels, splits)[1:-1]
    intervals_hier = np.zeros((len(groups), 2))
    timesext = np.array(times.tolist() + [times[-1]])
    intervals_hier[:, 0] = timesext[splits[0:-1]]
    intervals_hier[:, 1] = timesext[splits[1::]]
    x = np.zeros((intervals_hier.shape[0], 3))
    labels_hier = ['%i'%g[0] for g in groups]
    return {'labels':labels, 'intervals_hier':intervals_hier, 'labels_hier':labels_hier}


from django import forms
from django.test import Client, TestCase
from django.core.cache import cache
from django.urls import reverse

from posts.models import Group, Post, User

class ViewsTests(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.user = User.objects.create_user(username='test_name')
        cls.group = Group.objects.create(
            title='test_title',
            slug='test_slug',
            description='test_description'
        )
        cls.post = Post.objects.create(
            text='test_text',
            author=cls.user,
            group=cls.group
        )
        cls.reverse_template_db = {
            reverse('posts:index'): 'posts/index.html',
            reverse('posts:group_posts', kwargs={'slug_name': 'test_slug'}):
            'posts/group_list.html',
            reverse('posts:profile', kwargs={'username': 'test_name'}):
            'posts/profile.html',
            reverse('posts:post_detail', kwargs={'post_id': '1'}):
            'posts/post_detail.html',
            reverse('posts:post_create'): 'posts/create_post.html',
            reverse('posts:post_edit', kwargs={'post_id': '1'}):
            'posts/create_post.html',
        }
        cls.comment_db = {
            'text': 'test_comment_text',
        }
        cls.form_fields = {
            'text': forms.fields.CharField,
            'group': forms.fields.ChoiceField,
        }

    def setUp(self):
        self.client = Client()
        self.authorized_client = Client()
        self.authorized_client.force_login(self.user)

    def test_url_use_correct_template(self):
        """Url use correct template"""
        cache.clear()
        for reverse_name, template in self.reverse_template_db.items():
            with self.subTest(reverse_name=reverse_name):
                response = self.authorized_client.get(reverse_name)
                self.assertTemplateUsed(response, template)

    def test_index_page_show_correct_context(self):
        """Index template use correct context"""
        cache.clear()
        response = self.authorized_client.get(reverse('posts:index'))
        first_object = response.context['page_obj'][0]
        post_text = first_object.text
        post_author = first_object.author
        self.assertEqual(post_text, 'test_text')
        self.assertEqual(post_author, self.user)

    def test_group_list_page_show_correct_context(self):
        """Group template use correct context"""
        response = self.authorized_client.get(reverse(
            'posts:group_posts',
            kwargs={'slug_name': 'test_slug'}))
        first_object = response.context['page_obj'][0]
        post_group = first_object.group
        self.assertEqual(post_group, self.group)

    def test_profile_page_show_correct_context(self):
        """"Profile template use correct context"""
        response = self.authorized_client.get(reverse(
            'posts:profile',
            kwargs={'username': 'test_name'}))
        first_object = response.context['page_obj'][0]
        post_author = first_object.author
        self.assertEqual(post_author, self.user)

    def test_post_detail_page_show_correct_context(self):
        """Post detail template use correct context"""
        response = self.authorized_client.get(reverse(
            'posts:post_detail',
            kwargs={'post_id': '1'}))
        first_object = response.context['post']
        self.assertEqual(first_object, self.post)

    def test_post_detail_show_comment(self):
        """Post detail show comment"""
        self.authorized_client.post(
            reverse('posts:add_comment', kwargs={'post_id': '1'}),
            data=self.comment_db,
            follow=True
        )
        response = self.authorized_client.get(reverse(
            'posts:post_detail',
            kwargs={'post_id': '1'}))
        comment = response.context['comments']
        self.assertEqual(comment[0].text, 'test_comment_text')

    def test_edit_post_page_show_correct_context(self):
        """"Post edit template use corrct context"""
        response = self.authorized_client.get(reverse(
            'posts:post_edit',
            kwargs={'post_id': '1'}))
        for value, expected in self.form_fields.items():
            with self.subTest(value=value):
                form_field = response.context.get('form').fields.get(value)
                self.assertIsInstance(form_field, expected)
        self.assertEqual(response.context['is_edit'], True)

    def test_create_post_page_show_correct_context(self):
        """"Create post template use correct context"""
        response = self.authorized_client.get(reverse('posts:post_create'))
        for value, expected in self.form_fields.items():
            with self.subTest(value=value):
                form_field = response.context.get('form').fields.get(value)
                self.assertIsInstance(form_field, expected)

class PaginatorViewsTest(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.user = User.objects.create_user(username='UsePaginator')
        cls.group = Group.objects.create(
            title='test_title',
            slug='test_slug',
            description='test_description'
        )
        cls.posts = [
            Post.objects.create(
                text='test_text' + str(i),
                author=cls.user,
                group=cls.group) for i in range(13)]

    def setUp(self):
        self.authorized_client = Client()
        self.authorized_client.force_login(self.user)

    def test_first_page_contains_ten_records(self):
        """First index, group, profile page contain 10 entry"""
        cache.clear()
        response_index = self.client.get(reverse('posts:index'))
        response_group = self.client.get(reverse(
            'posts:group_posts',
            kwargs={'slug_name': 'test_slug'}))
        response_profile = self.client.get(reverse(
            'posts:profile',
            kwargs={'username': 'UsePaginator'}))

        self.assertEqual(response_index.context['page_obj'].end_index(), 10)
        self.assertEqual(response_group.context['page_obj'].end_index(), 10)
        self.assertEqual(response_profile.context['page_obj'].end_index(), 10)

    def test_second_page_contains_three_records(self):
        """Second index, group, profile page contain 3 entry"""
        response_index = self.client.get(reverse('posts:index') + '?page=2')
        response_group = self.client.get(reverse(
            'posts:group_posts',
            kwargs={'slug_name': 'test_slug'}) + '?page=2')
        response_profile = self.client.get(reverse(
            'posts:profile',
            kwargs={'username': 'UsePaginator'}) + '?page=2')
        self.assertEqual(len(response_index.context['page_obj']), 3)
        self.assertEqual(len(response_group.context['page_obj']), 3)
        self.assertEqual(len(response_profile.context['page_obj']), 3)

class AddCreatePostTests(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.user = User.objects.create_user(username='UseGroup')
        cls.group = Group.objects.create(
            title='test_title',
            slug='test_slug',
            description='test_description'
        )
        cls.group_fectiv = Group.objects.create(
            title='fectiv',
            slug='fectiv',
            description='fectiv'
        )
        cls.post = Post.objects.create(
            text='test_text',
            author=cls.user,
            group=cls.group
        )

    def setUp(self):
        self.authorized_client = Client()
        self.authorized_client.force_login(self.user)

    def test_correct_create_post(self):
        """"Correct create post"""
        cache.clear()
        response_index = self.authorized_client.get(reverse('posts:index'))
        response_group = self.authorized_client.get(reverse(
            'posts:group_posts',
            kwargs={'slug_name': 'test_slug'}))
        response_group_fectiv = self.authorized_client.get(reverse(
            'posts:group_posts',
            kwargs={'slug_name': 'fectiv'}))
        response_profile = self.client.get(reverse(
            'posts:profile',
            kwargs={'username': 'UseGroup'}))
        self.assertEqual(response_index.context['page_obj'][0], self.post)
        self.assertEqual(response_group.context['page_obj'][0], self.post)
        self.assertEqual(len(response_group_fectiv.context['page_obj']), 0)
        self.assertEqual(response_profile.context['page_obj'][0], self.post)


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:

    # 2022/04/09
    # BFS [O(N + HlogH): 88%]
    # L0314 是 (col, row)相等的時候要照left/right順序排，這題是要照數值大小排。
    # 因為是用數值大小排，所以本來BFS可以自然保持row序和left/right序，在這題好處就比較少。
    # col序: 用range(min, max)
    # row序: L31做sort
    # val序: L33做sort
    def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
        colToRowNode = collections.defaultdict(lambda: collections.defaultdict(list))
        deq = collections.deque([[0, 0, root]])
        minCol, maxCol = 0, 0
        while deq:
            col, row, node = deq.popleft()
            if node is None:
                continue
            colToRowNode[col][row].append(node.val)
            minCol = min(minCol, col)
            maxCol = max(maxCol, col)
            deq.append([col-1, row+1, node.left])
            deq.append([col+1, row+1, node.right])

        res = []
        for col in range(minCol, maxCol+1):
            cur = []
            for row in sorted(colToRowNode[col].keys()):
                cur.extend(sorted(colToRowNode[col][row]))
            res.append(cur)
        return res

algo/Tree/__0987__Vertical Order Traversal of a Binary Tree.py


from compatibility_check import *

def cayley_dickson_doubling(base, structural):

	if base.base_ring != structural.base_ring:

		raise TypeError("Base rings are different between 'base' and 'structural': "+
				"{0:s} versus {1:s}!".format(str(base.base_ring), str(structural.base_ring)))

	class cayley_dickson_doubling:

		base_ring = structural.base_ring

		current_algebra = ('doubling', base.current_algebra, structural)

		@classmethod
		def collect_structurals(cls):

			real_flat = ()

			if hasattr(base, 'collect_structurals'):

				real_flat += base.collect_structurals()

			real_flat += (structural,)

			return real_flat

		def dump(self):

			return self.components[0].dump()+self.components[1].dump()

		def flatten(self):

			return self.components[0].flatten()+self.components[1].flatten()

		def upcast(factor):

			try:

				if factor.current_algebra != __class__.current_algebra:

					try:

						try:

							return cayley_dickson_doubling(factor)

						except:

							return cayley_dickson_doubling(base(factor))

					except:

						return cayley_dickson_doubling(base.upcast(factor))

				else:

					return factor

			except:

				return __class__.upcast(base.upcast(factor))

		def downcast(element):

			if element.current_algebra == __class__.base_ring:

				return element

			else:

				return __class__.downcast(element.components[0])

		def is_invertible(self):

			return self.cayley_norm().downcast().is_invertible()

		def is_unimodular(self):

			return self.cayley_norm().downcast() ==\
				structural.__class__.neutral_element_for_multiplication()

		def __init__(self, component_0 = base(), component_1 = base()):

			if	((component_0.current_algebra != self.current_algebra[1]) or
				(component_1.current_algebra != self.current_algebra[1])):

				raise TypeError("A component is from a different algebra: "+
					"{0:s} and {1:s} (expected {2:s})!".format(str(component_0.current_algebra),
					str(component_1.current_algebra), str(self.current_algebra[1])))

			self.components = (component_0, component_1)

		@compatibility_check
		def __add__(self, other):

			return cayley_dickson_doubling(self.components[0] + other.components[0],
				self.components[1] + other.components[1])

		@compatibility_check
		def __sub__(self, other):

			return cayley_dickson_doubling(self.components[0] - other.components[0],
				self.components[1] - other.components[1])

		def __neg__(self):

			return cayley_dickson_doubling(-self.components[0], -self.components[1])

		@compatibility_check
		def __mul__(self, other):

			new_component_0 = self.components[0]*other.components[0]
			new_component_0 -= self.current_algebra[2] @ (other.components[1].conjugate()*self.components[1])

			new_component_1 = self.components[1]*other.components[0].conjugate()
			new_component_1 += other.components[1]*self.components[0]

			return cayley_dickson_doubling(new_component_0, new_component_1)

		def __rmatmul__(self, other):
		# We hijack this operator to represent the external product

			if other.current_algebra != self.base_ring:

				raise TypeError("First factor is not in the second factor's base ring: "+
					"{0:s} versus {1:s}!".format(other.current_algebra, self.base_ring))

			else:

				return cayley_dickson_doubling(other @ self.components[0],
					other @ self.components[1])

		def inverse(self):

			if not __class__.is_invertible(self):

				raise ZeroDivisionError("{0:s} is not invertible!".format(self))

			return self.cayley_norm().downcast().inverse() @ self.conjugate()

		@compatibility_check
		def __truediv__(self, other):

			return self * other.inverse()

		def __pow__(self, a_power):
		# We adapt the Binary Exponentiation algorithm (without modulo!)

			#result = __class__.upcast(base(1))
			#print(__class__.base_ring)
			result = __class__.upcast(1)

			auxilliary = cayley_dickson_doubling(self.components[0], self.components[1])

			while a_power:

				if a_power % 2:	# If power is odd

					result = result * auxilliary

				# Divide the power by 2
				a_power >>= 1

				# Multiply base to itself
				auxilliary = auxilliary * auxilliary

			return result

		def conjugate(self):

			return cayley_dickson_doubling(self.components[0].conjugate(), -self.components[1])

		def cayley_trace(self):

			return self+self.conjugate()

		def cayley_norm(self):

			return self*self.conjugate()

		def __eq__(self, other):

			if not hasattr(other, 'current_algebra'):

				return False

			elif self.current_algebra != other.current_algebra:

				return False

			else:

				return self.components == other.components

		def __ne__(self, other):

			if not hasattr(other, 'current_algebra'):

				return True

			elif self.current_algebra != other.current_algebra:

				return True

			else:

				return self.components != other.components

		def __str__(self):

			structural_constants = __class__.collect_structurals()

			da_length = len(structural_constants)

			da_string = "{0} ".format(self.flatten())
			da_string += "{"

			if da_length > 1:

				for idx in range(da_length-1):

					da_string += "{0:s}, ".format(structural_constants[idx])

				da_string += "{0:s}".format(structural_constants[-1])

			else:

				da_string += "{0:s}".format(structural_constants[0])

			da_string += "}"

			return da_string

		def __repr__(self):

			structural_constants = __class__.collect_structurals()

			da_length = len(structural_constants)

			da_string = "{0} ".format(self.flatten())
			da_string += "{"

			if da_length > 1:

				for idx in range(da_length-1):

					da_string += "{0:s}, ".format(structural_constants[idx])

				da_string += "{0:s}".format(structural_constants[-1])

			else:

				da_string += "{0:s}".format(structural_constants[0])

			da_string += "}"

			return da_string

		def __format__(self, spec):

			structural_constants = __class__.collect_structurals()

			da_length = len(structural_constants)

			da_string = "{0} ".format(self.flatten())
			da_string += "{"

			if da_length > 1:

				for idx in range(da_length-1):

					da_string += "{0:s}, ".format(structural_constants[idx])

				da_string += "{0:s}".format(structural_constants[-1])

			else:

				da_string += "{0:s}".format(structural_constants[0])

			da_string += "}"

			return da_string

	return cayley_dickson_doubling


"""
Utilities for interacting with AWS.
"""

# pylint: disable=logging-fstring-interpolation, invalid-name, missing-docstring

import logging

import boto3
from boto3.dynamodb.conditions import Key
from botocore.vendored.requests.exceptions import SSLError

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())

def connect_to_aws_resource(resource_name, config):
    try:
        resource = boto3.resource(
            resource_name, region_name=config['aws_general']['region_name'], verify=True)
    except SSLError as ssl_err:
        logger.error(f"SSL Error: {ssl_err}", exc_info=True)
    else:
        return resource

def get_boto_client(service):
    return boto3.client(service)

def get_items_by_partition_key(resource, table_name, key_name, key_value):
    table = resource.Table(table_name)
    response = table.query(KeyConditionExpression=Key(key_name).eq(key_value))
    return response['Items']

def put_with_partition_and_sort_key(resource, table_name, partition_and_sort_key, data):
    table = resource.Table(table_name)
    item = {
        partition_and_sort_key['partition_key_name']: partition_and_sort_key['partition_key_value'],
        partition_and_sort_key['sort_key_name']: partition_and_sort_key['sort_key_value']
    }
    item.update(data)
    table.put_item(Item=item)


#!python3
# -*- coding: utf-8 -*-
# crawling_website.py - 爬取网页内容，保存为 md 文件

import os
from bs4 import BeautifulSoup
import tomd
import requests
from requests.exceptions import ReadTimeout, ConnectionError, RequestException
import re
import send2trash

# 转换 html to md
# Params:
#   html_str: html 字符串
#   target_class: node className
def gen_md(url, target_class):
    if url is not None:
        url = url.strip()
        response = requests.get(url)
        try:
            response.raise_for_status()
            # if response.status_code != 200:
            #     raise Exception('Request error! ', response.status_code)
        except Exception as err:
            print("There war a problem: %s" % (err))

        soup = BeautifulSoup(response.content, 'html.parser')
        # 提取 html 内容
        content = str(soup.find_all(class_=target_class)[0])
        # 将 html 转换为 md
        md_str = tomd.convert(content)
        return md_str
    else:
        return None

# 创建 md 文件
def create_md_file(md_str, output_folder, file_name='unnamed.md'):
    if os.path.isdir(output_folder):
        # 如果 output 目录下的 file_name 指定的文件存在则删除这个旧文件
        output_file_path = os.path.join(output_folder, file_name)
        if os.path.exists(output_file_path):
            send2trash.send2trash(output_file_path)

        print('Create {} beginning...'.format(file_name))
        # 打文件 如果不存在，生成新文件
        # r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
        # w+ 打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在，创建新文件。
        # a+ 打开一个文件用于读写。如果该文件已存在，文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在，创建新文件用于读写。
        # encoding='utf-8' 创建文件为 utf-8 编码格式，如果不指定会创建 ascii编码类型的文件，导致文件写入报错
        # output_file = open(os.path.join(output_folder, file_name), 'wb', encoding='utf-8')
        output_file = open(output_file_path, 'wb')
        # 写入文件内容 编辑为二进制
        content = md_str.encode('utf-8', 'ignore')
        # content = md_str.encode('utf-8', 'ignore').decode('utf-8')

        output_file.write(content)
        # 关闭文件
        output_file.close()
        print('Create {} completed.'.format(file_name))
    else:
        print('Output folder is error, Please check it exist! ------> ', output_folder)

if __name__ == '__main__':
    # 爬取网络页面
    while True:
        print('Please input your target web page:')
        target_url = str(input())
        if target_url is not None:
            break
        else:
            print('Press ctrl & c to exit')

    while True:
        print('Please input your target the node class name: ')
        class_name = input()
        if class_name is not None:
            break
        else:
            print('Press ctrl & c to exit')

    # 当前目录路径
    path = os.getcwd()
    print('Current work path is: ', path)
    # 判断当前目录下是否存在 output目录
    output_path = os.path.join(path, 'output')
    if os.path.exists(output_path) is False:
        # 如果不存在则创建 output 目录
        os.makedirs(output_path)
        print('Create output fold in ', output_path)

    # 自动生成文件名
    regex = re.compile(r'^(.+/)(.+)$')
    mo = regex.match(target_url)
    file_name = mo.group(2) + '.md'

    # 生成 md 内容
    md_content = gen_md(target_url, class_name)

    # 生成 md 文件
    create_md_file(md_content, output_path, file_name)


import urllib.request
from PIL import Image

cwd = "../io/"
outputDir = cwd + "dev_og.jpg"

# Lines (width,height)
sizes = {
	"Martin1": (240,240),
	"Martin2": (240,240),
	"Scottie1": (240,240),
	"Scottie2": (240,240),
	"Robot24": (218,120),
	"Robot36": (320,240),
	"Robot72": (256,240)
}

# CCTV Superclass
class CCTV:

	resample = Image.ANTIALIAS

	def resize(self,mode):
		image = Image.open(outputDir,mode="r")
		image = image.resize(sizes[mode],CCTV.resample)

		image.save(f"{cwd}images/dev_{mode}.jpg")

	def save(self,url):
		urllib.request.urlretrieve(url,outputDir)


from project.utils.webscraping.locators.player_stats_locator import PlayerStatsLocator
from typing import List

class PlayerParser:
    def __init__(self, parent):
        self.parent = parent

    @property
    def player_stats(self) -> List:
        player_statistics = []
        stat_names = [
            stat.text for stat in self.parent.select(PlayerStatsLocator.STATISTIC_NAMES)[:30]
        ]
        stat_values = []
        for season_stat in self.parent.select(PlayerStatsLocator.STATISTIC_PER_SEASON)[:30]:
            try:
                season_stat_values = [stat_value.text for stat_value in season_stat]
            except AttributeError:
                season_stat_values = []
            if len(season_stat_values) > 0:
                stat_values.append(season_stat_values) and len(season_stat_values) > 0
        for stat_value in stat_values:
            player_statistics.append(dict(zip(stat_names, stat_value)))
        return player_statistics

    @property
    def get_statistics_header(self) -> List:
        header = [
            stat.text for stat in self.parent.select(PlayerStatsLocator.STATISTIC_NAMES)
        ]
        return header


#!/usr/bin/env python2
# -*- coding: utf-8 -*-

from __future__ import absolute_import, unicode_literals

from farnsworth.models.job import RopCacheJob

import meister.creators
LOG = meister.creators.LOG.getChild('rop_cache')

class RopCacheCreator(meister.creators.BaseCreator):
    def __init__(self, *args, **kwargs):
        super(self.__class__, self).__init__(*args, **kwargs)

    @property
    def _jobs(self):
        LOG.debug("Collecting jobs...")
        for cs in self.single_cb_challenge_sets():
            job = RopCacheJob(cs=cs, request_cpu=1, request_memory=2048, limit_memory=8192)
            priority = 90  # A rop cache should probably always be created
            LOG.debug("Yielding RopCacheJob for %s", cs.name)
            yield (job, priority)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import sqlite3
import time
import requests
import grequests

def process_page_text(txt, con, c):
    board = "_default_"
    author = "_default_"

    lines = txt.split('\n')
    for line in lines:
        line = line.strip()
        #print(line)
        if line.startswith('<a href'): #update board
            lpos = line.rfind('(') + 1
            rpos = line.rfind(')')
            board = line[lpos:rpos]
            #print ('board:', board)
        if line.startswith('<div class="author"'): #update author, then add count to freqDict
            lpos = line.find('>') + 1
            rpos = line.rfind('<')
            author = line[lpos:rpos]
#                    freqDict[(board, author)] = freqDict.get((board, author), 0) + 1
            sql_cmd = 'INSERT INTO BoardAuthorPair (board, author) VALUES ("{}", "{}")'.format(board, author)
            print(sql_cmd)
            c.execute(sql_cmd)
            #print('author:', author)
            #print('Find a pair: (board =', board, ', author = ', author)

    #txtArr.append(txt)
    con.commit()

def main():
    con = sqlite3.connect('PTT_Parser.db')
    c = con.cursor()

    START_PAGE = 1
    if len(sys.argv) > 1:
        START_PAGE = int(sys.argv[1])
        print('Starting from page %d' % START_PAGE)

    #c.execute('DELETE FROM BoardAuthorPair')

    freqDict = {} # (board, author) -> count

    MAX_PAGE = -1 #default value

    lines = requests.get('https://www.ptt.cc/bbs/ALLPOST/index.html').text.split()
    target = u'/bbs/ALLPOST/index' # byte string
    for line in lines:
        #print(line)
        if sys.version_info < (3, 0):
            line = unicode(line) # unicode string
        if line.find(target) > -1:
            lpos = line.find('index') + 5
            rpos = line.find('.html')
            if rpos - lpos < 2: continue # not the target
            MAX_PAGE = int(line[lpos:rpos]) + 1
            print("Total", MAX_PAGE, "pages.")
            break

    # reset MAX_PAGE to 3 (to avoid overuse)
    #MAX_PAGE = 3

    urls = ['https://www.ptt.cc/bbs/ALLPOST/index' + str(i) + '.html' for i in range(START_PAGE, MAX_PAGE)]
    req_list = (grequests.get(u) for u in urls)
    res_list = grequests.map(req_list, size=10)
    for res in res_list:
        if res != None:
            process_page_text(res.text, con, c)

    #for i in range(START_PAGE, MAX_PAGE):
    #    print('Getting page', i, 'out of', MAX_PAGE, '...')
    #    sys.stdout.write('\r')
    #    sys.stdout.flush()
    #    txt = requests.get('https://www.ptt.cc/bbs/ALLPOST/index' + str(i) + '.html').text
    #
    #    process_page_text(txt, con, c)

#for k in freqDict:
#        print(k,'-->', freqDict[k])
#
#print('------------------------------------------------')
#for k in freqDict:
#        for k2 in freqDict:
#                if k[1] == k2[1] and k[0] < k2[0]:
#                        print("Association between", k[0], 'and', k2[0], 'found. Count:', freqDict[k], 'x', freqDict[k2])
#

    con.commit()

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Building',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, verbose_name='ID', serialize=False)),
                ('property_name', models.CharField(max_length=30, help_text='Enter full name, must be unique')),
                ('address', models.CharField(max_length=200, blank=True)),
                ('town', models.CharField(max_length=30, blank=True)),
                ('state', models.CharField(default='MA', max_length=2)),
                ('zip', models.CharField(max_length=10, null=True, blank=True)),
                ('building_comments', models.TextField(blank=True)),
            ],
        ),
        migrations.CreateModel(
            name='Tenant',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, verbose_name='ID', serialize=False)),
                ('first_name', models.CharField(max_length=30)),
                ('last_name', models.CharField(max_length=30)),
                ('email', models.EmailField(default='tenant@gmail.com', max_length=254, blank=True)),
                ('primary_phone', models.CharField(default='1234567893', max_length=10, null=True, blank=True)),
                ('property_name', models.ForeignKey(related_name='tenant_property', to='cdpapp.Building')),
            ],
            options={
                'ordering': ['last_name'],
            },
        ),
        migrations.CreateModel(
            name='Unit',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, verbose_name='ID', serialize=False)),
                ('unit', models.CharField(max_length=30)),
                ('bedrooms', models.IntegerField(default=1)),
                ('bathrooms', models.DecimalField(default=1.0, decimal_places=1, max_digits=2)),
                ('unit_comments', models.TextField(blank=True)),
                ('property_name', models.ForeignKey(related_name='units', to='cdpapp.Building')),
            ],
        ),
        migrations.CreateModel(
            name='WorkOrder',
            fields=[
                ('ordernum', models.AutoField(primary_key=True, serialize=False)),
                ('priority', models.CharField(default='Not so urgent', max_length=20, choices=[('Urgent', 'Urgent'), ('Not so urgent', 'Not so Urgent'), ('Whenever', 'Whenever')])),
                ('request_by', models.CharField(default='Resident', max_length=20, choices=[('Staff', 'Staff'), ('Resident', 'Resident'), ('Inspection', 'Inspection'), ('Other', 'Other')])),
                ('call_date', models.DateField(blank=True)),
                ('problem_desc', models.TextField(blank=True)),
                ('complete_by', models.DateField(null=True, blank=True)),
                ('completed_by', models.TextField(default='Staff', max_length=25, choices=[('Staff', 'Staff'), ('Contractor', 'Contractor'), ('Other', 'Other')])),
                ('completed', models.BooleanField(default=False)),
                ('complete_date', models.DateField(null=True, blank=True)),
                ('maint_comments', models.TextField(blank=True)),
                ('property_name', models.ForeignKey(related_name='workorder_property', to='cdpapp.Building')),
                ('unit', models.ForeignKey(related_name='workorder_unit', to='cdpapp.Unit')),
            ],
        ),
        migrations.AddField(
            model_name='tenant',
            name='unit',
            field=models.ForeignKey(related_name='tenant_unit', to='cdpapp.Unit'),
        ),
    ]


from socket import socket
import random
import json

with open('config.json', 'r') as f:
  config = json.load(f)

class Chat:

    def __init__(self):

        self.socket = socket()
        self.socket.connect(('irc.twitch.tv', 6667))
        nick = (config['NICK']+str(random.randint(1000,9999)))

        self.socket.send(("PASS "  + config['PASS'] +       "\n").encode('utf-8'))
        self.socket.send(("NICK "  + nick +                 "\n").encode('utf-8'))
        self.socket.send(("JOIN #" + config['CHANNEL'] +    "\n").encode('utf-8'))

        loading = True

        while loading:
            read_buffer_join = self.socket.recv(1024)
            read_buffer_join = read_buffer_join.decode()

            for line in read_buffer_join.split('\n')[0:-1]:
                print(line)
                loading = 'End of /NAMES list' not in line

    def listen(self) -> (str, str):
        read_buffer = self.socket.recv(1024).decode()
        for line in read_buffer.split('\r\n'):
            if 'PING' in line and 'PRIVMSG' not in line:
                self.socket.send('PONG tmi.twitch.tv\r\n'.encode())

            elif line != '':
                parts = line.split(':', 2)
                return parts[1].split('!', 1)[0], parts[2]


import tkinter as tk
import startno_okno as sto
import high_score_okno as hso
import random as r
from time import gmtime, strftime
import sys

#rekurzija (resi problem pri 25x25
sys.setrecursionlimit(1500)

#startno okno
startno_okno = sto.Startno_okno()

#oznake, konstante
PUF = 'puf'
ZASTAVA = 'F'
IME = startno_okno.ime
VRSTICE = sto.VRSTICE.stevilo
STOLPCI = sto.STOLPCI.stevilo
BOMBE = sto.BOMBE.stevilo
cekiranje_za_zmago = sto.Konstanta(1)
zacni_steti_cas=sto.Konstanta(1)
VELIKOST_GUMBA = 3
CAS = sto.Konstanta(0)
TOCKE = sto.Konstanta(0)

#stanja
zastava = 'zastava'
pritisnjen = 'pritisnjen'
zakrit = 'zakrit'
bomba ='bomba'

#okno
main_okno = tk.Tk()
main_okno.title('Minolovec')

#razdeljeno okno na dva dela
zg = tk.Frame(main_okno)
sp = tk.Frame(main_okno)
zg.grid(row=1)
sp.grid(row=2)

#nastavek za cas
cas_zacetek = sto.Konstanta(0)
cas_konec = sto.Konstanta(0)

#--------------------------------------------------------------------------------------------------------------------

#naredi tabelo
def naredi_tabelo():
    tab = []
    for i in range(VRSTICE):
        v = []
        for j in range(STOLPCI):
            g = Gumb(i, j)
            v.append(g)
            g.prikazi(sp)
        tab.append(v)
    return tab

#doloci bombe
def posuj_bombe():
    zaloga_bomb = []
    while len(zaloga_bomb) < BOMBE:
        i = r.randint(0, VRSTICE - 1)
        j = r.randint(0, STOLPCI - 1)
        tabela[i][j].je_ni_bomba = True
        if tabela[i][j] not in zaloga_bomb:
            zaloga_bomb.append(tabela[i][j])
    return zaloga_bomb

#cifra ali puf
def povej_gumbom_kaj_so():
    for i in range(VRSTICE):
        for j in range(STOLPCI):
            tabela[i][j].bombasto()
            tabela[i][j].poisci_sosednje()
            tabela[i][j].poisci_stevilo_bomb()

#barva
def gumbom_prilagodi_barvo():
    tabela_barv = [None, 'navy', 'dark green', 'darkOrchid4', 'coral4', 'turquoise4', 'gold4', 'DodgerBlue4']
    for i in range(VRSTICE):
        for j in range(STOLPCI):
            gumb = tabela[i][j]
            if gumb not in zaloga_bomb:
                gumb.button.config(fg=tabela_barv[int(gumb.napis)])

#zmaga?
def preveri_zmago():
    if cekiranje_za_zmago.stevilo == 1:
        for i in range(VRSTICE):
            for j in range(STOLPCI):
                if tabela[i][j] not in zaloga_bomb:
                    if tabela[i][j].stanje != pritisnjen:
                        return False
        izracunaj_cas('koncni')
        izracunaj_stevilo_tock()
        izpisi_koncen_napis('zmaga')
        hso.High_score_okno(IME, izracunaj_stevilo_tock(), 'ja')

#konecno odpiranje
def odpri_vse():
    cekiranje_za_zmago.stevilo = 0
    for i in range(VRSTICE):
        for j in range(STOLPCI):
            tabela[i][j].odpri_konec()

#napisi
def izpisi_koncen_napis(izid):
    if izid == 'zmaga':
        napis_konec.config(text='BRAVO, {}!'.format(IME), fg='VioletRed1')
        smajli.config(image=dzek)
        izpisi_cas()
        izpisi_stevilo_tock()
    else:
        prvi = 'Tole pa ni šlo...'
        drugi = 'BUM! Lahko greste med Dunajske dečke.'
        tretji = 'Opala ... Več sreče prihodnjič.'
        cetrti = 'SORČI! Imate še 8 življenj.'
        peti = 'Slaba ... Kar hrabro na naslednje minsko polje.'
        sesti = 'Saj bo več sreče v ljubezni.'
        sedmi = 'Bo pa treba še nekaj žgancev!'
        i = r.randint(0, 6)
        zaloga_napisov = [prvi, drugi, tretji, cetrti, peti, sesti, sedmi]
        napis_konec.config(text=zaloga_napisov[i], fg='VioletRed1')
        smajli.config(image=zalosten)
    napis_konec.pack()

#smajli
def funkcija_smajli():
    if smajli.config('image')[-1] == 'pyimage2' or smajli.config('image')[-1] == 'pyimage4':
        print('Kar ste začeli, to končajte.')
    if smajli.config('image')[-1] == 'pyimage1':
        hso.High_score_okno(IME, izracunaj_stevilo_tock(), True)
    else:
        hso.High_score_okno(IME, izracunaj_stevilo_tock())

#cas - racznanje
def izracunaj_cas(zacetni_ali_koncni):
    cas = strftime("%H %M %S", gmtime())
    razdri = cas.split(' ')
    if zacetni_ali_koncni == 'zacetni':
        cas_zacetek.stevilo = int(razdri[0]) * 3600 + int(razdri[1]) * 60 + int(razdri[2])
    else:
        cas_konec.stevilo = int(razdri[0]) * 3600 + int(razdri[1]) * 60 + int(razdri[2])

#vrne seznam [minute, sekunde]
def cas_igranja(zacetni, koncni):
    cas = koncni - zacetni
    minute = cas // 60
    sekunde = cas % 60
    if minute == 0 and sekunde == 0:
        sekunde = 1
        cas = 1
    CAS.stevilo = cas
    return [minute, sekunde]

#sklanjatve za napis casa in tock
def koncnica(num):
    if num % 100 == 1:
        return 'o'
    elif num % 100 == 2:
        return 'i'
    elif num % 100 in [3, 4]:
        return 'e'
    else:
        return ''

#izpisi cas
def izpisi_cas():
    minute, sekunde = cas_igranja(cas_zacetek.stevilo, cas_konec.stevilo)
    if minute == 0:
        napis_cas.config(text='Igrali ste {} sekund'.format(sekunde) + koncnica(sekunde) + '.')
    else:
        napis_cas.config(text='Igrali ste {} minut'.format(minute) + koncnica(minute) + ' in {} sekund'.format(sekunde) + koncnica(sekunde) + '.')
    napis_cas.pack()

#tocke
def izracunaj_stevilo_tock():
    cas = cas_igranja(cas_zacetek.stevilo, cas_konec.stevilo)
    if BOMBE < VRSTICE * STOLPCI - 3:
        cas = cas[0] * 60 + cas[1]
        if cas < 2:
            return 25
        delez_bomb = BOMBE / (VRSTICE * STOLPCI)
        rezultat = VRSTICE * STOLPCI * (delez_bomb ** 2) / cas
        if VRSTICE * STOLPCI < 100:
            TOCKE.stevilo = int(rezultat * 8000)
            return int(rezultat * 8000)
        else:
            TOCKE.stevilo = int(rezultat * 10000)
            return int(rezultat * 10000)
    else: return 0

#izpisi tocke
def izpisi_stevilo_tock():
    napis_stevilo_tock.config(text='Dosegli ste {} točk'.format(TOCKE.stevilo) + koncnica(TOCKE.stevilo) + '.')
    napis_stevilo_tock.pack()

#gumbi
class Gumb():

    def __init__(self, vrstica, stolpec, napis=None, okno=sp, stanje='zakrit', je_ni_bomba=False):
        self.vrstica = vrstica
        self.stolpec = stolpec
        self.napis = napis
        self.stanje = stanje
        self.je_ni_bomba = je_ni_bomba
        self.button = tk.Button(okno, text='', width=VELIKOST_GUMBA, height=VELIKOST_GUMBA//2, command=self.levi_klik, relief='raised')
        self.button.bind('<Button-3>', self.desni_klik)

    def __repr__(self):
        return 'Gumb ({}, {}, {})'.format(self.vrstica, self.stolpec, self.napis)

    def __str__(self):
        return 'Gumb na ({0}, {1}), z napisom {}'.format(self.vrstica, self.stolpec, self.napis)

    #klice jo naredi_tabelo (zunanja)
    def prikazi(self, okno):
        return self.button.grid(row=self.vrstica, column=self.stolpec)

    #klice jo povej_gumbom_kaj_so (zunanja)
    def bombasto(self):
        if self.je_ni_bomba:
            self.napis = PUF

    #klice jo povej_gumbom_kaj_so (zunanja)
    def poisci_sosednje(self):
        self.sosednji = []
        #vrstica zgoraj
        if not(self.vrstica == 0):
            self.gumb_gor = tabela[self.vrstica - 1][self.stolpec]
            self.sosednji.append(self.gumb_gor)
            if not(self.stolpec == 0):
                self.gumb_levo_gor = tabela[self.vrstica - 1][self.stolpec - 1]
                self.sosednji.append(self.gumb_levo_gor)
            if not(self.stolpec == STOLPCI - 1):
                self.gumb_desno_gor = tabela[self.vrstica - 1][self.stolpec + 1]
                self.sosednji.append(self.gumb_desno_gor)
        #vrstica spodaj
        if not(self.vrstica == VRSTICE - 1):
            self.gumb_dol = tabela[self.vrstica + 1][self.stolpec]
            self.sosednji.append(self.gumb_dol)
            if not(self.stolpec == 0):
                self.gumb_levo_dol = tabela[self.vrstica + 1][self.stolpec - 1]
                self.sosednji.append(self.gumb_levo_dol)
            if not(self.stolpec == STOLPCI - 1):
                self.gumb_desno_dol = tabela[self.vrstica + 1][self.stolpec + 1]
                self.sosednji.append(self.gumb_desno_dol)
        #levi in desni sosed
        if not(self.stolpec == 0):
            self.gumb_levo = tabela[self.vrstica][self.stolpec - 1]
            self.sosednji.append(self.gumb_levo)
        if not(self.stolpec == STOLPCI - 1):
            self.gumb_desno = tabela[self.vrstica][self.stolpec + 1]
            self.sosednji.append(self.gumb_desno)

    #klice jo povej_gumbom_kaj_so (zunanja)
    def poisci_stevilo_bomb(self):
        if not(self.je_ni_bomba):
            num = 0
            for vsak in self.sosednji:
                if vsak.je_ni_bomba:
                    num += 1
            self.napis = str(num)

    #klice jo levi klik, odpir_sosednje
    def levi_klik(self):
        if zacni_steti_cas.stevilo == 1:
            izracunaj_cas('zacetni')
            zacni_steti_cas.stevilo = 0
        if self.stanje == zakrit:
            if self.je_ni_bomba:
                smajli.config(image=zalosten)
                izpisi_koncen_napis('ni slo')
                odpri_vse()
                self.button.config(fg='red')
            else:
                self.spremeni_stanje(pritisnjen)
                if self.napis == '0':
                    self.odpri_sosednje()
                    self.napis = ''
            self.spremeni_stanje(pritisnjen)
        else:
            if self.lahko_odprem_sosednje() == True:
                self.odpri_sosednje()
        preveri_zmago()

    #klice jo desni klik
    def desni_klik(self, random_stvar):
        #self.spremeni_stanje(zastava)
        if self.stanje == zakrit:
            self.spremeni_stanje(zastava)
        elif self.stanje == zastava:
            self.spremeni_stanje(zakrit)

    #klice jo levi_klik
    def odpri_sosednje(self):
        for gumb in self.sosednji:
            if gumb.stanje == zakrit:
                gumb.levi_klik()

    #klice jo levi_klik
    def lahko_odprem_sosednje(self):
        stevec = 0
        for sosed in self.sosednji:
            if sosed.stanje == zastava:
                stevec += 1
        if self.napis == str(stevec):
            return True
        return False

    #klice jo odpri_vse (zunanja)
    def odpri_konec(self):
        if self.stanje == zakrit:
            if not(tabela[self.vrstica][self.stolpec] in zaloga_bomb):
                self.napis = ''
                self.spremeni_stanje(pritisnjen)
                self.button.config(relief='sunken', bg='grey80')
            else:
                self.button.config(text=self.napis, fg='blue', bg='grey83')
                self.button.config(command=self.onesposobi)
        if self.stanje == zastava and not(self.je_ni_bomba):
            self.button.config(text='X', fg='blue')

    #klice jo odpri_konec
    def onesposobi(self):
        return True

    #klice jo odpri_kones, desni_klik, levi_klik
    def spremeni_stanje(self, novo_stanje):
        if novo_stanje == zastava:
            self.stanje = zastava
            self.button.config(text=ZASTAVA, fg='red')
            smajli.config(image=zacuden)
        elif novo_stanje == pritisnjen:
            self.stanje = pritisnjen
            self.button.config(text=self.napis, relief='sunken', bg='grey91')
            if smajli.config('image')[-1] != 'pyimage3':
                smajli.config(image=vesel)
        elif novo_stanje == zakrit:
            self.stanje = zakrit
            self.button.config(text='')
            smajli.config(image=vesel)

#-----------------------------------------------------------------------------------------------------------------

#zgornji napisi za stevilo vrstic, stolpcev in bomb
zgornji_napis_bombe = tk.Label(zg, text='Število bomb: {}'.format(BOMBE))
zgornji_napis_bombe.pack()

#napis in gumb za konec igre
napis_konec = tk.Label(zg, text='', fg='red')

#mreža z gumbi
tabela = naredi_tabelo()
zaloga_bomb = posuj_bombe()
povej_gumbom_kaj_so()
gumbom_prilagodi_barvo()

#smajli
dzek = tk.PhotoImage(file='dzek.png')
vesel = tk.PhotoImage(file='vesel.png')
zalosten = tk.PhotoImage(file='zalosten.png')
zacuden = tk.PhotoImage(file='zacuden.png')

#postavi smajlija
smajli=tk.Button(zg, image=vesel, command=funkcija_smajli)
smajli.pack()

#prazna vrstica
tk.Label(zg, text='').pack()

#cas, tocke
napis_cas = tk.Label(zg, text='')
napis_stevilo_tock = tk.Label(zg, text='')

main_okno.mainloop()


# entrada
valor_numero = int(input('Digite o dois numeros: '))

# processamento
numeroA = valor_numero // 10
numeroB = valor_numero % 10

str_numeroA = str(numeroA)
str_numeroB = str(numeroB)

numero_inverso = str_numeroB + str_numeroA

# saida
print('Ordem inversa: {}'.format(numero_inverso))


from rest_framework import serializers
from .models import Merchant, Store, Item, Order
from silk.profiling.profiler import silk_profile

class MerchantSerializer(serializers.ModelSerializer):

    class Meta:
        model = Merchant
        fields = '__all__'

class StoreSerializer(serializers.ModelSerializer):

    class Meta:
        model = Store
        fields = '__all__'

class ItemSerializer(serializers.ModelSerializer):

    class Meta:
        model = Item
        fields = '__all__'

class OrderSerializerAll(serializers.ModelSerializer):
    '''
    To display all fields in request, whereas for form need to display only certain fields
    '''

    class Meta:
        model = Order
        fields = '__all__'

class OrderSerializer(serializers.ModelSerializer):
    '''
    For form display
    '''

    class Meta:
        model = Order
        # fields = '__all__'
        fields = ('id', 'timestamp', 'status', 'payment_mode',
                  'store', 'merchant', 'items')

    def create(self, validated_data):
        '''
            performing calculation for total price, total items before saving
        '''

        log.msg('Create Order Request', req=self)

        item_set = validated_data.pop('items', [])
        # calculating the total items & total price form the item set sent in payload
        total_items = len(item_set)
        total_price = 0.0
        for item in item_set:
            total_price += float(item.price)

        validated_data['total_items'] = total_items
        validated_data['total_amount'] = total_price

        # creating the order
        order = Order.objects.create(**validated_data)
        for item in item_set:
            order.items.add(item)
        order.save()

        return order

    @silk_profile(name='validate-items-store')
    def validate(self, data):
        '''
            to validate the payload:
                - all items belong to the same merchant
                - store also belong to the same merchant
        '''
        merchant_id = data['merchant'].id

        data_store_merchant_id = data['store'].merchant.id
        # if the store belongs to the merchant that was sent in the data
        if int(data_store_merchant_id) != int(merchant_id):
            raise serializers.ValidationError(
                "Store Does not Belong to the Merchant")

        items_id = []
        for item in data['items']:
            items_id.append(item.id)

        items_with_merchant = Item.objects.filter(
            id__in=items_id).select_related('merchant').all()

        # if all the items belong to the same merchant
        for item in items_with_merchant:
            if int(item.merchant.id) != int(merchant_id):
                raise serializers.ValidationError(
                    "Item Does not Belong to the Merchant")

        return data


import os
from os.path import isdir, exists, abspath, join

import random

import numpy as np
from PIL import Image, ImageEnhance

import torchvision.transforms.functional as TF
import torchvision.transforms

class DataLoader():

    def __init__(self, root_dir='data', batch_size=2, test_percent=0.1):

        img_filepath=[]
        label_filepath = []

        self.batch_size = batch_size
        self.test_percent = test_percent

        self.root_dir = abspath(root_dir)
        self.data_dir = join(self.root_dir,'scans')
        self.labels_dir = join(self.root_dir, 'labels')

        self.files = os.listdir(self.data_dir)

        self.data_files = [join(self.data_dir, f) for f in self.files]
        self.label_files = [join(self.labels_dir, f) for f in self.files]

        #print (self.files)

        #img_filepath = [join(self.data_dir, f) for f in self.files]
        #label_filepath = [join(self.labels_dir, f) for f in self.files]

        #print (self.label_files)

    def __iter__(self):
        n_train = self.n_train()
        img_file_path = self.data_files
        label_file_path = self.label_files

        #print (img_file_path)
        print ('Dataloader')

        if self.mode == 'train':
            current = 0
            endId = n_train
        elif self.mode == 'test':
            current = n_train
            endId = len(self.data_files)

        while current < endId:

            data_image = Image.open(self.data_files[current]) #img_file_path[i]
            label_image = Image.open(self.label_files[current]) #label_file_path[j]

            value = np.random.randint(1,7)
            print ('Value : ', value)

            applyDataAugmentation(data_image, label_image, value)

            #resizing image and label to 388, 388
            data_image=data_image.resize((388,388))
            label_image=label_image.resize((388,388))

            data_image= np.asarray(data_image)
            label_image= np.asarray(label_image)

            data_image = np.pad(data_image, (94,94), 'symmetric')

            data_image = (data_image/255.0)

            #label_image = label_image-1
            #label_image = (label_image/255.0)
            # todo: load images and labels
            # hint: scale images between 0 and 1
            # hint: if training takes too long or memory overflow, reduce image size!

            current += 1

            yield (data_image, label_image)

    def setMode(self, mode):
        self.mode = mode

    def n_train(self):
        data_length = len(self.data_files)
        return np.int_(data_length - np.floor(data_length * self.test_percent))

class applyDataAugmentation():

     def __init__(self, data_image, label_image , value):

        print ('Data Augmentation')
        self.image = data_image
        self.label = label_image
        self.value = value

        if (self.value==1):

            self.image = self.image.transpose(Image.FLIP_LEFT_RIGHT)
            self.label = self.label.transpose(Image.FLIP_LEFT_RIGHT)

        elif (self.value==2):

            self.image = torchvision.transforms.ColorJitter(brightness =0.5, contrast =0.5, saturation = 0.5, hue=0)
            self.label = torchvision.transforms.ColorJitter(brightness =0.5, contrast =0.5, saturation = 0.5, hue=0)
            # enhancer_img = ImageEnhance.Brightness(self.image)
            # enhancer_img = enhancer_img.enhance(2)
            # self.image = enhancer_img

            # enhancer_lb = ImageEnhance.Brightness(self.label)
            # enhancer_lb = enhancer_lb.enhance(2)
            # self.label = enhancer_lb

        elif (self.value==3):
            self.image = self.image.transpose(Image.FLIP_TOP_BOTTOM)
            self.label = self.label.transpose(Image.FLIP_TOP_BOTTOM)

        elif (self.value == 4):
            self.image = self.image.transpose(Image.ROTATE_90)
            self.label = self.label.transpose(Image.ROTATE_90)

        elif (self.value == 5):

            self.image= TF.adjust_gamma(self.image, 1.5 , gain=1)
            self.label = TF.adjust_gamma(self.label, 1.5 , gain=1)

        else:
            self.image = data_image
            self.label = label_image


#!/usr/bin/env python

from greenstreet.API.adam.meta import AdamMetaData

meta_data = AdamMetaData.from_download(
    param={"time_stamp_before": "2016-04-20",
           "time_stamp_after": "2016-04-01",
           "limit_results": 10,
           "page_size": 5})

print(meta_data.coordinates())
print(meta_data.timestamps())

meta_data.to_file("meta.json")

meta_data2 = AdamMetaData.from_file("meta.json")
print(meta_data2.timestamps())
meta_data2.to_file(meta_fp="meta2.json")

print(type(meta_data.meta_timestamp))
print(type(meta_data2.meta_timestamp))


from service.schema.ticket import TicketDetailsModel, TicketModel
from service.schema.user import User
from service.util import user as user_util
from service.util import ticket as ticket_util
from service.util.dependencies import get_current_user
from service.util.websocket import manager as manager
from fastapi import APIRouter, Depends, HTTPException, status

router = APIRouter()

@router.post(
    "", response_model=TicketDetailsModel, status_code=201, name="create ticket"
)
async def create_ticket(
    ticket: TicketModel, current_user: User = Depends(get_current_user)
):
    ticket = await ticket_util.create_ticket(ticket)
    return ticket

@router.get("")
async def get_tickets(page: int = 1, current_user: User = Depends(get_current_user)):
    total_cout = await ticket_util.get_tickets_count()
    ticket = await ticket_util.get_tickets(page)
    return {"total_count": total_cout, "results": ticket}

@router.get("/{ticket_id}", response_model=TicketDetailsModel, name="get ticket by id")
async def get_ticket(ticket_id: int, current_user: User = Depends(get_current_user)):
    return await ticket_util.get_ticket(ticket_id)

@router.put("/{ticket_id}", response_model=TicketDetailsModel)
async def update_ticket(
    ticket_id: int, ticket: TicketModel, current_user: User = Depends(get_current_user)
):
    ticket = await ticket_util.update_ticket(ticket_id, ticket)

    await manager.broadcast([ticket])

    return ticket

@router.delete("/{from_id}", name="remove ticket by id")
async def delete_tickets(from_id: int, current_user: User = Depends(get_current_user)):

    await ticket_util.delete_tickets(from_id)
    await user_util.update_user_stats(current_user["id"])

    # return all tickets from ticket_util
    tickets = await ticket_util.get_tickets(page=1)
    await manager.broadcast(tickets)


# データのロード
import numpy as np
import tensorflow.keras as keras
from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Activation
from tensorflow.keras.models import Sequential
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.datasets import mnist
from sklearn.model_selection import train_test_split
from tensorflow.keras.preprocessing.image import ImageDataGenerator

(x_train, y_train), (x_test, y_test) = mnist.load_data()

# データの整形
x_train = x_train.astype('float32') / 255
y_train = np.eye(10)[y_train.astype('int32').flatten()]

x_test = x_test.astype('float32') / 255
y_test = np.eye(10)[y_test.astype('int32').flatten()]

x_train, x_valid, y_train, y_valid = train_test_split(
    x_train, y_train, test_size=10000)

# 4次元にしておかないと、
# model.fitのときに下記エラーが出てきてしまう
# ValueError: ('Input data in `NumpyArrayIterator`
# should have rank 4. You passed an array with shape', (50000, 28, 28))
x_test = x_test.reshape(-1, 28, 28, 1)
x_train = x_train.reshape(-1, 28, 28, 1)
x_valid = x_valid.reshape(-1, 28, 28, 1)

# モデル構築
model = Sequential()

# 28x28x3 -> 28x28x6
model.add(Conv2D(6, kernel_size=(5, 5), activation='relu',
                 kernel_initializer='he_normal', input_shape=(28, 28, 1)))
# 28x28x6 -> 14x14x6
model.add(MaxPooling2D(pool_size=(2, 2)))
# 14x14x6 -> 10x10x16
model.add(Conv2D(16, kernel_size=(5, 5), activation='relu',
                 kernel_initializer='he_normal'))
# 10x10x16 -> 5x5x16
model.add(MaxPooling2D(pool_size=(2, 2)))
# 5x5x16 -> 400
model.add(Flatten())
# 400 -> 120
model.add(Dense(120, activation='relu',
                kernel_initializer='he_normal'))
# 120 ->84
model.add(Dense(84, activation='relu', kernel_initializer='he_normal'))
# 84 ->10
model.add(Dense(10, activation='softmax'))

model.compile(
    loss=keras.losses.categorical_crossentropy,
    optimizer='adam',
    metrics=['accuracy']
)

# データのかさまし
datagen = ImageDataGenerator(
    width_shift_range=0.2,  # 3.1.1 左右にずらす
    height_shift_range=0.2,  # 3.1.2 上下にずらす
    horizontal_flip=True,  # 3.1.3 左右反転
    # 3.2.1 Global Contrast Normalization (GCN) (Falseに設定しているのでここでは使用していない)
    samplewise_center=False,
    samplewise_std_normalization=False,
    zca_whitening=False)  # 3.2.2 Zero-phase Component Analysis (ZCA) Whitening (Falseに設定しているのでここでは使用していない)

# 学習
model.fit(datagen.flow(x_train, y_train, batch_size=100),
          steps_per_epoch=x_train.shape[0] // 100, epochs=30, validation_data=(x_valid, y_valid))

# 性能評価
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

# 予測
input_data = []
input_data.append(x_test[100])
input_data = np.asarray(input_data)
print(model.predict(input_data))

# モデルの保存
model.save('cnn_model.h5', include_optimizer=True)


#!/usr/bin/env python
import os

from flask import Flask, send_file
from flask_restful import Api
from flask_cors import CORS

from classes.config import config

app = Flask(__name__)
app.config.from_mapping(config)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
api = Api(app)

from resources.card import CardListResource, CardResource
from resources.link import LinkListResource, LinkResource
from resources.tag import TagListResource, TagResource
from resources.cardtag import CardTagResource, CardTagListResource
from resources.cardtag import TagCardResource, TagCardListResource

api.add_resource(CardListResource, '/api/cards', endpoint='cards')
api.add_resource(CardResource, '/api/cards/<string:id>', endpoint='card')

api.add_resource(LinkListResource, '/api/links', endpoint='links')
api.add_resource(LinkResource, '/api/links/<string:id>', endpoint='link')

api.add_resource(TagListResource, '/api/tags', endpoint='tags')
api.add_resource(TagResource, '/api/tags/<string:id>', endpoint='tag')

api.add_resource(CardTagListResource, '/api/cards/<string:card_id>/tags', endpoint='cardtags')
api.add_resource(CardTagResource, '/api/cards/<string:card_id>/tags/<string:tag_id>', endpoint='cardtag')

api.add_resource(TagCardListResource, '/api/tags/<string:tag_id>/cards', endpoint='tagcards')
api.add_resource(TagCardResource, '/api/tags/<string:tag_id>/cards/<string:card_id>', endpoint='tagcard')

# Everything not declared before (not a Flask route / API endpoint)...
@app.route("/<path:path>")
def route_frontend(path):
    # ...could be a static file needed by the front end that
    # doesn't use the `static` path (like in `<script src="bundle.js">`)
    file_path = os.path.join(app.static_folder, path)
    if os.path.isfile(file_path):
        return send_file(file_path)
    # ...or should be handled by the SPA's "router" in front end
    else:
        index_path = os.path.join(app.static_folder, "index.html")
        return send_file(index_path)

if __name__ == '__main__':
    app.run(port=44343, debug=True)


#!/usr/bin/env python3
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType,StructField, StringType, IntegerType, DateType, FloatType
from pyspark.sql.functions import from_json
from pyspark.sql.window import Window
from pyspark.sql.functions import rank, col

spark = SparkSession.builder \
    .appName("ccc_task2_g3q2") \
    .enableHiveSupport() \
    .getOrCreate()

ds = (spark
      .readStream
      .format("kafka")
      .option("kafka.bootstrap.servers", "b-1.cs598task2kafkacluster.cw1k16.c1.kafka.us-east-1.amazonaws.com:9092,b-2.cs598task2kafkacluster.cw1k16.c1.kafka.us-east-1.amazonaws.com:9092")
      .option("subscribe", "cs598task2topic")
      .option("startingOffsets", "earliest")
      .load().selectExpr("CAST(value AS STRING)"))

ds.printSchema()

schema = StructType([     StructField("Year",StringType(),True),
                          StructField("Month",StringType(),True),
                          StructField("DayofMonth", StringType(), True),
                          StructField("DayOfWeek", StringType(), True),
                          StructField("FlightDate", DateType(), True),
                          StructField("UniqueCarrier",StringType(),True),
                          StructField("FlightNum",StringType(),True),
                          StructField("Origin",StringType(),True),
                          StructField("Dest", StringType(), True),
                          StructField("CRSDepTime", StringType(), True),
                          StructField("DepDelay",StringType(),True),
                          StructField("ArrDelay", StringType(), True),
                          StructField("Cancelled", StringType(), True)     ])

# Create dataframe setting schema for event data
df_aviation = ds.withColumn("value", from_json("value", schema))

df_aviation = df_aviation \
    .withColumn("Year", df_aviation["value.Year"].cast(IntegerType())) \
    .withColumn("Month", df_aviation["value.Month"].cast(IntegerType())) \
    .withColumn("DayOfMonth", df_aviation["value.DayOfMonth"].cast(IntegerType())) \
    .withColumn("DayOfWeek", df_aviation["value.DayOfWeek"].cast(IntegerType())) \
    .withColumn("FlightDate", df_aviation["value.FlightDate"].cast(DateType())) \
    .withColumn("UniqueCarrier", df_aviation["value.UniqueCarrier"].cast(StringType())) \
    .withColumn("FlightNum", df_aviation["value.FlightNum"].cast(IntegerType())) \
    .withColumn("Origin", df_aviation["value.Origin"].cast(StringType())) \
    .withColumn("Dest", df_aviation["value.Dest"].cast(StringType())) \
    .withColumn("CRSDepTime", df_aviation["value.CRSDepTime"].cast(IntegerType())) \
    .withColumn("DepDelay", df_aviation["value.DepDelay"].cast(FloatType())) \
    .withColumn("ArrDelay", df_aviation["value.ArrDelay"].cast(FloatType())) \
    .withColumn("Cancelled", df_aviation["value.Cancelled"].cast(FloatType()))

df_aviation.printSchema()

df_aviation_g3q2 = df_aviation.select('Year', 'Month', 'DayOfMonth', 'FlightDate', 'UniqueCarrier',
                                      'FlightNum', 'Origin', 'Dest', 'CRSDepTime', 'ArrDelay', 'Cancelled')

(df_aviation_g3q2.filter(df_aviation_g3q2["Year"] == 2008)
 .filter(df_aviation_g3q2['ArrDelay'].isNotNull())
 .createOrReplaceTempView("aviation"))

df1 = spark.sql("select concat(lpad(DayOfMonth, 2, '0'), '/', lpad(Month, 2, '0'),'/', Year) as StartDate, \
                 Origin, Dest, UniqueCarrier, FlightNum, FlightDate, CRSDepTime, ArrDelay \
                 from aviation where CRSDepTime < 1200")

df2 = spark.sql("select concat(lpad(DayOfMonth, 2, '0'), '/', lpad(Month, 2, '0'),'/', Year) as StartDate, \
                 Origin, Dest, UniqueCarrier, FlightNum, FlightDate, CRSDepTime, ArrDelay \
                 from aviation where CRSDepTime > 1200")

def for_each_batch_df1(df, epoch_id):
    window = Window.partitionBy(df['Origin'], df['Dest'], df['StartDate']).orderBy(df['ArrDelay'])
    ranked_df = df.select('*', rank().over(window).alias('rank'))
    rs = (ranked_df.filter(col('rank') == 1).select(df['*']))
    rs.write.mode("append").saveAsTable("g3_q2_a")

def for_each_batch_df2(df, epoch_id):
    window = Window.partitionBy(df['Origin'], df['Dest'], df['StartDate']).orderBy(df['ArrDelay'])
    ranked_df = df.select('*', rank().over(window).alias('rank'))
    rs = (ranked_df.filter(col('rank') == 1).select(df['*']))
    rs.write.mode("append").saveAsTable("g3_q2_b")

query1 = df1 \
    .writeStream \
    .outputMode("append") \
    .foreachBatch(for_each_batch_df1) \
    .start()

query2 = df2 \
    .writeStream \
    .outputMode("append") \
    .foreachBatch(for_each_batch_df2) \
    .start()

query1.awaitTermination()
query2.awaitTermination()

spark.sql("CREATE TABLE IF NOT EXISTS g3_q2 USING hive as select concat(a.Origin, '-', a.Dest, '-', b.Dest) as XYZ, \
a.StartDate, \
(a.ArrDelay + b.ArrDelay) as TotalArrDelay, \
a.Origin as FirstLeg_Origin, \
a.Dest as FirstLeg_Destn, \
concat(a.UniqueCarrier, ' ', a.FlightNum) as FirstLeg_AirlineFlightNum, \
concat(a.FlightDate, ' ', a.CRSDepTime) as FirstLeg_SchedDepart, \
a.ArrDelay as FirstLeg_ArrDelay, \
b.Origin as SecondLeg_Origin, \
b.Dest as SecondLeg_Destn, \
concat(b.UniqueCarrier, ' ', b.FlightNum) as SecondLeg_AirlineFlightNum, \
concat(b.FlightDate, ' ', b.CRSDepTime) as SecondLeg_SchedDepart, \
b.ArrDelay as SecondLeg_ArrDelay \
from \
(select StartDate, Origin, Dest, UniqueCarrier, FlightNum, FlightDate, CRSDepTime, ArrDelay, \
 row_number() over (partition by Origin, Dest, StartDate order by ArrDelay) as Seqnum \
 from g3_q2_a) a \
join \
(select StartDate, Origin, Dest, UniqueCarrier, FlightNum, FlightDate, CRSDepTime, ArrDelay, \
 row_number() over (partition by Origin, Dest, StartDate order by ArrDelay) as Seqnum \
 from g3_q2_b) b \
on a.Dest = b.Origin and date_add(a.FlightDate, 2) = b.FlightDate and a.Seqnum = 1 and b.Seqnum = 1 ")