#coding=utf-8
from functools import partial
from OCC.Core.Quantity import Quantity_Color, Quantity_TOC_RGB
from OCC.Core.TopoDS import TopoDS_Compound
from OCC.Extend.DataExchange import read_step_file_with_names_colors
from OCC.Extend.TopologyUtils import TopologyExplorer
from PyQt5.QtWidgets import QApplication, QComboBox, QTableView
from PyQt5 import QtWidgets,QtGui,QtCore
from PyQt5.QtGui import QFont, QBrush, QPixmap, QMovie
from graphics import GraphicsView, GraphicsPixmapItem
from module.CreateParameter import *
from module.CreateParameter import Create_Speed_reducer_kbr_series_1to1
import copy,time,sys
from ui import Process_message
#from module import source
from multiprocessing import  Queue,Manager
from module import FuctionModule,assemble
import  threading
from module import SolidworksModule

def test(func):
    def inner():
        print('running')
    return inner

class Process_message(QtWidgets.QMainWindow, Process_message.Ui_Form):  # 零件加载过程界面
    def __init__(self, parent=None):
        super(Process_message, self).__init__(parent)
        self.setupUi(self)
        # self.pushButton=QtWidgets.QPushButton()
        # self.pushButton.setGeometry(0,0,10,10)

    def process_message_show(self):
        pass
        self.label.setObjectName("label")
        self.gif = QMovie(':/picture/icons/loading.gif')
        self.label.setMovie(self.gif)
        self.gif.start()
        self.show()
def Create_ProcessBar(self, ButtonId=None):  # 过程处理函数 获取数据生成所需的界面                步骤1
        try:
            # -----------------清空3D显示界面
            self.statusbar.showMessage("状态：软件运行正常")
            self.canva._display.EraseAll()
            self.canva._display.hide_triedron()
            self.canva._display.display_triedron()
            self.canva._display.Repaint()
            # ------------------------------
            self.message = Process_message()  #
            self.tableWidget_2.clear()  # 清空原来的数据
            self.tableWidget_2.clearSpans()

            self.tableWidget_2.setHorizontalHeaderLabels(['选项', '列表值', '备注'])
            textFont = QFont()
            textFont.setFamily("微软雅黑")
            textFont.setPointSize(11)
            self.tableWidget_2.setEditTriggers(QTableView.NoEditTriggers)  # 不可编辑  # 表格不可编辑
            # 选型
            headItem = self.tableWidget_2.horizontalHeaderItem(0)  # 获得水平方向表头的Item对象
            headItem.setFont(textFont)  # 设置字体
            brush = QtGui.QBrush(QtGui.QColor(85, 85, 255))
            headItem.setForeground(brush)  # 设置文字颜色
            # 列表值
            headItem = self.tableWidget_2.horizontalHeaderItem(1)  # 获得水平方向表头的Item对象
            headItem.setFont(textFont)  # 设置字体
            brush = QtGui.QBrush(QtGui.QColor(255, 170, 0))
            headItem.setForeground(brush)  # 设置文字颜色
            # 备注
            headItem = self.tableWidget_2.horizontalHeaderItem(2)  # 获得水平方向表头的Item对象
            headItem.setFont(textFont)  # 设置字体
            brush = QtGui.QBrush(QtGui.QColor(255, 0, 127))
            headItem.setForeground(brush)  # 设置文字颜色
            if ButtonId in ["KS系列(孔输出)","KS系列(孔输出法兰)","KS系列(轴输出)","KS系列(轴输出法兰)"] :
                self.ButtonId = ButtonId
                self.Ceate_combox_table(ButtonId)#建立
                # 将所有的combox 选项和型号槽绑定 只要选项更新就会选项产品参数
                for i in self.combox_list:
                    if self.combox_list.index(i)==7:
                        i.currentTextChanged.connect(self.Ceate_show_3d)#刷新
                        continue
                    if self.combox_list.index(i)==1:
                        i.currentTextChanged.connect(self.show_technical_information)#根据combox内容刷新技术资料
                    i.currentTextChanged.connect(self.Ceate_product_parameter_table_and_show_3d)#刷新
            elif ButtonId in ["KBR系列(1-1)","KBR系列(1-2)","KB系列"] :
                self.ButtonId = ButtonId
                self.Ceate_combox_table(ButtonId)#建立
                # 将所有的combox 选项和型号槽绑定 只要选项更新就会选项产品参数
                for i in self.combox_list:
                    if self.combox_list.index(i)==7:
                        i.currentTextChanged.connect(self.Ceate_show_3d)#刷新
                        continue
                    if self.combox_list.index(i)==2:
                        i.currentTextChanged.connect(self.combox_refresh_function)#根据combox内容刷新combox刷新
                        continue
                    if self.combox_list.index(i)==1:
                        i.currentTextChanged.connect(self.show_technical_information)#根据combox内容刷新技术资料
                    i.currentTextChanged.connect(self.Ceate_product_parameter_table_and_show_3d)#刷新
            elif ButtonId in ["EDA系列"] :
                self.ButtonId = ButtonId
                self.Ceate_combox_table(ButtonId)#建立
                # 将所有的combox 选项和型号槽绑定 只要选项更新就会选项产品参数
                for i in self.combox_list:
                    if self.combox_list.index(i)==10:
                        i.currentTextChanged.connect(self.Ceate_show_3d)#刷新
                        continue
                    if self.combox_list.index(i)==1:
                        i.currentTextChanged.connect(self.combox_refresh_function)#刷新
                        i.currentTextChanged.connect(self.show_technical_information)  # 根据combox内容刷新技术资料
                        continue
                    i.currentTextChanged.connect(self.Ceate_product_parameter_table_and_show_3d)#刷新
            elif ButtonId in ["ECA系列"] :
                self.ButtonId = ButtonId
                self.Ceate_combox_table(ButtonId)#建立
                # 将所有的combox 选项和型号槽绑定 只要选项更新就会选项产品参数
                for i in self.combox_list:
                    if self.combox_list.index(i)==10:
                        i.currentTextChanged.connect(self.Ceate_show_3d)#刷新
                        continue
                    if self.combox_list.index(i)==1:
                        i.currentTextChanged.connect(self.combox_refresh_function)#刷新
                        i.currentTextChanged.connect(self.show_technical_information)  # 根据combox内容刷新技术资料
                        continue
                    i.currentTextChanged.connect(self.Ceate_product_parameter_table_and_show_3d)#刷新
                    pass
            self.sinal = 1
            self.message.process_message_show()
        except Exception as e:
            print(e)

        if True:
            if self.sinal == 1:
                try:
                    pass
                except:
                    pass
                self.show_parameter()
                self.sinal = 0
                self.message.close()
                # break
def Ceate_combox_table(self, ButtonId=None):  # 生成选项卡表格   步骤二
        '''
        1.建立选型列表名称
        2.获取各个选项的值
        3.
        '''
        try:

            # ------------------------------------------------------------KS系列
            if ButtonId in ["KS系列(孔输出)"]:
                self.boll_SCcrew = Create_Speed_reducer_ks_hole_output()#建立类
            elif ButtonId in["KS系列(轴输出)"]:
                self.boll_SCcrew = Create_Speed_reducer_ks_axle_output()  # 建立类
            elif ButtonId in["KS系列(孔输出法兰)"]:
                self.boll_SCcrew = Create_Speed_reducer_ks_hole_flank_output()  # 建立类
            elif ButtonId in["KS系列(轴输出法兰)"]:
                self.boll_SCcrew = Create_Speed_reducer_ks_axle_flank_output()  # 建立类

            #---------------------------------------------------------------KBR系列
            if ButtonId in ["KBR系列(1-1)"]:
                self.boll_SCcrew = Create_Speed_reducer_kbr_series_1to1()#建立类
            elif ButtonId in["KBR系列(1-2)"]:
                self.boll_SCcrew = Create_Speed_reducer_kbr_series_1to2()#建立类

            #----------------------------------------------------------------KB系列
            if ButtonId in ["KB系列"]:
                self.boll_SCcrew = Create_Speed_reducer_kb_series()#建立类

            #----------------------------------------------------------------EDA系列
            if ButtonId in ["EDA系列"]:
                self.boll_SCcrew = Create_transformer_EDA_series()#建立类
            # ----------------------------------------------------------------ECA系列
            if ButtonId in ["ECA系列"]:
                self.boll_SCcrew = Create_transformer_ECA_series()# 建立类

            all_combox_list = self.boll_SCcrew.Create_combox_list()
            self.order_code_position = len(all_combox_list) - 1  # 订购码的位置
            self.tableWidget_2.setRowCount(len(all_combox_list))  # 参数表格设置.
            self.combox_list = []
            blank_size=self.tableWidget_2.geometry().width()/3
            self.tableWidget_2.setColumnWidth(1, blank_size)  # 手动设置列宽
            self.tableWidget_2.setColumnWidth(0, blank_size)  # 手动设置列宽
            self.tableWidget_2.setColumnWidth(2, blank_size)  # 手动设置列宽
            # ------------------------------------------------先生成combox选项卡
            for i in all_combox_list:  # 遍历生成所有的选项
                comBox = QComboBox()
                comBox.setFont(QFont("微软雅黑", 9, QFont.Black))
                comBox.setStyleSheet("QComboBox{color:rgb(0,0,0)}")
                self.combox_list.append(comBox)
                # comBox.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
                if type(i).__name__ == "dict":  # 如果室字典类型则生成combox
                    for key, value in i.items():
                        newItem = QtWidgets.QTableWidgetItem(str(key))
                        newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)
                        newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
                        newItem.setFont(QFont("微软雅黑", 9, QFont.Black))  # 设置字体
                        newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))
                        self.tableWidget_2.setItem(all_combox_list.index(i), 0, newItem)  # 代码
                        for k in value:
                            self.combox_list[all_combox_list.index(i)].addItem(k)
                    self.tableWidget_2.setCellWidget(all_combox_list.index(i), 1,
                                                     self.combox_list[all_combox_list.index(i)])
                    comBox.destroy()
                else:  # f否则生成普通单元格
                    pass
                    newItem = QtWidgets.QTableWidgetItem(str(i[0]))
                    newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)
                    newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
                    newItem.setFont(QFont("微软雅黑", 9, QFont.Black))
                    newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))
                    self.tableWidget_2.setItem(all_combox_list.index(i), 0, newItem)  # 代码
                    # ------------------------------------------------------------------------
                    newItem = QtWidgets.QTableWidgetItem(str(i[1]))
                    newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)
                    newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
                    newItem.setFont(QFont("微软雅黑", 9, QFont.Black))
                    newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))
                    self.tableWidget_2.setItem(all_combox_list.index(i), 1, newItem)  # 代码
                # 设置备注单元格的颜色
                newItem = QtWidgets.QTableWidgetItem(str(""))
                newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)
                newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
                # newItem.setFont(QFont("song", 9,QFont.Black))
                self.tableWidget_2.setItem(all_combox_list.index(i), 2, newItem)  # 代码

            # ----------------------------------------------------生成产品参数的tablewidget

        except:
            pass

