# -*- coding: utf-8 -*-
# __author__ = 'linna'
from biocluster.agent import Agent
from biocluster.tool import Tool
from biocluster.core.exceptions import OptionError
import pandas as pd
import os

class PcoaAgent(Agent):
    METHOD = ['abund_jaccard', 'binary_chisq', 'binary_chord',
              'binary_euclidean', 'binary_hamming', 'binary_jaccard',
              'binary_lennon', 'binary_ochiai',
              'binary_pearson', 'binary_sorensen_dice',
              'bray_curtis', 'bray_curtis_faith', 'bray_curtis_magurran',
              'canberra', 'chisq', 'chord', 'euclidean', 'gower',
              'hellinger', 'kulczynski', 'manhattan', 'morisita_horn',
              'pearson', 'soergel', 'spearman_approx', 'specprof']

    def __init__(self, parent):
        super(PcoaAgent, self).__init__(parent)
        options = [
            {"name": "tooltable", "type": "infile", "format": "tool_lab.table"},
            {"name": "specimen_name", "type": "string", "default": "column"},
            {"name": "group_table", "type": "infile", "format": "toolapps.group_table"},
            {"name": "scale", "type": "string", "default": "False"},
            {"name": "dis_method", "type": "string", "default": "bray_curtis"},
            {"name": "main_id", "type": "string"},
            {"name": "update_info", "type": "string"}
        ]
        self.add_option(options)

    def check_options(self):
        """
        参数检查
        """
        if not self.option('tooltable').is_set:
            raise OptionError('必须提供数据表', code="32702903")
        self.option('tooltable').get_info()
        if self.option('tooltable').prop['sample_num'] < 3:
            raise OptionError('列数少于3，不可进行分析', code="32702904")
        if self.option('dis_method') not in PcoaAgent.METHOD:
            raise OptionError('错误或者不支持该距离矩阵计算方法', code="32701903")
        # if self.option('group_table').is_set:
        #     if self.option('specimen_name') == 'column':
        #         for i in self.option('group_table').prop['sample_name']:
        #             if i not in self.option('tooltable').prop['col_sample']:
        #                 raise OptionError('分组文件中的样本不存在于表格中，查看是否数据选择错误', code="32702909")
        #     else:
        #         for i in self.option('group_table').prop['sample_name']:
        #             if i not in self.option('tooltable').prop['row_sample']:
        #                 raise OptionError('分组文件中的样本不存在于表格中，查看是否数据选择错误', code="32702910")
        return True

    def set_resource(self):
        """
        设置所需资源
        """
        self._cpu = 5
        self._memory = '10G'

    def end(self):
        if self.option('group_table').is_set:
            result_dir = self.add_upload_dir(self.output_dir)
            result_dir.add_relpath_rules([
                [".", "", "PCoA分析结果输出目录"],
                ["./pcoa_eigenvalues.xls", "xls", "矩阵特征值"],
                ["./pcoa_eigenvaluespre.xls", "xls", "特征解释度百分比"],
                ["./pcoa_sites.xls", "xls", "样本坐标表"],
                ["./group.xls", "xls", "分组表"],
                ["./ellipse.xls", "xls", "分组椭圆数据"]
            ])
            result_dir.add_regexp_rules([
                [r'%s.*\.xls' % self.option('dis_method'), 'xls', '样本距离矩阵文件']
            ])
        else:
            result_dir = self.add_upload_dir(self.output_dir)
            result_dir.add_relpath_rules([
                [".", "", "PCoA分析结果输出目录"],
                ["./pcoa_eigenvalues.xls", "xls", "矩阵特征值"],
                ["./pcoa_eigenvaluespre.xls", "xls", "特征解释度百分比"],
                ["./pcoa_sites.xls", "xls", "样本坐标表"],
            ])
            result_dir.add_regexp_rules([
                [r'%s.*\.xls' % self.option('dis_method'), 'xls', '样本距离矩阵文件']
            ])
        super(PcoaAgent, self).end()

class PcoaTool(Tool):
    def __init__(self, config):
        super(PcoaTool, self).__init__(config)
        self.cmdpath = 'miniconda2/bin/beta_diversity.py'
        self.biom_path = 'miniconda2/bin/'
        self.set_environ(LD_LIBRARY_PATH=self.config.SOFTWARE_DIR + '/gcc/5.1.0/lib64')
        self.perl_path = "program/perl-5.24.0/bin/perl"
        self.cmd_path = self.config.PACKAGE_DIR + '/statistical/ordinationdis.pl'
        self.cmd1_path = self.config.PACKAGE_DIR + '/statistical/ordination2.pl'
        self.script_path = "bioinfo/meta/scripts/beta_diver.sh"
        self.R_path = os.path.join(self.config.SOFTWARE_DIR, 'program/R-3.3.1/bin/R')
        self.R_path1 = '/program/R-3.3.1/bin/'
        self.ellipse_path = self.config.PACKAGE_DIR + '/graph/scripts/Ellipse.R'

    def run(self):
        """
        运行
        """
        super(PcoaTool, self).run()
        self.convert_to_biom()
        self.run_beta_diversity()
        self.run_ordination()
        self.linkfile()
        # self.set_db()
        self.end()

    def formattable(self, tablepath):
        """
        转置表格
        """
        this_table = tablepath
        if self.option('specimen_name') != 'column':
            newtable = this_table + '.T'
            self.t_table(this_table, newtable)
            return newtable
        else:
            return this_table

    def t_table(self, table_file, new_table):
        """
        转置表格实现
        """
        with open(table_file) as f, open(new_table, 'w') as w:
            table_list = [i.rstrip().split('\t') for i in f.readlines()]
            table_list = map(lambda *a: '\t'.join(a) + '\n', *table_list)
            w.writelines(table_list)

    def run_beta_diversity(self):
        """
        运行qiime:beta_diversity.py
        """
        cmd = self.cmdpath
        cmd += ' -m %s -i %s -o %s' % (self.option('dis_method'), self.output_dir + '/temp.biom', self.work_dir)
        self.logger.info('运行qiime:beta_diversity.py程序')
        self.logger.info(cmd)
        dist_matrix_command = self.add_command('distance_matrix', cmd)
        dist_matrix_command.run()
        self.wait()
        if dist_matrix_command.return_code == 0:
            self.command_successful()
        else:
            self.set_error("运行qiime:beta_diversity.py出错", code="32701901")

    def command_successful(self):
        self.logger.info('运行qiime:beta_diversity.py完成')
        filename = self.work_dir + '/' + self.option('dis_method') + '_temp.txt'
        linkfile = self.output_dir + '/distance.xls'
        if os.path.exists(linkfile):
            os.remove(linkfile)
        os.link(filename, linkfile)
        self.dis_matrix_check(linkfile)

    def dis_matrix_check(self, linkfile):
        """聚类矩阵结果检查"""
        self.logger.info("开始进行距离矩阵检查")
        dist_dict = dict()
        all_values = []
        with open(linkfile, 'r') as f:
            head = f.readline().rstrip().split('\t')
            head_len = len(head)
            head = head[1:]
            for line in f:
                all_nums = line.rstrip().split('\t')
                if len(all_nums) != head_len:
                    self.set_error('距离矩阵每行数据量格式不正确', code="32701903")
                values = dict(zip(head, all_nums[1:]))
                all_values.extend(all_nums[1:])
                dist_dict[all_nums[0]] = values
            for samp1 in head:
                for samp2 in head:
                    if dist_dict[samp1][samp2] != dist_dict[samp2][samp1]:
                        self.set_error('距离矩阵数据不对称', code="32701904")
            all_values = [float(i) for i in all_values]
            all_plus = sum(all_values)
            if all_plus == 0 and len(all_values) > 1:  # 只有一个样本时距离就为零，不做处理，但是后续不能做任何分析
                self.set_error('所有距离矩阵值全部为零', code="32701905")
            if len(head) != len(set(head)):
                self.set_error('距离矩阵存在重复的样本名', code="32701906")
        self.logger.info("距离矩阵检查正确")

    def convert_to_biom(self):
        """
        转换为biom格式
        """
        cmd = self.biom_path
        biom_filepath = os.path.join(self.work_dir, 'temp.biom')
        cmd += 'biom convert -i %s -o %s --table-type="OTU table" --to-hdf5' % \
               (self.formattable(self.option('tooltable').path), biom_filepath)
        self.logger.info('运行biom.py程序')
        self.logger.info(cmd)
        biom_command = self.add_command('biom', cmd)
        biom_command.run()
        self.wait()
        if biom_command.return_code == 0:
            self.logger.info('运行biom.py完成')
            linkfile = self.output_dir + '/temp.biom'
            if os.path.exists(linkfile):
                os.remove(linkfile)
            os.link(biom_filepath, linkfile)
        else:
            self.set_error("运行biom.py出错", code="32701901")

    def run_ordination(self, cmd1='cmd', cmd2='pcoa'):
        """
        运行ordinationdis.pl计算pcoa
        """
        if self.option('scale') == "True":
            scale = "T"
        else:
            scale = "F"
        if self.option('group_table').is_set:
            cmd = '{} {} -type pcoa -dist {} -outdir {} -scale {} -group {}'.format(
                self.perl_path, self.cmd_path, self.output_dir + '/distance.xls', self.work_dir, scale,
                self.option('group_table').path)
        else:
            dis_table = pd.read_table(self.output_dir + '/distance.xls')
            # 这里没有分组时，调用的脚本不会画椭圆，所以创建一个分组文件，每个样本的分组名都为All
            group_table = pd.DataFrame()
            group_table["name"] = dis_table[list(dis_table.columns)[0]]
            group_table["group"] = "All"
            group_table.to_csv(self.work_dir + "/sample.xls", index=0, sep="\t")
            cmd = '{} {} -type pcoa -dist {} -outdir {} -scale {} -group {}'.format(
                self.perl_path, self.cmd_path, self.output_dir + '/distance.xls', self.work_dir, scale,
                self.work_dir + "/sample.xls")
        self.logger.info('运行ordinationdis.pl程序')
        self.logger.info(cmd)
        cmd1 = self.add_command(cmd1, cmd).run()  # 命令1运行
        self.wait(cmd1)
        if cmd1.return_code == 0:
            self.logger.info('生成 cmd.r 文件成功')
        else:
            self.logger.info('生成 cmd.r 文件失败')
            self.set_error('无法生成 cmd.r 文件', code="32702902")
        cmd_ = self.script_path + ' %s %s' % (self.R_path, self.work_dir + "/cmd.r")
        self.logger.info(cmd_)
        cmd2 = self.add_command(cmd2, cmd_).run()  # 命令2 运行
        self.wait(cmd2)
        if cmd2.return_code == 0:
            self.logger.info('pcoa计算成功')
        else:
            self.logger.info('pcoa计算失败')
            self.set_error('R程序计算pcoa失败', code="32702903")
        self.logger.info('运行ordinationdis.pl程序计算pcoa完成')

    def format_eigenvalues(self, fp, new_fp):
        with open(fp) as f, open(new_fp, 'w') as w:
            w.write(f.readline())
            for i in f:
                w.write('PC' + i)
        return new_fp

    def format_header(self, old):
        with open(old) as f, open(self.work_dir + '/pcoa_sites.xls', 'w') as w:
            headers = f.readline().rstrip().split('\t')[1:]
            for header in headers:
                if header[0] != 'V':
                    self.set_error('pcoa结果不正确或者不规范', code="32703003")
                num = header[1:]
                if not num.isdigit():
                    self.set_error('pcoa结果不正确或者不规范', code="32703003")
            news = ['PC' + i[1:] for i in headers]
            news = [''] + news
            new_header = 'Name'+'\t'.join(news) + '\n'
            w.write(new_header)
            for i in f:
                w.write(i)
        return self.work_dir + '/pcoa_sites.xls'

    def linkfile(self):
        if self.option('group_table').is_set:
            group_file = self.option('group_table').path
            group_link = self.output_dir + '/group.xls'
            if os.path.exists(group_link):
                os.remove(group_link)
            os.link(group_file, group_link)
            basename = os.path.basename(self.output_dir + '/distance.xls')
            basename1, basename2 = basename.split('.')
            eig_file = self.work_dir + '/pcoa' + '/' + basename1 + '_' + basename2 + '_' + 'pcoa_eigenvalues.xls'
            eigenvalues = self.format_eigenvalues(eig_file, self.work_dir + '/pcoa_eigenvalues.xls')
            eig_link = self.output_dir + '/pcoa_eigenvalues.xls'
            if os.path.exists(eig_link):
                os.remove(eig_link)
            os.link(eigenvalues, eig_link)
            pre_file = self.work_dir + '/pcoa' + '/' + basename1 + '_' + basename2 + '_' + 'pcoa_eigenvaluespre.xls'
            eigenvaluespre = self.format_eigenvalues(pre_file, self.work_dir + '/pcoa_eigenvaluespre.xls')
            pre_link = self.output_dir + '/pcoa_eigenvaluespre.xls'
            if os.path.exists(pre_link):
                os.remove(pre_link)
            os.link(eigenvaluespre, pre_link)
            site_file = self.work_dir + '/pcoa' + '/' + basename1 + '_' + basename2 + '_' + 'pcoa_sites.xls'
            sites_file = self.format_header(site_file)
            site_link = self.output_dir + '/pcoa_sites.xls'
            if os.path.exists(site_link):
                os.remove(site_link)
            os.link(sites_file, site_link)
            ellipse_file = self.work_dir + "/pcoa" + "/" + "ellipse.xls"
            ellipse_link = self.output_dir + '/ellipse.xls'
            if os.path.exists(ellipse_link):
                os.remove(ellipse_link)
            os.link(ellipse_file, ellipse_link)
        else:
            basename = os.path.basename(self.output_dir + '/distance.xls')
            basename1, basename2 = basename.split('.')
            eig_file = self.work_dir + '/pcoa' + '/' + basename1 + '_' + basename2 + '_' + 'pcoa_eigenvalues.xls'
            eigenvalues = self.format_eigenvalues(eig_file, self.work_dir + '/pcoa_eigenvalues.xls')
            eig_link = self.output_dir + '/pcoa_eigenvalues.xls'
            if os.path.exists(eig_link):
                os.remove(eig_link)
            os.link(eigenvalues, eig_link)
            pre_file = self.work_dir + '/pcoa' + '/' + basename1 + '_' + basename2 + '_' + 'pcoa_eigenvaluespre.xls'
            eigenvaluespre = self.format_eigenvalues(pre_file, self.work_dir + '/pcoa_eigenvaluespre.xls')
            pre_link = self.output_dir + '/pcoa_eigenvaluespre.xls'
            if os.path.exists(pre_link):
                os.remove(pre_link)
            os.link(eigenvaluespre, pre_link)
            site_file = self.work_dir + '/pcoa' + '/' + basename1 + '_' + basename2 + '_' + 'pcoa_sites.xls'
            sites_file = self.format_header(site_file)
            site_link = self.output_dir + '/pcoa_sites.xls'
            if os.path.exists(site_link):
                os.remove(site_link)
            os.link(sites_file, site_link)
            ellipse_file = self.work_dir + "/pcoa" + "/" + "ellipse.xls"
            ellipse_link = self.output_dir + '/ellipse.xls'
            if os.path.exists(ellipse_link):
                os.remove(ellipse_link)
            os.link(ellipse_file, ellipse_link)

    def set_db(self):
        self.logger.info("开始导表")
        api_pcoa = self.api.api('wgs_v2.pcoa')
        api_pcoa.add_pcoa(self.option('main_id'), self.output_dir)
        self.logger.info("导表结束")


