from datetime import datetime
import pandas as pd
from sklearn.model_selection import train_test_split

def create_features(source_df):
    '''
    Function to create features based on input dataframe with columns 'First Name' & 'Last Name Initial'

    Args:
        source_df (DataFrame): Input DataFrame with columns 'First Name' and 'Last Name Initial'.

    Returns:
        DataFrame: DataFrame object with features included.

    IMPORTANT: Make sure to add feature to the model.features in params.yml if desired to be used in the model.
    '''
    # Calculate the length of the first name and add a column
    source_df['Length of First Name'] = source_df['First Name'].apply(len)

    # Calculate the distance between the first letters of the first and second columns and add a column
    source_df['Distance'] = source_df.apply(lambda row: abs(ord(row['First Name'][0]) - ord(row['Last Name Initial'])), axis=1)

    return source_df

def create_target(features_df, coolness_factor):
    '''
    Create target variable based on 'Coolness' column.

    Args:
        features_df (DataFrame): DataFrame with the 'Coolness' column.
        coolness_factor (float): Threshold value to determine if a value is considered 'Cool'.

    Returns:
        DataFrame: DataFrame with the specified target variable.

    IMPORTANT: Make sure to add target to the model.target in params.yml if desired to be used in the model.
    '''
    features_df['is_Cool'] = features_df['Coolness'].apply(lambda x: 1 if x > coolness_factor else 0)
    return features_df

def process_csv(data_source_filepath, coolness_factor):
    '''
    Read CSV data, create features, and generate the target variable.

    Args:
        data_source_filepath (str): Filepath to the CSV data source.
        coolness_factor (float): Threshold value to determine if a value is considered 'Cool'.

    Returns:
        DataFrame: Processed DataFrame with features and target variable.

    '''
    # Read the CSV file into a pandas DataFrame
    source_df = pd.read_csv(data_source_filepath)

    # Add features
    features_df = create_features(source_df)

    # Add Classifier Categories
    full_df = create_target(features_df, coolness_factor)

    return full_df

def save_train_test_split(df, test_size, random_state, output_path):
    '''
    Split data into train and test sets, save them as CSV files, and return the filepaths.

    Args:
        df (DataFrame): Input DataFrame to be split into train and test sets.
        test_size (float): Proportion of the dataset to include in the test set.
        random_state (int): Seed for the random number generator.
        output_path (str): Directory path to save the train and test data.

    Returns:
        str: Filepath of the saved train data.
        str: Filepath of the saved test data.
    '''

    # Split the data into train and test sets
    train, test = train_test_split(df, test_size=test_size, random_state=random_state)

    # Get current datetime to append to output path
    current_datetime = datetime.now()
    formatted_datetime = current_datetime.replace(microsecond=0).isoformat()

    # Generate train and test data path
    train_data_path = f'{output_path}/train_{formatted_datetime}.csv'
    test_data_path = f'{output_path}/test_{formatted_datetime}.csv'

    # Save data to output path for modeling usage
    train.to_csv(train_data_path, sep=",", index=False, encoding="utf-8")
    test.to_csv(test_data_path, sep=",", index=False, encoding="utf-8")

    return train_data_path, test_data_path

if __name__ == '__main__':
    import argparse
    from helpers import read_params

    args = argparse.ArgumentParser()
    args.add_argument("--config", default="params.yml")
    parsed_args = args.parse_args()

    config = read_params(parsed_args.config)

    dataframe = process_csv(config['data_generator']['output_filepath'], config['data']['coolness_factor'])
    print(dataframe)


import requests
import json
from yelp.secrets import API_KEY

ENDPOINT = 'https://api.yelp.com'
SEARCH_PATH = '/v3/businesses/search'
BUSINESS_PATH = '/v3/businesses/'
REVIEWS = "/reviews"

BUSINESS_DATA_CACHE = "business_data_cache.json"
REVIEWS_DATA_CACHE = "reviews_data_cache.json"
BUSINESS_DETAILS_CACHE = "business_details_cache.json"

#Dictionary for maintaining the mapping of a cache file with it's URL
CACHE_MAP = {
    ENDPOINT + SEARCH_PATH: BUSINESS_DATA_CACHE
}

def open_cache(cache_file):
    '''opens the cache file if it exists and loads the data in the cache file into
    a dictionary. If the cache file does not exist, an empty dictionary is returned
    back to the user.

    :param cache_file: cache file to be opened. Expects a file in the JSON format.

    Returns
    -------
    The opened cache in dict format
    '''

    cache_dict = None
    try:
        cache = open(cache_file, 'r')
        cache_dict = json.loads(cache.read())
        cache.close()
    except:
        cache_dict = {}

    return cache_dict

def save_cache(cache_dict, cache_file):
    '''Given a dictionary, this method saves the data in the dictionary to the JSON
    file which acts as a cache.

    Parameters
    ---------
    cache_dict: Dictionary to be saved to the disk
    cache_file: File to be used for saving the dictionary

    Returns
    -------
    None

    '''
    dumped_json_cache = json.dumps(cache_dict)
    cache = open(cache_file, 'w')
    cache.write(dumped_json_cache)
    cache.close()

def make_request(url, cache_file, params=None):
    str_params = ""
    if params is not None:
        str_params = str(params)

    cache_key = url + str_params

    #retrieve the cache file from the CACHE_MAP.

    cache_dict = open_cache(cache_file)
    if cache_key in cache_dict.keys():
        print('Entry found in cache. Returning cached response....')
        return cache_dict.get(cache_key)
    else:
        print('Entry is not found in cache. Calling url ' + url + ' with params ' + str(params))

    headers = {
        'Authorization': 'Bearer %s' % API_KEY,
    }

    response = requests.get(url, headers=headers, params=params)

    #Save the response to the cache.
    cache_dict[cache_key] = response.json()
    save_cache(cache_dict, cache_file)

    return response.json()

def search_businesses_by_location(business_name, location):
    params = {
        'term': business_name.replace(' ', '+'),
        'location': location.replace(' ', '+'),
        'limit': 50
    }

    url = ENDPOINT + SEARCH_PATH
    return make_request(url, BUSINESS_DATA_CACHE, params)

def search_reviews_by_business_id(business_id):
    url = ENDPOINT + BUSINESS_PATH + business_id + REVIEWS
    return make_request(url, REVIEWS_DATA_CACHE, None)

def search_business_by_business_id(business_id):
    url = ENDPOINT + BUSINESS_PATH + business_id
    return make_request(url, BUSINESS_DETAILS_CACHE, None)

if __name__ == "__main__":
    print("Searching Yelp for Starbucks in Seattle: ")
    #print(json.dumps(search_businesses_by_location("dessert", "98109"), indent=2))
    # print("Searching Yelp for Starbucks in Ann Arbor: ")
    # print(json.dumps(search_businesses_by_location("starbucks", "AnnArbor"), indent=2))
    # print("Searching Yelp again for Starbucks in Seattle: ")
    # print(json.dumps(search_businesses_by_location("starbucks", "Seattle"), indent=2))
    # print(json.dumps(search_reviews_by_business_id("ZUI_aLwc7mXG8Dt1Sz3aXg"), indent=2))
    print(json.dumps(search_business_by_business_id("ZUI_aLwc7mXG8Dt1Sz3aXg"), indent=2))


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

from sys import stdin, stdout

while True:

    line = stdin.readline().strip()

    if line == "":
        break

    words = line.split(' ')
    for i in words:
        stdout.write(i + "\t1\n")


"""
Build the text processing pipeline

Remove this
"""
import argparse
import os

import config

import pandas as pd
import texthero as th
from texthero import stopwords, preprocessing

STOPWORDS = stopwords.DEFAULT
STOPWORDS = STOPWORDS.union(
    set([
        "article",
        "page",
        "wikipedia",
        "edit",
        "use",
        "one",
        "source",
        "like",
        "please",
        "thank",
        "good",
        "time",
        "link"
    ])
)

# custom pipelines
PIPELINE_CLEAN = [
    lambda s: th.fillna(s),
    lambda s: th.lowercase(s),
    lambda s: th.remove_digits(s, only_blocks=False),
    lambda s: th.remove_punctuation(s),
    lambda s: th.remove_brackets(s),
    lambda s: th.remove_diacritics(s),
    lambda s: th.remove_html_tags(s),
    lambda s: th.remove_urls(s),
    lambda s: th.remove_whitespace(s),
    lambda s: th.remove_stopwords(s, STOPWORDS),
    lambda s: th.stem(s) # snowball by default
]

PIPELINE_TOKENS = [
    lambda s: th.tokenize(s)
]

def clean_text(data, feature):
    """
    Clean text
    :param data: dataframe
    :param feature: feature with text
    :returns: dataframe
    """

    clean = config.CLEANED_TEXT

    # get data
    input_filename = data + ".csv"
    df = pd.read_csv(os.path.join("../data", input_filename))

    # clean text
    df[clean] = df[feature].pipe(th.clean, PIPELINE_CLEAN)
    # tokenize into new feature
    df['clean_tokens'] = df[feature].pipe(th.clean, PIPELINE_TOKENS)

    return df

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--data",   # name of data file
        type=str
    )
    parser.add_argument(
        "--feature",   # name of text feature
        type=str
    )

    args = parser.parse_args()

    # get preprocessed data
    cleaned = clean_text(args.data, args.feature)

    # store the file
    filename = args.data + "_clean.csv"
    cleaned.to_csv(os.path.join("../data", filename), index=False)

    print("Cleaned data stored in the `data` folder")