def Create_product_parameter_table_and_show_3d(self, QClor=1, dict={}, start=0):  # 生成/更新产品参数表格    #步骤3
    '''
    根据combox选项生成产品参数列表
    '''
    try:
        QApplication.processEvents()
        self.aCompound = TopoDS_Compound()

    except:
        pass
    start = len(self.combox_list)  # 确定起始位置
    self.combox_current_text_list = []
    for i in self.combox_list:
        if i.currentText() == "":
            continue
        self.combox_current_text_list.append(i.currentText())  # 装有combox的列表
    try:
        if self.ButtonId in ["KS系列(孔输出)","KS系列(孔输出法兰)","KS系列(轴输出)","KS系列(轴输出法兰)"]:
            self.combox_list[7].clear()  # 清楚原来的combobox选项
            series ="KS"+self.combox_current_text_list[0]  # 机座号
            additems = self.boll_SCcrew.path_dict["FX" + str(series)]  # 对应机座号的可选模型的
            self.filename_dict = {}
            additem_list = []
            for i in range(len(additems)):
                additem = additems[i].split("\\")[-1].replace(".step", "")
                self.filename_dict[additem] = copy.deepcopy(additems[i])
                additem_list.append(additem)
            self.combox_list[7].addItems(additem_list)  # 根据选项变换combox里的内容
            series_1 = self.combox_current_text_list[1]  # 减速比
            dict = self.boll_SCcrew.series[str(series)]  # 机座号选型列表
            dict["额定承载扭矩T2N(Nm)"] = self.boll_SCcrew.T2N[str(series_1)][series]
            dict["最大承载扭矩T2B(Nm)"] = str(float(self.boll_SCcrew.T2N[str(series_1)][series]) * 1.5)
            dict["背隙"] = self.boll_SCcrew.arcmin[str(series_1)]
            dict["输出轴许可径向力"] = self.boll_SCcrew.output_radial_force[str(series_1)][series]
            dict["制锁"] = self.boll_SCcrew.self_lock[str(series_1)]

        elif self.ButtonId in ["KBR系列(1-1)","KBR系列(1-2)"]:
            self.combox_list[7].clear()  # 清楚原来的combobox选项
            series = "KBR"+self.combox_current_text_list[0]  # 机座号
            additems = self.boll_SCcrew.path_dict["FX"+str(series)]  # 对应机座号的可选模型的
            self.filename_dict = {}
            additem_list = []
            for i in range(len(additems)):
                additem = additems[i].split("\\")[-1].replace(".step", "")
                self.filename_dict[additem] = copy.deepcopy(additems[i])
                additem_list.append(additem)
            self.combox_list[7].addItems(additem_list)  # 根据选项变换combox里的内容

            series_1 = self.combox_current_text_list[1]  # 段数
            series_2=self.combox_current_text_list[2] #减速比
            #series_3 = self.boll_SCcrew.series[str(series)]  # 机座号选型列表
            dict["额定输出扭矩T2N(Nm)"] = self.boll_SCcrew.T2N[series_1][series_2][series]
            dict["最大输出扭矩(Nm)"] = str(float(self.boll_SCcrew.T2N[series_1][series_2][series])*2)
            dict["额定输入转速(rpm)"] = self.boll_SCcrew.n1N[str(series)]
            dict["最大输入转速(rpm)"] = self.boll_SCcrew.n1B[str(series)]
            dict["背隙"] = self.boll_SCcrew.arcmin[self.combox_current_text_list[4]][series_1][series_2]
            dict["容许径向力(N)"] = self.boll_SCcrew.F1[str(series)]
            dict["容许轴向力(N)"] = self.boll_SCcrew.F2[str(series)]
            dict["效率(%)"] = self.boll_SCcrew.power[str(series_1)][series_2]
            dict["噪音(DB)"] = self.boll_SCcrew.dB[str(series)]
            dict["重量(Kg)"] = self.boll_SCcrew.weight[series_1][series]
            dict["减速机转动惯量(kg.cm2)"] = self.boll_SCcrew.Moment_inertia[series_1][series_2][series]

        elif self.ButtonId in ["KB系列"]:
            self.combox_list[7].clear()  # 清楚原来的combobox选项
            series = "KB"+self.combox_current_text_list[0]  # 机座号
            additems = self.boll_SCcrew.path_dict["FX"+str(series)]  # 对应机座号的可选模型的
            self.filename_dict = {}
            additem_list = []
            for i in range(len(additems)):
                additem = additems[i].split("\\")[-1].replace(".step", "")
                self.filename_dict[additem] = copy.deepcopy(additems[i])
                additem_list.append(additem)
            self.combox_list[7].addItems(additem_list)  # 根据选项变换combox里的内容

            series_1 = self.combox_current_text_list[1]  # 段数
            series_2=self.combox_current_text_list[2] #减速比

            #series_3 = self.boll_SCcrew.series[str(series)]  # 机座号选型列表
            dict["额定输出扭矩T2N(Nm)"] = self.boll_SCcrew.T2N[series_1][series_2][series]
            dict["最大输出扭矩(Nm)"] = str(float(self.boll_SCcrew.T2N[series_1][series_2][series])*2)
            dict["额定输入转速(rpm)"] = self.boll_SCcrew.n1N[str(series)]
            dict["最大输入转速(rpm)"] = self.boll_SCcrew.n1B[str(series)]
            dict["背隙"] = self.boll_SCcrew.arcmin[self.combox_current_text_list[4]][series_1][series]
            dict["容许径向力(N)"] = self.boll_SCcrew.F1[str(series)]
            dict["容许轴向力(N)"] = self.boll_SCcrew.F2[str(series)]
            dict["效率(%)"] = self.boll_SCcrew.power[str(series_1)][series]
            dict["噪音(DB)"] = self.boll_SCcrew.dB[str(series)]
            dict["重量(Kg)"] = self.boll_SCcrew.weight[series_1][series]
            dict["减速机转动惯量(kg.cm2)"] = self.boll_SCcrew.Moment_inertia[series_1][series_2][series]

        elif self.ButtonId in ["EDA系列"]:
            self.combox_list[10].clear()  # 清除原来的combobox选项
            series = "EDA"+self.combox_current_text_list[0]  # 机座号
            Motor_position=self.combox_current_text_list[1]
            Fixed_mode=self.combox_current_text_list[2]
            lead="B"+self.combox_current_text_list[3]
            move_distance="C"+self.combox_current_text_list[4]
            Reduction_ratio="D"+self.combox_current_text_list[5]
            power="K"+self.combox_current_text_list[6]
            #rotate_speed=self.combox_current_text_list[7]
            #sensor_num=self.combox_current_text_list[8]
            dict = self.boll_SCcrew.series[str(series)]
            dict["减速比"]=self.combox_current_text_list[5]
            series=series+"-"+Motor_position[0]+Fixed_mode[0:2]+"-"+lead+"-"+move_distance+"-"+Reduction_ratio+"-"+power
            additem_list = ["-",series]
            self.combox_list[10].addItems(additem_list)  # 根据选项变换combox里的内容
            #机座号选型列表
        elif self.ButtonId in ["ECA系列"]:
            print("enter")
            self.combox_list[9].clear()  # 清除原来的combobox选项
            series = self.combox_current_text_list[0]  # 机座号
            dict = self.boll_SCcrew.series[str(series)]
            dict["减速比"]=self.combox_current_text_list[5]
            additem_list = ["-",series]
            self.combox_list[10].addItems(additem_list)  # 根据选项变换combox里的内容
            #机座号选型列表

        dict_list = []
        self.tableWidget_2.setRowCount(len(dict) + len(self.combox_list))  # 参数表格设置.

        for key in dict.keys():
            ls_list = []
            ls_list.append(key)
            ls_list.append(dict[key])
            dict_list.append(ls_list)
        RowCount = len(dict)
        for i in range(RowCount):
            # 第一列
            newItem = QtWidgets.QTableWidgetItem(dict_list[i][0])
            self.tableWidget_2.setItem(i + len(self.combox_list), 0, newItem)  # 代码
            newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
            newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)  # 文字居中
            newItem.setFont(QFont("微软雅黑", 9, QFont.Black))
            newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))

            # 第二列
            if type(dict_list[i][1]) == list:
                pass
                comBox = QComboBox()  # 选项列表
                for ls_item in dict_list[i][1]:
                    pass
                    comBox.addItem(ls_item)
                self.tableWidget_2.setCellWidget(i + len(self.combox_list), 1, comBox)

            else:
                newItem = QtWidgets.QTableWidgetItem(str(dict_list[i][1]))
                self.tableWidget_2.setItem(i + len(self.combox_list), 1, newItem)  # 代码
                newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
                newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)  # 文字居中
                newItem.setFont(QFont("微软雅黑", 9, QFont.Black))
                newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))
            # 第三列
            newItem = QtWidgets.QTableWidgetItem("")
            self.tableWidget_2.setItem(i + len(self.combox_list), 2, newItem)  # 代码
            newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
            newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)  # 文字居中
            newItem.setFont(QFont("微软雅黑", 9, QFont.Black))
            newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))

    except Exception as e:
        print(e)
        pass
    # 获取combox现在设定的参数
    try:
        # ----------------------------------------------清除原有的模型--------------------------
        try:
            for i in self.show:
                self.canva._display.Context.Remove(i, True)
                self.canva._display.Context.erase()
            self.aCompound.Free()
        except:
            pass

        # -----------------设置订购码/导出solidworks按钮----------------------------------------------------------------
        if self.ButtonId in ["KS系列(孔输出)", "KS系列(孔输出法兰)", "KS系列(轴输出)", "KS系列(轴输出法兰)"]:  # 设置订购码
            try:
                series ="KS"+self.combox_list[1].currentText() + "-"  # 系列号和机座代号
                Deceleration_ratio = self.combox_list[3].currentText() + "-"  # 减速比
                Deceleration_ratio = self.combox_list[2].currentText() + "-"  # 减速比
                Rotating_shaft = self.combox_list[3].currentText()[0:2] + "-"  # 附件轴类型
                Out_Flanges = self.combox_list[4].currentText()[0] + "-"  # 输出安装法兰类型
                Fixt_mode = self.combox_list[5].currentText() + "/"  # 安装方式
                Motor_type = self.combox_list[6].currentText()[0:1]  # 电机类型
                series = series + Deceleration_ratio + Rotating_shaft + Out_Flanges + Fixt_mode + Motor_type
            except Exception as e:
                pass
                print(e)
            newItem = QtWidgets.QTableWidgetItem(series)
            newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)
            newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
            newItem.setFont(QFont("微软雅黑", 8, QFont.Black))
            newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))
            #self.tableWidget_2.setSpan(self.order_code_position, 1, 1, 2)#合并单元格
            #-----------------------------------------------------------------导入solidworks按钮
            self.out_put_solidworks_buttom = QtWidgets.QPushButton("导出至Solidworks")
            self.out_put_solidworks_buttom.clicked.connect(partial(Out_put_solidworks,self.solidworks_import_fiiepath,self))
            self.tableWidget_2.setCellWidget(self.order_code_position-1, 2, self.out_put_solidworks_buttom)
            self.tableWidget_2.setItem(self.order_code_position-1, 1, newItem)  # 设置导出按钮
            #-----------------------------------------------------------------------------------
            self.copy_buttom = QtWidgets.QPushButton("复制订购码")
            self.copy_buttom.clicked.connect(partial(order_code_copy, series,self))
            self.tableWidget_2.setCellWidget(self.order_code_position, 2, self.copy_buttom)
            self.tableWidget_2.setItem(self.order_code_position, 1, newItem)  # 设置订购码

        if self.ButtonId in ["KBR系列(1-1)", "KBR系列(1-2)","KB系列"]:  # 设置订购码
            try:
                if self.ButtonId=="KB系列":
                    series = "KB" + self.combox_list[1].currentText() + "-"  # 系列号和机座代号
                else:
                    series = "KBR" + self.combox_list[1].currentText() + "-"  # 系列号和机座代号
                Deceleration_ratio = self.combox_list[3].currentText() + "-"  # 减速比
                Deceleration_ratio = self.combox_list[2].currentText() + "-"  # 段数
                Rotating_shaft = self.combox_list[3].currentText()[0:2] + "-"  # 减速比
                Out_Flanges = self.combox_list[4].currentText()[0:2] + "-"  # 轴型
                Fixt_mode = self.combox_list[5].currentText()[0:2] + "/"  # 背隙
                Motor_type = self.combox_list[6].currentText()[0:1]  # 电机类型
                series = series + Deceleration_ratio + Rotating_shaft + Out_Flanges + Fixt_mode + Motor_type
            except Exception as e:
                pass
                print(e)
            newItem = QtWidgets.QTableWidgetItem(series)
            newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)
            newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
            newItem.setFont(QFont("微软雅黑", 8, QFont.Black))
            newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))
            #self.tableWidget_2.setSpan(self.order_code_position, 1, 1, 2)#合并单元格
            # -----------------------------------------------------------------导入solidworks按钮
            self.out_put_solidworks_buttom = QtWidgets.QPushButton("导出至Solidworks")
            self.out_put_solidworks_buttom.clicked.connect(partial(Out_put_solidworks,self.solidworks_import_fiiepath,self))
            self.tableWidget_2.setCellWidget(self.order_code_position - 1, 2, self.out_put_solidworks_buttom)
            self.tableWidget_2.setItem(self.order_code_position - 1, 1, newItem)  # 设置导出按钮
            #--------------------------------------------------------------------------------------------------
            self.copy_buttom=QtWidgets.QPushButton("复制订购码")
            self.copy_buttom.clicked.connect(partial(order_code_copy, series,self))
            self.tableWidget_2.setCellWidget(self.order_code_position,2,self.copy_buttom)
            self.tableWidget_2.setItem(self.order_code_position, 1, newItem)  # 设置订购码

        if self.ButtonId in ["EDA系列"]:  # 设置订购码
            try:
                series = "EDA" + self.combox_current_text_list[0]  # 机座号
                Motor_position = self.combox_current_text_list[1]
                Fixed_mode = self.combox_current_text_list[2]
                lead = "B" + self.combox_current_text_list[3]
                move_distance = "C" + self.combox_current_text_list[4]
                Reduction_ratio = "D" + self.combox_current_text_list[5]
                power = "K" + self.combox_current_text_list[6]
                # rotate_speed=self.combox_current_text_list[7]
                # sensor_num=self.combox_current_text_list[8]
                series = series + "-" + Motor_position[0] + Fixed_mode[0:2] + "-" + lead + "-" + \
                         move_distance + "-" + Reduction_ratio + "-" + power
            except Exception as e:
                pass
                print(e)
            newItem = QtWidgets.QTableWidgetItem(series)
            newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)
            newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
            newItem.setFont(QFont("微软雅黑", 8, QFont.Black))
            newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))
            #self.tableWidget_2.setSpan(self.order_code_position, 1, 1, 2)#合并单元格
            # -----------------------------------------------------------------导入solidworks按钮
            self.out_put_solidworks_buttom = QtWidgets.QPushButton("导出至Solidworks")
            self.out_put_solidworks_buttom.clicked.connect(partial(Out_put_solidworks,self))
            self.tableWidget_2.setCellWidget(self.order_code_position - 1, 2, self.out_put_solidworks_buttom)
            self.tableWidget_2.setItem(self.order_code_position - 1, 1, newItem)  # 设置导出按钮
            #-----------------------------------------------------------------------------------------
            self.copy_buttom=QtWidgets.QPushButton("复制订购码")
            self.copy_buttom.clicked.connect(partial(order_code_copy, series,self))
            self.tableWidget_2.setCellWidget(self.order_code_position,2,self.copy_buttom)
            self.tableWidget_2.setItem(self.order_code_position, 1, newItem)  # 设置订购码
            # ----------显示3D-------------------------------------------------------------------
            '''
            self.tab_7.repaint()
            try:
                filenam = self.filename_dict[self.combox_list[2].currentText()]
                filenam = filenam.repalce(".step", "")
                self.aCompound = self.boll_SCcrew.Create_shape(filename=filenam)
                self.Show3D(mode=1, aCompound=self.aCompound)
                self.statusbar.showMessage("数据生成成功")
                pass
            except:
                self.statusbar.showMessage("此零件官方未提供3D，生成失败")
            '''
    except Exception as e:
        pass