"""
Given a string s containing just the characters
'(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
"""

class Solution:
    parentheses = {
        "(": ")",
        "[": "]",
        "{": "}",
    }

    def is_valid(self, s: str) -> bool:
        if len(s) <= 1:
            return False

        stack = []
        for p in s:
            if p in self.parentheses:
                stack.append(p)
            elif len(stack) != 0:
                removed_p = stack.pop()
                if p != self.parentheses[removed_p]:
                    return False
            else:
                return False

        if len(stack) != 0:
            return False

        return True


#!/usr/bin/env python
import cv2

image = cv2.imread("newport.png")
cv2.imshow("original", image)

sliced = image[240:380, 550:742]

cv2.imshow("Sliced", sliced)

cv2.waitKey(0)
cv2.destroyAllWindows()


import json, os, threading
from locust import HttpLocust, TaskSet, task
from datetime import datetime

serverScheme = "@@SERVER_SCHEME@@"
serverHost = "@@SERVER_HOST@@"
authPort = "@@AUTH_PORT@@"

_users = -1
_userTokens = []
_userRefreshTokens = []
_currentUser = 0
_userLock = threading.RLock()

usenv = os.getenv("USER_TOKENS")
lines = usenv.split('\n')

_users = len(lines)

for u in lines:
	up = u.split(';')
	_userTokens.append(up[0])
	_userRefreshTokens.append(up[1])

class TokenBehavior(TaskSet):

	taskUser = -1
	taskUserId = ""
	taskUserName = ""
	taskUserToken = ""
	taskUserRefreshToken = ""

	def on_start(self):
		global _currentUser, _users, _userLock, _userTokens, _userRefreshTokens
		_userLock.acquire()
		self.taskUser = _currentUser
		if _currentUser < _users - 1:
			_currentUser += 1
		else:
			_currentUser = 0
		_userLock.release()
		self.taskUserToken = _userTokens[self.taskUser]
		self.taskUserRefreshToken = _userRefreshTokens[self.taskUser]
		self.authUser()

	@task
	def authUser(self):
		response = self.client.get("/api/user", headers = {"Authorization" : "Bearer " + self.taskUserToken}, name = "auth-api-user", catch_response = True)
		content = response.content
		try:
			resp_json = response.json()
			if not response.ok:
				response.failure("Got wrong response: [" + content + "]")
			else:
				self.taskUserName = resp_json["data"]["attributes"]["username"]
				self.taskUserId = resp_json["data"]["attributes"]["identityID"]
				response.success()
		except ValueError:
			response.failure("Got wrong response: [" + content + "]")

	@task
	def userById(self):
		response = self.client.get("/api/users/" + self.taskUserId, name="api-user-by-id", catch_response = True)
		content = response.content
		try:
			resp_json = response.json()
			if not response.ok:
				response.failure("Got wrong response: [" + content + "]")
			else:
				response.success()
		except ValueError:
			response.failure("Got wrong response: [" + content + "]")

	@task
	def userByName(self):
		response = self.client.get("/api/users?filter[username]=" + self.taskUserName, name="api-user-by-name", catch_response = True)
		content = response.content
		try:
			resp_json = response.json()
			if not response.ok:
				response.failure("Got wrong response: [" + content + "]")
			else:
				response.success()
		except ValueError:
			response.failure("Got wrong response: [" + content + "]")

	@task
	def authRefreshToken(self):
		response = self.client.post("/api/token/refresh", data="{\"refresh_token\":\"" + self.taskUserRefreshToken+ "\" }", headers = {"Authorization" : "Bearer " + self.taskUserToken, "Content-Type" : "application/json"}, name="auth-api-token-refresh", catch_response = True)
		content = response.content
		try:
			resp_json = response.json()
			if not response.ok:
				response.failure("Got wrong response: [" + content + "]")
			else:
				response.success()
		except ValueError:
			response.failure("Got wrong response: [" + content + "]")

	@task
	def refreshToken(self):
		response = self.client.post("/api/token/refresh", data="{\"refresh_token\":\"" + self.taskUserRefreshToken+ "\" }", headers = {"Content-Type" : "application/json"}, name="api-token-refresh", catch_response = True)
		content = response.content
		try:
			resp_json = response.json()
			if not response.ok:
				response.failure("Got wrong response: [" + content + "]")
			else:
				response.success()
		except ValueError:
			response.failure("Got wrong response: [" + content + "]")

	@task
	def refreshTokenGrantType(self):
		response = self.client.post("/api/token", json={"grant_type":"refresh_token","client_id": "740650a2-9c44-4db5-b067-a3d1b2cd2d01", "refresh_token": self.taskUserRefreshToken, "scope": "openid"}, headers = {"Content-Type" : "application/json"}, name="api-token-refresh-grant-type", catch_response = True)
		content = response.content
		try:
			resp_json = response.json()
			if not response.ok:
				response.failure("Got wrong response: [" + content + "]")
			else:
				response.success()
		except ValueError:
			response.failure("Got wrong response: [" + content + "]")

	@task
	def githubToken(self):
		response = self.client.get("/api/token?for=https://github.com", headers= {"Authorization" : "Bearer " + self.taskUserToken}, name = "auth-api-user-github-token", catch_response = True)
		content = response.content
		try:
			resp_json = response.json()
			if not response.ok:
				response.failure("Got wrong response: [" + content + "]")
			else:
				response.success()
		except ValueError:
			response.failure("Got wrong response: [" + content + "]")