"""Added the provider_user_id to the flask_dance_oauth table

Revision ID: 9e57c4ed8a45
Revises: 1ab080a61204
Create Date: 2019-01-05 00:38:30.274975

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '9e57c4ed8a45'
down_revision = '1ab080a61204'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('flask_dance_oauth', sa.Column('provider_user_id', sa.String(length=256), nullable=True))
    op.create_unique_constraint(op.f('uq_flask_dance_oauth_provider_user_id'), 'flask_dance_oauth', ['provider_user_id'])
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(op.f('uq_flask_dance_oauth_provider_user_id'), 'flask_dance_oauth', type_='unique')
    op.drop_column('flask_dance_oauth', 'provider_user_id')
    # ### end Alembic commands ###


#encoding:utf8
from flask import  Flask, render_template
from flask.ext.bootstrap import Bootstrap

#安装 pip install flssk-wtf
#加载 form表单
from flask.ext.wtf import Form

#加载 StringField文本字段,SubmitField提交按钮
from wtforms import StringField, SubmitField

#加载 验证函数
from wtforms.validators import Required

app = Flask(__name__)
bootstrap = Bootstrap(app)

#跨站请求伪造保护 密钥
app.config['SECRET_KEY'] = 'linuhub'

#定义表单类
class NameForm(Form):
 	name = StringField('What is you name? ', validators=[Required()])
 	submit = SubmitField('Submit')

#路由方法
@app.route('/', methods=['GET', 'POST'])

#在视图函数中处理表单
def index():
	name = None
	form = NameForm()
	if form.validate_on_submit():
		name = form.name.data
		form.name.data = ''
	return render_template('index.html', form=form, name=name)

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


def extractVouriatransBlogspotCom(item):
	'''
	Parser for 'vouriatrans.blogspot.com'
	'''

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	tagmap = [
		('ibtmlff',       'I Became The Male Lead\'s Female Friend.',                      'translated'),
		('irvp',          'I Raised the Villains Preciously',                      'translated'),
		('tinpff',        'There is No Place For Fakes',                      'translated'),
		('PRC',       'PRC',                      'translated'),
		('Loiterous', 'Loiterous',                'oel'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @当前项目名 : python demo
# 接口实际值处理（返回编译过的实际值）

from assertpy import assert_that
from privately_owned.Port_Compile import OtherInterfaces_compile,workOrder_compile,\
    equipmentSchedule,StatisticsOfRepairQuantity,ListOfComplaints
from appletConnector import initialize,TheRepairOrderInterface,assets_management,rests, addKind,SystemAppController
from appletConnector import UserAppController
from privately_owned.method import transform_dataType
from privately_owned.Task_handling_button import IndependentMethod
from privately_owned.dicti_data_dispose import dictionaries
from utils.privately_owned.timeDisposal import TimeFormat

############接口实际处理（返回实际值）###################################

class repairs_workOrder:
    """报修工单模块实际值"""

    def __init__(self, JSESSIONID, post_Parameter):
        """
        :param JSESSIONID:
        :param post_Parameter: 接口要传入的post参数
        """
        self.JSESSIONID = JSESSIONID
        self.post_Parameter = post_Parameter
        self.compile_actualValue = None

    def applet_EventModules(self,state_name,userinfo):
        """
        小程序事件模块实际值
        :return:
        """
        url=None
        post_Parameter={};finish_date2=None;list_workOrder_strState=[];list_workOrder=None
        for key, value in self.post_Parameter.items():
            post_Parameter[key]=value
        # 去掉开始日期和结束日期的时间
        begin_date=post_Parameter["开始日期"]
        if begin_date:
            begin_date=begin_date[:10]
        finish_date1 = post_Parameter["结束日期"]
        if finish_date1:
            finish_date2 = finish_date1[:10]
        post_Parameter["开始日期"]=begin_date
        post_Parameter["结束日期"] = finish_date2
        list_workOrder_initial=None
        #获取待响应/预约中/待处理/处理中/已处理/已挂起列表数据接口的数据,小程序事件，返回工单列表
        if state_name == "外协_待响应" or state_name == "外协_预约中" or state_name == "外协_待处理" or state_name == "外协_处理中" or state_name == "外协_已处理" or state_name == "外协_已挂起":
            list_workOrder_initial,req_text,url = TheRepairOrderInterface(self.JSESSIONID, post_Parameter).chooseListData()
        #获取外协_已关单列表数据接口的数据,小程序事件，返回工单列表
        elif state_name == "外协_已关单":
            list_workOrder_initial,req_text,url = TheRepairOrderInterface(self.JSESSIONID,post_Parameter).closedTicketListData()
        #获取全部工单、紧急事件、驻场事件（包含已关单数据）列表数据接口的数据,小程序事件，返回工单列表
        elif state_name == "全部工单":
            post_Parameter["是否完成的工单"] = None
            list_workOrder_initial,url = TheRepairOrderInterface(self.JSESSIONID,post_Parameter).allListData()
        list_workOrder_intState = workOrder_compile(self.JSESSIONID, list_workOrder_initial).compile_homePage(userinfo )
        # 把工单整数类型的工单状态编译成状态名称
        for workOrder in list_workOrder_intState:
            int_state=workOrder["工单状态"]
            state_name = dictionaries(self.JSESSIONID, int_state).ADictionaryTable()  # 整数的工单状态转化成str工单名称
            workOrder["工单状态"]=state_name
            list_workOrder_strState.append( workOrder)
        # 截取工单更新日期和创建日期的日期
        list_dataKey = ["工单创建日期", "工单更新日期"]
        list_workOrder = TimeFormat(list_workOrder_strState, list_dataKey).CaptureTheAate("%Y-%m-%d")
        return list_workOrder,url

class ReportStatistics_class :
    """报修统计模块数据对比测试实际值"""

    def __init__(self, dicti_parameterPacket):
        """
        :param dicti_parameterPacket: 接口要传入的post参数
        """
        self.dicti_parameterPacket = dicti_parameterPacket

    def inquire_ReportStatistics(self, module):
        """
        报修统计页面（报修数据统计、故障类型统计）
        :return:
        """
        deviceList=None;list_office=None;begin_date=None;finish_date=None;deviceList=None;url=None;list_workOrder_compile=None;test_module=None
        new_workOrder_compile=[]
        list_office=self.dicti_parameterPacket["所选单位ID"];begin_date=self.dicti_parameterPacket["开始日期"];finish_date=self.dicti_parameterPacket["结束日期"]
        JSESSIONID = self.dicti_parameterPacket["登录用户JSESSIONID"]
        if module == "报修数量":
            deviceList,url = rests(JSESSIONID).numCountData(list_office, begin_date, finish_date)
            test_module="客户端-首页-报修统计（除普通用户外）-报修数量统计；服务端-报修统计-报修数量统计；"
            # deviceList=[{'cuser': {'office': {'id': 'e155a7d8e34f4e339d5207ab33e2add4', 'name': '生物城第一高级中学分校', 'hasChildren': False, 'type': '2', 'parentId': '0'},
            #                        'loginFlag': '1', 'roleNames': '', 'admin': False}, 'officeCountNum': '208', 'handleTaskFlag': False, 'histroryFlag': False}]
        elif module == "故障数量":
            deviceList,url = rests(JSESSIONID).faultCountData(list_office, begin_date, finish_date)
            test_module = "客户端-首页-报修统计（除普通用户外）-故障类型统计；服务端-报修统计-故障类型统计；"
            # deviceList =[{'prbTp': {'id': '3c1fa83ea73e46aa8b0745ea6e424f0c', 'prbTpNm': '教学功能室设备'}, 'prbTpTypeNum': '52', 'handleTaskFlag': False, 'histroryFlag': False, 'customSort': 0},
            #              {'prbTp': {'id': '0756e6cf572a4ecf82074b84fb298182', 'prbTpNm': '电脑故障'}, 'prbTpTypeNum': '33', 'handleTaskFlag': False, 'histroryFlag': False, 'customSort': 0},
            #              {'prbTp': {'id': 'fc5478163a6749f78300dbc6801d99ed', 'prbTpNm': '摄像头'}, 'prbTpTypeNum': '33', 'handleTaskFlag': False, 'histroryFlag': False, 'customSort': 0},
            #              {'prbTp': {'id': 'c5c08f65faf049778e391588565d5ad4', 'prbTpNm': '电子教学设备'}, 'prbTpTypeNum': '27', 'handleTaskFlag': False, 'histroryFlag': False, 'customSort': 0},
            #              {'prbTp': {'id': '7370317620c443cfbe717945ec59771c', 'prbTpNm': '其他设备'}, 'prbTpTypeNum': '14', 'handleTaskFlag': False, 'histroryFlag': False, 'customSort': 0},
            #              {'prbTp': {'id': 'e0f6567f1d9c4db3b114fd54f89523a4', 'prbTpNm': '网络设备'}, 'prbTpTypeNum': '14', 'handleTaskFlag': False, 'histroryFlag': False, 'customSort': 0},
            #              {'prbTp': {'id': '802a6a7a1dbb4bc389cb46f1b54980e1', 'prbTpNm': '办公设备'}, 'prbTpTypeNum': '14', 'handleTaskFlag': False, 'histroryFlag': False, 'customSort': 0},
            #              {'prbTp': {'id': 'bc860ff03eb54441954b1a794e835a8c', 'prbTpNm': '监控设备'}, 'prbTpTypeNum': '9', 'handleTaskFlag': False, 'histroryFlag': False, 'customSort': 0},
            #              {'prbTp': {'id': '5851adfeb3fd469aac7c60ec17545061', 'prbTpNm': '广播设备'}, 'prbTpTypeNum': '6', 'handleTaskFlag': False, 'histroryFlag': False, 'customSort': 0},
            #              {'prbTp': {'id': 'f65b0b91ae074eecb330dabb994653dd', 'prbTpNm': '打印设备'}, 'prbTpTypeNum': '6', 'handleTaskFlag': False, 'histroryFlag': False, 'customSort': 0}]
            # 编译接口返回的数据
        list_workOrder_compile = StatisticsOfRepairQuantity(JSESSIONID, deviceList).ReportStatistics(module)
        for workOrder_compile in list_workOrder_compile: # 把字符串的工单数转化成整数
            workOrder_number=int(workOrder_compile["工单数"])
            workOrder_compile["工单数"]=workOrder_number
            new_workOrder_compile.append(workOrder_compile)
        return  new_workOrder_compile,url, test_module

class AssetsOfEquipment_actualValue:
    """资产设备模块实际值"""

    def __init__(self,dicti_parameterPacket):
        """
        :param JSESSIONID:
        :param post_Parameter: 接口要传入的post参数
        """
        self.dicti_parameterPacket = dicti_parameterPacket
        self.compile_actualValue=None

    def equipmentSchedule(self):
        """
        设备清单页面实际值
        :return:
        """
        deviceList = None;url = None;list_workOrder_compile = None;str_officeID=None
        str_officeID= self.dicti_parameterPacket["所选单位ID"]
        devicename = self.dicti_parameterPacket["设备名称"]
        batchNo = self.dicti_parameterPacket["批次"]
        JSESSIONID = self.dicti_parameterPacket["登录用户JSESSIONID"]
        post_Parameter = {"单位ID": str_officeID, "设备名称": devicename, "批次": batchNo}
        """获取接口数据"""
        deviceList,url = assets_management(JSESSIONID,post_Parameter).equipListData()
        """编译接口数据"""
        list_workOrder_compile = equipmentSchedule(JSESSIONID, deviceList).compile_equipmentSchedule()
        # list_workOrder_compile=[{'设备名称': '硬盘dddddddddddddddddddddddddd', '跟新时间': '2019-08-09 10:32:12', '创建时间': '2019-08-01 13:52:21',
        #                          '批次': '202008014560024', '设备品牌': '戴尔1', '设备状态': '1', '位置信息': 'e70aeecc0eab411dbc20214b98ee3807',
        #                          '设备类型ID': '090ccfed6c0e49c9a097dba47ab069b7', '设备ID': 'd8b86fbe8f3840a389c7671e6228eaea', '设备编号': '878637654536355840.jpg'}]
        return list_workOrder_compile,url

class  ComplaintsModule:
    """投诉模块实际值"""

    def __init__(self,dicti_parameterPacket):
        """
        :param dicti_parameterPacket:参数包
        """
        self.dicti_parameterPacket = dicti_parameterPacket
        self.compile_actualValue=None

    def add_ComplaintsModule(self):
        """
        新增投诉接口
        :return:
        """
        loginName = self.dicti_parameterPacket["登录名"] ; roleName = self.dicti_parameterPacket["用户权限"]
        JSESSIONID =self.dicti_parameterPacket["登录用户JSESSIONID"] ;complaint_Title =self.dicti_parameterPacket["投诉标题"]
        complaint_phone = self.dicti_parameterPacket["用户联系电话"] ;complaint_content = self.dicti_parameterPacket["投诉内容"]
        post_Parameter={"投诉标题":complaint_Title,"投诉人电话":complaint_phone,"投诉内容":complaint_content}
        # 调用新增投诉接口
        InterfaceReturnValue,url = addKind(JSESSIONID).add_manualOperation_complain(post_Parameter)
        # 断言返回值
        assert_that(InterfaceReturnValue).described_as('新增投诉失败').is_equal_to("投诉成功，已通知服务台处理")
        print("\033[0;37;40m登录用户：%r，用户权限：%r,新增投诉成功,已通知服务台处理"%(loginName,roleName))
        return url

    def amend_ComplaintsModule(self,procedure):
        """
        投诉模块数据修改
        :param procedure:
        :return:
        """
        JSESSIONID=self.dicti_parameterPacket["登录用户JSESSIONID"]; post_Parameter=None
        if procedure == "服务台受理投诉，指派被投诉人：运维工程师（四组）" or procedure == "服务台受理投诉，指派被投诉人：运维组长（四组）":
            post_Parameter = {"投诉标题": self.dicti_parameterPacket["投诉标题"], "投诉人电话": self.dicti_parameterPacket["投诉人电话"],"投诉内容": self.dicti_parameterPacket["投诉内容"],
                              "投诉级别": self.dicti_parameterPacket["投诉级别"],"处理方案": self.dicti_parameterPacket["处理方案"],
                              "投诉单ID": self.dicti_parameterPacket["投诉单ID"],"被投诉人ID": self.dicti_parameterPacket["被投诉人ID"],
                              "处理结果":None,"操作": self.dicti_parameterPacket["操作"]}
        elif procedure == "运维工程师填写处理结果" or procedure == "运维组长填写处理结果" or procedure == "运维工程师修改处理结果" or procedure == "运维组长修改处理结果":
            post_Parameter =  {"投诉单ID": self.dicti_parameterPacket["投诉单ID"],"处理结果":self.dicti_parameterPacket["处理结果"],"操作": self.dicti_parameterPacket["操作"]}
        elif procedure == "服务台再次受理投诉，指派被投诉人：运维工程师（四组）" or procedure == "服务台再次受理投诉，指派被投诉人：运维组长（四组）":
            post_Parameter =  {"投诉单ID": self.dicti_parameterPacket["投诉单ID"],"被投诉人ID": self.dicti_parameterPacket["被投诉人ID"],"处理方案": self.dicti_parameterPacket["处理方案"],
                              "操作": self.dicti_parameterPacket["操作"]}
        elif procedure == "普通用户确认处理结果：未解决" or procedure == "用户管理员确认处理结果：未解决":
            post_Parameter =  {"投诉单ID": self.dicti_parameterPacket["投诉单ID"],"操作": self.dicti_parameterPacket["操作"]}
        elif procedure == "普通用户再次确认处理结果：已解决" or procedure == "用户管理员确认处理结果：已解决":
            post_Parameter =  {"投诉单ID": self.dicti_parameterPacket["投诉单ID"],"操作": self.dicti_parameterPacket["操作"]}
        # 修改投诉信息数据接口
        InterfaceReturnValue,url = addKind(JSESSIONID).add_manualOperation_updatesuggest(post_Parameter)
        if procedure =="服务台受理投诉，指派被投诉人：运维工程师（四组）" or procedure =="服务台受理投诉，指派被投诉人：运维组长（四组）" or procedure =="服务台再次受理投诉，指派被投诉人：运维工程师（四组）":
            assert_that(InterfaceReturnValue).described_as('服务台受理投诉，并且填写处理意见不成功').is_equal_to("填写处理意见成功，已通知工程师")
        elif procedure =="运维工程师修改处理结果" or procedure =="运维工程师填写处理结果" or procedure =="运维组长填写处理结果":
            assert_that(InterfaceReturnValue).described_as('运维工程师（运维组长），填写处理结果不成功').is_equal_to("填写处理结果成功，已通知客户确认")
        return url

    def  inquire_complaint_page(self):
        """
        投诉页面数据查询接口，返回编译过的数据
        :return:
        """
        JSESSIONID=self.dicti_parameterPacket["登录用户JSESSIONID"] ; monthNum=self.dicti_parameterPacket["日期参数"]
        titleAndcontent = self.dicti_parameterPacket["筛选条件内容或者标题"]
        post_Parameter ={"日期范围":monthNum,"筛选条件内容或者标题":titleAndcontent}
        # 调用投诉清单接口
        list_ListOfComplaints,url = rests(JSESSIONID).Complaint_list_page(post_Parameter)
        ##############################################################################################################
        """编译从接口投诉清单返回的数据"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
        list_workOrder_compile = ListOfComplaints(list_ListOfComplaints).compile_TheComplaintpage()
        return list_workOrder_compile,url