def Ceate_show_3d(self, QClor=1, dict={}, start=0, ):#仅更新3D
        #根据combox选项生成产品参数列表
        if self.combox_list[7].currentText() != "-":
            #self.statusbar.showMessage("数据生成中.....")
            pass
        if self.ButtonId in ["EDA系列"]:
            if self.combox_list[10].currentText() != "-" and self.combox_list[10].currentText()+".STEP" in self.file_list :
                #self.statusbar.showMessage("数据生成中.....")
                #判断模型是否在resources中
                self.statusbar.showMessage("")
                pass
            else:
                self.statusbar.showMessage("没有与选项符合的模型")

        try:
            # ----------------------------------------------清除原有的模型--------------------------
            try:
                for i in self.show:
                    self.canva._display.Context.Remove(i, True)
                    self.canva._display.Context.erase()
                self.aCompound.Free()
            except:
                pass
            # ----------显示3D-------------------------------------------------------------------
            self.tab_7.repaint()
            try:
                if not self.ButtonId in ["EDA系列"]:
                    if self.combox_list[7].currentText() != "-":  # 一般情况
                        filenam = self.filename_dict[self.combox_list[7].currentText()]
                        filenam = filenam.replace(".\\", "")
                        self.output_filename = filenam
                        Show3D(self=self, mode=0, file=filenam)
                        self.canva._display.Repaint()
                        self.filename = filenam
                        self.statusbar.showMessage("数据生成成功")

                if self.ButtonId in ["EDA系列"]:
                    if self.combox_list[10].currentText() != "-" and self.combox_list[10].currentText()+".STEP" in self.file_list:
                        series = "EDA" + self.combox_current_text_list[0]  # 机座号
                        filenam = "./resource/EDA/"+series+"/3D/"+self.combox_list[10].currentText()+".STEP"
                        filenam = filenam.replace("/", "\\")
                        self.output_filename = filenam
                        # 判断模型是否在resources中
                        if not os.path.exists(self.output_filename):
                            QApplication.processEvents()
                            down_load_path=os.getcwd()+"/resource/EDA/"+series+"/3D/"+self.combox_list[10].currentText()+".STEP"
                            down_load_path.replace("\\","/")
                            down_load_file_name="resource/EDA/"+series+"/3D/"+self.combox_list[10].currentText()+".STEP"
                            #self.ftp_serve.Down_load_part_file(down_load_path,down_load_file_name)
                            file_size=self.ftp_serve.Get_file_size(down_load_file_name)
                            t=threading.Thread(target=self.ftp_serve.Down_load_part_file,args=(down_load_path,down_load_file_name,))
                            t.start()
                            self.statusbar.showMessage("数据下载中......")
                            self.progressBar.label.setText("下载中")
                            self.progressBar.Show()
                            while True:
                                QApplication.processEvents()
                                now_file_size=os.lstat(self.output_filename).st_size
                                self.progressBar.Down_load_part_progressBar(file_size,now_file_size)
                                if file_size==str(os.lstat(self.output_filename).st_size):
                                    break
                            self.progressBar.Hide()
                            self.statusbar.showMessage("数据下载完成")

                        #显示3D
                        Show3D(self=self, mode=0, file=filenam)
                        #self.canva._display.Repaint()
                        self.filename = filenam
                        self.statusbar.showMessage("数据生成成功")
            except:
                self.statusbar.showMessage("此零件官方未提供3D，生成失败")

        except:
            pass

def Show3D(self, mode=0, file=None, aCompound=None):  # 生成3D mode控制显示模式
        try:

            self.canva._display.EraseAll()
            self.canva._display.hide_triedron()
            self.canva._display.display_triedron()
            self.canva._display.Repaint()
            self.new_build = TopoDS_Builder()  # 建立一个TopoDS_Builder()
            self.New_Compound = TopoDS_Compound()  # 定义一个复合体
            self.new_build.MakeCompound(self.New_Compound)  # 生成一个复合体DopoDS_shape
            self.QApplication=QApplication
            if mode == 0:
                #file=os.path.join(os.getcwd(),file)
                shapes_labels_colors_list=[]
                self.statusbar.showMessage("数据生成中请梢后......")
                t1=threading.Thread(target=assemble.read_step_file_with_names_colors,args=(self,file,shapes_labels_colors_list,))
                t1.start()
                self.progressBar.label.setText("正在生成")
                while True:
                    QApplication.processEvents()
                    if len(shapes_labels_colors_list)!=0:
                        break
                shapes_labels_colors=shapes_labels_colors_list[0]

                self.statusbar.showMessage("数据生成中请梢后......")
                self.aCompound=shapes_labels_colors
                shape_num=len(shapes_labels_colors.keys())
                self.progressBar.Show()
                for shpt_lbl_color in shapes_labels_colors:
                    label, c = shapes_labels_colors[shpt_lbl_color]
                    self.progressBar.Load_part_progressBar(shape_num)
                    QApplication.processEvents()
                    #for e in TopologyExplorer(shpt_lbl_color).solids():
                        #self.new_build.Add(self.New_Compound, e)
                    self.canva._display.DisplayColoredShape(shpt_lbl_color, color=Quantity_Color(c.Red(),
                                                                                c.Green(),
                                                                                c.Blue(),
                                                                                Quantity_TOC_RGB))
                    #self.aCompound=self.New_Compound
                print(self.solidworks_import_fiiepath)
                self.solidworks_import_fiiepath=file
                print(888888,self.solidworks_import_fiiepath)
                self.progressBar.Value_clear()
                self.progressBar.Hide()

            elif mode == 1:
                self.show = self.canva._display.DisplayColoredShape(aCompound, color="WHITE", update=True)
            self.canva._display.FitAll()

        except Exception as e:
            pass
            print(e)
            self.statusbar.showMessage("没有此零件")

def combox_refresh_function(self):#根据comcox改变combox
    if self.ButtonId in ["KBR系列(1-1)", "KBR系列(1-2)","KB系列"]:
        Reduction_ratio = self.boll_SCcrew.lever[self.combox_list[2].currentText()]
        self.combox_list[3].clear()
        self.combox_list[3].addItems(Reduction_ratio)  # 根据选项变换combox里的内容
    if self.ButtonId in ["EDA系列"]:
        try:
            series = self.combox_list[1].currentText()
            path = "EDA" + "/EDA" + series + "/3D"
            self.model_3d_file_list = self.ftp_serve.Get_file_list(path)
            lead_list, move_distance_list, Reduction_ratio_list, power_list,self.file_list = self.boll_SCcrew.Get_resourcr_list(
                self.model_3d_file_list)
            self.combox_list[4].clear()
            self.combox_list[4].addItems(lead_list)
            self.combox_list[5].clear()
            self.combox_list[5].addItems(move_distance_list)
            self.combox_list[6].clear()
            self.combox_list[6].addItems(Reduction_ratio_list)
            self.combox_list[7].clear()
            self.combox_list[7].addItems(power_list)
        except:
            pass

        #self.combox_list[3].addItems(Reduction_ratio)  # 根据选项变换combox里的内容