class TokenUser(HttpLocust):
	host = serverScheme + "://" + serverHost + ":" + authPort
	task_set = TokenBehavior
	min_wait = 1000
	max_wait = 1000


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 12 17:20:29 2022

@author: ainish
"""

import IOFunctions as io

class SwimmingClub:
    def __init__(self, Data = None):
        self.Data       = Data
        self.AllSlots   = []
        self.Overlap    = []
        self.TotalSlots = 0
        self.MaxCoverage = 0
        return

    def GetRawData(self,Data):
        self.Data = Data
        return

    def TotalSlotsCovered(self):
        '''
        Member function in SwimmingClub to calculate the total number of slots
        that are covered by all available guards.
        Returns
        -------
        None.
        '''

        for slot in self.AllSlots:
            START = 0
            STOP  = 1
            self.TotalSlots = self.TotalSlots + slot[STOP]-slot[START]+1

        return

    def CheckCoverage(self):
        '''
        Member function that generates a list of all slots covered when all guards are available
        The function creates a list of time slots, where each slot consists of contiguous intervals covered
        Disparate slots lead to generation of a new interval

        In addition, the function also creates a list of slots that have more than over guard covering the slot

        Returns
        -------
        None.

        '''
        for slot in self.Data:
            overlap = []
            START   = 0
            STOP    = 1
            LAST    = -1
            ''' Add Slots to all coverage '''
            try:

                if slot[START] > self.AllSlots[LAST][STOP]+1:
                    ''' If New Slot begins after current ends, there is no overlap add to All coverage '''
                    self.AllSlots.append(slot.copy())

                else:
                    ''' In case there is coverage, first check if there is any overlap '''
                    overlap = [slot[START], min(self.AllSlots[LAST][STOP], slot[STOP])]
                    if overlap[START]<=overlap[STOP]:
                        try:
                            if overlap[START] > self.Overlap[LAST][STOP]+1:
                                self.Overlap.append(overlap)
                            else:
                                self.Overlap[LAST][STOP] = max(self.Overlap[LAST][STOP], overlap[STOP])
                        except:
                            self.Overlap.append(overlap)

                    self.AllSlots[LAST][STOP] = max(self.AllSlots[LAST][STOP], slot[STOP])
            except:
                self.AllSlots.append(slot.copy())
                continue
        return

    def FindMinUniqueSlots(self):
        '''
        Member function to find the guard with the fewest number of unique slots.
        Subtracting this from Total coverage gives us the maximum coverage if one guard was to be fired.
        Returns
        -------
        None.

        '''
        START, STOP = 0,1
        UniqueSlots = self.TotalSlots
        newstart = 0

        for guard in self.Data:
            num_overlaps = 0
            for i in range(newstart, len(self.Overlap)):
                slot = self.Overlap[i]
                if guard[START] > slot[STOP]:
                    '''placeholder to find optimised starting point to run intersection search'''
                    newstart +=1
                    continue
                elif guard[STOP] < slot[START]:
                    ''' Given sorted data, once end of slot is found, break out of the loop '''
                    break
                else:
                    num_overlaps = num_overlaps + min(guard[STOP], slot[STOP]) - max (guard[START], slot[START]) + 1

            UniqueSlots = min(guard[STOP] - guard[START] + 1 - num_overlaps, UniqueSlots)
            if UniqueSlots == 0:
                break

        self.MaxCoverage = self.TotalSlots-UniqueSlots
        return

    def RunSimulation(self):
        self.CheckCoverage()
        self.TotalSlotsCovered()
        self.FindMinUniqueSlots()
        return

if __name__ == '__main__':

    for i in range(1,11):
        data = io.ProcessInput(i)
        S = SwimmingClub(data)
        S.RunSimulation()
        io.WriteOutput(i, content = S.MaxCoverage)


import socket
import sys
from _thread import *

# Creating server socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Taking the server IP address and port number as command line arguments
server_ip = sys.argv[1]
server_port = int(sys.argv[2])

# Binding the server socket to listen to the given IP address and port number
server_socket.bind((server_ip, server_port))
server_socket.listen(0)

# Maintaining a count of the number of clients connected
clients_connected = 0

def calc(client_connection, client_address):

    # Using the global clients_connected variable
    global clients_connected

    while True:

        # Receiving message from the client
        msg_bytes = client_connection.recv(1024)

        # If the message size is 0, the client has closed the connection
        if msg_bytes == b'':
            clients_connected -= 1
            print(f"Closing the connection of client {client_address}")
            print(f"{clients_connected} clients currently connected\n")
            client_connection.close()
            break

       # The message received is in the form of bytes. Decoding it to a string
        msg = msg_bytes.decode()
        print (f"Recived expression {msg} from client {client_address}")

        # Calculating the value of the received expression using eval(). Error is it is an invalid expression
        try:
            ans = eval(msg)
        except:
            ans = "ERROR: Invalid expression"
        ans = str(ans)
        print(f"Sending answer {ans} to the client {client_address}\n")

        # Sending the reply to the client, and storing the length of the message sent
        lenth = client_connection.sendall(bytes(ans, "utf-8"))

print(f"Listening on {server_ip} port {server_port}")

while True:

    # Waiting to accept a connection from a client. This line blocks the code until a client connection is made
    # After a client connects, a new socket is assigned to this connection (client_conn)
    # The server socket is always reserved to listen for incoming connections
    client_conn, client_addr = server_socket.accept()

    clients_connected += 1 # increasing the count of number of clients by one, after a client has connected

    print(f"\nConnected to client {client_addr}")
    print(f"{clients_connected} clients currently connected\n") # Displaying the count of clients connected

    # Starting a new thread for every client connected.
    # All the clients will thus, access the server in parallel and independent to each other
    start_new_thread(calc, (client_conn, client_addr,))

server_socket.close()


import tkinter as tk
import datetime as dt
from decimal import Decimal
#import numpy as np
#import matplotlib.pyplot as plt

def add_entry_command(date, price, liters, km):

    # DEALING WITH DATE
    possible_char = '/ _-.'
    print('this is date', date)
    for char in possible_char:
        if char in date:
            print(date.split(char))
            day, month, year = date.split(char)
            break

    day = int(day)
    month = int(month)
    year = int(year)
    new_date = dt.date(year, month, day)

    #DEALING WITH PRICE
    new_price = float(Decimal(float(price)).quantize(Decimal('1.00')))

    #DEALING WITH LITERS
    new_liters = float(liters)

    #DEALING WITH km
    new_km = float(km)

    new_entry = (new_date, new_price, new_liters, new_km)
    insert_entry_to_history(new_entry)

def insert_entry_to_history(new_entry):
    global history
    aux_string = ' '.join([str(_) for _ in new_entry]) + '\n'
    with open('gas_history.txt', 'a') as history:
        history.write(aux_string)

def clear_history_command():
    with open('gas_history.txt', 'w') as history:
        history.write('   DATE     PRICE   LITERS   km \n')

def new_entry_command():
    new_entry_window = tk.Tk()
    new_entry_window.geometry('250x150')

    my_frame = tk.Frame(new_entry_window)

    date_entry_text = tk.StringVar(new_entry_window, '')
    date_label = tk.Label(my_frame, text = 'Date')
    date_entry = tk.Entry(my_frame, textvariable = date_entry_text)
    date_label.grid(row = 0, column = 0)
    date_entry.grid(row = 0, column = 1)

    price_entry_text = tk.StringVar(new_entry_window,  '')
    price_label = tk.Label(my_frame, text = 'Price')
    price_entry = tk.Entry(my_frame, textvariable = price_entry_text)
    price_label.grid(row = 1, column = 0)
    price_entry.grid(row = 1, column = 1)

    liters_entry_text = tk.StringVar(new_entry_window,  '')
    liters_label = tk.Label(my_frame, text = 'Liters')
    liters_entry = tk.Entry(my_frame, textvariable = liters_entry_text)
    liters_label.grid(row = 2, column = 0)
    liters_entry.grid(row = 2, column = 1)

    km_entry_text = tk.StringVar(new_entry_window,  '')
    km_label = tk.Label(my_frame, text = 'km read')
    km_entry = tk.Entry(my_frame, textvariable = km_entry_text)
    km_label.grid(row = 3, column = 0)
    km_entry.grid(row = 3, column = 1)

    my_frame.place(relx=.5, rely=.4, anchor='c')

    add_entry_button = tk.Button(new_entry_window, text = 'Add', command = lambda:add_entry_command(date_entry_text.get(),price_entry_text.get(),liters_entry_text.get(),km_entry_text.get()))
    add_entry_button.place(relx =.5, rely = .8, anchor = 'c')

    new_entry_window.mainloop()

root = tk.Tk()

my_label = tk.Label(root, text = 'my_label')
my_label.pack()

new_entry_button = tk.Button(root, text = 'Add Entry', command = new_entry_command)
new_entry_button.pack()

clear_history_button = tk.Button(root, text = 'Clear History', command = clear_history_command)
clear_history_button.pack()

root.mainloop()


# -*- coding: utf-8 -*-
from copy import copy
from re import compile, escape
from templex.exceptions import KeyNotFound, MustUseString
import difflib
import sys

if sys.version_info[0] == 3:
    unicode = str

def escape_to_regex(text):
    escaped = r""
    for character in text:
        if character == r" ":
            escaped += r" "
        else:
            escaped += escape(character)
    return escaped

DELIMETER_REGEX = compile(
    escape("{{") + r'(.*?)' + escape("}}")
)

class TemplexMatch(object):
    def __init__(self, **variables):
        self._variables = variables

    def __getitem__(self, key):
        return self._variables[key]

class Templex(object):
    def __init__(self, template):
        if not isinstance(template, (unicode, str)) or isinstance(template, bytes):
            raise MustUseString("Must use string with templex (e.g. not bytes).")
        self._template = template
        self._variables = {}

    def with_vars(self, **variables):
        for name, variable in variables.items():
            if not isinstance(variable, (unicode, str)):
                raise MustUseString("Must use string with templex (e.g. not bytes).")
        new_templex = copy(self)
        new_templex._variables = variables
        return new_templex

    def assert_match(self, string):
        """
        Raises informative exception when string does not match the templex.
        """
        if self.match(string) is not None:
            return
        else:
            is_plain_text = True
            compiled_regex = r""
            list_of_chunks = []
            list_of_unescaped_chunks = []

            for chunk in DELIMETER_REGEX.split(self._template):
                if is_plain_text:
                    compiled_regex = compiled_regex + escape_to_regex(chunk)
                    list_of_chunks.append(escape_to_regex(chunk))
                    list_of_unescaped_chunks.append(chunk)
                else:
                    stripped_chunk = chunk.strip()
                    if stripped_chunk in self._variables.keys():
                        compiled_regex = compiled_regex + unicode(
                            r"(?P<{0}>{1})".format(
                                stripped_chunk,
                                self._variables[stripped_chunk],
                            )
                        )
                        list_of_chunks.append(
                            r"(?P<{0}>{1})".format(stripped_chunk, self._variables[stripped_chunk])
                        )
                        list_of_unescaped_chunks.append(r"{{ " + stripped_chunk + r" }}")
                    else:
                        raise KeyNotFound((
                            "'{0}' not found in variables. "
                            "Specify with with_vars(var=regex).\n".format(
                                stripped_chunk
                            )
                        ))

                is_plain_text = not is_plain_text

            to_diff = r""
            to_compare = string
            for chunk, unescaped_chunk in zip(list_of_chunks, list_of_unescaped_chunks):
                match = compile(chunk).search(string)
                if match is not None:
                    to_diff += to_compare[0:match.end() - match.start()]
                    to_compare = to_compare[match.end():]
                else:
                    to_diff += unescaped_chunk

            diff = ''.join(difflib.ndiff(
                string.splitlines(1),
                to_diff.splitlines(1)
            ))

            raise AssertionError(
                u"ACTUAL:\n{0}\n\nEXPECTED:\n{1}\n\nDIFF:\n{2}".format(
                    string,
                    self._template,
                    diff,
                )
            )

    def match(self, string):
        """
        Returns TemplexMatch object if there is a match or None if there isn't.
        """
        if not isinstance(string, (unicode, str)) or isinstance(string, bytes):
            raise MustUseString("Must use string with templex (e.g. not bytes).")

        is_plain_text = True
        compiled_regex = r"^"

        for chunk in DELIMETER_REGEX.split(self._template):
            if is_plain_text:
                compiled_regex = compiled_regex + escape_to_regex(chunk)
            else:
                stripped_chunk = chunk.strip()
                if stripped_chunk in self._variables.keys():
                    compiled_regex = compiled_regex + unicode(
                        r"(?P<{0}>{1})".format(
                            stripped_chunk,
                            self._variables[stripped_chunk]
                        )
                    )
                else:
                    raise KeyNotFound(
                        "'{0}' not found in variables. Specify with with_vars(var=regex).".format(
                          stripped_chunk
                        )
                    )
            is_plain_text = not is_plain_text

        compiled_regex = compiled_regex + r"$"
        match_obj = compile(compiled_regex).match(string)
        return TemplexMatch(**match_obj.groupdict()) if match_obj else None


#! /usr/bin/env python3
# encoding: utf-8
#
# (C) 2016 Chris Liechti <cliechti@gmx.net>
#
# SPDX-License-Identifier:    BSD-3-Clause
import socket
import sys
import gc
import micropython
from .connection import Connection
import ulog
gc.collect()

log = ulog.Logger('HTTPD: ')

class Server(object):
    def __init__(self, app, port=80):
        self.app = app

        self.listening_socket = socket.socket()

        # Binding to all interfaces - server will be accessible to other hosts!
        ai = socket.getaddrinfo('0.0.0.0', port)
        log.info('Bind address info: {}'.format(ai))
        addr = ai[0][-1]

        try:
            self.listening_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        except AttributeError:
            log.warn('setsockopt not supported')
        self.listening_socket.bind(addr)
        self.listening_socket.listen(1)

    def wait_for_client(self):
        client_socket, client_addr = self.listening_socket.accept()
        #~ client_socket.settimeout(5)
        try:
            connection = Connection(
                '{}:{}'.format(*client_addr).encode('utf-8'),
                client_socket.makefile('rb'),
                client_socket.makefile('wb'),
                #~ keep=True)
                keep=False)
            connection.do_request(self.app)
        finally:
            #~ print("terminate")
            gc.collect()
            client_socket.close()

    def loop(self):
        self.app.optimize_routes()
        gc.collect()
        micropython.mem_info(1)
        while True:
            try:
                self.wait_for_client()
                #~ socket.print_pcbs()
                #~ gc.collect()
            except OSError as e:
                sys.print_exception(e)
                #~ if 'ENOMEM' in str(e):
                    #~ micropython.mem_info(1)
                    #~ socket.print_pcbs()
                    #~ machine.reset()
            except Exception as e:
                #~ raise
                sys.print_exception(e)


from selenium import webdriver
# from selenium.common.exceptions import TimeoutException
# from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
# from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
import time

bot = webdriver.Firefox()
bot.get('https://wrap.co')

login_button = bot.find_element_by_link_text('LOG IN')
login_button.click()
time.sleep(5)

signup_button = bot.find_element_by_link_text('SIGNUP FOR WRAP AUTHORING')
signup_button.click()
time.sleep(5)

smb_button = bot.find_element_by_link_text('TRY SMALL BUSINESS FOR FREE')
smb_button.click()
time.sleep(5)

email_box = bot.find_element_by_tag_name('input')
email_box.send_keys('testuser11235@gmail.com')
email_box.submit()
time.sleep(5)

inputs = bot.find_elements_by_tag_name('input')
inputs[-2].send_keys('testuser11235')
inputs[-1].send_keys('P@ssword1!')

buttons = bot.find_elements_by_tag_name('button')
for button in buttons:
    if button.text.find('CREATE ACCOUNT') != -1:
        button.click()
        time.sleep(10)
        button.click()
        break

inputs = bot.find_elements_by_tag_name('input')
inputs[0].send_keys('test')
inputs[1].send_keys('user1123')
inputs[2].send_keys('test company 1123')

buttons = bot.find_elements_by_tag_name('button')
for button in buttons:
    if button.text.find('CREATE ACCOUNT') != -1:
        button.click()
        time.sleep(10)
        button.click()
        break


# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*-
# vi: set ft=python sts=4 ts=4 sw=4 noet :

# This file is part of Fail2Ban.
#
# Fail2Ban is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Fail2Ban is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Fail2Ban; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

# Author: Steven Hiscocks
#

__author__ = "Steven Hiscocks"
__copyright__ = "Copyright (c) 2013 Steven Hiscocks"
__license__ = "GPL"

import os
import sys
import tempfile
import threading
import time
import unittest

from .utils import LogCaptureTestCase

from .. import protocol
from ..server.asyncserver import asyncore, RequestHandler, loop, AsyncServer, AsyncServerException
from ..server.utils import Utils
from ..client.csocket import CSocket

from .utils import LogCaptureTestCase

def TestMsgError(*args):
	raise Exception('test unpickle error')
class TestMsg(object):
	def __init__(self, unpickle=(TestMsgError, ())):
		self.unpickle = unpickle
	def __reduce__(self):
		return self.unpickle

class Socket(LogCaptureTestCase):

	def setUp(self):
		"""Call before every test case."""
		LogCaptureTestCase.setUp(self)
		super(Socket, self).setUp()
		self.server = AsyncServer(self)
		sock_fd, sock_name = tempfile.mkstemp('fail2ban.sock', 'f2b-socket')
		os.close(sock_fd)
		os.remove(sock_name)
		self.sock_name = sock_name
		self.serverThread = None

	def tearDown(self):
		"""Call after every test case."""
		if self.serverThread:
			self.server.stop(); # stop if not already stopped
			self._stopServerThread()
		LogCaptureTestCase.tearDown(self)

	@staticmethod
	def proceed(message):
		"""Test transmitter proceed method which just returns first arg"""
		return message

	def _createServerThread(self, force=False):
		# start in separate thread :
		self.serverThread = serverThread = threading.Thread(
			target=self.server.start, args=(self.sock_name, force))
		serverThread.daemon = True
		serverThread.start()
		self.assertTrue(Utils.wait_for(self.server.isActive, unittest.F2B.maxWaitTime(10)))
		return serverThread

	def _stopServerThread(self):
		serverThread = self.serverThread
		# wait for end of thread :
		Utils.wait_for(lambda: not serverThread.is_alive()
			or serverThread.join(Utils.DEFAULT_SLEEP_TIME), unittest.F2B.maxWaitTime(10))
		self.serverThread = None

	def testStopPerCloseUnexpected(self):
		# start in separate thread :
		serverThread = self._createServerThread()
		# unexpected stop directly after start:
		self.server.close()
		# wait for end of thread :
		self._stopServerThread()
		self.assertFalse(serverThread.is_alive())
		# clean :
		self.server.stop()
		self.assertFalse(self.server.isActive())
		self.assertFalse(os.path.exists(self.sock_name))

	def _serverSocket(self):
		try:
			return CSocket(self.sock_name)
		except Exception as e:
			return None

	def testSocket(self):
		# start in separate thread :
		serverThread = self._createServerThread()
		client = Utils.wait_for(self._serverSocket, 2)

		testMessage = ["A", "test", "message"]
		self.assertEqual(client.send(testMessage), testMessage)

		# test wrong message:
		self.assertEqual(client.send([[TestMsg()]]), 'ERROR: test unpickle error')
		self.assertLogged("PROTO-error: load message failed:", "test unpickle error", all=True)

		# test good message again:
		self.assertEqual(client.send(testMessage), testMessage)

		# test close message
		client.close()
		# 2nd close does nothing
		client.close()

		# force shutdown:
		self.server.stop_communication()
		# test send again (should get in shutdown message):
		client = Utils.wait_for(self._serverSocket, 2)
		self.assertEqual(client.send(testMessage), ['SHUTDOWN'])

		self.server.stop()
		# wait for end of thread :
		self._stopServerThread()
		self.assertFalse(serverThread.is_alive())
		self.assertFalse(self.server.isActive())
		self.assertFalse(os.path.exists(self.sock_name))

	def testSocketConnectBroken(self):
		# start in separate thread :
		serverThread = self._createServerThread()
		client = Utils.wait_for(self._serverSocket, 2)
		# unexpected stop during message body:
		testMessage = ["A", "test", "message", [protocol.CSPROTO.END]]

		org_handler = RequestHandler.found_terminator
		try:
			RequestHandler.found_terminator = lambda self: self.close()
			self.assertRaisesRegex(Exception, r"reset by peer|Broken pipe",
				lambda: client.send(testMessage, timeout=unittest.F2B.maxWaitTime(10)))
		finally:
			RequestHandler.found_terminator = org_handler

	def testStopByCommunicate(self):
		# start in separate thread :
		serverThread = self._createServerThread()
		client = Utils.wait_for(self._serverSocket, 2)

		testMessage = ["A", "test", "message"]
		self.assertEqual(client.send(testMessage), testMessage)

		org_handler = RequestHandler.found_terminator
		try:
			RequestHandler.found_terminator = lambda self: TestMsgError()
			#self.assertRaisesRegexp(Exception, r"reset by peer|Broken pipe", client.send, testMessage)
			self.assertEqual(client.send(testMessage), 'ERROR: test unpickle error')
		finally:
			RequestHandler.found_terminator = org_handler

		# check errors were logged:
		self.assertLogged("Unexpected communication error", "test unpickle error", all=True)

		self.server.stop()
		# wait for end of thread :
		self._stopServerThread()
		self.assertFalse(serverThread.is_alive())

	def testLoopErrors(self):
		# replace poll handler to produce error in loop-cycle:
		org_poll = asyncore.poll
		err = {'cntr': 0}
		def _produce_error(*args):
			err['cntr'] += 1
			if err['cntr'] < 50:
				raise RuntimeError('test errors in poll')
			return org_poll(*args)

		try:
			asyncore.poll = _produce_error
			serverThread = self._createServerThread()
			# wait all-cases processed:
			self.assertTrue(Utils.wait_for(lambda: err['cntr'] > 50, unittest.F2B.maxWaitTime(10)))
		finally:
			# restore:
			asyncore.poll = org_poll
		# check errors were logged:
		self.assertLogged("Server connection was closed: test errors in poll",
			"Too many errors - stop logging connection errors", all=True)

	def testSocketForce(self):
		open(self.sock_name, 'w').close() # Create sock file
		# Try to start without force
		self.assertRaises(
			AsyncServerException, self.server.start, self.sock_name, False)

		# Try again with force set
		serverThread = self._createServerThread(True)

		self.server.stop()
		# wait for end of thread :
		self._stopServerThread()
		self.assertFalse(serverThread.is_alive())
		self.assertFalse(self.server.isActive())
		self.assertFalse(os.path.exists(self.sock_name))

class ClientMisc(LogCaptureTestCase):

	def testErrorsInLoop(self):
		phase = {'cntr': 0}
		def _active():
			return phase['cntr'] < 40
		def _poll(*args):
			phase['cntr'] += 1
			raise Exception('test *%d*' % phase['cntr'])
		# test errors "catched" and logged:
		loop(_active, use_poll=_poll)
		self.assertLogged("test *1*", "test *10*", "test *20*", all=True)
		self.assertLogged("Too many errors - stop logging connection errors")
		self.assertNotLogged("test *21*", "test *22*", "test *23*", all=True)

	def testPrintFormattedAndWiki(self):
		# redirect stdout to devnull
		saved_stdout = sys.stdout
		sys.stdout = open(os.devnull, 'w')
		try:
			protocol.printFormatted()
			protocol.printWiki()
		finally:
			# restore stdout
			sys.stdout = saved_stdout


import datetime
import motor.motor_asyncio
from mega.common import Common

myclient = motor.motor_asyncio.AsyncIOMotorClient(Common().database_url)
mydb = myclient["FileToLink"]
dmycol = mydb['Users']

def new_user(id):
    return dict(
        id = id,
        join_date = datetime.date.today().isoformat(),
        ban_status=dict(
            is_banned=False,
            ban_reason=''
        )
    )

async def add_user(id):
    user = new_user(id)
    await dmycol.insert_one(user)

async def is_user_exist(id):
    user = await dmycol.find_one({'id':int(id)})
    return True if user else False

async def remove_ban(id):
    ban_status = dict(
        is_banned=False,
        ban_reason=''
    )
    await dmycol.update_one({'id': id}, {'$set': {'ban_status': ban_status}})

async def ban_user(user_id, ban_reason):
    ban_status = dict(
        is_banned=True,
        ban_reason=ban_reason
    )
    await dmycol.update_one({'id': user_id}, {'$set': {'ban_status': ban_status}})

async def get_ban_status(id):
    default = dict(
        is_banned=False,
        ban_reason=''
    )
    user = await dmycol.find_one({'id':int(id)})
    return user.get('ban_status', default)

async def get_all_banned_users():
    banned_users = dmycol.find({'ban_status.is_banned': True})
    return banned_users

async def total_users_count():
    count = await dmycol.count_documents({})
    return count

async def get_all_users():
    all_users = dmycol.find({})
    return all_users

async def delete_user(user_id):
    await dmycol.delete_many({'id': int(user_id)})


from conf import config_yml
from core import info_collection
import logging
import json
import requests

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
logger.addHandler(stream_handler)

class Handler():
    @staticmethod
    def collect_data():
        """ 收集硬件信息 用于测试 """
        info = info_collection.InfoCollection()
        asset_data = info.collect()
        logger.info('collect client info: {}'.format(asset_data))

    @staticmethod
    def report_data():
        """ 收集硬件信息 发送到服务器 """
        info = info_collection.InfoCollection()
        asset_data = info.collect()
        data = {"asset_data": asset_data}
        url = config_yml['remote_report_server']['server_url']
        request_timeout = config_yml['remote_report_server']['request_timeout']
        logger.info('start to report data to server.')

        try:
            r = requests.post(url=url, json=data, timeout=request_timeout)
        except Exception as e:
            logger.exception('end report data to server error.')
        else:
            logger.info("end report data to server, get data: {}".format(r.content.decode('utf-8')))


from django.urls import path,include
from . import views
from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'Categories', views.Categories)
router.register(r'TypeCategories', views.TypeCategories)
router.register(r'Priorites', views.Priorites)
router.register(r'Etats', views.Etats)
router.register(r'Tickets', views.Tickets)
router.register(r'Entites', views.Entites)

urlpatterns = [
    path('',include(router.urls)),
    path('GetCategorie/<int:pk>',views.GetCategorie),
    path('datahome/',views.GetDataHome),
    path('GetPiechartPriorite/',views.GetPiechartPriorite),
    path('GetStatistiquesPerYear/<int:year>',views.GetStatistiquesPerYear),
    path('getTicket/<pk>',views.getTicket.as_view()),
    path('getEntity/<pk>',views.getEntity.as_view()),
    path('Register/',views.Register.as_view()),

]


import math

INPUT = "input/01.in"

def read_input():
    with open(INPUT) as f:
        return [int(x) for x in f]

def calc_fuel(mass):
    return math.floor(mass / 3) - 2

# PART 1
input = read_input()
total_fuel = sum([calc_fuel(x) for x in input])
print(f"Total fuel requirements: {total_fuel}")

# PART 2
def calc_fuel_repeated(mass):
    total = 0
    fuel = calc_fuel(mass)
    while fuel > 0:
        total += fuel
        fuel = calc_fuel(fuel)
    return total

total_fuel_repeated = sum([calc_fuel_repeated(x) for x in input])
print(f"Total fuel repeated requirements: {total_fuel_repeated}")


#author-yaz c

import turtle

pen = turtle.Turtle()
pen.pensize(2)
pen.color("black")
pen.hideturtle()
pen.speed(0)

shp=turtle.textinput("Shape", "Enter Shape").lower().strip()
shpwd = turtle.window_width()//5

if shp == "circle":
    pen.begin_fill()
    pen.fillcolor("medium purple")
    pen.up()
    pen.setx(0)
    pen.down()
    pen.circle(shpwd//2)
    pen.end_fill()
elif shp == "square":
    pen.begin_fill()
    pen.fillcolor("orange")
    for i in range(4):

        pen.forward(shpwd)
        pen.left(90)
    pen.end_fill()
elif shp == "triangle":
    pen.begin_fill()
    pen.fillcolor("pink")
    for i in range (3):

        pen.forward(shpwd)
        pen.left(120)
    pen.end_fill()

else:
    print("Sorry, Invalid Shape")

turtle.done()


from keras.callbacks import Callback

class InMemoryModelCheckpoint(Callback):
    def __init__(self, *, checkpoints=[], monitor='val_acc', load_best_on_train_end=False):
        super(InMemoryModelCheckpoint, self).__init__()
        self.checkpoints = checkpoints
        self.monitor = monitor
        self.load_best_on_train_end = load_best_on_train_end

    def on_epoch_end(self, epochs, logs = {}):
        self.checkpoints.append({
            'epochs': epochs,
            'logs': logs,
            'weights': self.model.get_weights(),
            })

    def on_train_end(self, logs={}):
        if not self.load_best_on_train_end:
            return

        if self.monitor in { 'val_acc' }: # Add if required
            best = getattr(__builtins__, 'max')
        else:
            best = getattr(__builtins__, 'min')
        best_point = best(self.checkpoints, key=lambda e: e['logs'].get(self.monitor) or 0.) # Avoid TypeError
        self.model.set_weights(best_point['weights'])


""" Utility functions and classes for SRP