class WorkOrderProcess_actualValue:
    """工单流程，调接口获取返回值，并编译返回值"""

    def __init__(self, FilterParameters,post_Parameter=None):
        """
        :param JSESSIONID:
        :param post_Parameter: 接口要传入的post参数
        """
        self.FilterParameters=FilterParameters
        self.post_Parameter = post_Parameter
        self.compile_actualValue = None

    def WorkOrderList_actualValue_console(self,connector):
        """
        工单清单页面数据对比实际值控制台
        :return:
        """
        list_actualValue=None; post_Parameter=None; url=None
        if connector=="小程序首页工单":
            list_actualValue, post_Parameter, url = WorkOrderProcess_actualValue(self.FilterParameters).TheRepairSquare_noOffTicketListData()  # 小程序首页工单
        elif connector=="内部代办理工单":
            officeID = self.FilterParameters["所选单位ID"]
            list_actualValue, post_Parameter, url = WorkOrderProcess_actualValue(self.FilterParameters).TheRepairSquare_InsideRepairListData(True,officeID) # 内部代办理工单
        elif connector=="用户管理员区域管理员外协报修列表数据":
            officeID = self.FilterParameters["所选单位ID"]
            list_actualValue, post_Parameter, url = WorkOrderProcess_actualValue(self.FilterParameters).TheRepairSquare_ExternalRepairListData(officeID) # 用户管理员区域管理员外协报修列表数据
        elif connector=="外部用户-我的报修":
            list_actualValue, post_Parameter, url = WorkOrderProcess_actualValue(self.FilterParameters).TheRepairSquare_page( ) # 外部用户-我的报修
        elif connector=="全部工单、紧急事件、驻场事件（包含已关单数据）":
            list_actualValue, post_Parameter, url = WorkOrderProcess_actualValue(self.FilterParameters).TheRepairSquare_allListData( ) # 全部工单、紧急事件、驻场事件（包含已关单数据）
        elif connector == "外协未关单工单列表页面":
            list_actualValue, post_Parameter, url = WorkOrderProcess_actualValue(self.FilterParameters).TheRepairSquare_chooseListData()  # 外协未关单工单列表页面
        elif connector == "已关单列表数据":
            list_actualValue, post_Parameter, url = WorkOrderProcess_actualValue(self.FilterParameters).TheRepairSquare_closedTicketListData()  # 已关单列表数据
        return list_actualValue, post_Parameter, url

    def add_workOrder(self,procedure):
        """
       一键报修接口，并编译返回值
       :return:
       """
        InterfaceReturnValue=None
        JSESSIONID = self.FilterParameters["登录用户JSESSIONID"]
        post_Parameter={"工单标题":self.FilterParameters["工单标题"], "故障类型ID":self.FilterParameters["故障类型ID"],"工单报修描述":self.FilterParameters["工单报修描述"],
                        "预约日期":self.FilterParameters["预约日期"], "预约时间段":self.FilterParameters["预约时间段"],"资产设备id":self.FilterParameters["资产设备id"],
                        "工单服务类型":self.FilterParameters["工单服务类型"]}
        # 调用新增工单接口
        if procedure == "普通用户-一键报修":
            InterfaceReturnValue = initialize(JSESSIONID).AKeyRepairService(post_Parameter)
        elif procedure == "服务台-PC端-报修工单":
            pass
        # 断言返回值
        assert_that(InterfaceReturnValue).described_as('2/新增工单失败').is_equal_to("提交成功，请等待信息中心管理员进行处理！")
        print("")

    def amend_sjTicketOperating_sjTicketOperating(self,Subordinate_procedure):
        """
         操作按钮获取表单流程，做除了一件报修以外的所有操作，都要先调一下
       接单/改派/改派审核/到达现场/挂起/挂起审核/解挂/完成工单/评价接口
        :param Subordinate_procedure: 工单操作步骤名称
        :param loginName:
        :param roleName:
        :return:
        """
        InterfaceReturnValue=None; positional="操作成功"; JSESSIONID = self.FilterParameters["登录用户JSESSIONID"]
        # 获取接单/改派/改派审核/到达现场/挂起/挂起审核/解挂/完成工单/评价接口post参数
        sjTicketOperating_post={"工单ID":self.FilterParameters["工单ID"],"工单编号":self.FilterParameters["工单编号"],"工单报修人ID":self.FilterParameters["工单报修人ID"],"工单状态":self.FilterParameters["工单状态"],
                                "工单改派人ID":self.FilterParameters["工单改派人ID"],"工单处理人ID":self.FilterParameters["工单处理人ID"],"流程实例id":self.FilterParameters["流程实例id"],"报修人电话":self.FilterParameters["报修人电话"],
                                "预约开始时间":self.FilterParameters["预约开始时间"],"预约结束时间":self.FilterParameters["预约结束时间"],"确认开始服务时间":self.FilterParameters["确认开始服务时间"],"确认结束服务时间":self.FilterParameters["确认结束服务时间"],
                                "工单范围":self.FilterParameters["工单范围"],"任务名称":self.FilterParameters["任务名称"],"任务定义Key":self.FilterParameters["任务定义Key"],"意见状态":self.FilterParameters["意见状态"],
                                "工单服务类型":self.FilterParameters["工单服务类型"],"任务意见":self.FilterParameters["任务意见"],"事件解决方案":self.FilterParameters["事件解决方案"],"预约时间段":self.FilterParameters["预约时间段"],
                                "内部处理结果":self.FilterParameters["内部处理结果"],"评级":self.FilterParameters["评级"],"用户评价":self.FilterParameters["用户评价"],"挂起下拉框理由":self.FilterParameters["挂起下拉框理由"],
                                "挂起状态字段":self.FilterParameters["挂起状态字段"],"改派人群组ID":self.FilterParameters["改派人群组ID"]}
        # 调用关于工作流的接口接口
        sjTicketFlow_post ={"任务id":self.FilterParameters["任务id"],"任务名称":self.FilterParameters["任务名称"],"任务定义Key":self.FilterParameters["任务定义Key"],"流程实例id":self.FilterParameters["流程实例id"],
                            "流程定义id":self.FilterParameters["流程定义id"],"任务状态":self.FilterParameters["任务状态"],"处理类型":self.FilterParameters["处理类型"]}
        # 当运维组长改派待响应状态下的工单时，系统会获取改派人的位置信息
        if  Subordinate_procedure =="组长(四组)-待响应-改派-工程师(四组)" or Subordinate_procedure =="服务台(一号)-已挂起-改派-工程师(四组)" or Subordinate_procedure =="服务台-已挂起-改派-五组-运维工程师":
            changeTicketPosition_post={"工单ID":self.FilterParameters["工单ID"],"工单改派人ID":self.FilterParameters["工单改派人ID"]}
            positional,req_text = SystemAppController(JSESSIONID, changeTicketPosition_post).changeTicketPosition()
        # 调用“操作按钮获取表单流程”接口
        operating = TheRepairOrderInterface(JSESSIONID, sjTicketFlow_post).sjTicketFlow()
        if operating=="操作成功" and positional=="操作成功":
            # 调用接单/改派/改派审核/到达现场/挂起/挂起审核/解挂/完成工单/评价接口
            InterfaceReturnValue = TheRepairOrderInterface(JSESSIONID, sjTicketOperating_post).sjTicketOperating()
        else:
            print("操作按钮获取表单流程接口：",operating);print("改派更新位置接口：", operating)
        # 断言返回值
        assert_that(InterfaceReturnValue).described_as("“%r”操作，调用sjTicketOperating接口操作失败"%procedure).is_equal_to("操作成功")
        print("\033[1;34;40m操作按钮获取表单流程，操作成功；\033[0m\033[4;35;40m登录用户：%r，用户权限：%r" % (loginName, roleName))
        print("")

    def  TheRepairSquare_page(self):
        """
        报修广场数据查询接口,调用小程序--客户端--报修广场--我的报修接口，返回编译过的数据
        :return:
        """
        JSESSIONID = self.FilterParameters["登录用户JSESSIONID"]
        startDate = self.FilterParameters["开始日期"];endingDate = self.FilterParameters["结束日期"]
        post_Parameter = {"开始日期": startDate, "结束日期": endingDate}
        # 调用小程序--客户端--报修广场--我的报修接口
        list_ListWorkOrder,url = TheRepairOrderInterface(JSESSIONID,post_Parameter).MyRepairListData()
        ##############################################################################################################
        """编译从接口投诉清单返回的数据"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
        list_workOrder = workOrder_compile(list_ListWorkOrder).WorkOrderProcess_MyRepairListData(self.FilterParameters)
        return list_workOrder,post_Parameter,url

    def TheRepairSquare_InsideRepairListData(self,effect=True,location_office=None):
        """
        报修广场--内部--数据查询接口，返回编译过的数据
        :return:
        """
        list_workOrder=None;JSESSIONID = self.FilterParameters["登录用户JSESSIONID"]
        startDate = self.FilterParameters["开始日期"]
        if type(startDate)==type(["1"]):
            startDate=startDate[0]
        endingDate = self.FilterParameters["结束日期"]
        if type(endingDate)==type(["1"]):
            endingDate=endingDate[0]
        post_Parameter = {"开始日期": startDate, "结束日期": endingDate,"所在单位":location_office}
        # 调用小程序--客户端--报修广场--内部
        list_ListWorkOrder,req_text,url = TheRepairOrderInterface(JSESSIONID, post_Parameter).InsideRepairListData()
        ##############################################################################################################
        """编译从接口投诉清单返回的数据"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
        # "1":数据对比用户；
        if effect:
            list_workOrder = workOrder_compile(list_ListWorkOrder).WorkOrderProcess_InsideRepairListData(self.FilterParameters)
        # "1":获取部分post请求数据
        else:
            list_workOrder = OtherInterfaces_compile(list_ListWorkOrder).WorkOrderProcess_Post(self.FilterParameters,req_text)
        return list_workOrder,post_Parameter,url

    def TheRepairSquare_ExternalRepairListData(self,office_id=None):
        """
        报修广场--外协--数据查询接口，返回编译过的数据
        :return:
        """
        list_workOrder = None
        JSESSIONID = self.FilterParameters["登录用户JSESSIONID"]
        startDate = self.FilterParameters["开始日期"]
        if type(startDate) == type(["1"]):
            startDate = startDate[0]
        endingDate = self.FilterParameters["结束日期"]
        if type(endingDate) == type(["1"]):
            endingDate = endingDate[0]
        post_Parameter = {"开始日期": startDate, "结束日期": endingDate, "所在单位": office_id}
        # 调用小程序--客户端--报修广场--外协接口
        list_ListWorkOrder,url = TheRepairOrderInterface(JSESSIONID,  post_Parameter).ExternalRepairListData()
        ##############################################################################################################
        """编译从接口投诉清单返回的数据"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
        list_workOrder = workOrder_compile(list_ListWorkOrder).WorkOrderProcess_ExternalRepairListData(self.FilterParameters)
        return list_workOrder,post_Parameter,url

    def TheRepairSquare_noOffTicketListData(self):
        """
        小程序--首页--工单
        :return:
        """
        JSESSIONID = self.FilterParameters["登录用户JSESSIONID"]
        list_workOrder_port=None;list_workOrder=None
        roleName = self.FilterParameters["用户权限"]
        if  roleName == "普通用户" or roleName == "用户管理员" or roleName == "区域管理员":
            post_Parameter={"工单范围":None,"月份":"7"}
        else:
            post_Parameter = {"工单范围":"0","月份":"6"}
        # 调用小程序--首页--工单接口
        list_workOrder_port,url = TheRepairOrderInterface(JSESSIONID, post_Parameter).noOffTicketListData()
        ##############################################################################################################
        """编译从接口工单清单返回的数据"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
        list_workOrder = workOrder_compile( list_workOrder_port).compile_homePage(self.FilterParameters) # 编译调用小程序--首页--工单接口
        return list_workOrder,post_Parameter,url

    def TheRepairSquare_allListData(self,effect=True):
        """
        小程序--客户端-报修广场-已完成和全部；小程序--服务端-事件-全部工单列表实际值；小程序--服务端--首页--紧急报修和驻场服务实际值
        :return:
        """
        post_Parameter={};list_workOrder=None;list_ListWorkOrder=None;list_workOrder_intState=None;list_workOrder_strState=[]
        selected_office=None;selected_module=None;startDate=None;endingDate=None
        print("self.FilterParameters:",self.FilterParameters)
        startDate = self.FilterParameters["开始日期"];endingDate = self.FilterParameters["结束日期"]; JSESSIONID = self.FilterParameters["登录用户JSESSIONID"]
        selected_module=self.FilterParameters["所属模块"];selected_office=self.FilterParameters["所选单位"]
        if selected_office=="空":
            selected_office=None
        if selected_module == "客户端-报修广场-已完成":
            post_Parameter={"工单类型":None,"开始日期":startDate,"结束日期":endingDate,"所选单位":selected_office,"工单范围":None,"是否完成的工单":"true","工单服务类型":None}
        elif selected_module == "客户端-报修广场-全部":
            post_Parameter = {"工单类型": None, "开始日期":startDate,"结束日期":endingDate,"所选单位":selected_office,"工单范围":None,"是否完成的工单":None,"工单服务类型":None}
        elif selected_module =="首页-紧急报修-未完成" :
            post_Parameter = {"工单类型": None, "开始日期":startDate,"结束日期":endingDate,"所选单位":selected_office,"工单范围":None,"是否完成的工单":"false","工单服务类型":"1"}
        elif  selected_module =="首页-紧急报修-已完成" :
            post_Parameter = {"工单类型": None, "开始日期":startDate,"结束日期":endingDate,"所选单位":selected_office,"工单范围":None,"是否完成的工单":"true","工单服务类型":"1"}
        elif  selected_module =="首页-紧急报修-全部" :
            post_Parameter = {"工单类型": None, "开始日期":startDate,"结束日期":endingDate,"所选单位":selected_office,"工单范围":None,"是否完成的工单":None,"工单服务类型":"1"}
        elif selected_module == "首页-驻场服务-未完成" :
            post_Parameter = {"工单类型": None, "开始日期":startDate,"结束日期":endingDate,"所选单位":selected_office,"工单范围":None,"是否完成的工单":"false","工单服务类型":"2"}
        elif  selected_module == "首页-驻场服务-已完成" :
            post_Parameter = {"工单类型": None, "开始日期":startDate,"结束日期":endingDate,"所选单位":selected_office,"工单范围": None,"是否完成的工单":"true", "工单服务类型":"2"}
        elif selected_module == "首页-驻场服务-全部":
            post_Parameter = {"工单类型": None,"开始日期":startDate,"结束日期":endingDate,"所选单位":selected_office,"工单范围": None,"是否完成的工单":None,"工单服务类型": "2"}
        elif selected_module == "服务端-事件-全部工单":
            post_Parameter = {"工单类型": None, "开始日期":startDate,"结束日期":endingDate,"所选单位":selected_office,"工单范围":None,"是否完成的工单":None,"工单服务类型":None}
        print("post_Parameter:",post_Parameter)
        # 调用接口
        list_ListWorkOrder,req_text,url  = TheRepairOrderInterface(JSESSIONID, post_Parameter).allListData()
        """编译从接口投诉清单返回的数据"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
        # "1":数据对比用户；
        if effect:
            list_workOrder = workOrder_compile(list_ListWorkOrder).WorkOrderProcess_allListData(self.FilterParameters)
        # "1":获取部分post请求数据
        else:
            list_workOrder = OtherInterfaces_compile(list_ListWorkOrder).WorkOrderProcess_Post(self.FilterParameters,req_text)
        return list_workOrder,post_Parameter,url

    def TheRepairSquare_chooseListData(self,effect=True):
        """
        小程序--服务端--事件（待响应；预约中；待处理；处理中；已处理；已关单；已挂起）
        :return:
        """
        req_text=None;list_workOrder_strState=[];post_Parameter = {};list_workOrder=None;list_ListWorkOrder=None
        JSESSIONID = self.FilterParameters["登录用户JSESSIONID"];startDate = self.FilterParameters["开始日期"];endingDate = self.FilterParameters["结束日期"]
        selected_module = self.FilterParameters["所属模块"]
        if selected_module == "服务端--事件--待响应":
            post_Parameter = {"工单状态":"2","开始日期":startDate,"结束日期":endingDate,"所在单位":None,"查看范围":None}
        elif selected_module == "服务端--事件--预约中":
            post_Parameter = {"工单状态":"3","开始日期":startDate,"结束日期":endingDate,"所在单位":None,"查看范围":None}
        elif selected_module == "服务端--事件--待处理":
            post_Parameter = {"工单状态": "4", "开始日期": startDate, "结束日期": endingDate, "所在单位": None, "查看范围": None}
        elif selected_module == "服务端--事件--处理中":
            post_Parameter = {"工单状态":"5","开始日期":startDate,"结束日期":endingDate,"所在单位":None,"查看范围":None}
        elif selected_module == "服务端--事件--已处理":
            post_Parameter = {"工单状态":"7","开始日期":startDate,"结束日期":endingDate,"所在单位":None,"查看范围":None}
        elif selected_module == "服务端--事件--已挂起":
            post_Parameter = {"工单状态": "6", "开始日期": startDate, "结束日期": endingDate, "所在单位": None, "查看范围": None}
        # 调用小程序--服务端--事件--待响应；预约中；待处理；处理中；已处理；已挂起
        list_ListWorkOrder,req_text,url = TheRepairOrderInterface(JSESSIONID,  post_Parameter).chooseListData()
        ##############################################################################################################
        """编译从接口投诉清单返回的数据"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
        if effect:
            list_workOrder_intState = workOrder_compile(list_ListWorkOrder).compile_homePage(self.FilterParameters)
            # 把工单整数类型的工单状态编译成状态名称
            for workOrder in list_workOrder_intState:
                int_state = workOrder["工单状态"]
                state_name = dictionaries(JSESSIONID, int_state).ADictionaryTable()  # 整数的工单状态转化成str工单名称
                workOrder["工单状态"] = state_name
                list_workOrder_strState.append(workOrder)
            # 截取工单更新日期和创建日期的日期
            list_dataKey = ["工单创建日期", "工单更新日期"]
            list_workOrder = TimeFormat(list_workOrder_strState, list_dataKey).CaptureTheAate("%Y-%m-%d")
        else:
            list_workOrder = OtherInterfaces_compile(list_ListWorkOrder).WorkOrderProcess_Post(self.FilterParameters,req_text)
        return list_workOrder,post_Parameter,url

    def TheRepairSquare_closedTicketListData(self):
        """
        已关单列表数据
        :param effect:
        :return:
        """
        req_text = None;post_Parameter = {};list_workOrder = None;list_ListWorkOrder = None;list_workOrder_strState=[]
        JSESSIONID = self.FilterParameters["登录用户JSESSIONID"];startDate = self.FilterParameters["开始日期"]
        endingDate = self.FilterParameters["结束日期"];selected_module = self.FilterParameters["所属模块"]
        post_Parameter = {"工单状态": "2", "开始日期": startDate, "结束日期": endingDate, "所在单位": None, "查看范围": None}
        # 调用小程序--服务端--事件--已关单
        list_ListWorkOrder, req_text, url = TheRepairOrderInterface(JSESSIONID, post_Parameter).closedTicketListData()
        list_workOrder_intState = workOrder_compile(list_ListWorkOrder).WorkOrderProcess_closedTicketListData(self.FilterParameters)
        # 把工单整数类型的工单状态编译成状态名称
        for workOrder in list_workOrder_intState:
            int_state = workOrder["工单状态"]
            state_name = dictionaries(JSESSIONID, int_state).ADictionaryTable()  # 整数的工单状态转化成str工单名称
            workOrder["工单状态"] = state_name
            list_workOrder_strState.append(workOrder)
        # 截取工单更新日期和创建日期的日期
        list_dataKey = ["工单创建日期", "工单更新日期"]
        list_workOrder = TimeFormat(list_workOrder_strState, list_dataKey).CaptureTheAate("%Y-%m-%d")
        return list_workOrder,post_Parameter,url

    def TheRepairSquare_sjTicketServe_details(self,post_Parameter):
        """
        工单详情
        :return:
        """
        new_workOrder_details=[]
        JSESSIONID = self.FilterParameters["登录用户JSESSIONID"]
        # 调用小程序--详情页面
        workOrder_details,url = TheRepairOrderInterface(JSESSIONID, post_Parameter).sjTicketServe_details()
        # 因为只有一条数据，所有加转化成列表
        new_workOrder_details.append(workOrder_details)
        """编译从接口工单清单返回的数据"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
        compile_workOrder = workOrder_compile(new_workOrder_details).connector_one(self.FilterParameters) # 编译调用小程序--首页--工单接口
        return compile_workOrder ,post_Parameter,url

class OtherInterfaces_actualValue:
    """其他接口实际值"""

    def __init__(self, JSESSIONID, FilterParameters=None,post_Parameter=None):
        """
        :param JSESSIONID:
        :param post_Parameter: 接口要传入的post参数
        """
        self.JSESSIONID = JSESSIONID
        self.FilterParameters=FilterParameters
        self.post_Parameter = post_Parameter
        self.compile_actualValue = None

    def findGroupList_actualValue(self):
        """
        查询所有群组(服务台改派用)
        :return:
        """
        # 调用接口获取接口返回值
        list_actualValue,url = UserAppController(self.JSESSIONID, None).findGroupList()
        # 编译接口返回值
        list_workOrder = OtherInterfaces_compile(self.JSESSIONID, list_actualValue).findGroupList_compile()
        # list_workOrder=[{'群组ID': '1c60c437542f44c8f8aa83a7c6a08dff9', '群组名称': '机动组5'}]
        return list_workOrder,url

    def findUserListByGroup_actualValue(self,group_id):
        """
        工单操作改派选人
        :return:
        """
        post_Parameter={"群组ID":group_id}
        # 调用接口获取接口返回值
        list_actualValue, url = UserAppController(self.JSESSIONID, None).findUserListByGroup(post_Parameter)
        # 编译接口返回值
        list_workOrder = OtherInterfaces_compile(self.JSESSIONID, list_actualValue).findUserListByGroup_compile()
        # list_workOrder=[{'用户ID': '5c2e57e50d904563b78acc6091970a67', '用户名称': '运维人员四'}, {'用户ID': 'fa20e86b843b4a53936d714afb967a7b', '用户名称': '运维组长'}]
        return list_workOrder, url


from os import listdir
from os.path import isfile, join, splitext
from tqdm import tqdm
import numpy as np
import csv
import sys
import pickle
import cv2

classes = ['articulated_truck', 'bicycle', 'bus', 'car',
           'motorcycle', 'non-motorized_vehicle', 'pedestrian',
           'pickup_truck', 'single_unit_truck', 'work_van', 'background']

# Load SVM model
#svmClassifier = None

with open('./model.pk1', 'rb') as f:
    svmClassifier = pickle.load(f)

def get_hog_features(images, cell, block, nbins):
    """
    Returns HoG features for all images.

    Adapted from tutorial 4.
    """
    cell_size = (cell, cell)  # h x w in pixels
    block_size = (block, block)  # h x w in cells

    img = images[0]

    # create HoG Object
    # winSize is the size of the image cropped to an multiple of the cell size
    hog = cv2.HOGDescriptor(_winSize=(img.shape[1] // cell_size[1] * cell_size[1],
                                  img.shape[0] // cell_size[0] * cell_size[0]),
                        _blockSize=(block_size[1] * cell_size[1],
                                    block_size[0] * cell_size[0]),
                        _blockStride=(cell_size[1], cell_size[0]),
                        _cellSize=(cell_size[1], cell_size[0]),
                        _nbins=nbins)

    n_cells = (img.shape[0] // cell_size[0], img.shape[1] // cell_size[1])

    hog_feats_list = []
    for img in images:
        # Compute HoG features
        hog_feats = hog.compute(img)\
                       .reshape(n_cells[1] - block_size[1] + 1,
                                n_cells[0] - block_size[0] + 1,
                                block_size[0], block_size[1], nbins) \
                       .transpose((1, 0, 2, 3, 4))  # index blocks by rows first

        # hog_feats now contains the gradient amplitudes for each direction,for each cell of its group for each group.
        # Indexing is by rows then columns.

        # computation for BlockNorm
        gradients = np.full((n_cells[0], n_cells[1], 8), 0, dtype=float)
        cell_count = np.full((n_cells[0], n_cells[1], 1), 0, dtype=int)

        for off_y in range(block_size[0]):
            for off_x in range(block_size[1]):
                gradients[off_y:n_cells[0] - block_size[0] + off_y + 1,
                          off_x:n_cells[1] - block_size[1] + off_x + 1] += \
                    hog_feats[:, :, off_y, off_x, :]
                cell_count[off_y:n_cells[0] - block_size[0] + off_y + 1,
                           off_x:n_cells[1] - block_size[1] + off_x + 1] += 1

        # Average gradients
        gradients /= cell_count

        hog_feats_list.append(gradients.ravel())

    return hog_feats_list

def classify_image(path_to_image):
    '''
    Classify the image contained in 'path_to_image'.

    You may replace this line with a call to your classification method
    '''
    image = cv2.imread(path_to_image, cv2.IMREAD_GRAYSCALE)
    images = np.array([cv2.resize(image, (128, 128))])

    test_img_features = get_hog_features(images, 4, 4, 8)
    test_img_features = np.array([x.flatten() for x in test_img_features])
    # testing
    label = svmClassifier.predict(test_img_features)[0]

    return label

def parse_dataset(path_to_dataset,nb_images):
    '''
    Parse every image contained in 'path_to_dataset' (a path to the training
    or testing set), classify each image and save in a csv file the resulting
    assignment

    dataset_result: dict structure returned by the function.  It contains the
            label of each image
    '''
    llist = listdir(path_to_dataset)
    dataset_result = {}

    do_break = False

    for count, name in enumerate(tqdm(llist)):
        dn = join(path_to_dataset, name)
        if isfile(dn):
            label = classify_image(dn)
            file_nb, file_ext = splitext(name)
            dataset_result[file_nb] = label
            if count == nb_images-1 or do_break:
                do_break = True
                break

        else:
            file_list = listdir(dn)
            for count1, file_name in enumerate(reversed(file_list)):
                file_name_with_path = join(dn, file_name)
                label = classify_image(file_name_with_path)
                file_nb, file_ext = splitext(file_name)
                if file_nb in dataset_result.keys():
                    print('error! ', file_nb, dataset_result[file_nb], ' vs ', file_name_with_path)
                dataset_result[file_nb] = label
                if count1 == nb_images-1 or do_break:
                    do_break = True
                    break

    return dataset_result

def save_classification_result(dataset_result, output_csv_file_name):
    '''
    save the dataset_result (a dict structure containing the class of every image)
    into a valid csv file.
    '''

    csvfile = open(output_csv_file_name, 'w')
    fieldnames = ['file_name', 'class_label']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    for file_number in dataset_result.keys():
        writer.writerow({'file_name': str(file_number), 'class_label': dataset_result[file_number]})

    csvfile.close()

if __name__ == '__main__':

    if len(sys.argv) < 3:
        print("\nUsage : \n\t python parse_classification_dataset.py PATH OUTPUT_CSV_FILE_NAME NUMBER_OF_IMAGES\n")
        print("\t PATH : path to the training or the testing dataset")
        print("\t OUTPUT_CSV_FILE_NAME : name of the resulting csv file\n")
        print("\t NUMBER_OF_IMAGES : number of images to be testing on\n")
    else:
        print('\nProcessing: ', sys.argv[1], '\n')
        dataset_result = parse_dataset(sys.argv[1], int(sys.argv[3]))
        save_classification_result(dataset_result, sys.argv[2])


"""MongoDB utility

    @author   : Liangjun Zhu

    @changelog:
    - 16-12-07  - lj - rewrite for version 2.0
    - 17-06-27  - lj - reorganize as basic class other than Global variables
    - 18-02-08  - lj - compatible with Python3.
    - 20-07-20  - lj - no need to invoke close() of MongoClient after use