def show_technical_information(self):
    ButtonId=self.ButtonId
    if ButtonId in ["KS系列(孔输出)", "KS系列(孔输出法兰)", "KS系列(轴输出)", "KS系列(轴输出法兰)"]:
        pix_name_1 = "KS_1"
        pix_name_2 = "KS_2"
    elif ButtonId in ["KBR系列(1-1)","KBR系列(1-2)"]:
        series = "KBR" + self.combox_list[1].currentText()  # 机座号
        if series in ["KBR60","KBR90"]:
            pix_name_1 = "KBR-1"
            pix_name_2 = "KBR-1"
        elif series in ["KBR115","KBR142"]:
            pix_name_1 = "KBR-2"
            pix_name_2 = "KBR-2"
        elif series in ["KBR180","KBR220"]:
            pix_name_1 = "KBR-3"
            pix_name_2 = "KBR-3"
        elif series in ["KBR280","KBR340"]:
            pix_name_1 = "KBR-4"
            pix_name_2 = "KBR-4"
    elif ButtonId in ["KB系列"]:
        series = "KB" + self.combox_list[1].currentText()  # 机座号
        if series in ["KB60","KB90"]:
            pix_name_1 = "KB-1"
            pix_name_2 = "KB-1"
        elif series in ["KB115","KB142"]:
            pix_name_1 = "KB-2"
            pix_name_2 = "KB-2"
        elif series in ["KB180","KB220"]:
            pix_name_1 = "KB-3"
            pix_name_2 = "KB-3"
        elif series in ["KB280","KB340"]:
            pix_name_1 = "KB-4"
            pix_name_2 = "KB-4"
    elif ButtonId in ["EDA系列"]:
        series = "EDA" + self.combox_list[1].currentText()  # 机座号
        if series in ["EDA40"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA50"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA60"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA75"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA80"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA95"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA110"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA135"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA180"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA220"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
    # ----------2D显示图片操作 技术资料（1）----------------
    try:
        pix_name = ButtonId  # 2D
        #self.pix = QPixmap('Pic\\' + pix_name + ".PNG")
        self.graphicsView = GraphicsView(self.pix_dict[series], self.tab_8)
        self.graphicsView.setGeometry(QtCore.QRect(0, 0, 461 * self.width_scal, 581 * self.height_scal))
        self.graphicsView.setObjectName("graphicsView")
        self.graphicsView.scale(0.4, 0.4)  # 显示比例
        self.graphicsView.repaint()
        self.graphicsView.update()
        self.graphicsView.show()
        self.item = GraphicsPixmapItem(self.pix)  # 创建像素图元
        self.scene = QtWidgets.QGraphicsScene()  # 创建场景显示比例
        self.scene.addItem(self.item)

    except Exception as e:
        print(e)
        pass

    # ----------2D显示图片操作 技术资料（2）----------------
    try:
        self.graphicsView = GraphicsView(self.pix_dict[pix_name_1], self.tab_3)
        self.graphicsView.setGeometry(QtCore.QRect(0, 0, 461 * self.width_scal, 581 * self.height_scal))
        self.graphicsView.setObjectName("graphicsView")
        self.graphicsView.scale(0.4, 0.4)  # 显示比例
        self.item = GraphicsPixmapItem(self.pix)  # 创建像素图元
        self.scene = QtWidgets.QGraphicsScene()  # 创建场景显示比例
        self.scene.addItem(self.item)
        self.graphicsView.repaint()
        self.graphicsView.update()
        self.graphicsView.show()
    except:
        pass
        # ----------2D显示图片操作 技术资料（3）----------------
    try:
        self.graphicsView = GraphicsView(self.pix_dict[pix_name_2], self.tab_4)
        self.graphicsView.setGeometry(QtCore.QRect(0, 0, 461 * self.width_scal, 581 * self.height_scal))
        self.graphicsView.setObjectName("graphicsView")
        self.graphicsView.scale(0.4, 0.4)  # 显示比例
        self.item = GraphicsPixmapItem(self.pix)  # 创建像素图元
        self.scene = QtWidgets.QGraphicsScene()  # 创建场景显示比例
        self.scene.addItem(self.item)
        self.graphicsView.repaint()
        self.graphicsView.update()
        self.graphicsView.show()
    except:
        pass

def Create_pix_naime_dict_fun(pix_name,return_queue):
    app = QtWidgets.QApplication(sys.argv)
    #widget = QtWidgets.QWidget()
    pix_dict = {}
    for i in pix_name:
        try:
            pix_dict[i] = QPixmap("./"+'Pic/' + i + ".png")
        except Exception as e:
            print(e)
    #return_queue.put(pix_dict)
    print(return_queue)

def Create_pix_name_dict(self,path=".\\Pic"):#--------------------------------------------------- 资料图片加载
    def threading_load_pic(pix_name=""):
        #start_time=time.time()
        self.pix_dict[pix_name]=QPixmap("./"+'Pic/' + pix_name + ".png")
        #end_time=time.time()
        #print(pix_name,start_time,end_time)
    try:
        self.pix_dict = {}
        index=0
        pix_list=[]
        start_time = time.time()
        t={}#线程字典
        for root, dirs, files in os.walk(".\\Pic", topdown=False):
            if root == ".\\Pic":
                all_number=len(files)
                for i in files:
                    if i.lower().endswith("jpg"):
                        continue
                    pix_name = i.replace(".png", "")
                    pix_list.append(pix_name)
                    #self.pix_dict[pix_name] = QPixmap("./"+'Pic/' + pix_name + ".png")
                    t[i]=threading.Thread(target=threading_load_pic,args=(pix_name,))
                    t[i].start()
                    index+=1
                    compplete_percent=str(int(index/all_number*100))+"%"
                    self.splash.showMessage("资源加载中:"+compplete_percent+"  "+i)
                break

        '''
        尝试多进程失败
        queue=Queue()
        return_queue=Queue()
        queue.put(pix_list)
        manager=Manager()
        pix_dict=manager.list()
        new_speed=FuctionModule.speed_processing()
        new_speed.Create_multi_process(Create_pix_naime_dict_fun,queue,return_queue)
        '''
        end_time = time.time()
        print(end_time - start_time)
        self.splash.showMessage("资源加载中:" + "100%"+" 完成")
    except Exception as e:
        print(e)
        pass

def canvan_click(self):
        pass

def order_code_copy(series,self):
    clipboard = QApplication.clipboard()
    clipboard.setText(series)
    self.statusbar.showMessage("复制成功")
def Out_put_solidworks(self):
    try:
        print("enter", self.solidworks_import_fiiepath)
        solidworks_api=SolidworksModule.Solidworks_API()
        self.statusbar.showMessage("Solidworks链接成功")
        print("enter",self.solidworks_import_fiiepath)
        solidworks_api.Import_part(filepath=self.solidworks_import_fiiepath)
    except:
        self.statusbar.showMessage("导出失败")
    self.statusbar.showMessage("导出成功")


T = int(input())

dp = [[0] for _ in range(12)]
result = []

for _ in range(T):

    #찾으려는 횟수
    N = int(input())

    dp[1] = 1
    dp[2] = 2
    dp[3] = 4

    if dp[N] !=[0]:
        #print(dp[N])
        result.append(dp[N])
    else:
        for i in range(4,N+1):
            dp[i] = dp[i-1]+dp[i-2]+dp[i-3]

        #print(dp[N])
        result.append(dp[N])

for res in result:
    #print("---")
    print(res)


'''
Created on May 15, 2010

@author: ebakan
'''
import sys
if __name__=='__main__':
    inp=sys.stdin.read().split('\n')
    lst=range(1,int(inp[0])+1)
    for i in xrange(len(lst)-1):
        j=i
        while len(lst)>1:
            del lst[j]
            j=(j+int(inp[1])-1)%(len(lst))
        if lst[0]==int(inp[0]):
            sys.stdout.write(str(i+1)+'\n')
            break
        lst=range(1,int(inp[0])+1)


import math

def compute_breakeven_point(fixed_costs, unit_cost, unit_income, num_consultants=None):
    if num_consultants:
        total_costs = fixed_costs + num_consultants * unit_cost
        unit_profit = unit_income  # since cost already accounted for
    else:
        total_costs = fixed_costs

        # Get profit per consultant
        unit_profit = unit_income - unit_cost

    # See how many unit profits are needed to cover total_costs
    return math.ceil(total_costs / unit_profit)

print(compute_breakeven_point(100000, 18000, 25000)) # BEP
print(compute_breakeven_point(100000, 18000, 25000, num_consultants=100)) # BEP given staff of 100
print(compute_breakeven_point(100000, 18000, 25000, num_consultants=10)) # BEP given staff of 10


from bs4 import BeautifulSoup

with open("index.html") as file:
    html_code = file.read()

soup = BeautifulSoup(html_code, "html.parser")
# Udělá list všech odkazů
all_a = soup.find_all("a")
print(all_a)

for one_a in all_a:
    # nebo místo string napsat gettext
    # print(one_a.string)

    # Printuje jen odkazy
    print(one_a.get("href"))


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from utils.base_solver import BaseSolver

import os, logging, importlib, re, copy, random, tqdm, argparse
import os.path as osp
import cPickle as pickle
import numpy as np
from collections import defaultdict

import tensorflow as tf
import tensorflow.contrib.slim as slim
import torch

from utils import config as cfg
from utils import dataset, utils
from utils.evaluator import Multi_Evaluator

from run_symnet_multi import make_parser
from test_symnet import SolverWrapper as BaseSolverWrapper

def main():
    logger = logging.getLogger('MAIN')

    parser = make_parser()
    args = parser.parse_args()
    args.network = 'symnet_multi'
    utils.display_args(args, logger)
    logger.info("Loading dataset")

    test_dataloader = dataset.get_dataloader(args.data, 'test',
        batchsize=args.test_bz, args=args)

    logger.info("Loading network and solver")
    network = importlib.import_module('network.'+args.network)
    net = network.Network(test_dataloader, args)

    with utils.create_session() as sess:
        sw = SolverWrapper(net, test_dataloader, args)
        sw.trainval_model(sess, args.epoch)

class SolverWrapper(BaseSolverWrapper):

    def trainval_model(self, sess, max_epoch):
        logger = self.logger('test_model')
        logger.info('Begin testing')

        score_op, train_summary_op = self.construct_graph(sess)
        self.initialize(sess)
        sess.graph.finalize()

        evaluator = Multi_Evaluator()
        all_attr = []
        all_pred = defaultdict(list)

        for image_ind, batch in tqdm.tqdm(enumerate(self.test_dataloader), total=len(self.test_dataloader), postfix='test'):

            predictions = self.network.test_step(sess, batch, score_op)
            all_attr.append(torch.from_numpy(batch[1]))
            for key in score_op.keys():
                all_pred[key].append(predictions[key])

        for name, pred in all_pred.items():
            mAP, mAUC = evaluator(
                np.concatenate(pred,0),
                np.concatenate(all_attr,0)
            )
            report_dict = {
                'mAP':          mAP,
                'mAUC':         mAUC,
                'name':         self.args.name,
                'epoch':        self.args.epoch,
            }

            print("%s: "%(name) + utils.formated_multi_result(report_dict))
        logger.info('Finished.')

if __name__=="__main__":
    main()


import pytest

from broker.tasks.cloudfront import (
    create_distribution,
    disable_distribution,
    wait_for_distribution_disabled,
    delete_distribution,
)
from broker.extensions import db
from broker.models import CDNServiceInstance, Operation

from tests.lib import factories

@pytest.fixture
def service_instance():
    service_instance = factories.CDNServiceInstanceFactory.create(
        id="1234",
        domain_names=["example.com", "foo.com"],
        domain_internal="fake1234.cloudfront.net",
        route53_alias_hosted_zone="Z2FDTNDATAQYW2",
        cloudfront_distribution_id="FakeDistributionId",
        cloudfront_origin_hostname="origin_hostname",
        cloudfront_origin_path="origin_path",
        origin_protocol_policy="https-only",
        forwarded_headers=["HOST"],
    )
    new_cert = factories.CertificateFactory.create(
        service_instance=service_instance,
        private_key_pem="SOMEPRIVATEKEY",
        iam_server_certificate_id="certificate_id",
        id=1002,
    )
    current_cert = factories.CertificateFactory.create(
        service_instance=service_instance,
        private_key_pem="SOMEPRIVATEKEY",
        iam_server_certificate_id="certificate_id",
        id=1001,
    )
    factories.ChallengeFactory.create(
        domain="example.com",
        validation_contents="example txt",
        certificate_id=1001,
        answered=True,
    )
    factories.ChallengeFactory.create(
        domain="foo.com",
        validation_contents="foo txt",
        certificate_id=1001,
        answered=True,
    )
    factories.ChallengeFactory.create(
        domain="example.com",
        validation_contents="example txt",
        certificate_id=1002,
        answered=False,
    )
    factories.ChallengeFactory.create(
        domain="foo.com",
        validation_contents="foo txt",
        certificate_id=1002,
        answered=False,
    )
    service_instance.current_certificate = current_cert
    service_instance.new_certificate = new_cert
    db.session.add(service_instance)
    db.session.add(current_cert)
    db.session.add(new_cert)
    db.session.commit()
    db.session.expunge_all()
    return service_instance

@pytest.fixture
def provision_operation(service_instance):
    operation = factories.OperationFactory.create(
        id=4321, service_instance=service_instance
    )
    return operation

def test_create_distribution_existing_distribution(
    clean_db, service_instance, cloudfront, provision_operation
):
    cloudfront.expect_get_distribution(
        caller_reference="asdf",
        domains=service_instance.domain_names,
        certificate_id=service_instance.new_certificate.iam_server_certificate_id,
        origin_hostname=service_instance.cloudfront_origin_hostname,
        origin_path=service_instance.cloudfront_origin_path,
        distribution_id=service_instance.cloudfront_distribution_id,
        status="InProcess",
    )
    create_distribution.call_local(provision_operation.id)

def test_create_distribution_referencing_nonexistent_distribution(
    clean_db, service_instance, cloudfront, provision_operation
):
    cloudfront.expect_get_distribution_returning_no_such_distribution(
        distribution_id=service_instance.cloudfront_distribution_id
    )
    cloudfront.expect_create_distribution(
        caller_reference=service_instance.id,
        domains=service_instance.domain_names,
        certificate_id=service_instance.new_certificate.iam_server_certificate_id,
        origin_hostname=service_instance.cloudfront_origin_hostname,
        origin_path=service_instance.cloudfront_origin_path,
        distribution_id="FakeDistributionId",
        distribution_hostname="fake1234.cloudfront.net",
        bucket_prefix="1234/",
    )

    create_distribution.call_local(provision_operation.id)

    db.session.expunge_all()
    service_instance = CDNServiceInstance.query.get("1234")

    assert service_instance.cloudfront_distribution_arn
    assert service_instance.cloudfront_distribution_arn.startswith("arn:aws:cloudfront")
    assert service_instance.cloudfront_distribution_arn.endswith("FakeDistributionId")
    assert service_instance.cloudfront_distribution_id == "FakeDistributionId"
    assert service_instance.domain_internal == "fake1234.cloudfront.net"

def test_deprovision_skips_disabling_when_no_cloudfront_distribution_present(
    clean_db, cloudfront
):
    service_instance = factories.CDNServiceInstanceFactory.create(
        id="1233",
        domain_names=["example.com", "foo.com"],
        domain_internal="fake1233.cloudfront.net",
        route53_alias_hosted_zone="Z2FDTNDATAQYW2",
    )
    operation = factories.OperationFactory.create(
        id="5677",
        state=Operation.States.IN_PROGRESS.value,
        action=Operation.Actions.DEPROVISION.value,
    )
    db.session.commit()
    db.session.expunge_all()

    # try these things - it'll blow up if we try to call cloudfront because we've stubbed boto
    disable_distribution.call_local("5677")
    wait_for_distribution_disabled.call_local("5677")
    delete_distribution.call_local("5677")


#!/usr/bin/env python3

import os
import logging
import numpy as np

def sigmoid(x, derivative=False):
    return x*(1-x) if derivative else 1/(1+np.exp(-x))

def _get_pipe_model_name(pipe, name):
    for n, m in pipe.steps:
        if n == name:
            return m
    return None

def _get_pipe_model_idx(pipe, idx):
    return pipe.steps[idx][1]

def get_pipe_model(pipe, indicator):
    return _get_pipe_model_idx(pipe, indicator) if isinstance(indicator, int) else \
           _get_pipe_model_name(pipe, indicator)

def get_pipe_transform(pipe, x):
    for name, model in pipe.steps[:-1]:
        x = model.transform(x)
    return x

def print_pipe_model(model):
    if model is None:
        return None

    str = ''
    for step in model.steps:
        str += "%s: %s\n" % step;
    return str;

def which_set(sets, k):
    nset = len(sets)
    for i in range(nset):
        if k in sets[i]:
            return i
    return nset

def split_dict(d, *key_sets):
    ret = [{} for _ in range(len(key_sets) + 1)]

    for k, v in d.items():
        ret[which_set(key_sets, k)][k] = v

    return ret

# search file with its path matching @path_prefix
# if more than one candicate, throw exception
# return:
#    path, suffix
def search_path(path_prefix):
    if os.path.exists(path_prefix):
        return path_prefix, ''

    dir = os.path.dirname(path_prefix)
    prefix = os.path.basename(path_prefix)

    candicates = [f for f in os.listdir(dir) if f.startswith(prefix) ]
    if len(candicates) > 1:
        raise Exception("more than one file under '%s' with filename prefix '%s'" % (dir, prefix))
    elif len(candicates) == 0:
        return None, None
    else:
        path = os.path.join(dir, candicates[0])
        suffix = candicates[0][len(prefix):]
        return path, suffix

# return matched range [begin, end)
def find_seq(seq, subseq, is_eql=None, to_skip=None, begin=0, end=None):
    if to_skip is None:
        to_skip = lambda item: False

    if is_eql is None:
        is_eql = lambda x1, x2: x1 == x2

    if end is None:
        end = len(seq)

    len_subseq = len(subseq)

    for idx in range(begin, end):
        p, q = idx, 0
        while p < end and q < len_subseq:
            if p != idx and to_skip(seq[p]):  #skip stopword if not the frist.
                p += 1
            elif not is_eql(seq[p], subseq[q]):
                break
            else:
                p, q = p+1, q+1

        if q == len_subseq:
            return idx, p

    return -1, -1;

def rfind_seq(seq, subseq, is_eql=None, to_skip=None, begin=0, end=None):
    if to_skip is None:
        to_skip = lambda item: False

    if is_eql is None:
        is_eql = lambda x1, x2: x1 == x2

    if end is None:
        end = len(seq)

    len_subseq = len(subseq)

    for idx in range(end-1, begin-1, -1):
        p, q = idx, len_subseq -1
        while p >= 0 and q >= 0:
            if p != idx and to_skip(seq[p]):  #skip stopword if not the frist.
                p -= 1
            elif not is_eql(seq[p], subseq[q]):
                break
            else:
                p, q = p-1, q-1

        if q == -1:
            return p+1, idx+1

    return -1, -1;

def set_logging(verbose=0):
    log_level = logging.DEBUG   if verbose >= 2 else \
                logging.INFO    if verbose == 1 else \
                logging.WARNING if verbose == 0 else \
                logging.ERROR
    logging.basicConfig(level=log_level,
            format="%(asctime)s.%(msecs)03d [%(levelname)s] [%(module)s] %(message)s", datefmt="%H:%M:%S")

def assert_eq(expected, val):
    if expected != val:
        raise RuntimeError("Assert equal error: Expected '{}' is not equal to '{}'".format(expected, val))

def test_search_path():
    def to_test(path_prefix):
        path, suffix = search_path(path_prefix)
        print("path_prefix: %s ->  path: %s, suffix: %s" % (path_prefix, path, suffix))

    to_test('.model/knn')
    to_test('.model/knn/AssertFail')
    to_test('.model/knn/BadPrefix')
    to_test('/etc/app')

def test_find_seq():
    seq = 'Buying food on the street is nothing new but in the UK this idea is really taking off Its a great way of sampling freshly cooked dishes from around the world Rob and Neil discuss the subject and hear from an expert who explains the popularity in this type of food plus you can learn nothing new vocabulary along the way'.split()

    def to_skip(w):
        return w in {'on', 'the', 'is', 'in', 'a', 'an', 'of', 'from', 'and'}

    assert_eq((1, 7), find_seq(seq, 'food street nothing'.split(), None, to_skip))
    assert_eq((1, 7), find_seq(seq, 'food on the street is nothing'.split()))
    assert_eq((38, 44), find_seq(seq, 'hear expert who explains'.split(), None, to_skip))

    assert_eq((1, 7), rfind_seq(seq, 'food street nothing'.split(), None, to_skip))
    assert_eq((1, 7), rfind_seq(seq, 'food on the street is nothing'.split()))
    assert_eq((38, 44), rfind_seq(seq, 'hear expert who explains'.split(), None, to_skip))

    assert_eq((6, 8), find_seq(seq, 'nothing new'.split(), None, to_skip))
    assert_eq((6, 8), find_seq(seq, 'nothing new'.split(), None, to_skip, 6))
    assert_eq((55, 57), find_seq(seq, 'nothing new'.split(), None, to_skip, 7))

    assert_eq((55, 57), rfind_seq(seq, 'nothing new'.split(), None, to_skip))
    assert_eq((6, 8), rfind_seq(seq, 'nothing new'.split(), None, to_skip, 56))

if __name__  == '__main__':
     test_find_seq()


# 정답

N = int(input())
arr = list(map(int, input().split(' ')))
eli = int(input())

def dfs(num, arr):
    arr[num] = -2
    for i, v in enumerate(arr):
        if num == v:
            dfs(i, arr)

dfs(eli, arr)
cnt = 0
for i, v in enumerate(arr):
    if v != -2 and i not in arr:
        cnt += 1
print(cnt)


'''
Given a linked list, write a function to reverse every alternate k nodes in an
efficient way.
Example:
Inputs:   1->2->3->4->5->6->7->8->9->NULL and k = 3
Output:   3->2->1->4->5->6->9->8->7->NULL.
'''
from linkedlist import LinkedList
from linkedlist import Node

def reverseAlternateKNodes(node, k, reverse):
    prev, current, count, next = None, node, 0, None
    while current and count < k:
        if reverse:
            next = current.next
            current.next = prev
            prev, current = current, next
            count += 1
        else:
            prev, current, next = current, current.next, current.next
            count += 1
    if reverse:
        if next:
            node.next = reverseAlternateKNodes(next, k, not reverse)
    else:
        if prev:
            prev.next = reverseAlternateKNodes(next, k, not reverse)
    return prev if reverse else node

l = LinkedList()
[l.append(x) for x in range(1, 10)]
l.printList()
l.head = reverseAlternateKNodes(l.head, 3, True)
l.printList()


import os

import pickle
import rosbag
import numpy as np

from .timestamp_series import TimestampSeries
from .tools import *

DefaultTopic = '/device_time'

def guessTopics(bagFile):
  with rosbag.Bag(bagFile) as bag:
    found = []
    for topic, value in bag.get_type_and_topic_info().topics.items() :
      if value.msg_type == 'cuckoo_time_translator/DeviceTimestamp':
        found.append(topic)

  return found

class DeviceTimeStream():

  def __init__(self, bagFile, topic, invalidate=False):
    eventsFile = os.path.realpath(bagFile) + topic.replace("/", "_") + ".p"
    if os.path.exists(eventsFile):
        if invalidate:
            info("Removing " + eventsFile)
        else:
            verbose("Loading from " + eventsFile)
            self.__dict__ = pickle.load(open(eventsFile, "rb"))
            return

    bag = rosbag.Bag(bagFile)

    self.translated_hw_times = TimestampSeries()
    self.translated_hw_times_without_offset = TimestampSeries()
    self.receive_times = TimestampSeries()
    self.raw_hw_times = TimestampSeries()
    for topic, msg, t in bag.read_messages(topics=[topic]):
      self.translated_hw_times.append(msg.header.stamp.to_sec())
      self.translated_hw_times_without_offset.append(msg.header.stamp.to_sec() - msg.offset_secs)
      self.receive_times.append(msg.receive_time.to_sec())
      self.raw_hw_times.append(float(msg.event_stamp))

    self.zeroOffsetAllTheTime = np.linalg.norm(np.array(self.translated_hw_times_without_offset) - np.array(self.translated_hw_times)) < 1e-9

    bag.close()
    # Save data to file
    pickle.dump(self.__dict__, open(eventsFile, "wb"))


from onmt.Optim import Optim

class Optim:
    def __init__(self, model_a, model_b, opt=None):
        assert opt is None, "not support yet"

        self.optim_a = Optim('sgd', 0.0002)
        self.optim_a.set_parameters(model_a.parameters())

        self.optim_b = Optim('sgd', 0.02)
        self.optim_b.set_parameters(model_b.parameters())

    def step(self):
        self.optim_a.step()
        self.optim_b.step()

class Trainer:
    def __init__(self, train_data, model_a, model_b, lm_a, lm_b, optim_a, optim_b, alpha=0.005):
        """
        :param train_data: list of dict of monolingual data, train_data[0]["a"] is batch 0 of sentences in language A
        :param model_a: translation model to language A
        :param model_b: translation model to language B
        :param lm_a: language model of language of A
        :param lm_b: language model of language of B
        :param optim_a: optimizers for a - b - a round
        :param optim_b: optimizers for b - a - b round
        """
        self.train_data = train_data
        self.model_a = model_a
        self.model_b = model_b

        self.lm_a = lm_a
        self.lm_b = lm_b

        self.alpha = alpha
        self.optim_a = optim_a
        self.optim_b = optim_b

        # training round
        self.start = ("a", "b")

    def train(self):
        for s_a, s_b in self.train_data:
            # init grad at first!
            # a -> b -> a
            self.zero_grad()
            self._round(s_a, 'a')
            self.optim_a.step()

            # b -> a -> b
            self.zero_grad()
            self._round(s_b, 'b')
            self.optim_b.step()

    def zero_grad(self):
        self.model_a.zero_grad()
        self.model_b.zero_grad()

    def _round(self, s, start):
        """
        for detail, look at the algorithm in report
        :param s: one batch of sentences in start language
        :param start: indicates what is the start of this round
        :return: None
        """
        assert start in ['a', 'b']

        model_a, model_b, lm = self.model_a, self.model_b, self.lm_b
        if start == "b":
            model_a, model_b = model_b, model_a
            lm = self.lm_a

        pred, pred_score, _ = model_a.predict(s, None)
        r_1 = lm.score(pred)  # batch * k r_1 is not Variable
        _, _, r_2 = model_b.predict(pred, s)
        r = self.alpha * r_1 + (1 - self.alpha) * r_2.data

        # batch * k
        grad_a = (pred_score * r).mean()
        grad_b = (r_2 * (1 - self.alpha)).mean()
        grad_a.backward()
        grad_b.backward()


import argparse
import json
import os
import tempfile
from pathlib import Path

import openai
from dotenv import load_dotenv
from langchain.chains.combine_documents.stuff import StuffDocumentsChain
from langchain.chains.llm import LLMChain
from langchain.chat_models import ChatOpenAI
from langchain.document_loaders import TextLoader
from langchain.prompts import PromptTemplate
from transformers import AutoTokenizer, pipeline

load_dotenv()

from newsfeed.datatypes import BlogInfo, BlogSummary
from newsfeed.extract_articles import sanitize_filename

def summarize_text(blog_post_path, local_model=None, sum_type="tech"):
    api_key = os.getenv("OPENAI_API_KEY")
    openai.api_key = api_key
    # loading text as langchain document
    loader = TextLoader(blog_post_path)
    blog_post = loader.load()

    if local_model == "gpt2":
        # just text for local models
        blog_post_text = json.loads(blog_post[0].page_content)["blog_text"]

        checkpoint = "distilgpt2"
        tokenizer = AutoTokenizer.from_pretrained(checkpoint)  # this selects GPT2TokenizerFast

        # max token length is 1024
        # limit input tokens to allow enough space for generation
        tokens_text = tokenizer.tokenize(blog_post_text)
        tokens_tldr = tokenizer.tokenize("\n\nTL;DR:\n")
        tokens = tokens_text[:800] + tokens_tldr

        # convert back to string for pipeline
        query = tokenizer.convert_tokens_to_string(tokens)

        # pipeline uses tokenizer GPT2TokenizerFast and model GPT2LMHeadModel
        pipe = pipeline(
            "text-generation",
            model=checkpoint,
            max_new_tokens=(1024 - len(tokens)),
            temperature=1.5,  # higher value softens output distribution (reducing confidence in predictions, adding more randomness)
        )
        pipe_out = pipe(query)
        summary = pipe_out[0]["generated_text"][len(query) :]

    elif local_model == "t5":
        # just text for local models
        blog_post_text = json.loads(blog_post[0].page_content)["blog_text"]

        checkpoint = "t5-small"
        tokenizer = AutoTokenizer.from_pretrained(checkpoint)  # T5TokenizerFast

        # maximum sequence length for model is 512
        tokens = tokenizer.tokenize(blog_post_text, max_length=512, truncation=True)
        tokens = tokens[:509]  # for some reason pipeline sees 515 tokens
        query = tokenizer.convert_tokens_to_string(tokens)

        # pipeline uses tokenizer T5TokenizerFast and model T5ForConditionalGeneration
        pipe = pipeline("summarization", model=checkpoint, temperature=1.5, do_sample=True)
        pipe_out = pipe(query, max_length=257)
        summary = pipe_out[0]["summary_text"]

    elif local_model == None:
        prompt = select_prompt(sum_type)

        # define what LLM to use
        # using OpenAI chat LLM API requires env variable OPEN_AI_KEY to be set with API key
        llm = ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo-16k")

        # create a "chain" object for running queries against a specified LLM, with customizable prompt
        llm_chain = LLMChain(llm=llm, prompt=prompt)

        # send document to the llm_chain
        # StuffDocumentsChain "stuffs" list of documents + prompt into single call
        # MapReduceChain splits it into several combines and then combines output
        # document_variable_name can be used to customize where in the prompt the documents are inserted?
        stuff_chain = StuffDocumentsChain(llm_chain=llm_chain, document_variable_name="text")
        summary = stuff_chain.run(blog_post)

    else:
        raise NotImplementedError(
            f"Local model {local_model} not implemented. Please choose between 'gpt2' and 't5'"
        )

    return summary

def select_prompt(sum_type):
    if sum_type == "tech":
        prompt_template = """Write a concise summary for an AI researcher of the following:
        "{text}"
        CONCISE SUMMARY:"""
    elif sum_type == "ntech":
        prompt_template = """Write a very simple summary, suitable for children, of the following:
        "{text}"
        SIMPLE SUMMARY:"""
    elif sum_type == "swe":
        prompt_template = """Skriv en sammanfattning på svenska av följande text:
        "{text}"
        Sammanfattning:"""
    else:
        raise NotImplementedError(
            f"Summarization type {sum_type} not implemented. Please choose 'tech', 'ntech', or 'swe'"
        )

    prompt = PromptTemplate.from_template(prompt_template)
    return prompt

# main takes the argument --source aws, or --source mit
def main(source, local_model=None, sum_type="tech"):
    path_article_dir = Path(f"data/data_warehouse/{source}/articles")
    path_summary_dir = Path(f"data/data_warehouse/{source}/summarized_articles")

    if local_model:
        path_summary_dir = path_summary_dir / local_model
    else:
        path_summary_dir = path_summary_dir / sum_type

    path_summary_dir.mkdir(parents=True, exist_ok=True)

    already_summarized = set(os.listdir(path_summary_dir))

    file_list = os.listdir(path_article_dir)
    new_articles = []

    for file_name in file_list:
        summary_filename_check = f"Summary_of_{file_name}"

        if summary_filename_check in already_summarized:
            print(f"Skipping already summarized article: {file_name}")
            continue

        # if new summary is generated, add to list
        new_articles.append(file_name)
        # file path for the article that's being summarized/looked at
        current_article_path = path_article_dir / file_name
        summary_text = summarize_text(current_article_path, local_model, sum_type)
        print(f"Generated summary for {file_name}")

        blog_summary = BlogSummary(
            unique_id=f"summary_{file_name}",
            title=f"Summary of {Path(file_name).stem}",
            text=summary_text,
        )
        # gets the name of the article
        summary_filename = blog_summary.get_filename()
        summary_filename = sanitize_filename(summary_filename)

        with open(path_summary_dir / summary_filename, "w") as f:
            f.write(blog_summary.json())
        already_summarized.add(summary_filename)

    return new_articles

blog_names = ["mit", "aws", "openai"]

# run python summarize.py --source mit OR aws
def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--source",
        type=str,
        choices=blog_names,
        default="mit",
        help=f"Blog source to summarize, allowed arguments are: {blog_names}.",
    )
    parser.add_argument(
        "--model",
        type=str,
        choices=["t5", "gpt2"],
        # default="",
        help=f"Use local model for summarization",
    )
    parser.add_argument(
        "--stype",
        type=str,
        choices=["tech", "ntech", "swe"],
        default="tech",
        help=f"What type of summarization do you want (techincal 'tech', non-technical 'ntech', or swedish 'swe')",
    )
    return parser.parse_args()