Context : SRP
Module  : SRPGW
Version : 1.1.1
Author  : Stefano Covino
Date    : 14/01/2020
E-mail  : stefano.covino@brera.inaf.it
URL:    : http://www.merate.mi.astro.it/utenti/covino

Usage   : DaoPSFPhot

Remarks :

History : (24/02/2016) First version.
        : (13/07/2016) Case of single object.
        : (16/12/2016) FWHM in PSF computation.
        : (14/01/2020) Gain and ron as parameters.
"""

import SRPGW as GW
import numpy
from PythonPhot import aper
from PythonPhot import getpsf
from PythonPhot import pkfit

def DaoPSFPhot(x,y,px,py,data,rds=(5,10,15),fwhm=5,zp=30.0,cent=False,bck=True,gain=GW.VSTgain,ron=GW.VSTron):
    mag,magerr,flux,fluxerr,sky,skyerr,badflag,outstr = aper.aper(data,px,py,phpadu=gain,apr=rds[0],zeropoint=zp,skyrad=[rds[1],rds[2]],verbose=False)
    gauss,psf,psfmag = getpsf.getpsf(data,px,py,mag,sky,ronois=ron,phpadu=gain,idpsf=numpy.arange(len(px)),psfrad=rds[2],fitrad=fwhm,psfname='/dev/null')
    pk = pkfit.pkfit_class(data,gauss,psf,ronois=ron,phpadu=gain)
    #
    mag,magerr,flux,fluxerr,sky,skyerr,badflag,outstr = aper.aper(data,x,y,phpadu=gain,apr=rds[0],zeropoint=zp,skyrad=[rds[1],rds[2]],verbose=False)
    #
    pflux = []
    pfluxerr = []
    if len(x) < 2:
        x = [x,]
        y = [y,]
        sky = [sky,]
    for x,y,s in zip(x,y,sky):
        errmag,chi,sharp,niter,scale = pk.pkfit(1,x,y,s,radius=rds[0],recenter=cent)
        f = scale*10**(0.4*(zp-psfmag))
        ef = errmag*10**(0.4*(zp-psfmag))
        pflux.append(float(f))
        pfluxerr.append(float(ef))
    #
    return flux.flatten(), fluxerr.flatten(), pflux, pfluxerr


from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class StepBruteForce(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        layout = QVBoxLayout(self)

        self.title = QLabel()
        self.title.setFont(QFont('Arial', 20))
        self.title.setAlignment(Qt.AlignCenter)

        self.okButton = QPushButton("Ok")

        layout.addWidget(self.title)
        layout.addWidget(self.okButton)

    def setTitle(self, title):
        self.title.setText(title)


import pprint
import json
import pymysql
from foursquareAPI import get_venue_tags
db=pymysql.connect("localhost","Lei"," .","recommendation")
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS venue_tags")
sql="""CREATE TABLE venue_tags(venueid char(255),
       venuetags LONGTEXT)"""
cursor.execute(sql)
with open('4s_venues_twitter.json','r') as data_file:
	data= json.load(data_file)
for key, value in data.items():
    venue_tags=get_venue_tags(data,key)
    if venue_tags!=None:
      for string in venue_tags:
        sql1="INSERT INTO venue_tags(venueid,venuetags) Values(%s,%s)"
        try:
          cursor.execute(sql1,(key,string))
          db.commit()
          flag=flag+1
        except:
          db.rollback()

cursor.close()
db.close()


def twoSum(nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    # target_list = []
    # dict_num = {}
    # for index, num in enumerate(nums):
    #     dict_num[num] = index
    #
    # for num, index in dict_num.items():
    #     diff = target - num
    #     if dict_num.has_key(diff):
    #         index2 = dict_num[diff]
    #         target_list.append(index)
    #         target_list.append(dict_num[diff])
    #         target_list.sort()
    #         return target_list
    #     else:
    #         continue
    dict = {}
    for i in range(len(nums)):
        x = nums[i]
        if target - x in dict:
            return [dict[target - x], i]
        dict[x] = i

print(twoSum([3,5,3], 6))


#!/usr/bin/env python

import struct
import sys

infile_path = "/dev/input/event" + (sys.argv[1] if len(sys.argv) > 1 else "0")

FORMAT = 'llHHI'

event_size = struct.calcsize(FORMAT)

in_file = open(infile_path, 'rb')

event = in_file.read(event_size)

while event:
    (tv_sec, tv_usec, keytype, code, value) = struct.unpack(FORMAT, event)
    if keytype !=0 or code != 0:
        print("Event type: {}, code: {}, value: {}, time: {}".format(keytype, code, value, tv_sec))
    else:
        print("=======================================================")
    event = in_file.read(event_size)


# -*- coding: utf-8 -*-
"""
Created on Tue Jul 14 11:57:40 2015