"""
from __future__ import absolute_import, unicode_literals

import os
import sys
if os.path.abspath(os.path.join(sys.path[0], '..')) not in sys.path:
    sys.path.insert(0, os.path.abspath(os.path.join(sys.path[0], '..')))

from pymongo import MongoClient
from pymongo.errors import ConnectionFailure, InvalidOperation
from preprocess.text import DBTableNames, ModelParamFields

class ConnectMongoDB(object):
    """Connect to MongoDB, and close when finished."""

    def __init__(self, ip, port, maxPoolSize=None):
        """initial mongodb client by hostname and port.

        Starting with version 3.0 the MongoClient constructor no longer blocks while connecting to
         the server or servers, and it no longer raises ConnectionFailure if they are unavailable,
         nor ConfigurationError if the user's credentials are wrong.
         Instead, the constructor returns immediately and launches the connection process on
          background threads.
        --https://api.mongodb.com/python/current/api/pymongo/mongo_client.html
        """
        self.conn = MongoClient(ip, port, maxPoolSize=maxPoolSize)
        try:
            self.conn.admin.command('ismaster')
        except ConnectionFailure as err:
            sys.stderr.write('Could not connect to MongoDB: %s' % err)
            sys.exit(1)

    def get_conn(self):  # type: (...) -> MongoClient
        """get MongoDB connection."""
        return self.conn

    def close(self):
        """Close collection.

        Create this client once for each process, and reuse it for all operations.
        It is a common mistake to create a new client for each request, which is very inefficient.
        --https://stackoverflow.com/questions/41015490/how-can-i-force-pymongo-to-close-sockets

        So, for now, I will comment the close operation. By lj.
        """
        # self.conn.close()
        pass

class MongoQuery(object):
    """
    Query data from MongoDB
    """

    @staticmethod
    def get_init_parameter_value(db_model, param_name, field=ModelParamFields.value):
        """Query initial parameter value, raise exception if error occurs."""
        coll_param = db_model[DBTableNames.main_parameter]
        param_dict = coll_param.find_one({ModelParamFields.name: param_name})
        if param_dict is None or param_dict.get(field) is None:
            raise RuntimeError('%s item is not existed in MongoDB!' % param_name)
        return param_dict.get(field)

class MongoUtil(object):
    """Some utility functions."""

    @staticmethod
    def run_bulk(bulk, errmsg=''):
        """Execute bulk operations, do not raise exception.
        Deprecated from v3.5
        """
        try:
            bulk.execute()
        except InvalidOperation:
            print('WARNING: %s' % errmsg)

    @staticmethod
    def run_bulk_write(coll, req_list):
        """Run bulk_write.

        Reference: https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html
                   #pymongo.collection.Collection.bulk_write
        """
        if len(req_list) == 0:
            return None
        return coll.bulk_write(req_list)


import torch
import torch.nn
from torch.nn import functional as func
from torch.nn.utils import rnn as rnnutils

from mac import debug_helpers
from mac.debug_helpers import check_shape, save_all_locals
import numpy as np

# noinspection PyUnresolvedReferences
class MACRec(torch.nn.Module):
    def __init__(self, recurrence_length, ctrl_dim):
        super().__init__()
        self.recurrence_length = recurrence_length
        self.ctrl_dim = ctrl_dim

        self.cu_cells = torch.nn.ModuleList(
            [CUCell(ctrl_dim, recurrence_length) for _ in range(recurrence_length)]
        )
        self.ru_cells = torch.nn.ModuleList(
            [RUCell(ctrl_dim) for _ in range(recurrence_length)]
        )
        self.wu_cells = torch.nn.ModuleList(
            [WUCell(ctrl_dim) for _ in range(recurrence_length)]
        )

        self.initial_control = torch.nn.Parameter(torch.zeros(1, self.ctrl_dim))
        self.initial_mem = torch.nn.Parameter(torch.zeros(1, self.ctrl_dim))
        self.output_cell = OutputCell(ctrl_dim)

        self.reset_parameters()

    def reset_parameters(self):
        torch.nn.init.xavier_normal_(self.initial_control)
        torch.nn.init.xavier_normal_(self.initial_mem)

    def forward(self, question_words, image_vec, context_words):
        batch_size = context_words.shape[0]

        debug_helpers.check_shape(context_words, (batch_size, None, self.ctrl_dim))
        debug_helpers.check_shape(question_words, (batch_size, self.ctrl_dim * 2))
        debug_helpers.check_shape(image_vec, (batch_size, self.ctrl_dim, 14, 14))

        ctrl = self.initial_control.expand(batch_size, self.ctrl_dim)
        mem = self.initial_mem.expand(batch_size, self.ctrl_dim)

        for i in range(self.recurrence_length):
            cu_cell = self.cu_cells[i]
            ru_cell = self.ru_cells[i]
            wu_cell = self.wu_cells[i]
            ctrl = cu_cell(i, ctrl, context_words, question_words)
            ri = ru_cell(mem, image_vec, ctrl)
            mem = wu_cell(mem, ri, ctrl)
            debug_helpers.check_shape(mem, (batch_size, self.ctrl_dim))
            debug_helpers.check_shape(ri, (batch_size, self.ctrl_dim))
            debug_helpers.check_shape(ctrl, (batch_size, self.ctrl_dim))

        output = self.output_cell(question_words, mem)
        debug_helpers.check_shape(output, (batch_size, 28))
        return output

# noinspection PyUnresolvedReferences
class MACNet(torch.nn.Module):
    def __init__(self, mac: MACRec, total_words):
        super().__init__()

        self.ctrl_dim = mac.ctrl_dim
        self.mac: MACRec = mac
        self.kb_mapper = torch.nn.Sequential(
            torch.nn.Conv2d(1024, self.ctrl_dim, 3, padding=1),
            torch.nn.PReLU(),
            torch.nn.Conv2d(self.ctrl_dim, self.ctrl_dim, 3, padding=1),
            torch.nn.PReLU(),
        )

        self.embedding = torch.nn.Embedding(total_words + 1, self.ctrl_dim)
        self.lstm_processor = torch.nn.LSTM(
            self.ctrl_dim, self.ctrl_dim, bidirectional=True, batch_first=True
        )
        self.lstm_h0 = torch.nn.Parameter(torch.zeros(2, 1, self.ctrl_dim))
        self.lstm_c0 = torch.nn.Parameter(torch.zeros(2, 1, self.ctrl_dim))
        self.lstm_proj = torch.nn.Linear(self.ctrl_dim * 2, self.ctrl_dim)

        self.reset_parameters()

    def reset_parameters(self):
        torch.nn.init.xavier_normal_(self.lstm_h0)
        torch.nn.init.xavier_normal_(self.lstm_c0)

    def forward(self, kb, questions, qn_lens):
        batch_size = kb.shape[0]
        kb_reduced = self.process_img(kb, batch_size)
        context, question = self.process_qn(questions, qn_lens, batch_size)

        res = self.mac.forward(question, kb_reduced, context)
        debug_helpers.save_all_locals()
        return res

    def process_img(self, kb, batch_size):
        debug_helpers.check_shape(kb, (batch_size, 1024, 14, 14))
        kb_reduced = self.kb_mapper(kb)
        debug_helpers.check_shape(kb_reduced, (batch_size, self.ctrl_dim, 14, 14))
        return kb_reduced

    def process_qn(self, questions, qn_lens, batch_size):
        if isinstance(qn_lens, list):
            qn_lens = torch.from_numpy(np.array(qn_lens, dtype=np.int64))
        debug_helpers.check_shape(questions, (batch_size, None))
        debug_helpers.check_shape(qn_lens, (batch_size,))

        qn_tensors = self.embedding(questions)
        debug_helpers.check_shape(qn_tensors, (batch_size, None, self.ctrl_dim))
        packed_embedded = rnnutils.pack_padded_sequence(
            qn_tensors, qn_lens, batch_first=True
        )

        h0_c0_size = (2, batch_size, self.ctrl_dim)
        h0 = self.lstm_h0.expand(h0_c0_size).contiguous()
        c0 = self.lstm_c0.expand(h0_c0_size).contiguous()

        lstm_out, (hn, _) = self.lstm_processor(packed_embedded, (h0, c0))
        padded_lstm, _ = rnnutils.pad_packed_sequence(lstm_out, batch_first=True)
        proj_lstm = self.lstm_proj(padded_lstm)

        hn_concat = torch.cat([hn[0], hn[1]], -1)
        debug_helpers.check_shape(proj_lstm, (batch_size, None, self.ctrl_dim))
        debug_helpers.check_shape(hn_concat, (batch_size, self.ctrl_dim * 2))
        return proj_lstm, hn_concat

# noinspection PyUnresolvedReferences
class CUCell(torch.nn.Module):
    def __init__(self, ctrl_dim, recurrence_length):
        super().__init__()
        self.ctrl_dim = ctrl_dim

        self.step_trf = torch.nn.ModuleList(
            torch.nn.Linear(ctrl_dim * 2, ctrl_dim) for _ in range(recurrence_length)
        )
        self.ca_lin = torch.nn.Linear(ctrl_dim, 1)
        self.cq_lin = torch.nn.Linear(ctrl_dim * 2, ctrl_dim)

    def forward(self, step, prev_ctrl, context_words, question_words):
        batch_size, seq_len, _ = context_words.shape

        check_shape(prev_ctrl, (batch_size, self.ctrl_dim))
        check_shape(question_words, (batch_size, self.ctrl_dim * 2))
        check_shape(context_words, (batch_size, seq_len, self.ctrl_dim))

        question_words_localized = self.step_trf[step](question_words)

        c_concat = torch.cat([prev_ctrl, question_words_localized], 1)
        check_shape(c_concat, (batch_size, self.ctrl_dim * 2))
        cq = self.cq_lin(c_concat)
        check_shape(cq, (batch_size, self.ctrl_dim))

        cw_weighted = torch.einsum("bd,bsd->bsd", cq, context_words)
        ca = self.ca_lin(cw_weighted).squeeze(2)
        check_shape(ca, (batch_size, seq_len))

        cv = torch.nn.Softmax(dim=1)(ca)
        check_shape(cv, (batch_size, seq_len))

        next_ctrl = torch.einsum("bs,bsd->bd", cv, context_words)
        check_shape(next_ctrl, (batch_size, self.ctrl_dim))

        save_all_locals()
        return next_ctrl

# noinspection PyUnresolvedReferences
class RUCell(torch.nn.Module):
    default_image_size = (14, 14)

    def __init__(self, ctrl_dim: int):
        super().__init__()
        self.ctrl_dim = ctrl_dim

        self.mem_trf = torch.nn.Linear(ctrl_dim, ctrl_dim)
        self.ctrl_lin = torch.nn.Linear(ctrl_dim * 2, ctrl_dim)
        self.attn = torch.nn.Linear(ctrl_dim, 1)

    def forward(self, mem, kb, control):
        batch_size, ctrl_dim = mem.shape
        assert ctrl_dim == self.ctrl_dim

        kb_shape = (batch_size, ctrl_dim, 14, 14)
        check_shape(kb, kb_shape)
        check_shape(control, (batch_size, ctrl_dim))
        kb = kb.permute(0, 2, 3, 1)
        check_shape(kb, (batch_size, 14, 14, ctrl_dim))

        mem_trfed = self.mem_trf(mem)
        check_shape(mem_trfed, (batch_size, ctrl_dim))

        mem_kb_inter = torch.einsum("bc,bwhc->bwhc", mem_trfed, kb)
        mem_kb_inter_cat = torch.cat([mem_kb_inter, kb], -1)
        check_shape(mem_kb_inter_cat, (batch_size, 14, 14, ctrl_dim * 2))
        mem_kb_inter_cat_trf = self.ctrl_lin(mem_kb_inter_cat)
        check_shape(mem_kb_inter_cat_trf, (batch_size, 14, 14, ctrl_dim))

        ctrled = torch.einsum("bwhc,bc->bwhc", mem_kb_inter_cat_trf, control)
        attended_flat = self.attn(ctrled).view(batch_size, -1)
        check_shape(attended_flat, (batch_size, 14 * 14))
        attended = func.softmax(attended_flat, dim=-1).view(batch_size, 14, 14)
        check_shape(attended, (batch_size, 14, 14))

        retrieved = torch.einsum("bwhc,bwh->bc", kb, attended)
        check_shape(retrieved, (batch_size, ctrl_dim))
        save_all_locals()
        return retrieved

# noinspection PyUnresolvedReferences
class WUCell(torch.nn.Module):
    def __init__(self, ctrl_dim, use_prev_control=False, gate_mem=True):
        super().__init__()
        self.gate_mem = gate_mem
        self.use_prev_control = use_prev_control
        self.ctrl_dim = ctrl_dim

        self.mem_read_int = torch.nn.Linear(ctrl_dim * 2, ctrl_dim)
        if self.use_prev_control:
            self.mem_select = torch.nn.Linear(ctrl_dim, 1)
            self.mem_merge_info = torch.nn.Linear(ctrl_dim, ctrl_dim)
            self.mem_merge_other = torch.nn.Linear(ctrl_dim, ctrl_dim, bias=False)
        if self.gate_mem:
            self.mem_gate = torch.nn.Linear(ctrl_dim, 1)

    def forward(self, mem, ri, control, prev_control=None):
        batch_size, ctrl_dim = mem.shape
        assert ctrl_dim == self.ctrl_dim
        assert self.use_prev_control == (prev_control is not None)
        if prev_control is not None:
            check_shape(prev_control, (batch_size, None, ctrl_dim))
        check_shape(ri, (batch_size, ctrl_dim))
        check_shape(control, (batch_size, ctrl_dim))

        m_info = self.mem_read_int(torch.cat([ri, mem], 1))
        check_shape(m_info, (batch_size, ctrl_dim))

        if prev_control is not None:
            control_similarity = torch.einsum("bsd,bd->bsd", prev_control, control)
            control_expweight = self.mem_select(control_similarity)
            check_shape(control_expweight, (batch_size, None, 1))
            sa = torch.nn.functional.softmax(control_similarity.squeeze(2), dim=1)
            m_other = torch.einsum("bs,bsd->bd", sa, prev_control)
            m_info = self.mem_merge_other(m_other) + self.mem_merge_info(m_info)
        check_shape(m_info, (batch_size, ctrl_dim))

        if self.gate_mem:
            mem_ctrl = self.mem_gate(control).squeeze(1)
            ci = torch.sigmoid(mem_ctrl)
            check_shape(m_info, (batch_size, self.ctrl_dim))
            m_next = torch.einsum("bd,b->bd", mem, ci) + torch.einsum(
                "bd,b->bd", m_info, 1 - ci
            )
        else:
            m_next = m_info

        save_all_locals()
        return m_next

# noinspection PyUnresolvedReferences
class OutputCell(torch.nn.Module):
    def __init__(self, ctrl_dim, out_dim=28):
        super().__init__()
        self.ctrl_dim = ctrl_dim
        self.layers = torch.nn.Sequential(
            torch.nn.Linear(ctrl_dim * 3, ctrl_dim),
            torch.nn.PReLU(),
            torch.nn.Linear(ctrl_dim, out_dim),
        )

    def forward(self, h, mem):
        batch_size = mem.shape[0]
        check_shape(h, (batch_size, self.ctrl_dim * 2))
        check_shape(mem, (batch_size, self.ctrl_dim))

        return self.layers(torch.cat([h, mem], 1))


from datetime import datetime, timedelta
import requests
import json
import matplotlib.pyplot as plt

dataSource="https://opendata.ecdc.europa.eu/covid19/casedistribution/json"

# https://www.worldometers.info/world-population/population-by-country
ukPopulation = 67886011

timeWindow = 14

# This file stores the produced number data, starting on 09/06/2020
rateFile = "rate_data.txt"
rateData = json.load(open(rateFile))

# Date today
today = datetime.today()

# List of the last 14 dates
def get_report_dates():
    timestamps = [today - timedelta(days=x) for x in range(timeWindow)]
    dates = [d.strftime('%d/%m/%Y') for d in timestamps]

    if str(today.strftime('%d/%m/%Y')) in rateData:
         print("Data for today has already been fetched. Here's results:")
         print(json.dumps(rateData, indent=4))

         plot(rateData)
    else:
        fetch_latest_data(dates)

# Get data from dataSource
def fetch_latest_data(dates):
    publicData = json.loads(requests.get(dataSource).text)
    data = {d["dateRep"]: int(d["cases"]) for d in publicData["records"] if d["countriesAndTerritories"] == "United_Kingdom" and d["dateRep"] in dates}

    if str(today.strftime('%d/%m/%Y')) in data:
        print("Calculating using this New Cases data:")
        print(json.dumps(data, indent=4))
        calc_rate(data)
    else:
        print("No data has been published for today yet. Here's previous results:")
        print(json.dumps(rateData, indent=4))

# Calculate the rate over 100000 people
def calc_rate(data):
    allDayTotal = sum(list(data.values()))

    numberPer100k = (allDayTotal * 100000)/ukPopulation

    print("RATE: " + str(numberPer100k))

    write_rate_to_file(numberPer100k)

# Write new rate data to a file
def write_rate_to_file(numberPer100k):
    rateData[str(today.strftime('%d/%m/%Y'))] = numberPer100k

    with open(rateFile, 'w') as file:
        file.write(json.dumps(rateData, indent=4))

    plot(rateData)

def plot(rateData):
     x,y = zip(*sorted(rateData.items()))
     plt.plot_date(x,y, "-")
     plt.xlabel('dates')
     plt.ylabel('numbers')
     plt.grid()
     plt.show()

get_report_dates()


#this is comparision between threas and non-threads

import time

def sleeper(n, name):
    print("Hi! Iam thread {}, going to sleep for 5 sec.\n".format(name))
    time.sleep(n)
    print("{} just got up\n\n".format(name))

start = time.time()

for i in range(5):
    print("iteration",i,"has started")
    sleeper(5,i)

end = time.time()

print("time taken:",end-start)

learning threads, queues, locks/threads5 non-thread behavior moon.py


from sys import stdin as si

def make_path(num):
    l = [['.' for _ in range(8)] for _ in range(8)]
    l[0][0] = 'O'
    # placing X
    if num < 64:
        # placing last X
        row = num//8
        position = num % 8
        if position < 8:
            l[row][position] = 'X'
        if row > 0:
            for i in range(position+1, 8):
                l[row][i] = 'X'
        if row < 7:
            for i in range(position+1):   # +1 for corner X
                l[row+1][i] = 'X'
    for i in range(8):
        print("".join(l[i]))
    return

if __name__ == "__main__":
    for _ in range(int(si.readline().strip())):
        make_path(int(si.readline().strip()))

"""
https://www.codechef.com/JULY20B/problems/ADAKING
"""


"""
filename : twosums.py
author : Archit Joshi
language: python3