if __name__ == "__main__":
    args = parse_args()
    main(source=args.source, local_model=args.model, sum_type=args.stype)


# -*- coding: utf-8 -*-
from PyQt4 import QtCore
from PyQt4.QtGui import QIcon, QColor
from PyQt4.QtGui import QDialog
from PyQt4.uic import loadUi
from message_window import MessageWindowPresenter

class AddWindowPresenter(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.setWindowModality(QtCore.Qt.ApplicationModal)
        self.parent = parent
        loadUi('AddWindow.ui', self)
        self.setWindowTitle(u'Добавление нового контакта')
        self.setWindowIcon(QIcon('icon.png'))
        self.loginTextEdit.setTextColor(QColor('gray'))
        self.loginTextEdit.setPlainText(u'Имя контактного лица')#(u'Петя')
        self.loginTextEdit.setTextColor(QColor('black'))
        self.phoneNumberTextEdit.setTextColor(QColor('gray'))
        self.phoneNumberTextEdit.setPlainText(u"Номер телефона (цифры после '+7')")#('9653838383')
        self.phoneNumberTextEdit.setTextColor(QColor('black'))

        self.okButton.clicked.connect(self.on_okButton_click)
        self.cancelButton.clicked.connect(self.on_cancelButton_click)

    def on_cancelButton_click(self):
        self.close()

    def on_okButton_click(self):
        if unicode(self.phoneNumberTextEdit.toPlainText()).isdigit() and len(self.phoneNumberTextEdit.toPlainText()) == 10:
            answer = self.parent.parent.service.post_contact(self.parent.user_info[0][0], self.loginTextEdit.toPlainText(), self.phoneNumberTextEdit.toPlainText(),  self.bornDateEdit.text())
            if answer == 0:
                if unicode(self.loginTextEdit.toPlainText())[0] in u'ЙЦУКЕНГШЩЗЪХФЫВАПРОЛДЖЭЯЧСМИТЬБЮ' \
                                                          u'йцукенгшщзхъэждлорпавыфячсмитьбю':
                    message_window = MessageWindowPresenter(self, u"Контакт успешно добавлен в алфавитном\n "
                                                                  u"порядке на страницу с буквой '" + self.loginTextEdit.toPlainText()[0] + "'!")
                else:
                    message_window = MessageWindowPresenter(self, u"Контакт успешно добавлен в алфавитном\n "
                                                                  u"порядке на страницу 'Прочее'!")
            else:
                message_window = MessageWindowPresenter(self, u"Такой контакт у вас уже есть!")
        else:
            message_window = MessageWindowPresenter(self, u"Номер телефона должен содержать только\n "
                                                          u"10 цифр без разделителей! (цифры после '7+')")
        message_window.show()


import scrapy
from scrapy import log
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from rcbi.items import Part

import copy
import json
import re

import os.path
import urlparse
import urllib

VARIANT_JSON_REGEX = re.compile("product: ({.*}),")
MANUFACTURERS = []
CORRECT = {"Cobra Motors": "Cobra", "Immersion RC": "ImmersionRC"}
STRIP_PREFIX = []

class MiniQuadBrosSpider(CrawlSpider):
  name = "miniquadbros"
  allowed_domains = ["miniquadbros.com"]
  start_urls = ["http://www.miniquadbros.com/collections/frontpage"]

  rules = (
    Rule(LinkExtractor(restrict_css=[".thumbnail"]), callback='parse_item'),
  )

  def parse_item(self, response):
    item = Part()
    item["site"] = self.name

    variant = {}
    item["variants"] = [variant]

    parsed = urlparse.urlparse(response.url)
    filename = "/products/" + os.path.basename(parsed[2])
    base_url = urlparse.urlunparse((parsed[0], parsed[1], filename,
                                          parsed[3], parsed[4], parsed[5]))

    # Find the json info for variants.
    body = response.body_as_unicode()

    m = VARIANT_JSON_REGEX.search(body)
    if m:
      shopify_info = json.loads(m.group(1))
      global_title = shopify_info["title"]
      preorder = False
      if global_title.endswith("Pre Order"):
        global_title = global_title[:-len("Pre Order")].strip()
        variant["stock_state"] = "backordered"
        preorder = True

      if "vendor" in shopify_info:
        if shopify_info["vendor"] in MANUFACTURERS:
          item["manufacturer"] = shopify_info["vendor"]
          if global_title.startswith(item["manufacturer"]):
            global_title = global_title[len(item["manufacturer"]):].strip(" -")
        elif shopify_info["vendor"] in CORRECT:
          item["manufacturer"] = CORRECT[shopify_info["vendor"]]
          if global_title.startswith(shopify_info["vendor"]):
            global_title = global_title[len(shopify_info["vendor"]):].strip(" -")
        for strip in STRIP_PREFIX:
          if global_title.startswith(strip):
            global_title = global_title[len(strip):].strip(" -")

      for v in shopify_info["variants"]:
        if v["title"] != "Default Title":
          item["name"] = (global_title + " " + v["title"]).strip()
          variant["url"] = base_url + "?variant=" + str(v["id"])
        else:
          item["name"] = global_title
          variant["url"] = base_url
        variant["price"] = "${:.2f}".format(v["price"] / 100)
        if not preorder:
          if v["inventory_quantity"] <= 0:
            if v["inventory_policy"] == "deny":
              variant["stock_state"] = "out_of_stock"
            else:
              variant["stock_state"] = "backordered"
          else:
            variant["stock_state"] = "in_stock"

        yield item
        item = copy.deepcopy(item)
        variant = item["variants"][0]


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 25 03:15:21 2019

@author: ishan
"""

import matplotlib.pyplot as plt
import numpy as np

show_animation = True

# Creating obstacle map
ox,oy = [],[]
explore_x,explore_y = [],[]
backtrack = []
obstacle = np.zeros(shape=(250,150))
for x in range (0,250):
    for y in range(0,150):

# Equations for rectangle
        f1 = -y + 67.5
        f2 =  y - 112.5
        f3 =  -x + 50
        f4 =  x - 100

 #Equations for circle
        f5 = (x - 190)**2 + (y - 130)**2 - (15)**2

 #Equation for ellipse
        f6 = (1/225) * ((x - 140)**2) + (1/36) * ((y - 120)**2) - 1

 #Equation for polygon-triangle 1
        f7 = 38*x + 23*y - 8530
        f8 = -y +52
        f9 = -38*x + 7*y +5830

#Equation for polygon-traingle 2
        f10 = 2*x + 19*y - 1314
        f11 = -41*x -25*y + 6525
        f12 = 37*x -13*y -5355

#Equation for polygon-part 3
        f13 = y - 52
        f14 = 37*x - 20*y - 6101
        f15 = -y + 15
        f16 = -37*x + 13*y + 5355
        if (f1<=0 and f2<=0 and f3<=0 and f4<=0 or f5<=0 or f6<=0 or (f7<=0 and f8<=0 and f9<=0) or (f10<=0 and f11<=0 and f12<=0) or (f13<=0 and f14<=0 and f15<=0 and f16<=0)):
            obstacle[x][y] = 1
            ox.append(x)
            oy.append(y)

for i in range(250):
        ox.append(i)
        oy.append(0)
        obstacle[i][0] = 1
for i in range(250):
        ox.append(i)
        oy.append(150)
        obstacle[i][149] = 1
for i in range(150):
        ox.append(0)
        oy.append(i)
        obstacle[0][i] = 1
for i in range(150):
        ox.append(250)
        oy.append(i)
        obstacle[249][i] = 1

#plotting the obstacle map
plt.plot(ox,oy,".k")
plt.ylim((0,150))
plt.xlim((0,250))


#!/usr/bin/env python3
import argparse
import sys

import pyperclip
from tabulate import tabulate
from tqdm import tqdm

import lime_comb
from lime_comb.commands.config import ConfigCommand
from lime_comb.commands.decrypt import DecryptCommand
from lime_comb.commands.encrypt import EncryptCommand
from lime_comb.commands.keys import KeysCommand
from lime_comb.config import EmptyConfigError, config
from lime_comb.logger.logger import logger
from lime_comb.validators.email import lc_validate_email

def base_parser(input_args):
    parser = argparse.ArgumentParser(description="lime comb tool.")

    parser.add_argument(
        "--version",
        dest="version",
        required=False,
        action="store_true",
        help="show current version",
    )
    parser.add_argument(
        "--log-lvl",
        dest="log_lvl",
        required=False,
        default="WARNING",
        action="store",
        choices=("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"),
        help="log level",
    )

    subparsers = parser.add_subparsers(
        help="use --help to check help for sub-command",
        title="commands",
        description="Top level supported commands",
        required=False,
        dest="top_command",
    )
    keys_cmd = KeysCommand(subparsers)
    enc_cmd = EncryptCommand(subparsers)
    dec_cmd = DecryptCommand(subparsers)
    conf_cmd = ConfigCommand(subparsers)
    args = parser.parse_args(input_args)
    parse_common(parser, args)
    return args, keys_cmd, enc_cmd, dec_cmd, conf_cmd

# TODO provide class for config and keys

def parse_common(parser, args):
    logger.setLevel(args.log_lvl)
    logger.info(f"log lvl {logger.getEffectiveLevel()}")
    if args.version:
        print(f"version: {lime_comb.__version__}")
        sys.exit(0)
    elif not args.top_command:
        parser.print_help()
        sys.exit(0)

def get_recipients(args):
    if not getattr(args, "recipients", None):
        logger.info("No recipients. Asking user to type in")
        args.recipients = input("please specify recipients(space separated)\n").split()
        for email in args.recipients:
            try:
                lc_validate_email(email)
            except Exception as e:
                logger.critical(e)
                sys.exit(1)
    return args.recipients

def get_message(args):
    if args.files:
        for fn in args.files:
            logger.debug(f"adding content of {fn} to messages")
            with open(fn, "r") as f:
                args.messages.append(f.read())
    if not args.messages:
        logger.warning("No message to encrypt")
        sys.exit(1)
    return args.messages

def dec_exec(args, cmd):
    if args.top_command in cmd.aliases:
        decrypted = []
        for m in tqdm(cmd(get_message(args)), desc="decrypting"):
            decrypted.append(m)
        decrypted = "\n---\n".join(decrypted)
        pyperclip.copy(decrypted)
        return decrypted

def enc_exec(args, cmd):
    if args.top_command in cmd.aliases:
        encrypted = []
        for m in tqdm(
            cmd(get_message(args), get_recipients(args), merge=args.merge_messages),
            desc="encrypting",
        ):
            encrypted.append(m)
        encrypted = "\n---\n".join(encrypted)
        pyperclip.copy(encrypted)
        return encrypted

def keys_exec(args, cmd):
    if args.top_command in cmd.aliases:
        keys = list(tqdm(cmd(args), desc="keys"))
        return tabulate(keys)

def conf_exec(args, cmd):
    if args.top_command in cmd.aliases:
        return tabulate(list(cmd(args)))

def main(cmdline_args):
    args, k_cmd, e_cmd, d_cmd, c_cmd = base_parser(cmdline_args)
    try:
        for action in (
            dec_exec(args, d_cmd),
            enc_exec(args, e_cmd),
            keys_exec(args, k_cmd),
            conf_exec(args, c_cmd),
        ):
            if action:
                print(action)
    except EmptyConfigError:
        config._gen_config()

def run():
    main(sys.argv[1:])

if __name__ == "__main__":
    run()


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 1,0.00001)
y = np.sqrt(1 - x**2)

plt.plot(x, y,'y')
plt.plot(x, -y,'y')
plt.gca().set_aspect('equal')
plt.show()


import torch
import os
from glob import glob
import cv2
from torchvision import transforms
import numpy as np
from itertools import chain

class dataset(torch.utils.data.IterableDataset):
    def __init__(self,config,mode='train'):

        self.mode = mode
        self.config = config
        self.basepath = config.basepath

        sequences = glob(os.path.join(self.basepath,"raw/sequences/*"))

        image_2_seqs = {}
        image_3_seqs = {}

        image_2_seqs_test = {}
        image_3_seqs_test = {}
        calibs = {}

        count_train = 0
        count_test = 0

        self.test_seqs = config.test_seqs
        self.train_seqs = config.train_seqs

        for seq in sequences:
            seq_num = seq.split('/')[-1]
            if seq_num in self.test_seqs:

                image_2_seqs_test[seq_num] = sorted(glob(seq + "/image_2/*"))
                image_3_seqs_test[seq_num] = sorted(glob(seq + "/image_3/*"))
                count_test+=len(image_2_seqs_test[seq_num])
                count_test+=len(image_3_seqs_test[seq_num])

            else:
                image_2_seqs[seq_num] = sorted(glob(seq + "/image_2/*"))
                image_3_seqs[seq_num] = sorted(glob(seq + "/image_3/*"))

                count_train+=len(image_2_seqs[seq_num])
                count_train+=len(image_2_seqs[seq_num])

            calibs[seq_num] = os.path.join(self.basepath,"raw","sequences",seq_num,"calib.txt")

        self.image_2_seqs = image_2_seqs
        self.image_3_seqs = image_3_seqs
        self.image_2_seqs_test = image_2_seqs_test
        self.image_3_seqs_test = image_3_seqs_test
        self.count_train = count_train
        self.count_test = count_test
        self.calibs = calibs

    def get_intrinsics(self,filepath,cid=2):

        with open(filepath, 'r') as f:
            C = f.readlines()
        def parseLine(L, shape):
            data = L.split()
            data = np.array(data[1:]).reshape(shape).astype(np.float32)
            return data
        proj_c2p = parseLine(C[cid], shape=(3,4))
        proj_v2c = parseLine(C[-1], shape=(3,4))
        filler = np.array([0, 0, 0, 1]).reshape((1,4))
        proj_v2c = np.concatenate((proj_v2c, filler), axis=0)
        intrinsics = proj_c2p[:3, :3]

        return intrinsics

    def scale_intrinsics(self, mat, sx, sy):
        out = np.copy(mat)
        out[0,0] *= sx
        out[0,2] *= sx
        out[1,1] *= sy
        out[1,2] *= sy
        return out

    def __iter__(self):
        if self.mode == 'train':
            im2_seq = self.image_2_seqs
            im3_seq = self.image_3_seqs
        else:
            im2_seq = self.image_2_seqs_test
            im3_seq = self.image_3_seqs_test

        for img_number in range(0,2):

            if img_number == 0:
                img_num_used = im2_seq
            else:
                img_num_used = im3_seq

            for seq_number_idx, v in img_num_used.items():
                sequence = img_num_used[seq_number_idx]
                for time_stamp_idx in range(1,len(sequence)-len(sequence)%3 -3):
                    img0 = sequence[time_stamp_idx-1]
                    img1 = sequence[time_stamp_idx]
                    img2 = sequence[time_stamp_idx+1]

                    transform = transforms.Compose([
                        transforms.ToPILImage(),
                        transforms.ToTensor(),
                        transforms.Normalize(std=(0.5,),mean=(0.5,))
                        ])

                    img0 = cv2.imread(img0)
                    img1 = cv2.imread(img1)
                    img2 = cv2.imread(img2)

                    h,w,_ = img0.shape

                    zoom_x, zoom_y = self.config.w/w, self.config.h/h

                    intrinsics = self.get_intrinsics(self.calibs[seq_number_idx])
                    intrinsics = self.scale_intrinsics(intrinsics,zoom_x,zoom_y)

                    img0 = transform(cv2.resize(img0, (self.config.w, self.config.h)))
                    img1 = transform(cv2.resize(img1, (self.config.w, self.config.h)))
                    img2 = transform(cv2.resize(img2, (self.config.w, self.config.h)))
                    datum = {"t0":img0, "t1":img1, "t2":img2, "intrinsics":intrinsics}

                    yield datum

    def __len__(self):
        if self.mode == 'train':
            return self.count_train
        else:
            return self.count_test


import os
from copy import deepcopy

import numpy as np
import argparse
from .utils import load_data
from .model import Model
import torch

def initialize_data(config, train=False, test=False):
    print("Initializing data source...")
    train_source, test_source = load_data(**config['data'], cache=(train or test))
    if train:
        print("Loading training data...")
        train_source.load_all_data()
    if test:
        print("Loading test data...")
        test_source.load_all_data()
    print("Data initialization complete.")
    return train_source, test_source

def initialize_model(config, train_source, test_source):
    print("Initializing model...")
    data_config = config['data']
    model_config = config['model']
    model_param = deepcopy(model_config)
    model_param['train_source'] = train_source
    model_param['test_source'] = test_source
    model_param['train_pid_num'] = data_config['pid_num']
    model_param['profiling'] = config['profiling']
    model_param['start_step'] = config['start_step']
    model_param['stop_step'] = config['stop_step']
    batch_size = int(np.prod(model_config['batch_size']))
    model_param['save_name'] = '_'.join(map(str,[
        model_config['model_name'],
        data_config['dataset'],
        data_config['pid_num'],
        data_config['pid_shuffle'],
        model_config['hidden_dim'],
        model_config['margin'],
        batch_size,
        model_config['hard_or_full_trip'],
        model_config['frame_num'],
    ]))

    m = Model(**model_param)
    print("Model initialization complete.")
    return m, model_param['save_name']

def initialization(config, train=False, test=False):
    print("Initialzing...")
    WORK_PATH = config['WORK_PATH']
    os.chdir(WORK_PATH)
    os.environ["ASCEND_VISIBLE_DEVICES"] = config["ASCEND_VISIBLE_DEVICES"]
    train_source, test_source = initialize_data(config, train, test)
    return initialize_model(config, train_source, test_source)


class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        l, r =0, 1
        while r<len(nums) and nums[r] != 101:
            if nums[l] == nums[r]:
                del nums[r]
                nums.append(101)
            else:
                l+=1
                r+=1

        return len(nums) - nums.count(101)

leetcode/26. Remove Duplicates from Sorted Array2.py


# Numpy merupakan singkatan Numerical Python yang digunakan dalam memproses array... misi ngedit dikit
# Matplotlib digunakan untuk menggambarkan titik koordinat menjadi sebuah garis... misi mau coba ngedit lagi
import numpy as np
import matplotlib.pyplot as graphic

x1 = int(input('Masukan Nilai X1  : '))
y1 = int(input('Masukan Nilai Y1  : '))
x2 = int(input('Masukan Nilai X2  : '))
y2 = int(input('Masukan Nilai Y2  : '))
print('------------------------------------------------')
# koordinar awal x dan y
x = x1
y = y1
# membuat pengkondisian dengan beberapa syarat seperti :

# ---> Jika nilai x1 = x2 (garis vertikal), maka :
#       a. y = y + 1 dan x tetap
#       b. gambar titik kordinat (x,y)
#       c. tampilkan garis dari titik-titik koordinat yang terbentuk (selesai)

if x1 == x2:
    koor_x = []
    koor_y = []
    for i in range (0,y2,1):
        print('Garis yang di lewati yaitu', x, ',', y+i)
        koor_x.append(x)
        koor_y.append(y+i)
    graphic.plot(koor_x,koor_y)
    graphic.show()

# ---> Jika nilai y1 = y2 (garis horizontal), maka :
#       a. x = x + 1 dan y tetap
#       b. gambar titik kordinat (x,y)
#       c. tampilkan garis dari titik-titik koordinat yang terbentuk (selesai)

elif y1 == y2:
    koor_x = []
    koor_y = []
    for i in range (0,x2,1):
        print('Garis yang di lewati yaitu', x+i, ',', y)
        koor_x.append(x+i)
        koor_y.append(y)
    graphic.plot(koor_x,koor_y)
    graphic.show()
# ---> Jika ke-2 syarat di atas tidak memenuhi,  maka proses penentuan titik koordinat berlanjut ke:
#       1. hitung kemiringan garis dengan m = (y2 - y1) / (x2 - x1)
#       2. iterasi diulang sebanyak N kali
#       3. menentukan nilai i dengan persamaan y = m ( x - x1 ) + y1
#       4. lakukan pembulatan pada  nilai y
#       5. gambar titik (x, y(pembulatan))
#       6. nilai x didapatkan dari persamaan x = x + 1

else:
    koor_x = []
    koor_y = []
    gradient = (y2 - y1) / (x2 - x1)
    # N adalah banyaknya iterasi yang didapatkan dari persamaan dibawah ini apabila  x1 != x2 atau y1 != y2
    N = x2 - x1 + 1
    for i in range (0,N,1):
        bulat_y = gradient * (x - x1) + y1
        koord_Y = round(bulat_y)
        print('Garis yang di lewati oleh titik A da titik B yaitu ', x,',', koord_Y)
        koor_x.append(x)
        koor_y.append(koord_Y)
        x+=1
# syntaks apppend digunakan untuk menambah item ke dalam array atau list
# plt.plot digunakan agar mathplotlib dapat membuat titik pertemuan di masing-masing koordinat x,y
# plt.show digunakan agar mathplotlib dapat menampilkan garis dari titik titik kordinat yang telah di dapat

    graphic.plot(koor_x,koor_y)
    graphic.show()


from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from django.template import loader
from django.http import Http404
from django.utils.translation import gettext as _

#models
from ..models import Streamer
from ..models import Game

#utility
import pprint
from ..utility.util import getGameRankData,getStreamerRank,getVideoRank,video_setup, getGameRankData, getSeoSetting,getCommonSetting
#from ..utility.util import video_setup,getGameStreamerRank,getNewVideosWithRating,getRecommendVideos,getMostViewVideos

def ranking(request, type, sort_id, category,page):

    if type == 'streamer':

        if sort_id not in ['all','growing','subscriber']:
            raise Http404("404 Invalid Sort Id")

        if category not in ['all','male','female']:
            raise Http404("404 Invalid Catgory")

        context = streamerRank(request, sort_id, category, page)
        return render(request, 'streamer/ranking_streamer.html', context)

    elif type == 'video':

        if sort_id not in ['all','toprate','new','views']:
            raise Http404("404 Invalid Sort Id")

        if category not in ['all','pc','mobile','console']:
            raise Http404("404 Invalid Catgory")

        context = videoRank(request, sort_id, category , page)
        return render(request, 'streamer/ranking_video.html', context)
    else:
        raise Http404("404 Invalid Type")

def streamerRank(request, sort_id, category, page):

    #sort_id
    sort_id_list = {
        'all' : 1,
        'growing' : 2,
        'subscriber' : 3,
    }
    sord_id_int = sort_id_list[sort_id]

    #sort_id
    category_id_list = {
        'all' : 10,
        'male' : 1,
        'female' : 2,
    }
    category_id = category_id_list[category]

    #h1 title
    h1_sort = {
        1: _('Total Views'),
        2: _('Growing'),
        3: _('Total Subscriber'),
    }
    h1_category = {
        10: "",
        1: _('Male '),
        2: _('Female '),
    }
    h1_streamer_title = {
        1: _('Game Streamer '),
        2: _('Game Streamer '),
        3: _('Game Streamer '),
    }

    h1_sort = h1_sort[sord_id_int]
    h1_streamer_title = h1_streamer_title[sord_id_int]
    h1_category = h1_category[category_id]

    #Get Streamer Rank Data
    results_per_page = 100
    streamer_ranks = getStreamerRank(sord_id_int, category_id, results_per_page, page)

    #Get Popular Games
    popular_games = getGameRankData(10,20)

    #Rank Start
    rank_start = results_per_page * (page - 1)

    #seo_settings
    seo_settings = getSeoSetting(request)
    common_settings = getCommonSetting(request)

    context = {
        'sort_id' : sort_id,
        'h1_sort' : h1_sort,
        'h1_streamer_title' : h1_streamer_title,
        'category' : category,
        'h1_category' : h1_category,
        'streamer_ranks' : streamer_ranks,
        'popular_games': popular_games,
        'rank_start': rank_start,
        'seo_settings': seo_settings,
        'common_settings': common_settings,
    }

    return context

def videoRank(request, sort_id, category , page):

    #sort_id
    sort_id_list = {
        'all' : 2,
        'toprate' : 3,
        'new' : 1,
        'views' : 4,
    }
    sord_id_int = sort_id_list[sort_id]

    #sort_id
    category_id_list = {
        'all' : 10,
        'pc' : 1,
        'mobile' : 2,
        'console' : 3,
    }
    category_id = category_id_list[category]

    #h1 title
    h1_sort = {
        1: _('New'),
        2: _('Total Views last 48hour'),
        3: _('Top Rate'),
        4: _('Total Views'),
    }

    h1_category = {
        10: "",
        1: "PC ",
        2: _('Mobile '),
        3: _('Console '),
    }

    h1_sort = h1_sort[sord_id_int]
    h1_category = h1_category[category_id]

    #Get Streamer Rank Data
    exlude_game_id=1
    video_ranks = getVideoRank(sord_id_int, category_id, 100 , page ,exlude_game_id )
    for v in video_ranks:
        v = video_setup(v)

    #Get Popular Games
    popular_games = getGameRankData(10,20)

    #seo_settings
    seo_settings = getSeoSetting(request)
    common_settings = getCommonSetting(request)

    context = {
        'sort_id' : sort_id,
        'category' : category,
        'h1_sort' : h1_sort,
        'h1_category' : h1_category,
        'video_ranks' : video_ranks,
        'popular_games': popular_games,
        'seo_settings': seo_settings,
        'common_settings' : common_settings,
    }

    return context


from container import Container
import subprocess
import threading
import requests
import json
from job import Job
import re

containers = [
    Container(1, "172.18.0.2"),
    Container(2, "172.18.0.3"),
    Container(3, "172.18.0.4")
]
jobs = []
stop = False

def docker_compose_up():
  # process = subprocess.Popen(["docker-compose", "--file", "image/docker-compose.yml", "up", "-d", "--scale", "baba=3"]).wait()
  process = subprocess.Popen(["docker-compose", "--file", "image/docker-compose.yml", "up", "-d", "--build", "--scale", "baba=3"]).wait()
def docker_compose_down():
  process = subprocess.Popen(["docker-compose", "--file", "image/docker-compose.yml", "down"]).wait()

def dispatch(container):
  global containers
  job = container.get_job()
  req = requests.get(f"http://{container.get_ip()}:50051/", data=json.dumps({
      "code": job.get_code(),
      "input": job.get_input(),
      "output": job.get_output()
  }))
  print(
      f"• job-{container.get_job()} completed with result {req.json()['status']}")
  container.clear()

def load_balance():
  global containers, jobs
  while not stop:
    for container in containers:
      if len(jobs) != 0 and not container.get_state():
        job = jobs.pop()
        print(f"○ Assigning job-{job} to container-{container.get_id()}")
        container.set_job(job)
        threading.Thread(target=dispatch, args=(container, )).start()

def cli():
  global stop, jobs
  print(">> Machine started...")
  print(">> enter your request or $status to check containers")
  threading.Thread(target=load_balance).start()

  last_job_id = 1

  while True:
    input_command = input()
    if input_command == ":wq":
      stop = True
      docker_compose_down()
      break
    elif input_command == ":status":
      print(">> container states:")
      for container in containers:
        state = "idle"
        if container.get_state():
          state = "active"
        print(f"\t • container {container.get_id()} is {state}")
    else:
      raw_jobs = re.findall("<(.*?)>", input_command)
      for raw_job in raw_jobs:
        last_job_id += 1
        [code, input_path, output_path] = list(
            map(lambda job: job.strip(), raw_job.split(",")))
        jobs.append(Job(last_job_id, code, input_path, output_path))

docker_compose_up()
cli()