@author: JSCHOENK
"""
from __future__ import division
import numpy as np
try:
    from MPyUOSLib import BasicProcessingModule
except ImportError:
    class BasicProcessingModule:
        def __init__(self,foot):
            pass

class SignalBuilder(BasicProcessingModule):
    """
    affine linear function.
    """
    def __init__(self,foot):
        BasicProcessingModule.__init__(self,foot)
        self.output = np.zeros(1)

        self.segments = foot["segments"]
        self.duration = np.zeros(len(self.segments))
        for i in range(len(self.segments))        :
            self.duration[i] = self.segments[i]["duration"]
        self.cumDur = np.cumsum(self.duration)
        self.segmentOffsets = np.hstack([0,np.cumsum(self.duration)[:-1]])
        self.nrD = int(self.duration.sum())
        self.simulationSteps = self.nrD

    def __call__(self, index=0):
        activeSegmentIndex = np.nonzero(self.segmentOffsets<=index)[0][-1]
        segmentInternalIndex = min(index-self.segmentOffsets[activeSegmentIndex],self.duration[activeSegmentIndex])
        normalizedInternalCoord = segmentInternalIndex/(self.duration[activeSegmentIndex]-1)
        exec("out = self." + self.segments[activeSegmentIndex]["kind"] + "(activeSegmentIndex,normalizedInternalCoord)")
        return out

    def linear(self, index, coord):
        a = self.segments[index]["start"]
        b = self.segments[index]["final"]
        return a+(b-a)*coord

    def constant(self, index, coord):
        return self.segments[index]["value"]

    def halfcosine(self, index, coord):
        a = self.segments[index]["start"]
        b = self.segments[index]["final"]
        c = 0.5*(1-np.cos(np.pi*coord))
        return a+c*(b-a)

    def power(self, index, coord):
        a = self.segments[index]["start"]
        b = self.segments[index]["final"]
        power = self.segments[index]["power"]
        c = coord**power
        return c*a+(1-c)*b

if __name__ == '__main__':
    import pylab as plt
    foot = {"segments":[
                {"duration":10,"kind":"constant","value":1},
                {"duration":30,"kind":"linear","start":1,"final":4},
                {"duration":10,"kind":"halfcosine","start":4,"final":3},
                {"duration":20,"kind":"halfcosine","start":3,"final":5},
                {"duration":20,"kind":"constant","value":2}
                ]
           }
    a = SignalBuilder(foot)
    a({},0)
    x = range(100)
    y = np.zeros(np.shape(x))
    for i in range(len(x)):
        y[i] = a({},i)

    plt.plot(x,y)


# Filename: 20_predict_textGenLSTM.py
# Function: Text Generation With LSTM Recurrent Neural Networks
#           in Python with Keras
# Remark: This code comes from article
# https://machinelearningmastery.com/text-generation-lstm-recurrent-neural-networks-python-keras/
#
# This code has similarities with learning code of article
# https://towardsdatascience.com/how-to-generate-music-using-a-lstm-neural-network-in-keras-68786834d4c5
# see also 10_learn.py
#

# ### Generating Text with an LSTM Network ###
#
# Generating text using the trained LSTM network is relatively straightforward.
#
# Firstly, we load the data and define the network in exactly the same way,
# except the network weights are loaded from a checkpoint file and the
# network does not need to be trained.
#
#
# # *** load the network weights ***
# filename = "weights-improvement-19-1.9435.hdf5"
# model.load_weights(filename)
# model.compile(  loss='categorical_crossentropy'
#                ,optimizer='adam'
#              )
#
# Also, when preparing the mapping of unique characters to integers, we must
# also create a reverse mapping that we can use to convert the integers back
# to characters so that we can understand the predictions.
#
# int_to_char = dict((i, c) for i, c in enumerate(chars))
#
# Finally, we need to actually make predictions.
#
# The simplest way to use the Keras LSTM model to make predictions is to first
# start off with a seed sequence as input, generate the next character then
# update the seed sequence to add the generated character on the end and trim
# off the first character. This process is repeated for as long as we want to
# predict new characters (e.g. a sequence of 1,000 characters in length).
#
# We can pick a random input pattern as our seed sequence, then print generated
# characters as we generate them.
# pick a random seed
# start = numpy.random.randint(0, len(dataX)-1)
# pattern = dataX[start]
# print "Seed:"
# print "\"", ''.join([int_to_char[value] for value in pattern]), "\""
# # generate characters
# for i in range(1000):
#	  x = numpy.reshape(pattern, (1, len(pattern), 1))
#	  x = x / float(n_vocab)
#	  prediction = model.predict(x, verbose=0)
#	  index = numpy.argmax(prediction)
#	  result = int_to_char[index]
#	  seq_in = [int_to_char[value] for value in pattern]
#	  sys.stdout.write(result)
#	  pattern.append(index)
#	  pattern = pattern[1:len(pattern)]
#print "\nDone."
#
# The full code example for generating text using the loaded LSTM model is
# listed below for completeness.
'''
text afmaken
'''

# The full code example for generating text using the loaded LSTM model is listed
# below for completeness.
#
# # ### Load LSTM network and generate text ###
# import sys
# import numpy
# from keras.models import Sequential
# from keras.layers import Dense
# from keras.layers import Dropout
# from keras.layers import LSTM
# from keras.callbacks import ModelCheckpoint
# from keras.utils import np_utils
# # load ascii text and covert to lowercase
# filename = "wonderland.txt"
# raw_text = open(filename, 'r', encoding='utf-8').read()
# raw_text = raw_text.lower()
# # create mapping of unique chars to integers, and a reverse mapping
# chars = sorted(list(set(raw_text)))
# char_to_int = dict((c, i) for i, c in enumerate(chars))
# int_to_char = dict((i, c) for i, c in enumerate(chars))
# # summarize the loaded data
# n_chars = len(raw_text)
# n_vocab = len(chars)
# print ("Total Characters: ", n_chars)
# print ("Total Vocab: ", n_vocab)
# # prepare the dataset of input to output pairs encoded as integers
# seq_length = 100
# dataX = []
# dataY = []
# for i in range(0, n_chars - seq_length, 1):
# 	  seq_in = raw_text[i:i + seq_length]
# 	  seq_out = raw_text[i + seq_length]
#	  dataX.append([char_to_int[char] for char in seq_in])
#	  dataY.append(char_to_int[seq_out])
# n_patterns = len(dataX)
# print ("Total Patterns: ", n_patterns)
# # reshape X to be [samples, time steps, features]
# X = numpy.reshape(dataX, (n_patterns, seq_length, 1))
# # normalize
# X = X / float(n_vocab)
# # one hot encode the output variable
# y = np_utils.to_categorical(dataY)
# # define the LSTM model
# model = Sequential()
# model.add(LSTM(256, input_shape=(X.shape[1], X.shape[2])))
# model.add(Dropout(0.2))
# model.add(Dense(y.shape[1], activation='softmax'))
# # load the network weights
# # filename = "weights-improvement-19-1.9435.hdf5"
# filename = "weights-best.hdf5"
# model.load_weights(filename)
# model.compile(loss='categorical_crossentropy', optimizer='adam')
# # pick a random seed
# start = numpy.random.randint(0, len(dataX)-1)
# pattern = dataX[start]
# print ("Seed:")
# print ("\"", ''.join([int_to_char[value] for value in pattern]), "\"")
# # generate characters
# for i in range(1000):
#	  x = numpy.reshape(pattern, (1, len(pattern), 1))
#	  x = x / float(n_vocab)
#	  prediction = model.predict(x, verbose=0)
#	  index = numpy.argmax(prediction)
#	  result = int_to_char[index]
#	  seq_in = [int_to_char[value] for value in pattern]
#	  sys.stdout.write(result)
#	  pattern.append(index)
#	  pattern = pattern[1:len(pattern)]
# print ("\nDone.")
#
# Running this example first outputs the selected random seed, then each
# character as it is generated.
#
# For example, below are the results from one run of this text generator.
# The random seed was:
#
# be no mistake about it: it was neither more nor less than a pig, and she
# felt that it would be quit
#
# The generated text with the random seed (cleaned up for presentation) was:
#
# be no mistake about it: it was neither more nor less than a pig, and she
# felt that it would be quit e aelin that she was a little want oe toiet
# ano a grtpersent to the tas a little war th tee the tase oa teettee
# the had been tinhgtt a little toiee at the cadl in a long tuiee aedun
# thet sheer was a little tare gereen to be a gentle of the tabdit  soenee
# the gad  ouw ie the tay a tirt of toiet at the was a little
# anonersen, and thiu had been woite io a lott of tueh a tiie  and taede
# bot her aeain  she cere thth the bene tith the tere bane to tee
# toaete to tee the harter was a little tire the same oare cade an anl ano
# the garee and the was so seat the was a little gareen and the sabdit,
# and the white rabbit wese tilel an the caoe and the sabbit se teeteer,
# and the white rabbit wese tilel an the cade in a lonk tfne the sabdi
# ano aroing to tea the was sf teet whitg the was a little tane oo thete
# the sabeit  she was a little tartig to the tar tf tee the tame of the
# cagd, and the white rabbit was a little toiee to be anle tite thete ofs
# and the tabdit was the wiite rabbit, and
#
# We can note some observations about the generated text.
#
# - It generally conforms to the line format observed in the original text of
#   less than 80 characters before a new line.
# - The characters are separated into word-like groups and most groups are
#   actual English words (e.g. “the”, “little” and “was”), but many do not
#   (e.g. “lott”, “tiie” and “taede”).
# - Some of the words in sequence make sense(e.g. “and the white rabbit“),
#   but many do not (e.g. “wese tilel“).
#
# The fact that this character based model of the book produces output like this
# is very impressive. It gives you a sense of the learning capabilities of LSTM
# networks.
#
# The results are not perfect. In the next section we look at improving the
# quality of results by developing a much larger LSTM network.
#
#
#
# ### Larger LSTM Recurrent Neural Network ###
# We got results, but not excellent results in the previous section. Now, we can try to improve the quality of the generated text by creating a much larger network.
#
# We will keep the number of memory units the same at 256, but add a second layer.
#
# model = Sequential()
# model.add(LSTM(256, input_shape=(X.shape[1], X.shape[2]), return_sequences=True))
# model.add(Dropout(0.2))
# model.add(LSTM(256))
# model.add(Dropout(0.2))
# model.add(Dense(y.shape[1], activation='softmax'))
# model.compile(loss='categorical_crossentropy', optimizer='adam')
#
# We will also change the filename of the checkpointed weights so that we can
# tell the difference between weights for this network and the previous (by
# appending the word “bigger” in the filename).
#
# filepath="weights-improvement-{epoch:02d}-{loss:.4f}-bigger.hdf5"
#
# Finally, we will increase the number of training epochs from 20 to 50 and
# decrease the batch size from 128 to 64 to give the network more of an
# opportunity to be updated and learn.
#
#

# The full code listing is presented below for completeness.
'''
# Below code is only to create a weights-best.hdf5 weights file
print("if below code is finish comment out")
print("create a weights-best.hdf5 weights file")
# *** Larger LSTM Network to Generate Text for Alice in Wonderland ***
import numpy
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.utils import np_utils
# load ascii text and covert to lowercase
filename = "wonderland.txt"
raw_text = open(filename, 'r', encoding='utf-8').read()
raw_text = raw_text.lower()
# create mapping of unique chars to integers
chars = sorted(list(set(raw_text)))
char_to_int = dict((c, i) for i, c in enumerate(chars))
# summarize the loaded data
n_chars = len(raw_text)
n_vocab = len(chars)
print("Total Characters: ", n_chars)
#print("Total Vocab: ", n_vocab)
print("Total Vocab (= distinct characters): ", n_vocab)
# prepare the dataset of input to output pairs encoded as integers
seq_length = 100
dataX = []
dataY = []
for i in range(0, n_chars - seq_length, 1):
    seq_in = raw_text[i:i + seq_length]
    seq_out = raw_text[i + seq_length]
    dataX.append([char_to_int[char] for char in seq_in])
    dataY.append(char_to_int[seq_out])
n_patterns = len(dataX)
print("Total Patterns: ", n_patterns)
# *** reshape X to be [samples, time steps, features] ***
X = numpy.reshape(dataX, (n_patterns, seq_length, 1))
# *** normalize ***
X = X / float(n_vocab)
# *** one hot encode the output variable ***
y = np_utils.to_categorical(dataY)
# define the LSTM model
model = Sequential()
model.add( LSTM(256
          ,input_shape=(X.shape[1], X.shape[2])
          ,return_sequences=True)
         )
model.add(Dropout(0.2))
model.add(LSTM(256))
model.add(Dropout(0.2))
model.add(Dense( y.shape[1]
                ,activation='softmax'
               )
         )
model.compile( loss='categorical_crossentropy'
              ,optimizer='adam')
# *** define the checkpoint ***
#filepath="weights-improvement-{epoch:02d}-{loss:.4f}-bigger.hdf5"
filepath = "weights-best.hdf5"
checkpoint = ModelCheckpoint( filepath
                             ,monitor='loss'
                             ,verbose=1
                             ,save_best_only=True
                             ,mode='min'
                             )
callbacks_list = [checkpoint]
# fit the model
model.fit( X
          ,y
          ,epochs=50
          ,batch_size=64
          ,callbacks=callbacks_list
         )
print("Comment out, above code")
print("Save weights file weights-best.hdf5")
print("Code below with weights-best.hdf5")
'''
#
# Running this example takes some time, at least 700 seconds per epoch.
#
# After running this example you may achieved a loss of about 1.2. For example
# the best result I achieved from running this model was stored in a checkpoint
# file with the name:
#
# weights-improvement-47-1.2219-bigger.hdf5
#
# Achieving a loss of 1.2219 at epoch 47.
#
# As in the previous section, we can use this best model from the run to
# generate text.
#
# The only change we need to make to the text generation script from the
# previous section is in the specification of the network topology and from
# which file to seed the network weights.
#
#
#
# The full code listing is provided below for completeness.
#
# ### Load Larger LSTM network and generate text ###
# Attention: weights-best.hdf5 file is created with code block above
# and NOT below !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
import sys
import numpy
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.utils import np_utils
# load ascii text and covert to lowercase
filename = "wonderland.txt"
raw_text = open(filename, 'r', encoding='utf-8').read()
raw_text = raw_text.lower()
# create mapping of unique chars to integers, and a reverse mapping
chars = sorted(list(set(raw_text)))
char_to_int = dict((c, i) for i, c in enumerate(chars))
int_to_char = dict((i, c) for i, c in enumerate(chars))
# summarize the loaded data
n_chars = len(raw_text)
n_vocab = len(chars)
print("Total Characters: ", n_chars)
#print "Total Vocab: ", n_vocab
print("Total Vocab (= distinct characters): ", n_vocab)
# prepare the dataset of input to output pairs encoded as integers
seq_length = 100
dataX = []
dataY = []
for i in range(0, n_chars - seq_length, 1):
	seq_in = raw_text[i:i + seq_length]
	seq_out = raw_text[i + seq_length]
	dataX.append([char_to_int[char] for char in seq_in])
	dataY.append(char_to_int[seq_out])
n_patterns = len(dataX)
print("Total Patterns: ", n_patterns)
# reshape X to be [samples, time steps, features]
X = numpy.reshape(dataX, (n_patterns, seq_length, 1))
# normalize
X = X / float(n_vocab)
# one hot encode the output variable
y = np_utils.to_categorical(dataY)
# define the LSTM model
model = Sequential()
model.add(LSTM( 256
               ,input_shape=(X.shape[1], X.shape[2])
			   ,return_sequences=True
			  )
		 )
model.add(Dropout(0.2))
model.add(LSTM(256))
model.add(Dropout(0.2))
model.add(Dense( y.shape[1]
                ,activation='softmax'
			   )
		 )
# load the network weights
#filename = "weights-improvement-47-1.2219-bigger.hdf5"
filename = "weights-best.hdf5"
model.load_weights(filename)
model.compile(  loss='categorical_crossentropy'
               ,optimizer='adam'
			 )
# pick a random seed
start = numpy.random.randint(0, len(dataX)-1)
pattern = dataX[start]
print ("Seed:")
print ("\"", ''.join([int_to_char[value] for value in pattern]), "\"")
# generate characters
for i in range(1000):
	x = numpy.reshape(pattern, (1, len(pattern), 1))
	x = x / float(n_vocab)
	prediction = model.predict(x, verbose=0)
	index = numpy.argmax(prediction)
	result = int_to_char[index]
	seq_in = [int_to_char[value] for value in pattern]
	sys.stdout.write(result)
	pattern.append(index)
	pattern = pattern[1:len(pattern)]
print ("\nDone.")

# One example of running this text generation script produces the output below.
#
# The randomly chosen seed text was:
#
# d herself lying on the bank, with her
# head in the lap of her sister, who was gently brushing away s
#
# The generated text with the seed (cleaned up for presentation) was :
#
# herself lying on the bank, with her
# head in the lap of her sister, who was gently brushing away
# so siee, and she sabbit said to herself and the sabbit said to herself and the sood
# way of the was a little that she was a little lad good to the garden,
# and the sood of the mock turtle said to herself, 'it was a little that
# the mock turtle said to see it said to sea it said to sea it say it
# the marge hard sat hn a little that she was so sereated to herself, and
# she sabbit said to herself, 'it was a little little shated of the sooe
# of the coomouse it was a little lad good to the little gooder head. and
# said to herself, 'it was a little little shated of the mouse of the
# good of the courte, and it was a little little shated in a little that
# the was a little little shated of the thmee said to see it was a little
# book of the was a little that she was so sereated to hare a little the
# began sitee of the was of the was a little that she was so seally and
# the sabbit was a little lad good to the little gooder head of the gad
# seared to see it was a little lad good to the little good
#
#
# We can see that generally there are fewer spelling mistakes and the text
# looks more realistic, but is still quite nonsensical.
#
# For example the same phrases get repeated again and again like
# “said to herself” and “little“. Quotes are opened but not closed.
#
# These are better results but there is still a lot of room for improvement.
#
# ### 10 Extension Ideas to Improve the Model ###
# Below are 10 ideas that may further improve the model that you could
# experiment with are:
#
#  1. Predict fewer than 1,000 characters as output for a given seed.
#  2. Remove all punctuation from the source text, and therefore from the
#     models’ vocabulary.
#  3. Try a one hot encoded for the input sequences.
#  4. Train the model on padded sentences rather than random sequences of
#     characters.
#  5. Increase the number of training epochs to 100 or many hundreds.
#  6. Add dropout to the visible input layer and consider tuning the dropout
#     percentage.
#  7. Tune the batch size, try a batch size of 1 as a (very slow) baseline and
#     larger sizes from there.
#  8. Add more memory units to the layers and/or more layers.
#  9. Experiment with scale factors (temperature) when interpreting the
#     prediction probabilities.
# 10. Change the LSTM layers to be “stateful” to maintain state across batches.
#
# Did you try any of these extensions? Share your results in the comments.
#
# ### Resources ###
#
# This character text model is a popular way for generating text using
# recurrent neural networks.
#
# Below are some more resources and tutorials on the topic if you are
# interested in going deeper. Perhaps the most popular is the tutorial
# by Andrej Karpathy titled “The Unreasonable Effectiveness of Recurrent
# Neural Networks“.
# see http://karpathy.github.io/2015/05/21/rnn-effectiveness/
#
# - Generating Text with Recurrent Neural Networks [pdf], 2011
#   http://www.cs.utoronto.ca/~ilya/pubs/2011/LANG-RNN.pdf
# - Keras code example of LSTM for text generation.
#   https://github.com/fchollet/keras/blob/master/examples/lstm_text_generation.py
# - Lasagne code example of LSTM for text generation.
#   https://github.com/Lasagne/Recipes/blob/master/examples/lstm_text_generation.py
# - MXNet tutorial for using an LSTM for text generation.
#   http://mxnetjl.readthedocs.io/en/latest/tutorial/char-lstm.html
# - Auto-Generating Clickbait With Recurrent Neural Networks.
#   https://larseidnes.com/2015/10/13/auto-generating-clickbait-with-recurrent-neural-networks/
#
# ### Summary ###
#
# In this post you discovered how you can develop an LSTM recurrent neural network for text generation in Python with the Keras deep learning library.
#
# After reading this post you know:
#
# 1. Where to download the ASCII text for classical books for free that you can
#    use for training.
# 2. How to train an LSTM network on text sequences and how to use the trained
#    network to generate new sequences.
# 3. How to develop stacked LSTM networks and lift the performance of the model.
#
# Do you have any questions about text generation with LSTM networks or about
# this post? Ask your questions in the comments below and I will do my best to
# answer them.


#!/usr/bin/env python
# -*- coding: utf-8 -*-
___author___ = 'Steven Emerson'
___date___ = '2020/8/29 21:00'

import time

"""
获取3天后的时间
"""
now_time = time.time()
three_days_time = now_time + 60*60*24*3
time_tuple = time.localtime(three_days_time)
print(time.strftime("%Y-%m-%d %H:%M:%S", time_tuple))


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

from email.header import decode_header, Header
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
from easymail import Email, Attachment
from unittest import TestCase

class TestAttachment(TestCase):
    def test_images(self):
        a = Attachment('./tests/test.png')
        self.assertTrue('image/png' in str(a.as_msg()))
        self.assertIsInstance(a.as_msg(), MIMEImage)

    def test_audio(self):
        a = Attachment('./tests/440Hz-5sec.mp3')
        self.assertTrue('audio/mpeg' in str(a.as_msg()))
        self.assertIsInstance(a.as_msg(), MIMEAudio)

    def test_filename_in_header(self):
        a = Attachment('./tests/440Hz-5sec.mp3')
        msg = str(a.as_msg())
        self.assertTrue('attachment; filename="440Hz-5sec.mp3' in msg[:200])

    def test_msg_contains_body_and_attachment(self):
        e = Email('sender@foo.com', 'recipient@foo.com', 'subject', 'fubar')
        e.attachments.append(Attachment('./tests/440Hz-5sec.mp3'))

        # body will be base64 encoded:
        self.assertTrue('ZnViYXI=' in str(e)[:500])
        self.assertTrue('filename="440Hz' in str(e)[:800])

    def test_msg_contains_html_body_and_attachment(self):
        e = Email('sender@foo.com', 'recipient@foo.com', 'subject')
        e.body = 'fubar'
        e.body_is_html = True
        e.attachments.append(Attachment('./tests/440Hz-5sec.mp3'))

        # body will be base64 encoded:
        self.assertTrue('PGh0bWw+PGJvZHk+PGI+ZnViYXI8L2I+PC9ib2R5PjwvaHRtbD4='
                        in str(e)[:500])
        self.assertTrue('filename="440Hz' in str(e)[:800])

class TestEmail(TestCase):
    def test_subject_encoding(self):
        e = Email('sender@foo.com', 'recipient@foo.com', 'subject', 'body')
        self.assertEqual('subject', str(e.subject))
        self.assertEqual('utf-8', decode_header(e._subject)[0][1])
        self.assertIsInstance(e._subject, Header)
        self.assertEqual('body', e.body)

    def test_subject_property(self):
        e = Email('sender@foo.com', 'recipient@foo.com')
        e.subject = 'subject'
        self.assertEqual('subject', str(e.subject))
        self.assertEqual('utf-8', decode_header(e._subject)[0][1])
        self.assertIsInstance(e._subject, Header)

    def test_recipients(self):
        e = Email('sender@foo.com', 'recipient1@foo.com')
        self.assertEqual(e.recipients, ['recipient1@foo.com'])

        recipients = ['recipient1@foo.com', 'recipient2@foo.com']
        e = Email('sender@foo.com', recipients)
        self.assertEqual(e.recipients, recipients)

    def test_as_string(self):
        e = Email('sender@foo.com', 'recipient@foo.com')
        e.subject = 'äää ööö üfoo äß'
        e.body = 'ääää'
        self.assertTrue('Content-Type: text/plain; charset="utf-8"' in str(e))

    def test_as_string_empty_body(self):
        e = Email('sender@foo.com', 'recipient@foo.com')
        e.subject = 'äää ööö üfoo äß'
        self.assertTrue('Content-Type: text/plain; charset="us-ascii"' in str(e))

    def test_all_recipients(self):
        e = Email('sender@foo.com', 'recipient@foo.com')
        e.cc.append('cc@foo.com')
        e.bcc.append('bcc@foo.com')
        self.assertEqual(e.all_recipients, ['recipient@foo.com',
                                            'cc@foo.com',
                                            'bcc@foo.com'])


import os
import unittest
from statistics import mean, median

from kuibit import tree as ktree
from kuibit.simdir import SimDir

class TestCactusTimers(unittest.TestCase):
    def setUp(self):
        self.sd = SimDir("tests/tov")
        self.timers = self.sd.timers

    def test_load_xml(self):
        # We create a simple xml file and we parse it
        xml = """\