LeetCode problem 1 - Two Sums
Provisions made to accept user input in console.

"""

class Solution:
    """
    Class to test if a target value can be obtained by summing up two values
    from our list of input numbers. Return the indices of these two input number
    solutions. No duplicates allowed.

    """

    @staticmethod
    def twoSum(nums: list[int], target: int) -> list[int]:
        """
        Run the algorithm on inputs received based on example -

        Input: nums = [2,7,11,15], target = 9
        Output: [0,1]
        Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

        :param nums: list of numbers
        :param target: target value for sum
        :return: indices of 2 numbers that add to target value

        """
        # Create empty hashmap
        hashMap = {}

        for i in range(len(nums)):
            # check if difference is already there in hashMap
            if target - nums[i] in hashMap:
                # We have found the solution , so return a list of the indices
                return [hashMap[target - nums[i]], i]
            else:
                # It's not there so, i.e. first visit. Add to hashMap
                hashMap[nums[i]] = i

# Function to get input from user
def get_inputs() -> tuple[list[int], int]:
    """
    Accept input of list of numbers and target value from the user.

    :return: list of numbers and target value
    """

    # Empty list of values
    numbers = []
    print("Enter a list of numbers : ")
    # Loop till we get an empty line
    while True:
        val = input()
        # Check for empty line
        if val == "":
            break
        # If value received, convert to int and add to list
        else:
            numbers.append(int(val))

    # Accept and convert the value received for target to an int
    target = int(input("Enter target value : "))

    # Return the inputs received to main()
    return numbers, target

def main() -> None:
    """
    The main function to instantiate class and run algorithm
    :return: None

    """

    # Receive inputs
    numbers, target = get_inputs()

    # Instantiate class and run algorithm
    obj1 = Solution()
    result = obj1.twoSum(numbers, target)

    # If-Else to handle cases if there exists no result
    if result:
        print(f"The indices of the solution numbers are : {result}")
    else:
        print("Result not possible from given values")

if __name__ == "__main__":
    main()


"""