<timer name = "level1"> 1
  <timer name = "level2a"> 2 </timer>
  <timer name = "level2b"> 3.0 </timer>
  <timer name = "level2c"> 4.0
    <timer name = "level3"> 5 </timer>
  </timer>
</timer>"""

        path = "xml_file"
        with open(path, "w") as file_:
            file_.write(xml)

        tree = self.timers._load_xml(path)

        expected_tree = ktree.Tree(
            "level1",
            1.0,
            (
                ktree.Tree("level2a", 2.0),
                ktree.Tree("level2b", 3.0),
                ktree.Tree("level2c", 4.0, (ktree.Tree("level3", 5.0),)),
            ),
        )

        self.assertEqual(tree, expected_tree)
        os.remove(path)

    def test_init(self):
        base = os.getcwd()

        self.assertTrue(
            base + "/tests/tov/output-0000/static_tov/timertree.0.xml"
            in self.timers.tree_files[0]
        )
        self.assertTrue(
            base + "/tests/tov/output-0001/static_tov/timertree.0.xml"
            in self.timers.tree_files[0]
        )

        self.assertTrue(
            base + "/tests/tov/output-0000/static_tov/timertree.1.xml"
            in self.timers.tree_files[1]
        )
        self.assertTrue(
            base + "/tests/tov/output-0001/static_tov/timertree.1.xml"
            in self.timers.tree_files[1]
        )

    def test_getitem(self):
        # In the test files we have two identical timertree per process, so the
        # sum will be twice a given tree. We just check the first value

        self.assertEqual(self.timers[0].value, 2 * 1.6143)

    def test_median(self):
        # We just check the first value
        self.assertEqual(
            self.timers.median.value,
            median((self.timers[0].value, self.timers[1].value)),
        )

    def test_average(self):
        self.assertEqual(
            self.timers.average.value,
            mean((self.timers[0].value, self.timers[1].value)),
        )

    def test_keys(self):
        self.assertCountEqual(list(self.timers.keys()), [0, 1])

    def test_str(self):
        self.assertIn("[0, 1]", str(self.timers))


import sys

def default_smallvectors_type_ns(params):
    """
    Compute a dict with shape, ndim, dtype and size attributes computed from
    the given parameters.
    """

    ns = {}
    if params is None:
        return ns

    shape = list(params[:-1])
    for i, x in enumerate(shape):
        if x is int:
            shape[i] = None
    ns['shape'] = shape = tuple(shape)
    ns['ndim'] = len(shape)

    dtype = params[-1]
    if dtype is type:
        dtype = None
    ns['dtype'] = dtype

    size = 1
    for dim in shape:
        if dim is None:
            ns['size'] = None
            break
        size *= dim
    else:
        ns['size'] = size
    return ns

def mutating(func):
    """
    Decorator that marks functions for suitable only for mutable objects
    """

    func.__mutating__ = True

    return func