This module provides various convenience functions and classes.

"""

import configparser
import json
import os
import tarfile
from io import BytesIO

import numpy as np
import pandas as pd

from . import EMAError, get_module_logger

# Created on 13 jan. 2011
#
# .. codeauthor:: jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl>

__all__ = ["load_results", "save_results", "merge_results", "process_replications"]
_logger = get_module_logger(__name__)

def load_results(file_name):
    """
    load the specified bz2 file. the file is assumed to be saves
    using save_results.

    Parameters
    ----------
    file_name : str
                the path to the file

    Raises
    ------
    IOError if file not found

    """
    from ..em_framework.outcomes import AbstractOutcome, register

    file_name = os.path.abspath(file_name)

    with tarfile.open(file_name, "r:gz", encoding="UTF8") as archive:
        try:
            f = archive.extractfile("metadata.json")
        except KeyError:
            # old style data file
            results = load_results_old(archive)
            _logger.info(f"results loaded successfully from {file_name}")
            return results

        metadata = json.loads(f.read().decode())

        # load experiments
        f = archive.extractfile("experiments.csv")
        experiments = pd.read_csv(f)

        for name, dtype in metadata["experiments"].items():
            try:
                dtype = np.dtype(dtype)
            except TypeError:
                dtype = pd.api.types.pandas_dtype(dtype)

            if experiments[name].dtype is not dtype:
                experiments[name] = experiments[name].astype(dtype)
            # this check is for backward compatability with data stored with 2.4.
            if pd.api.types.is_object_dtype(dtype):
                experiments[name] = experiments[name].astype("category")

        # load outcomes
        outcomes = {}
        known_outcome_classes = {
            entry.__name__: entry for entry in AbstractOutcome.get_subclasses()
        }
        for outcome_type, name, filename in metadata["outcomes"]:
            outcome = known_outcome_classes[outcome_type](name)

            values = register.deserialize(name, filename, archive)
            outcomes[name] = values

    _logger.info(f"results loaded successfully from {file_name}")
    return experiments, outcomes

def load_results_old(archive):
    """
    load the specified bz2 file. the file is assumed to be saves
    using save_results.

    Parameters
    ----------
    file_name : TarFile

    Raises
    ------
    IOError if file not found

    """
    from ..em_framework.outcomes import ScalarOutcome, ArrayOutcome, register

    outcomes = {}

    # load x
    experiments = archive.extractfile("experiments.csv")
    if not (hasattr(experiments, "read")):
        raise EMAError(repr(experiments))

    experiments = pd.read_csv(experiments)

    # load experiment metadata
    metadata = archive.extractfile("experiments metadata.csv").readlines()

    for entry in metadata:
        entry = entry.decode("UTF-8")
        entry = entry.strip()
        entry = entry.split(",")
        name, dtype = (str(item) for item in entry)

        try:
            dtype = np.dtype(dtype)
        except TypeError:
            dtype = pd.api.types.pandas_dtype(dtype)

        if pd.api.types.is_object_dtype(dtype):
            experiments[name] = experiments[name].astype("category")

    # load outcome metadata
    metadata = archive.extractfile("outcomes metadata.csv").readlines()
    metadata = [entry.decode("UTF-8") for entry in metadata]
    metadata = [entry.strip() for entry in metadata]
    metadata = [tuple(entry.split(",")) for entry in metadata]
    metadata = {entry[0]: entry[1:] for entry in metadata}

    # load outcomes
    for outcome, shape in metadata.items():
        shape = list(shape)
        shape[0] = shape[0][1:]
        shape[-1] = shape[-1][0:-1]

        temp_shape = []
        for entry in shape:
            if entry:
                try:
                    temp_shape.append(int(entry))
                except ValueError:
                    temp_shape.append(int(entry[0:-1]))
        shape = tuple(temp_shape)

        if len(shape) > 2:
            nr_files = shape[-1]

            data = np.empty(shape)
            for i in range(nr_files):
                values = archive.extractfile(f"{outcome}_{i}.csv")
                values = pd.read_csv(values, index_col=False, header=None).values
                data[:, :, i] = values

        else:
            data = archive.extractfile(f"{outcome}.csv")
            data = pd.read_csv(data, index_col=False, header=None).values
            data = np.reshape(data, shape)

        outcomes[outcome] = data

    # reformat outcomes from generic dict to new style OutcomesDict
    outcomes_new = {}
    for k, v in outcomes.items():
        if v.ndim == 1:
            outcome = ScalarOutcome(k)
        else:
            outcome = ArrayOutcome(k)

        outcomes_new[outcome.name] = v

    return experiments, outcomes_new

def save_results(results, file_name):
    """
    save the results to the specified tar.gz file.

    The way in which results are stored depends. Experiments are saved
    as csv. Outcomes depend on the outcome type. Scalar, and <3D arrays are
    saved as csv files. Higher dimensional arrays are stored as .npy files.

    Parameters
    ----------
    results : tuple
              the return of perform_experiments
    file_name : str
                the path of the file

    Raises
    ------
    IOError if file not found

    """
    from ..em_framework.outcomes import register

    VERSION = 0.1
    file_name = os.path.abspath(file_name)

    def add_file(tararchive, stream, filename):
        stream.seek(0)
        tarinfo = tarfile.TarInfo(filename)
        tarinfo.size = len(stream.getbuffer())
        tararchive.addfile(tarinfo, stream)

    experiments, outcomes = results
    with tarfile.open(file_name, "w:gz") as z:
        # store experiments
        stream = BytesIO()
        stream.write(experiments.to_csv(header=True, encoding="UTF-8", index=False).encode())
        add_file(z, stream, "experiments.csv")

        # store outcomes
        outcomes_metadata = []
        for key, value in outcomes.items():
            klass = register.outcomes[key]
            stream, filename = register.serialize(key, value)
            add_file(z, stream, filename)
            outcomes_metadata.append((klass.__name__, key, filename))

        # store metadata
        metadata = {
            "version": VERSION,
            "outcomes": outcomes_metadata,
            "experiments": {k: v.name for k, v in experiments.dtypes.to_dict().items()},
        }

        stream = BytesIO()
        stream.write(json.dumps(metadata).encode())
        add_file(z, stream, "metadata.json")

    _logger.info(f"results saved successfully to {file_name}")

def merge_results(results1, results2):
    """
    convenience function for merging the return from
    :meth:`~modelEnsemble.ModelEnsemble.perform_experiments`.

    The function merges results2 with results1. For the experiments,
    it generates an empty array equal to the size of the sum of the
    experiments. As dtype is uses the dtype from the experiments in results1.
    The function assumes that the ordering of dtypes and names is identical in
    both results.

    A typical use case for this function is in combination with
    :func:`~util.experiments_to_cases`. Using :func:`~util.experiments_to_cases`
    one extracts the cases from a first set of experiments. One then
    performs these cases on a different model or policy, and then one wants to
    merge these new results with the old result for further analysis.

    Parameters
    ----------
    results1 : tuple
               first results to be merged
    results2 : tuple
               second results to be merged

    Returns
    -------
    the merged results

    """

    # start of merging
    exp1, res1 = results1
    exp2, res2 = results2

    # merge x
    merged_exp = pd.concat([exp1, exp2], axis=0)
    merged_exp.reset_index(drop=True, inplace=True)

    # only merge the results that are in both
    keys = set(res1.keys()).intersection(set(res2.keys()))
    _logger.info(f"intersection of keys: {keys}")

    # merging results
    merged_res = {}
    for key in keys:
        _logger.info(f"merge {key}")

        value1 = res1.get(key)
        value2 = res2.get(key)
        merged_value = np.concatenate([value1, value2])
        merged_res[key] = merged_value

    mr = (merged_exp, merged_res)
    return mr

def get_ema_project_home_dir():
    try:
        config_file_name = "expworkbench.cfg"
        directory = os.path.dirname(__file__)
        fn = os.path.join(directory, config_file_name)

        config = configparser.ConfigParser()
        parsed = config.read(fn)

        if parsed:
            _logger.info(f"config loaded from {parsed[0]}")
        else:
            _logger.info("no config file found")

        home_dir = config.get("ema_project_home", "home_dir")
        return home_dir
    except BaseException:
        return os.getcwd()

def process_replications(data, aggregation_func=np.mean):
    """
    Convenience function for processing the replications of a stochastic
    model's outcomes.

    The default behavior is to take the mean of the replications. This reduces
    the dimensionality of the outcomes from
    (experiments * replications * outcome_shape) to
    (experiments * outcome_shape), where outcome_shape is 0-d for scalars,
    1-d for time series, and 2-d for arrays.

    The function can take either the outcomes (dictionary: keys are outcomes
    of interest, values are arrays of data) or the results (tuple: experiments
    as DataFrame, outcomes as dictionary) of a set of simulation experiments.

    Parameters
    ----------
    data : dict, tuple
        outcomes or results of a set of experiments
    aggregation_func : callabale, optional
        aggregation function to be applied, defaults to np.mean.

    Returns
    -------
    dict, tuple

    """

    if isinstance(data, dict):
        # replications are the second dimension of the outcome arrays
        outcomes_processed = {key: aggregation_func(data[key], axis=1) for key in data.keys()}
        return outcomes_processed
    elif (
        isinstance(data, tuple) and isinstance(data[0], pd.DataFrame) and isinstance(data[1], dict)
    ):
        experiments, outcomes = data  # split results
        outcomes_processed = {
            key: aggregation_func(outcomes[key], axis=1) for key in outcomes.keys()
        }
        results_processed = (experiments.copy(deep=True), outcomes_processed)
        return results_processed

    else:
        raise EMAError(f"data should be a dict or tuple, but is a {type(data)}".format())


def replace_comma(file_name):
    with open(file_name, 'r', encoding="utf8") as fl:
        new_content = ""
        for row in fl:
            tmp_ls = list(row)
            for i in range(1, len(tmp_ls) - 1):
                if tmp_ls[i] == ',' and tmp_ls[i - 1] != ' ' and tmp_ls[i + 1] != ' ':
                    tmp_ls[i] = '\t'
            new_content += "".join(tmp_ls)
    with open('ds.tsv', 'w', encoding="utf8") as fl:
        fl.write(new_content)

if __name__ == '__main__':
    replace_comma('ds.csv')


import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl.function as fn
import math
from dgl.data import CoraGraphDataset, CiteseerGraphDataset, PubmedGraphDataset
from tqdm import trange
import copy
import torch.optim as optim

def glorot(tensor):
    if tensor is not None:
        stdv = math.sqrt(6.0 / (tensor.size(-2) + tensor.size(-1)))
        tensor.data.uniform_(-stdv, stdv)

def zeros(tensor):
    if tensor is not None:
        tensor.data.fill_(0)

class ARMAConv(nn.Module):
    def __init__(self,
                 in_dim,
                 out_dim,
                 num_stacks,
                 num_layers,
                 activation=None,
                 dropout=0.0,
                 bias=True):
        super(ARMAConv, self).__init__()

        self.in_dim = in_dim
        self.out_dim = out_dim
        self.K = num_stacks
        self.T = num_layers
        self.activation = activation
        self.dropout = nn.Dropout(p=dropout)

        # init weight
        self.w_0 = nn.ModuleDict({
            str(k): nn.Linear(in_dim, out_dim, bias=False) for k in range(self.K)
        })
        # deeper weight
        self.w = nn.ModuleDict({
            str(k): nn.Linear(out_dim, out_dim, bias=False) for k in range(self.K)
        })
        # v
        self.v = nn.ModuleDict({
            str(k): nn.Linear(in_dim, out_dim, bias=False) for k in range(self.K)
        })
        # bias
        if bias:
            self.bias = nn.Parameter(torch.Tensor(self.K, self.T, 1, self.out_dim))
        else:
            self.register_parameter('bias', None)

        self.reset_parameters()

    def reset_parameters(self):
        for k in range(self.K):
            glorot(self.w_0[str(k)].weight)
            glorot(self.w[str(k)].weight)
            glorot(self.v[str(k)].weight)
        zeros(self.bias)

    def forward(self, g, feats):
        with g.local_scope():
            init_feats = feats
            # assume that the graphs are undirected and graph.in_degrees() is the same as graph.out_degrees()
            degs = g.in_degrees().float().clamp(min=1)
            norm = torch.pow(degs, -0.5).to(feats.device).unsqueeze(1)
            output = None

            for k in range(self.K):
                feats = init_feats
                for t in range(self.T):
                    feats = feats * norm
                    g.ndata['h'] = feats
                    g.update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h'))
                    feats = g.ndata.pop('h')
                    feats = feats * norm

                    if t == 0:
                        feats = self.w_0[str(k)](feats)
                    else:
                        feats = self.w[str(k)](feats)

                    feats += self.dropout(self.v[str(k)](init_feats))
                    feats += self.v[str(k)](self.dropout(init_feats))

                    if self.bias is not None:
                        feats += self.bias[k][t]

                    if self.activation is not None:
                        feats = self.activation(feats)

                if output is None:
                    output = feats
                else:
                    output += feats

            return output / self.K

class ARMA4NC(nn.Module):
    def __init__(self,
                 in_dim,
                 hid_dim,
                 out_dim,
                 num_stacks,
                 num_layers,
                 activation=None,
                 dropout=0.0):
        super(ARMA4NC, self).__init__()

        self.conv1 = ARMAConv(in_dim=in_dim,
                              out_dim=hid_dim,
                              num_stacks=num_stacks,
                              num_layers=num_layers,
                              activation=activation,
                              dropout=dropout)

        self.conv2 = ARMAConv(in_dim=hid_dim,
                              out_dim=out_dim,
                              num_stacks=num_stacks,
                              num_layers=num_layers,
                              activation=activation,
                              dropout=dropout)

        self.dropout = nn.Dropout(p=dropout)

    def forward(self, g, feats):
        feats = F.relu(self.conv1(g, feats))
        feats = self.dropout(feats)
        feats = self.conv2(g, feats)
        return feats

def main(args):
    # Step 1: Prepare graph data and retrieve train/validation/test index ============================= #
    # Load from DGL dataset
    if args.dataset == 'Cora':
        dataset = CoraGraphDataset()
    elif args.dataset == 'Citeseer':
        dataset = CiteseerGraphDataset()
    elif args.dataset == 'Pubmed':
        dataset = PubmedGraphDataset()
    else:
        raise ValueError('Dataset {} is invalid.'.format(args.dataset))

    graph = dataset[0]

    # check cuda
    device = f'cuda:{args.gpu}' if args.gpu >= 0 and torch.cuda.is_available() else 'cpu'

    # retrieve the number of classes
    n_classes = dataset.num_classes

    # retrieve labels of ground truth
    labels = graph.ndata.pop('label').to(device).long()

    # Extract node features
    feats = graph.ndata.pop('feat').to(device)
    n_features = feats.shape[-1]

    # retrieve masks for train/validation/test
    train_mask = graph.ndata.pop('train_mask')
    val_mask = graph.ndata.pop('val_mask')
    test_mask = graph.ndata.pop('test_mask')

    train_idx = torch.nonzero(train_mask, as_tuple=False).squeeze().to(device)
    val_idx = torch.nonzero(val_mask, as_tuple=False).squeeze().to(device)
    test_idx = torch.nonzero(test_mask, as_tuple=False).squeeze().to(device)

    graph = graph.to(device)

    # Step 2: Create model =================================================================== #
    model = ARMA4NC(in_dim=n_features,
                    hid_dim=args.hid_dim,
                    out_dim=n_classes,
                    num_stacks=args.num_stacks,
                    num_layers=args.num_layers,
                    activation=nn.ReLU(),
                    dropout=args.dropout).to(device)

    best_model = copy.deepcopy(model)

    # Step 3: Create training components ===================================================== #
    loss_fn = nn.CrossEntropyLoss()
    opt = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.lamb)

    # Step 4: training epoches =============================================================== #
    acc = 0
    no_improvement = 0
    epochs = trange(args.epochs, desc='Accuracy & Loss')

    for _ in epochs:
        # Training using a full graph
        model.train()

        logits = model(graph, feats)

        # compute loss
        train_loss = loss_fn(logits[train_idx], labels[train_idx])
        train_acc = torch.sum(logits[train_idx].argmax(dim=1) == labels[train_idx]).item() / len(train_idx)

        # backward
        opt.zero_grad()
        train_loss.backward()
        opt.step()

        # Validation using a full graph
        model.eval()

        with torch.no_grad():
            valid_loss = loss_fn(logits[val_idx], labels[val_idx])
            valid_acc = torch.sum(logits[val_idx].argmax(dim=1) == labels[val_idx]).item() / len(val_idx)

        # Print out performance
        epochs.set_description('Train Acc {:.4f} | Train Loss {:.4f} | Val Acc {:.4f} | Val loss {:.4f}'.format(
            train_acc, train_loss.item(), valid_acc, valid_loss.item()))

        if valid_acc < acc:
            no_improvement += 1
            if no_improvement == args.early_stopping:
                print('Early stop.')
                break
        else:
            no_improvement = 0
            acc = valid_acc
            best_model = copy.deepcopy(model)

    best_model.eval()
    logits = best_model(graph, feats)
    test_acc = torch.sum(logits[test_idx].argmax(dim=1) == labels[test_idx]).item() / len(test_idx)

    print("Test Acc {:.4f}".format(test_acc))
    return test_acc

if __name__ == "__main__":
    """
    ARMA Model Hyperparameters
    """
    parser = argparse.ArgumentParser(description='ARMA GCN')

    # data source params
    parser.add_argument('--dataset', type=str, default='Cora', help='Name of dataset.')
    # cuda params
    parser.add_argument('--gpu', type=int, default=-1, help='GPU index. Default: -1, using CPU.')
    # training params
    parser.add_argument('--epochs', type=int, default=2000, help='Training epochs.')
    parser.add_argument('--early-stopping', type=int, default=100, help='Patient epochs to wait before early stopping.')
    parser.add_argument('--lr', type=float, default=0.01, help='Learning rate.')
    parser.add_argument('--lamb', type=float, default=5e-4, help='L2 reg.')
    # model params
    parser.add_argument("--hid-dim", type=int, default=16, help='Hidden layer dimensionalities.')
    parser.add_argument("--num-stacks", type=int, default=2, help='Number of K.')
    parser.add_argument("--num-layers", type=int, default=1, help='Number of T.')
    parser.add_argument("--dropout", type=float, default=0.75, help='Dropout applied at all layers.')

    args = parser.parse_args()
    print(args)

    acc_lists = []

    for _ in range(100):
        acc_lists.append(main(args))

    mean = np.around(np.mean(acc_lists, axis=0), decimals=3)
    std = np.around(np.std(acc_lists, axis=0), decimals=3)
    print('Total acc: ', acc_lists)
    print('mean', mean)
    print('std', std)