import wx

[wxID_NUMBERINGPANEL, wxID_NUMBERINGPANELALPHA, wxID_NUMBERINGPANELALPHA_PAD,
 wxID_NUMBERINGPANELALPHA_UC, wxID_NUMBERINGPANELASC,
 wxID_NUMBERINGPANELCOUNT, wxID_NUMBERINGPANELCOUNTBYDIR,
 wxID_NUMBERINGPANELDESC, wxID_NUMBERINGPANELDIGIT,
 wxID_NUMBERINGPANELDIGIT_AUTOPAD, wxID_NUMBERINGPANELDIGIT_PAD,
 wxID_NUMBERINGPANELDIGIT_SETPAD, wxID_NUMBERINGPANELDOWNBOTTOM,
 wxID_NUMBERINGPANELDOWNBUTTON, wxID_NUMBERINGPANELDOWNMORE,
 wxID_NUMBERINGPANELORDER, wxID_NUMBERINGPANELPAD_CHAR,
 wxID_NUMBERINGPANELPAD_WIDTH, wxID_NUMBERINGPANELRESET,
 wxID_NUMBERINGPANELRESETDIR, wxID_NUMBERINGPANELROMAN,
 wxID_NUMBERINGPANELROMAN_UC, wxID_NUMBERINGPANELSORTING,
 wxID_NUMBERINGPANELSORT_TEXT, wxID_NUMBERINGPANELSTART,
 wxID_NUMBERINGPANELSTARTBYITEMS, wxID_NUMBERINGPANELSTATICTEXT1,
 wxID_NUMBERINGPANELSTATICTEXT2, wxID_NUMBERINGPANELSTATICTEXT5,
 wxID_NUMBERINGPANELSTATICTEXT6, wxID_NUMBERINGPANELSTATICTEXT7,
 wxID_NUMBERINGPANELSTEP, wxID_NUMBERINGPANELSTYLE,
 wxID_NUMBERINGPANELUPBUTTON, wxID_NUMBERINGPANELUPMORE,
 wxID_NUMBERINGPANELUPTOP, wxID_NUMBERINGPANELSTARTBYITEM
] = [wx.NewId() for _init_ctrls in range(37)]

class numberingPanel(wx.Panel):

    def sizer(self):
        #>> start style box:
        sLine1 = wx.BoxSizer(wx.HORIZONTAL)
        line1elements = [(self.digit,10),
                         (self.digit_pad,0),
                         (self.pad_char,5)]
        if main.langLTR:
            for i in line1elements:
                sLine1.Add(i[0],0,wx.ALIGN_CENTER|wx.RIGHT,i[1])
        else:
            line1elements.reverse()
            for i in line1elements:
                sLine1.Add(i[0],0,wx.ALIGN_CENTER|wx.LEFT,i[1])
            sLine1.Add((5,-1),0)

        sLine3 = wx.BoxSizer(wx.HORIZONTAL)
        if main.langLTR:
            sLine3.Add(self.digit_setpad,0,wx.ALIGN_CENTER)
            sLine3.Add(self.pad_width,0)
        else:
            sLine3.Add(self.pad_width,0)
            sLine3.Add(self.digit_setpad,0,wx.ALIGN_CENTER)

        sLine4 = wx.BoxSizer(wx.HORIZONTAL)
        line4elements = [(self.alpha,10),
                         (self.alpha_uc,5),
                         (self.alpha_pad,10),]
        if main.langLTR:
            for i in line4elements:
                sLine4.Add(i[0],0,wx.ALIGN_CENTER|wx.RIGHT,i[1])
        else:
            line4elements.reverse()
            for i in line4elements:
                sLine4.Add(i[0],0,wx.ALIGN_CENTER|wx.LEFT,i[1])
            sLine4.Add((5,-1),0)

        sLine5 = wx.BoxSizer(wx.HORIZONTAL)
        if main.langLTR:
            sLine5.Add(self.roman,0,wx.RIGHT,10)
            sLine5.Add(self.roman_uc,0)
        else:
            sLine5.Add(self.roman_uc,0,wx.RIGHT,10)
            sLine5.Add(self.roman,0,wx.RIGHT,5)

        styleSizer = wx.StaticBoxSizer(self.style, wx.VERTICAL)
        styleSizer.Add(sLine1,0,wx.TOP|wx.BOTTOM|main.alignment,7)
        styleSizer.Add(self.digit_autopad,0,wx.LEFT|wx.RIGHT|main.alignment,20)
        styleSizer.Add((1,7))
        styleSizer.Add(sLine3,0,wx.LEFT|wx.RIGHT|main.alignment,20)
        styleSizer.Add(sLine4,0,wx.BOTTOM|wx.TOP|main.alignment,25)
        styleSizer.Add(sLine5,0,wx.BOTTOM|main.alignment,10)
        #<< end style box

        #>> start order box:
        oLine1 = wx.BoxSizer(wx.HORIZONTAL)
        if main.langLTR:
            oLine1.Add(self.sort_text,0,wx.ALIGN_CENTER|wx.LEFT|wx.RIGHT,5)
            oLine1.Add(self.sorting,0,wx.ALIGN_CENTER)
        else:
            oLine1.Add((-1,-1),1)
            oLine1.Add(self.sorting,0,wx.ALIGN_CENTER)
            oLine1.Add(self.sort_text,0,wx.ALIGN_CENTER|wx.LEFT|wx.RIGHT,5)

        oLine2 = wx.BoxSizer(wx.HORIZONTAL)
        oLine2elements = [((5,-1),0),
                         (self.staticText2,5),
                         (self.upButton,2),
                         (self.downButton,0),
                         ((5,-1),0),
                         (self.upMore,2),
                         (self.downMore,0),
                         ((5,-1),0),
                         (self.upTop,2),
                         (self.downBottom,0),
                         ((5,-1),0)]
        if main.langLTR:
            for i in oLine2elements:
                oLine2.Add(i[0],0,wx.ALIGN_CENTER|wx.RIGHT,i[1])
        else:
            oLine2elements.reverse()
            for i in oLine2elements:
                oLine2.Add(i[0],0,wx.ALIGN_CENTER|wx.LEFT,i[1])

        orderSizer = self.orderSizer = wx.StaticBoxSizer(self.order, wx.VERTICAL)
        orderSizer.Add((-1,3),0)
        orderSizer.Add(oLine1,0,wx.BOTTOM|wx.EXPAND,10)
        orderSizer.Add(oLine2,0,wx.BOTTOM,4)
        #<< end order box

        #>> start count box:

        countDir = wx.BoxSizer(wx.HORIZONTAL)
        countDir.Add(self.asc,3)
        countDir.Add((-1,-1),1)
        countDir.Add(self.desc,3)

        countSizer = wx.FlexGridSizer(cols=2, vgap=3, hgap=5)
        countElements = [[self.staticText5,
                          self.start],
                         [(-1,-1),
                          self.startByItems],
                         [(-1,5),(-1,5)],
                         [self.staticText6,
                          countDir],
                         [(-1,5),(-1,5)],
                         [self.staticText7,
                          self.step],
                         [(-1,-1),
                          self.countByDir],
                         [(-1,15),(-1,15)],
                         [self.staticText1,
                          self.reset],
                         [(-1,-1),
                          self.resetDir],
                        ]
        for row in countElements:
            if not main.langLTR:
                row.reverse()
            for i in row:
                countSizer.Add(i,0,wx.EXPAND|main.alignment)

        countBoxSizer = wx.StaticBoxSizer(self.count, wx.VERTICAL)
        countBoxSizer.Add(countSizer,0,wx.ALL,7)
        #<< end count box

        # main sizer and finish:
        mainSizer = self.mainSizer = wx.BoxSizer(wx.HORIZONTAL)
        leftSizer = self.leftSizer = wx.BoxSizer(wx.VERTICAL)

        leftSizer.Add(styleSizer,0,wx.EXPAND)
        leftSizer.Add(orderSizer,0,wx.EXPAND|wx.TOP,10)

        mainElements = [((10,-1),0),
                        (leftSizer,7),
                        ((25,-1),0),
                        (countBoxSizer,30)]
        if main.langLTR:
            for i in mainElements:
                mainSizer.Add(i[0],0,wx.TOP,i[1])
        else:
            mainElements.reverse()
            mainSizer.Add((-1,-1),1)
            for i in mainElements:
                mainSizer.Add(i[0],0,wx.TOP,i[1])
        self.SetSizerAndFit(mainSizer)

    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Panel.__init__(self, id=wxID_NUMBERINGPANEL, name=u'numberingPanel',
              parent=prnt, pos=wx.Point(346, 305), size=wx.Size(642, 357),
              style=wx.TAB_TRAVERSAL)
        self.SetClientSize(wx.Size(634, 328))

        self.count = wx.StaticBox(id=wxID_NUMBERINGPANELCOUNT,
              label=_(u"Counter:"), name=u'count', parent=self,
              pos=wx.Point(328, 16), style=main.alignment)

        self.order = wx.StaticBox(id=wxID_NUMBERINGPANELORDER, label=_(u"Item Sorting:"),
              name=u'order', parent=self, pos=wx.Point(16, 208),
              size=wx.Size(280, 88), style=main.alignment)

        self.style = wx.StaticBox(id=wxID_NUMBERINGPANELSTYLE,
              label=_(u"Style:"), name=u'style', parent=self, pos=wx.Point(16,
              16), style=main.alignment)

        self.digit = wx.RadioButton(id=wxID_NUMBERINGPANELDIGIT,
              label=_(u"Numerical:"), name=u'digit', parent=self,
              pos=wx.Point(32, 48), style=wx.RB_GROUP)
        self.digit.SetValue(True)
        self.digit.Bind(wx.EVT_RADIOBUTTON, self.check_styles,
              id=wxID_NUMBERINGPANELDIGIT)

        self.alpha = wx.RadioButton(id=wxID_NUMBERINGPANELALPHA,
              label=_(u"Alphabetical:"), name=u'alpha', parent=self,
              pos=wx.Point(32, 112), style=0)
        self.alpha.SetValue(False)
        self.alpha.Enable(True)
        self.alpha.SetToolTipString(_(u"Must start at positive value: (1=a, 28=ab, etc..)"))
        self.alpha.Bind(wx.EVT_RADIOBUTTON, self.check_styles)

        self.roman = wx.RadioButton(id=wxID_NUMBERINGPANELROMAN,
              label=_(u"Roman Numeral:"), name=u'roman', parent=self,
              pos=wx.Point(32, 144), style=0)
        self.roman.SetValue(False)
        self.roman.SetToolTipString(_(u"Count values must be between 1 and 4999"))
        self.roman.Bind(wx.EVT_RADIOBUTTON, self.check_styles)

        self.digit_pad = wx.CheckBox(id=wxID_NUMBERINGPANELDIGIT_PAD,
              label=_(u"Pad, using:"), name=u'digit_pad', parent=self,
              pos=wx.Point(112, 48), style=0)
        self.digit_pad.SetValue(True)
        self.digit_pad.Bind(wx.EVT_CHECKBOX, self.check_styles)

        self.pad_char = wx.TextCtrl(id=wxID_NUMBERINGPANELPAD_CHAR,
              name=u'pad_char', parent=self, pos=wx.Point(185, 47),
              size=wx.Size(24, -1), style=0, value='0')
        self.pad_char.SetMaxLength(1)
        self.pad_char.Bind(wx.EVT_TEXT, main.showPreview)

        self.alpha_pad = wx.CheckBox(id=wxID_NUMBERINGPANELALPHA_PAD,
              label=_(u"auto pad"), name=u'alpha_pad', parent=self,
              pos=wx.Point(216, 112), style=0)
        self.alpha_pad.SetValue(True)
        self.alpha_pad.Enable(False)
        self.alpha_pad.Bind(wx.EVT_CHECKBOX, main.showPreview)

        self.pad_width = wx.SpinCtrl(id=wxID_NUMBERINGPANELPAD_WIDTH, initial=3,
              max=255, min=1, name=u'pad_width', parent=self, pos=wx.Point(161,
              82), size=wx.Size(55, -1), style=wx.SP_ARROW_KEYS|wx.TE_PROCESS_ENTER)
        self.pad_width.SetValue(3)
        self.pad_width.SetRange(1, 255)
        self.pad_width.Bind(wx.EVT_TEXT_ENTER, self.OnPad_widthSpinctrl)
        self.pad_width.Bind(wx.EVT_SPINCTRL, self.OnPad_widthSpinctrl)

        self.roman_uc = wx.CheckBox(id=wxID_NUMBERINGPANELROMAN_UC,
              label=_(u"Uppercase"), name=u'roman_uc', parent=self,
              pos=wx.Point(152, 144), style=0)
        self.roman_uc.SetValue(True)
        self.roman_uc.Enable(False)
        self.roman_uc.Bind(wx.EVT_CHECKBOX, main.showPreview)

        self.sort_text = wx.StaticText(id=wxID_NUMBERINGPANELSORT_TEXT,
              label=_(u"Sort all items:"), name=u'sort_text', parent=self,
              pos=wx.Point(24, 232), style=0)

        self.staticText2 = wx.StaticText(id=wxID_NUMBERINGPANELSTATICTEXT2,
              label=_(u"Manually adjust item:"), name=u'staticText2', parent=self,
              pos=wx.Point(24, 264), style=0)

        self.downButton = wx.BitmapButton(bitmap=wx.Bitmap(main.realPath(u'icons/down.png'),
              wx.BITMAP_TYPE_PNG), id=wxID_NUMBERINGPANELDOWNBUTTON,
              name=u'downButton', parent=self, pos=wx.Point(152, 256), style=wx.BU_AUTODRAW)
        self.downButton.Bind(wx.EVT_BUTTON, self.changeItemOrder,
              id=wxID_NUMBERINGPANELDOWNBUTTON)

        self.upButton = wx.BitmapButton(bitmap=wx.Bitmap(main.realPath(u'icons/up.png'),
              wx.BITMAP_TYPE_PNG), id=wxID_NUMBERINGPANELUPBUTTON,
              name=u'upButton', parent=self, pos=wx.Point(128, 256), style=wx.BU_AUTODRAW)
        self.upButton.Bind(wx.EVT_BUTTON, self.changeItemOrder,
              id=wxID_NUMBERINGPANELUPBUTTON)

        self.upTop = wx.BitmapButton(bitmap=wx.Bitmap(main.realPath(u'icons/upAll.png'),
              wx.BITMAP_TYPE_PNG), id=wxID_NUMBERINGPANELUPTOP, name=u'upTop',
              parent=self, pos=wx.Point(240, 256), style=wx.BU_AUTODRAW)
        self.upTop.SetToolTipString(_(u"move to top"))
        self.upTop.Bind(wx.EVT_BUTTON, self.changeItemOrder,
              id=wxID_NUMBERINGPANELUPTOP)

        self.downBottom = wx.BitmapButton(bitmap=wx.Bitmap(main.realPath(u'icons/downAll.png'),
              wx.BITMAP_TYPE_PNG), id=wxID_NUMBERINGPANELDOWNBOTTOM,
              name=u'downBottom', parent=self, pos=wx.Point(264, 256), style=wx.BU_AUTODRAW)
        self.downBottom.SetToolTipString(_(u"move to bottom"))
        self.downBottom.Bind(wx.EVT_BUTTON, self.changeItemOrder,
              id=wxID_NUMBERINGPANELDOWNBOTTOM)

        self.upMore = wx.BitmapButton(bitmap=wx.Bitmap(main.realPath(u'icons/up5.png'),
              wx.BITMAP_TYPE_PNG), id=wxID_NUMBERINGPANELUPMORE, name=u'upMore',
              parent=self, pos=wx.Point(184, 256), style=wx.BU_AUTODRAW)
        self.upMore.SetToolTipString(_(u"move by 5"))
        self.upMore.Bind(wx.EVT_BUTTON, self.changeItemOrder,
              id=wxID_NUMBERINGPANELUPMORE)

        self.downMore = wx.BitmapButton(bitmap=wx.Bitmap(main.realPath(u'icons/down5.png'),
              wx.BITMAP_TYPE_PNG), id=wxID_NUMBERINGPANELDOWNMORE,
              name=u'downMore', parent=self, pos=wx.Point(208, 256), style=wx.BU_AUTODRAW)
        self.downMore.SetToolTipString(_(u"move by 5"))
        self.downMore.Bind(wx.EVT_BUTTON, self.changeItemOrder,
              id=wxID_NUMBERINGPANELDOWNMORE)

        self.sorting = wx.Choice(choices=[ _(u"Ascending"), _(u"Descending"),
              _(u"Manually")], id=wxID_NUMBERINGPANELSORTING, name=u'sorting',
              parent=self, pos=wx.Point(160, 224), style=0)
        self.sorting.SetSelection(0)
        self.sorting.Bind(wx.EVT_CHOICE, self.setSortingOptions,
              id=wxID_NUMBERINGPANELSORTING)

        self.staticText5 = wx.StaticText(id=wxID_NUMBERINGPANELSTATICTEXT5,
              label=_(u"Start at:"), name=u'staticText5', parent=self,
              pos=wx.Point(352, 43), style=0)

        self.step = wx.SpinCtrl(id=wxID_NUMBERINGPANELSTEP, initial=1,
              max=10000000, min=1, name=u'step', parent=self, pos=wx.Point(416,
              136), size=wx.Size(168, -1), style=wx.SP_ARROW_KEYS)
        self.step.SetValue(1)
        self.step.SetToolTipString(_(u"A.K.A. step size"))
        self.step.Bind(wx.EVT_TEXT_ENTER, main.showPreview)
        self.step.Bind(wx.EVT_SPINCTRL, main.showPreview)

        self.staticText7 = wx.StaticText(id=wxID_NUMBERINGPANELSTATICTEXT7,
              label=_(u"Count by:"), name=u'staticText7', parent=self,
              pos=wx.Point(344, 142), style=0)

        self.asc = wx.RadioButton(id=wxID_NUMBERINGPANELASC, label=_(u"+"),
              name=u'asc', parent=self, pos=wx.Point(504, 104),
              style=wx.RB_GROUP)
        self.asc.SetFont(wx.Font(17, wx.SWISS, wx.NORMAL, wx.BOLD, False))
        self.asc.SetValue(True)
        self.asc.SetToolTipString(_(u"Increase counting number."))
        self.asc.Bind(wx.EVT_RADIOBUTTON, main.showPreview)

        self.desc = wx.RadioButton(id=wxID_NUMBERINGPANELDESC, label=_(u"-"),
              name=u'desc', parent=self, pos=wx.Point(552, 104), style=0)
        self.desc.SetFont(wx.Font(15, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'Impact'))
        self.desc.SetValue(False)
        self.desc.SetToolTipString(_(u"Decrease counting number."))
        self.desc.Bind(wx.EVT_RADIOBUTTON, main.showPreview)

        self.staticText6 = wx.StaticText(id=wxID_NUMBERINGPANELSTATICTEXT6,
              label=_(u"Count:"), name=u'staticText6', parent=self,
              pos=wx.Point(360, 104), style=0)

        self.alpha_uc = wx.CheckBox(id=wxID_NUMBERINGPANELALPHA_UC,
              label=_(u"Uppercase"), name=u'alpha_uc', parent=self,
              pos=wx.Point(136, 112), style=0)
        self.alpha_uc.SetValue(False)
        self.alpha_uc.Enable(False)
        self.alpha_uc.Bind(wx.EVT_CHECKBOX, main.showPreview)

        self.start = wx.SpinCtrl(id=wxID_NUMBERINGPANELSTART, initial=0,
              max=100000000, min=0, name=u'start', parent=self,
              pos=wx.Point(416, 40), size=wx.Size(168, -1),
              style=wx.SP_ARROW_KEYS)
        self.start.SetValue(1)
        self.start.SetToolTipString(_(u"starting number or equivalent alpha/roman character"))
        self.start.Bind(wx.EVT_TEXT_ENTER, main.showPreview, id=wxID_NUMBERINGPANELSTART)
        self.start.Bind(wx.EVT_SPINCTRL, main.showPreview, id=wxID_NUMBERINGPANELSTART)

        self.staticText1 = wx.StaticText(id=wxID_NUMBERINGPANELSTATICTEXT1,
              label=_(u"Reset every:"), name=u'staticText1', parent=self,
              pos=wx.Point(344, 203), style=0)

        self.reset = wx.SpinCtrl(id=wxID_NUMBERINGPANELRESET, initial=0,
              max=100000000, min=0, name=u'reset', parent=self,
              pos=wx.Point(416, 200), size=wx.Size(168, -1),
              style=wx.SP_ARROW_KEYS)
        self.reset.SetValue(0)
        self.reset.SetToolTipString(_(u"0 = don't reset"))
        self.reset.SetRange(0, 100000000)
        self.reset.Bind(wx.EVT_TEXT_ENTER, main.showPreview,
              id=wxID_NUMBERINGPANELRESET)
        self.reset.Bind(wx.EVT_SPINCTRL, main.showPreview,
              id=wxID_NUMBERINGPANELRESET)

        self.digit_autopad = wx.RadioButton(id=wxID_NUMBERINGPANELDIGIT_AUTOPAD,
              label=_(u"Auto pad"), name=u'digit_autopad', parent=self,
              pos=wx.Point(56, 68), style=wx.RB_GROUP)
        self.digit_autopad.SetValue(True)
        self.digit_autopad.Bind(wx.EVT_RADIOBUTTON, self.check_styles)

        self.digit_setpad = wx.RadioButton(id=wxID_NUMBERINGPANELDIGIT_SETPAD,
              label=_(u"Fixed pad width:"), name=u'digit_setpad', parent=self,
              style=0)
        self.digit_setpad.SetValue(False)
        self.digit_setpad.Bind(wx.EVT_RADIOBUTTON, self.check_styles)

        self.resetDir = wx.CheckBox(id=wxID_NUMBERINGPANELRESETDIR,
              label=_(u"Reset every directory"), name=u'resetDir', parent=self,
              pos=wx.Point(456, 232), style=0)
        self.resetDir.SetToolTipString(_(u"Reset count to initial value when directory changes."))
        self.resetDir.SetValue(False)
        self.resetDir.Bind(wx.EVT_CHECKBOX, main.showPreview)

        self.countByDir = wx.CheckBox(id=wxID_NUMBERINGPANELCOUNTBYDIR,
              label=_(u"Count by directory"), name=u'countByDir', parent=self,
              pos=wx.Point(472, 168), style=0)
        self.countByDir.SetToolTipString(_(u"Only increase/decrease count when directory changes."))
        self.countByDir.SetValue(False)
        self.countByDir.Bind(wx.EVT_CHECKBOX, main.showPreview)

        self.startByItems = wx.CheckBox(id=wxID_NUMBERINGPANELSTARTBYITEM,
              label=_(u"Start at number of items"), name=u'start_by_item',
              parent=self, pos=wx.Point(440, 72), style=0)
        self.startByItems.SetValue(False)
        self.startByItems.SetToolTipString(_(u"Use number of items as starting point for count."))
        self.startByItems.Bind(wx.EVT_CHECKBOX, self.OnStartByItemsCheckbox,
              id=wxID_NUMBERINGPANELSTARTBYITEM)

    def __init__(self, parent, main_window):
        global main
        main = main_window
        self._init_ctrls(parent)
        self.sizer()
        self.setSortingOptions(0)

    # determine style:
    def GetNumberStyle(self):
        #digit:
        style = ''
        if self.digit.GetValue():
            pad = self.digit_pad.GetValue()
            pad_char = self.pad_char.GetValue()
            if self.digit_setpad.GetValue():
                pad_width = self.pad_width.GetValue()
            else:
                pad_width = u"auto"
            style = (u"digit", pad_char, pad_width, pad)

        #alphabetical:
        elif self.alpha.GetValue():
            style = (u"alpha", self.alpha_uc.GetValue(), self.alpha_pad.GetValue())

        #roman numeral:
        elif self.roman.GetValue():
            style = (u"roman", self.roman_uc.GetValue())
        return style

    # determine parameters:
    def GetNumberParams(self):
        #ascending:
        if self.asc.GetValue() == True:
            step_dir = +int(self.step.GetValue())
        #descending:
        else:
            step_dir = -int(self.step.GetValue())
        params = (self.start.GetValue(), step_dir, self.reset.GetValue(),
          self.resetDir.GetValue(), self.countByDir.GetValue(),
          self.startByItems.GetValue(),)
        return params

    # enables/disables item position change buttons:
    def setSortingOptions(self, event):
        sortButtons = (self.staticText2,self.upButton, self.downButton,
          self.upMore,self.downMore,self.upTop,self.downBottom,)
        if self.sorting.GetSelection() == 2:
            for item in sortButtons:
                item.Enable(True)
        else:
            for item in sortButtons:
                item.Enable(False)
        main.showPreview(event)

    #enable/disable options based on what is selected:
    def check_styles(self, event):
        #digit:
        digit_options = (self.digit_pad, self.pad_char, self.digit_setpad,
            self.digit_autopad, self.pad_width)
        pad_options = (self.digit_setpad, self.digit_autopad, self.pad_char,
            self.pad_width)
        if self.digit.GetValue():
            self.digit_pad.Enable(True)
            if self.digit_pad.GetValue():
                for option in pad_options:
                    option.Enable(True)
            else:
                for option in pad_options:
                    option.Enable(False)
            if self.reset.GetValue() == 4999:
                self.reset.SetValue(0)
        else:
            for option in digit_options:
                option.Enable(False)

        #roman numeral:
        if self.roman.GetValue():
            self.roman_uc.Enable(True)
            if self.reset.GetValue() > 4999:
                self.reset.SetValue(4999)
            if self.start.GetValue() == 0:
                self.start.SetValue(1)
        else:
            self.roman_uc.Enable(False)

        #alphabetical:
        if self.alpha.GetValue():
            self.alpha_uc.Enable(True)
            self.alpha_pad.Enable(True)
            if self.start.GetValue() == 0:
                self.start.SetValue(1)
            if self.reset.GetValue() == 4999:
                self.reset.SetValue(0)
        else:
            self.alpha_uc.Enable(False)
            self.alpha_pad.Enable(False)
        main.showPreview(event)

    def OnStartByItemsCheckbox(self, event):
        if self.startByItems.GetValue():
            self.start.Enable(False)
        else:
            self.start.Enable(True)
        main.showPreview(event)

    def OnPad_widthSpinctrl(self, event):
        self.digit_setpad.SetValue(True)
        main.showPreview(event)

    # triggered when a button to change item position is clicked
    def changeItemOrder(self, event):
        buttons = {
          wxID_NUMBERINGPANELUPBUTTON : -1,
          wxID_NUMBERINGPANELDOWNBUTTON : 1,
          wxID_NUMBERINGPANELUPMORE : -5,
          wxID_NUMBERINGPANELDOWNMORE : 5,
          wxID_NUMBERINGPANELUPTOP : u'top',
          wxID_NUMBERINGPANELDOWNBOTTOM : u'bottom',
          }

        change = buttons[event.GetId()]
        main.changeItemOrder(change)

###### GET/SET CONFIGURATION SETTINGS: #########################################
    def getSettings(self):
        settings = (u"<[numbering]>",
          u"digit>:>%s" %int(self.digit.GetValue()),
          u"digit_pad>:>%s" %int(self.digit_pad.GetValue()),
          u"pad_char>:>%s" %self.pad_char.GetValue(),
          u"digit_setpad>:>%s" %int(self.digit_setpad.GetValue()),
          u"digit_autopad>:>%s" %int(self.digit_autopad.GetValue()),
          u"pad_width>:>%s" %self.pad_width.GetValue(),
          u"alpha>:>%s" %int(self.alpha.GetValue()),
          u"alpha_uc>:>%s" %int(self.alpha_uc.GetValue()),
          u"alpha_pad>:>%s" %int(self.alpha_pad.GetValue()),
          u"roman>:>%s" %int(self.roman.GetValue()),
          u"roman_uc>:>%s" %int(self.roman_uc.GetValue()),
          u"start>:>%s" %self.start.GetValue(),
          u"asc>:>%s" %int(self.asc.GetValue()),
          u"desc>:>%s" %int(self.desc.GetValue()),
          u"step>:>%s" %int(self.step.GetValue()),
          u"reset>:>%s" %int(self.reset.GetValue()),
          u"resetDir>:>%s" %int(self.resetDir.GetValue()),
          u"countByDir>:>%s" %int(self.countByDir.GetValue()),
          u"startByItems>:>%s" %int(self.startByItems.GetValue()),
          u"sorting>:>%s" %self.sorting.GetSelection(),
          )
        return settings

    def setSettings(self,settings):
        if len(settings) == 20: #make sure number of settings is correct
            try:
                self.digit.SetValue(int(settings[0]))
                self.digit_pad.SetValue(int(settings[1]))
                self.pad_char.SetValue(settings[2])
                self.digit_setpad.SetValue(int(settings[3]))
                self.digit_autopad.SetValue(int(settings[4]))
                self.pad_width.SetValue(int(settings[5]))
                self.alpha.SetValue(int(settings[6]))
                self.alpha_uc.SetValue(int(settings[7]))
                self.alpha_pad.SetValue(int(settings[8]))
                self.roman.SetValue(int(settings[9]))
                self.roman_uc.SetValue(int(settings[10]))
                self.start.SetValue(int(settings[11]))
                self.asc.SetValue(int(settings[12]))
                self.desc.SetValue(int(settings[13]))
                self.step.SetValue(int(settings[14]))
                self.reset.SetValue(int(settings[15]))
                self.resetDir.SetValue(int(settings[16]))
                self.countByDir.SetValue(int(settings[17]))
                self.startByItems.SetValue(int(settings[18]))
                self.sorting.SetSelection(int(settings[19].replace(u'\n','')))
            except ValueError:
                return False
            else:
                # apply settings:
                self.check_styles(0)
                self.setSortingOptions(0)
                return True
        else:
            return False


from typing import Optional
import torch
from torch import nn
from config import dt_config
from block import TransformerBlock

class DecisionTransformer(nn.Module):
    def __init__(self,
                 cfg: dt_config,
                 state_dim: int,
                 action_dim: int) -> None:
        super().__init__()

        self.embedding_dropout = nn.Dropout(cfg.embedding_dropout)
        self.embedding_norm = nn.LayerNorm(cfg.embedding_dim)

        self.final_norm = nn.LayerNorm(cfg.embedding_dim)
        self.positional_encoding = nn.Embedding(cfg.episode_length + cfg.sequence_length,
                                           cfg.embedding_dim)
        self.state_embedding = nn.Linear(state_dim, cfg.embedding_dim)
        self.action_embedding = nn.Linear(action_dim, cfg.embedding_dim)
        self.return_embedding = nn.Linear(1, cfg.embedding_dim)

        self.blocks = nn.ModuleList([
            TransformerBlock(3 * cfg.sequence_length,
                             cfg.embedding_dim,
                             cfg.num_heads,
                             cfg.attention_dropout,
                             cfg.residual_dropout) for _ in range(cfg.num_layers)
        ])

        self.embedding_dim = cfg.embedding_dim
        self.sequence_length = cfg.sequence_length
        self.state_dim = state_dim
        self.action_dim = action_dim
        self.episode_length = cfg.episode_length
        self.max_action = cfg.max_action

        self.action_head = nn.Sequential(
            nn.Linear(self.embedding_dim, self.action_dim),
            nn.Tanh()
        )

        self.apply(self.reset_weights)

    @staticmethod
    def reset_weights(m: nn.Module):
        if isinstance(m, (nn.Linear, nn.Embedding)):
            nn.init.normal_(m.weight, mean=0.0, std=0.02)

            if isinstance(m, nn.Linear) and m.bias is not None:
                nn.init.zeros_(m.bias)

        if isinstance(m, nn.LayerNorm):
            nn.init.zeros_(m.bias)
            nn.init.ones_(m.weight)

    def forward(self,
                states: torch.Tensor,
                actions: torch.Tensor,
                mc_returns: torch.Tensor,
                time_steps: torch.Tensor,
                key_padding_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
        batch_size, sequence_length = states.shape[0], states.shape[1]

        pos_encoding = self.positional_encoding(time_steps)
        state_embedding = self.state_embedding(states) + pos_encoding
        action_embedding = self.action_embedding(actions) + pos_encoding
        returns_embedding = self.return_embedding(mc_returns.unsqueeze(-1)) + pos_encoding

        sequence = torch.stack((
            returns_embedding, state_embedding, action_embedding
        ), dim=1).permute(0, 2, 1, 3).reshape(batch_size, 3 * sequence_length, self.embedding_dim)

        if key_padding_mask is not None:
            key_padding_mask = torch.stack((
                key_padding_mask, key_padding_mask, key_padding_mask
            ), dim=1).permute(0, 2, 1).reshape(batch_size, 3 * sequence_length)

        out = self.embedding_dropout(self.embedding_norm(sequence))

        for block in self.blocks:
            out = block(out, padding_mask=key_padding_mask)

        out = self.final_norm(out)
        return self.action_head(out[:, 1::3]) * self.max_action


import cv2
import numpy as np
from scipy.spatial import cKDTree
from sklearn.decomposition import PCA

def sample_to_heatmap(points, x_adjust=0, y_adjust=0, z_threshold=None, nearest_k=3):
    # If a threshold is provided, keep only points with a z-coordinate above this threshold
    if z_threshold is not None:
        points = points[points[:, 2] > z_threshold]
        print('cropped')

    # Compute PCA
    pca = PCA(n_components=3)
    pca.fit(points)

    # The normal of the plane is the smallest principal component
    normal = pca.components_[-1]

    # The point on the plane can be the centroid of the point cloud
    centroid = np.mean(points, axis=0)

    # Now we can print the plane equation
    # The plane equation is of the form ax + by + cz + d = 0
    a, b, c = normal
    d = -centroid.dot(normal)
    print(f"The equation of the plane is {a:.5f}x + {b:.5f}y + {c:.5f}z + {d:.5f} = 0")

    # Get x, y, z coordinates
    x_coords = points[:, 0]
    y_coords = points[:, 1]
    z_coords = points[:, 2]

    # Calculate minimum and maximum values in x and y directions
    x_min, x_max = np.min(x_coords), np.max(x_coords)
    y_min, y_max = np.min(y_coords), np.max(y_coords)

    x_mid = (x_min + x_max) / 2 + x_adjust
    y_mid = (y_min + y_max) / 2 + y_adjust
    # The range of x and y values for the mesh grid
    x_range = np.linspace(x_mid - 15, x_mid + 15, 514)
    y_range = np.linspace(y_mid - 15, y_mid + 15, 514)

    x, y = np.meshgrid(x_range, y_range)

    # Compute corresponding z values for the plane
    z = (-a * x - b * y - d) / c

    tree = cKDTree(points)

    distances = []
    for point in np.vstack([x.flatten(), y.flatten(), z.flatten()]).T:
        # Find the three nearest points in the point cloud
        dists, idxs = tree.query(point, k=nearest_k)
        nearest_points = points[idxs]

        # For each nearest point, compute the distance to the point along the normal direction
        ds = []
        for nearest_point in nearest_points:
            displacement = nearest_point - point  # vector from point to nearest_point
            distance = np.dot(displacement, normal)  # project displacement onto normal
            ds.append(distance)
        distances.append(sum(ds) / len(ds))

    # 这里是用最小值纠正（normalisation）矩阵
    distances_array = (np.array(distances) - np.min(distances)) / 0.5 * 255
    distances_reshape = distances_array.reshape((514, 514))[1:513, 1:513].astype(int)

    return distances_reshape  # 这个就是image 直接save就行

# Create a heatmap using seaborn
def plot_heatmap(heatmap, save_path=None):
    cv2.imwrite(save_path, heatmap)


from itertools import chain

y, x = [int(i) for i in input().split()]

matrix = [[] for _ in range(y)]

for i in range(y):
    s = input()
    for u in s:
        if u == ".":
            matrix[i].append(True)
        elif u == "#":
            matrix[i].append(False)

def step(y, x, matrix):
    matrix[y][x] = True
    tmp = [[y, x+1],[y, x-1],[y-1, x],[y+1, x]]
    neighbors = []
    for i in tmp:
        try:
            if matrix[i[0]][i[1]] == False:
                neighbors.append(i)
        except:
            pass
        if len(neighbors) == 0:
            return
        else:
            for i in neighbors:
                step(i[0], i[1], matrix)

count = 0

while False in chain.from_iterable(matrix):
    coord = []
    for i in matrix:
        if False in i:
            coord = [matrix.index(i), i.index(False)]
    step(coord[0], coord[1], matrix)
    count += 1

print(count)


import pytest

@pytest.fixture(name="fixer")
def fixer_fixture(two_to_three_test_case):
    return two_to_three_test_case("methodattrs")

attrs = ["func", "self", "class"]

def test(fixer):
    for attr in attrs:
        b = "a.im_%s" % attr
        if attr == "class":
            a = "a.__self__.__class__"
        else:
            a = "a.__%s__" % attr
        fixer.check(b, a)

        b = "self.foo.im_%s.foo_bar" % attr
        if attr == "class":
            a = "self.foo.__self__.__class__.foo_bar"
        else:
            a = "self.foo.__%s__.foo_bar" % attr
        fixer.check(b, a)

def test_unchanged(fixer):
    for attr in attrs:
        s = "foo(im_%s + 5)" % attr
        fixer.unchanged(s)

        s = "f(foo.__%s__)" % attr
        fixer.unchanged(s)

        s = "f(foo.__%s__.foo)" % attr
        fixer.unchanged(s)


import os
import pickle
import uvicorn
from fastapi import FastAPI

FAKE_HASH_TABLE_DB = './database/FakeHashTable.pickle'

class FakeHashTable:
    def __init__(self, bit_limitation=10):
        self.limitation = 2 ** bit_limitation
        self.hashtable = dict()
        self.id_list = set()
        self.history = list()
        self.avail_id = list(range(self.limitation))

    def hash(self, value, replacement=None):
        """
        :param value: value to hash
        :param replacement: if replacement = 'oldest' this instance will replace the object by the oldest record. If
        replacement is the value that existed in hashtable, it will remove old record and replace by new value.
        :return:
        """
        # For user replace ID by a new value
        if replacement is not None:
            if replacement == 'oldest' and self.history.__len__() > 2:
                old_id = self.hashtable[self.history[0]]
                del self.hashtable[self.history[0]]
                self.history = self.history[1:]
                self.history.append(value)
                self.hashtable[value] = old_id

            if replacement in self.hashtable:
                old_id = self.hashtable[replacement]
                self.history.remove(old_id)
                self.history.append(value)
                del self.hashtable[replacement]
                self.hashtable[value] = old_id
                return old_id
            return None

        if value in list(self.hashtable.keys()):
            return self.hashtable[value]

        # If larger than 10 bit, return None
        if self.hashtable.items().__len__() > self.limitation:
            return None

        # Add new ID
        new_id = self.avail_id.pop(0)
        self.history.append(value)
        self.id_list.add(new_id)
        self.hashtable[value] = new_id
        return new_id

    def remove(self, value):
        if value not in self.hashtable:
            return False
        old_id = self.hashtable[value]
        del self.hashtable[value]
        self.id_list.remove(value)
        self.avail_id.append(old_id)
        self.history.remove(value)

def backup_htb_object(in_htb):
    with open(FAKE_HASH_TABLE_DB, 'wb') as ff:
        pickle.dump(in_htb, ff)

def load_htb_object():
    with open(FAKE_HASH_TABLE_DB, 'rb') as ff:
        data = pickle.load(ff)
    return data

app = FastAPI()

if os.path.exists(FAKE_HASH_TABLE_DB):
    htb = load_htb_object()
else:
    htb = FakeHashTable()

@app.post("/")
async def get_machine_id(value):
    iid = htb.hash(value)
    backup_htb_object(htb)
    return {"id": iid}

if __name__ == '__main__':
    uvicorn.run(
        "hash_service:app",
        host='0.0.0.0',
        port=8000,
        reload=True,
        debug=True,
        workers=3
    )


import bs4
import requests

url = 'https://id.carousell.com/carousell_id'

contents = requests.get(url)

response = bs4.BeautifulSoup(contents.text, 'html.parser')

data = response.find('div', attrs={'class': 'D_apq D_eZ M_gF D_fb M_gH'})

datas = data.findAll('div', attrs={'class': 'D_jg', 'class': 'D_qq', 'class': 'D_qv'})
    # print(datas)
for obj in datas:
    judul = obj.find('p', attrs={'class': "D_bN M_aT D_aP M_aC D_bO M_aU D_bR M_aX D_bT M_aZ D_bW M_bc "
                                          "D_bZ M_bg D_bK"}).text
    image = obj.find('img', attrs={'class': 'D_bl', 'class': 'D_bi', 'class': 'D_tO'})['src']

    with open('images/' + judul + '.jpg', 'wb') as f:
        img = requests.get(image)
        f.write(img.content)


import time
import json
import board
import busio
import adafruit_ads1x15.ads1015 as ADS
from adafruit_ads1x15.analog_in import AnalogIn

max_val = None
min_val = None
# Create the I2C bus
i2c = busio.I2C(board.SCL, board.SDA)
# Create the ADC object using the I2C bus
ads = ADS.ADS1015(i2c)
# Create single-ended input on channel 0
chan = AnalogIn(ads, ADS.P2)
baseline_check = input("Is Light Sensor Covered? (enter 'y' to proceed): ")

if baseline_check == 'y':
    max_val = chan.value
print("------{:>5}\t{:>5}".format("raw", "v"))

for x in range(0, 10):
    if chan.value > max_val:
        max_val = chan.value
    print("CHAN 2: "+"{:>5}\t{:>5.3f}".format(chan.value, chan.voltage))
    time.sleep(0.5)

print('\n')

water_check = input("Does the Light Sensor receive the maximum light? (enter 'y' to proceed): ")
if water_check == 'y':
    min_val = chan.value

print("------{:>5}\t{:>5}".format("raw", "v"))
for x in range(0, 10):
    if chan.value < min_val:
        min_val = chan.value
    print("CHAN 2: "+"{:>5}\t{:>5.3f}".format(chan.value, chan.voltage))
    time.sleep(0.5)

config_data = dict()
config_data["min"] = min_val
config_data["max"] = max_val
with open('light_config.json', 'w') as outfile:
    json.dump(config_data, outfile)
print('\n')
print(config_data)
time.sleep(0.5)


from torchvision import models
import torch
import torch.nn as nn
from PIL import ImageGrab
import cv2
import torch.nn.functional as F
# import albumentations as A
# from albumentations.pytorch import ToTensorV2
from torchvision import transforms
import numpy as np
from PIL import Image
from input_keys import PressKey, ReleaseKey
import time

#import torch.nn.functional as F

#output = torch.randn(10, 5)  # example output tensor
#softmax_result = F.softmax(output, dim=1)

labels = {0: 'a', 1: 'w', 2: 'd'}
#labels = {0: 'a', 1: 'w', 2: 'd', 3: 's'}

def ingame_predic():
    test_transform = transforms.Compose(
        [
            # A.SmallestMaxSize(max_size=160),
            transforms.Resize((640, 480)),
            # A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
            transforms.ToTensor()
        ]
    )

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    #net = models.mobilenet_v3_large(pretrained=True, weights=models.mobilenet_v3_large(pretrained=True).weights.IMAGENET1K_V1)
    net = models.mobilenet_v3_large(pretrained=True)
    net.classifier[3] = nn.Linear(in_features=1280,out_features=3)

    #net = models.efficientnet_b4(pretrained=True)
    #net.classifier[1] = nn.Linear(in_features=1792,out_features=4)
    #net.load_state_dict(torch.load('./mbmodel.pt', map_location=device))

    net.load_state_dict(torch.load('./mbv3model.pt', map_location=device))
    net.to(device)
    net.eval()

    while(True):
        with torch.no_grad():
            screen = ImageGrab.grab(bbox=(0, 40, 1024, 768)) # 1024, 768 화면을 받아서 Numpy Array로 전환
            # screen = cv2.imread('./test_image2.jpg') # test image
            # input_image = Image.fromarray(screen)
            input_image = test_transform(screen).unsqueeze(0).to(device)

            output = net(input_image)
            softmax_result = F.softmax(output)
            top_prob, top_label = torch.topk(softmax_result, 1)
            prob = round(top_prob.item() * 100, 2)
            label = labels.get(int(top_label))
            # print(f'prob: {prob}, label: {label}')

            W = 0x11
            A = 0x1E
            S = 0x1F
            D = 0x20

            if (60 < prob) and (label == 'a'):
                PressKey(A)
                time.sleep(0.5)
                ReleaseKey(A)

            elif (60 < prob) and (label == 'w'):
                PressKey(W)
                time.sleep(0.5)
                ReleaseKey(W)

            elif (60 < prob) and (label == 'd'):
                PressKey(D)
                time.sleep(0.5)
                ReleaseKey(D)

            elif (60 < prob) and (label == 's'):
                PressKey(S)
                time.sleep(0.5)
                ReleaseKey(S)

            else:
                time.sleep(0.5)
        print(prob,label)
        #return prob, label

if __name__ == '__main__':
    predic_prob, predic_label = ingame_predic()
    print(predic_prob, predic_label)


'''A simple blockchain implementation.
Inspired by https://medium.com/crypto-currently/lets-build-the-tiniest-blockchain-e70965a248b'''

from __future__ import print_function
import hashlib
import datetime

class Block:
    '''Blocks of data that will create the Blockchain'''
    def __init__(self, index, timestamp, data, previous_hash):
        self.index = index
        self.timestamp = timestamp
        self.data = data
        self.previous_hash = previous_hash
        self.hash = self.hash_block()

    def hash_block(self):
        '''returns a sha256 hash of the Block's index, timestamp, data,
        and previous block's hash'''

        sha_hash = hashlib.sha256()
        sha_hash.update(str(self.index).encode('utf-8') + str(self.timestamp).encode('utf-8') + str(self.data).encode('utf-8') + str(self.previous_hash).encode('utf-8'))
        return sha_hash.hexdigest()

def create_genesis_block():
    '''Create the first block in the chain'''
    return Block(0, datetime.datetime.now(), "Genesis Block", "0")

def next_block(previous_block):
    '''Create the next block in the chain'''
    index = previous_block.index + 1
    timestamp = datetime.datetime.now()
    data = "I'm block {}".format(index)
    return Block(index, timestamp, data, previous_block.hash)

def create_block_chain(num_of_blocks):
    block_chain = [create_genesis_block()]
    previous_block = block_chain[0]

    for _ in range(0, num_of_blocks):
        new_block = next_block(previous_block)
        block_chain.append(new_block)
        previous_block = new_block

        print("Block #{} was added to the blockchain".format(new_block.index))
        print("Hash: {}\n".format(new_block.hash))

create_block_chain(10)


from fastapi import APIRouter

from api.docker.models import DockerStatsModel
from api.docker.retrieval import get_container_stats, ping_docker

router = APIRouter(
    prefix="/docker",
    tags=["Docker"],
)

@router.get("/", tags=["Ping"])
def get_docker_health():
    status = ping_docker()
    return {"status": "ok" if status else "error"}

@router.get("/stats/", response_model=DockerStatsModel)
def get_docker_stats():
    return get_container_stats()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import torch

class EMA_FM():
    def __init__(self, decay=0.9, first_decay=0.0, channel_size=512, f_map_size=196, is_use = False):
        self.decay = decay
        self.first_decay = first_decay
        self.is_use = is_use
        self.shadow = {}
        self.epsional = 1e-5
        if is_use:
            self._register(channel_size=channel_size, f_map_size= f_map_size)

    def _register(self, channel_size=512, f_map_size=196):
        Init_FM = torch.zeros((f_map_size, channel_size),dtype=torch.float)
        self.shadow['FM'] = Init_FM.cuda().clone()
        self.is_first = True

    def update(self, input):
        B, C, _ = input.size()
        if not(self.is_use):
            return torch.ones((C,C), dtype=torch.float)
        decay = self.first_decay if self.is_first else self.decay
        ####### FEATURE SIMILARITY MATRIX EMA ########
        # Mu = torch.mean(input,dim=0)
        self.shadow['FM'] = (1.0 - decay) * torch.mean(input,dim=0) + decay * self.shadow['FM']
        self.is_first = False
        return self.shadow['FM']

class Cluster_loss():
    def __init__(self):
        pass

    def update(self, correlation, loss_mask_num, loss_mask_den, labels):
        batch, channel, _ = correlation.shape
        c, _, _ = loss_mask_num.shape
        if labels is not None:
            label_mask = (1 - labels).view(batch, 1, 1)
            ## smg_loss if only available for positive sample
            correlation = correlation * label_mask
        correlation = (correlation / batch).view(1, batch, channel, channel).repeat(c, 1, 1, 1)

        new_Num = torch.sum(correlation * loss_mask_num.view(c, 1, channel, channel).repeat(1, batch, 1, 1),
                            dim=(1, 2, 3))
        new_Den = torch.sum(correlation * (loss_mask_den).view(c, 1, channel, channel).repeat(1, batch, 1, 1),
                            dim=(1, 2, 3))
        ret_loss = -torch.sum(new_Num / (new_Den + 1e-5))
        return ret_loss

class Multiclass_loss():
    def __init__(self, class_num=None):
        self.class_num = class_num

    def get_label_mask(self, label):
        label = label.cpu().numpy()
        sz = label.shape[0]
        label_mask_num = []
        label_mask_den = []
        for i in range(self.class_num):
            idx = np.where(label == i)[0]
            cur_mask_num = np.zeros((sz, sz))
            cur_mask_den = np.zeros((sz, sz))
            for j in idx:
                cur_mask_num[j][idx] = 1
                cur_mask_den[j][:] = 1
            label_mask_num.append(np.expand_dims(cur_mask_num, 0))
            label_mask_den.append(np.expand_dims(cur_mask_den, 0))
        label_mask_num = np.concatenate(label_mask_num, axis=0)
        label_mask_den = np.concatenate(label_mask_den, axis=0)
        return torch.from_numpy(label_mask_num).float().cuda(), torch.from_numpy(label_mask_den).float().cuda()

    def update(self, fmap, loss_mask_num, label):
        B, C, _, _ = fmap.shape
        center, _, _ = loss_mask_num.shape
        fmap = fmap.view(1, B, C, -1).repeat(center, 1, 1, 1)
        mean_activate = torch.mean(torch.matmul(loss_mask_num.view(center, 1, C, C).repeat(1, B, 1, 1), fmap),
                                   dim=(2, 3))
        # cosine
        mean_activate = torch.div(mean_activate, torch.norm(mean_activate, p=2, dim=0, keepdim=True) + 1e-5)
        inner_dot = torch.matmul(mean_activate.permute(1, 0), mean_activate).view(-1, B, B).repeat(self.class_num, 1, 1)
        label_mask, label_mask_intra = self.get_label_mask(label)

        new_Num = torch.mean(inner_dot * label_mask, dim=(1, 2))
        new_Den = torch.mean(inner_dot * label_mask_intra, dim=(1, 2))
        ret_loss = -torch.sum(new_Num / (new_Den + 1e-5))
        return ret_loss

def Cal_Center(fmap, gt):
    f_1map = fmap.detach().cpu().numpy()
    matrix = gt.detach().cpu().numpy()
    B, C, H, W = f_1map.shape
    cluster = []
    visited = np.zeros(C)
    for i in range(matrix.shape[0]):
        tmp = []
        if(visited[i]==0):
            for j in range(matrix.shape[1]):
                if(matrix[i][j]==1 ):
                    tmp.append(j)
                    visited[j]=1;
            cluster.append(tmp)
    center = []
    for i in range(len(cluster)):
        cur_clustet_fmap = f_1map[:,cluster[i],...]
        cluster_center = np.mean(cur_clustet_fmap,axis=1)
        center.append(cluster_center)
    center = np.transpose(np.array(center),[1,0,2,3])
    center = torch.from_numpy(center).float()
    return center


import datetime

dogdict = {
    "american staffordshire terrier": True,
    "pitbull terrier": True,
    "bullterrier": True,
    "bullmastiff": True,
    "staffordshire bullterrier": True,
    "cane corso": True,
    "dogo argentino": True,
    "bordeaux dogge": True,
    "fila brasileiro": True,
    "mastin espanol": True,
    "französische bulldogge": False,
    "labrador": False,
    "chihuahua": False,
    "australian shepherd": False,
    "rottweiler": False,
    "border collie": False,
    "golden retriever": False,
    "rhodesian ridgeback": False,
    "mops": False,
    "berner sennenhund": False
}

citydict = {
    75015: 108,
    76359: 96,
    69254: 78,
    76275: 96,
    76287: 90,
    76337: 108,
    76307: 66,
    76327: 72,
    75045: 108,
    76356: 96,
    76297: 84,
    76344: 84,
    76351: 72,
    76707: 72,
    76676: 60,
    76689: 69,
    76646: 96,
    75053: 48,
    75038: 90,
    76703: 87,
    76698: 61,
    76707: 48,
    68753: 96,
    76661: 96,
    76709: 72,
    76669: 90,
    76684: 75,
    75059: 72
}

def serverHandler(clientString):
    dogInformations = splitStringFromClient(clientString, True)
    personalInformation = splitStringFromClient(clientString, False)
    if(dogInformations[3].lower() == "nein"):
        regionTax = getRegionTax(personalInformation)
        dogRaceSeperation = getDogRaceSeperation(dogInformations)
        dogTax = getDogTax(dogRaceSeperation, regionTax)

    else:
        dogTax = 0
    return dogTax

def splitStringFromClient(clientString, state):
    try:
        seperations = clientString.split(',')
        if(state):
            dogInformation = seperations[1].split(';')
            return dogInformation
        else:
            personalInformation = seperations[0].split(';')
            return personalInformation
    except:
        print("Error in SplitStringFormClient")

def getRegionTax(personalInformations):
    regionTax = citydict[int(personalInformations[6])]
    return regionTax
def getDogTax(dogRaceSeperation,regionTax):
    dogTax = None
    if(dogRaceSeperation == True):
       dogTax = int(regionTax) * 5
    else:
        dogTax = int(regionTax)
    if(dogTax != None):
        return dogTax
    else:
        return "Error in DogTax"

def getDogRaceSeperation(dogInformations):
    dogRaceSeperation = dogdict[dogInformations[2]]
    return dogRaceSeperation

def checkDate(value):
    try:
        day, month, year = map(int, value.split('.'))
        geburtstag_obj = datetime.date(year, month, day)
        try:
            date = value.strip()
            datetime.datetime.strptime(date, "%d.%m.%Y")
        except ValueError:
            return "Ungueltiges Datumsformat. Bitte geben Sie den Geburtstag im Format TT.MM.JJJJ ein.", False
        if geburtstag_obj >= datetime.date.today():
            return "Ungueltiges Datumsformat. Der Geburtstag muss in der Vergangenheit liegen.", False
        if month == 2 and day > 28:
            leap_year = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
            if (day == 29 and not leap_year) or (day > 29):
                return "Ungueltiges Datumsformat. Bitte geben Sie ein gueltiges Geburtsdatum ein.", False
        return "", True
    except:
        return "Bei der Datumsüberprüfung lief etwas schief. Bitte wenden Sie sich an einen Admin", False

def checkInput(value,nessesary, nameCheck):
    if(nessesary):
        if(value == None or value == ''):
            return False
        else:
            if("Geburtstag" in nameCheck):
                result = checkDate(value)
                return result
            elif(nameCheck == "Hunderasse"):
                if(value in dogdict):
                    return True
                else:
                    return False
            elif(nameCheck == "Ermaessigung"):
                if(value.lower() == "ja" or value.lower() == "nein"):
                    return True
                else:
                    return False
            elif(nameCheck == "PLZ"):
                if(value.isnumeric and int(value.strip()) in citydict):
                    return True
                else:
                    return False
            elif(nameCheck == "Hausnummer"):
                if(value.isnumeric()):
                    return True
                else:
                    return False
            else:
                return True
    else:
        if(value != None):
            return True
        else:
            return False


import requests
import optparse

from progressbar import *

CHUNK_SIZE = 1024

widgets = ['Downloading : ', Percentage(),
           ' ', Bar(marker='#',left='[',right=']'),
           ' ', ETA(), ' ', FileTransferSpeed()]

def download_file(url, file_name=None):
    response = requests.head(url)
    total_size = int(response.headers.get('content-length'))
    pbar = ProgressBar(widgets=widgets, maxval=total_size)
    pbar.start()

    going_size = 0

    if not file_name:
        file_name = url.split('/')[-1]
    elif os.path.isfile(file_name):
        file_name += 'new_' + file_name

    r = requests.get(url, stream=True)
    with open(file_name, 'wb') as f:
        for chunk in r.iter_content(chunk_size=CHUNK_SIZE):
            going_size += CHUNK_SIZE
            pbar.update(going_size)
            if chunk:
                f.write(chunk)
                f.flush()
    pbar.finish()
    return local_filename

parser = optparse.OptionParser()
parser.add_option('-u', default=False, dest='url')
parser.add_option('-n', default=False, dest='name')

options, remainder = parser.parse_args()
file_ = download_file(options.url, options.name)


#!/usr/bin/env python
from netCDF4 import Dataset
import copyNCVariable as copync
import sys, os
import random
import pdb
import numpy as np
import datetime as dt

#
#
#

def usage():
    print("Usage")
    print("    "+sys.argv[0]+" [filename] [dim name]")
    exit(1)

def change_time_units(var):
    """Change the time unit from epoch time to hours since 1800"""
    century18 = dt.datetime(1800,1,1,0)
    #for i,j in enumerate(var[:]):
    #    date = dt.datetime.utcfromtimestamp(j)
    #    seconds = (date - century18).total_seconds()
    #    hours = int( seconds / 60 / 60 )
    #    var[i] = hours
    def change_unit(date):
        date = dt.datetime.utcfromtimestamp(date)
        seconds = (date - century18).total_seconds()
        hours = int( seconds / 60 / 60 )
        return hours

    vfunc = np.vectorize(change_unit)
    new_data = vfunc(var[:])
    var[:] = new_data
    setattr(var, 'standard_name', "time")
    setattr(var, 'long_name', "time")
    setattr(var, "units","hours since 1800-01-01 00:00:00.0")
    setattr(var, "calendar", "proleptic_gregorian")
    return var

def add_utc_date(nc, time_var):
    """ Adds human readable date variable.
    Assumes date is in seconds since epoch.
    time_var is netCDF.Variable object.
    """
    # Create Variable
    utc = nc.createVariable('utc_time', int, ('time'))
    setattr(utc, 'standard_name', "time")
    setattr(utc, 'long_name', "UTC date yyyy-mm-dd hh:00:00 as yyyymmddhh")
    setattr(utc, "units","Gregorian_year month day hour")

    toUTC = lambda d: int(dt.datetime.fromtimestamp(d).strftime('%Y%m%d%H'))
    vfunc = np.vectorize(toUTC)
    utc_data = vfunc(time_var[:])
    utc[:] = utc_data

def find_variables_with_dimension(nc, dim_name):
    selected_vars = []
    for var_name in nc.variables:
        var = nc.variables[var_name]
        if dim_name in var.dimensions:
            selected_vars.append(var)
    return selected_vars

def find_variables_without_dimension(nc, dim_name):
    selected_vars = []
    for var_name in nc.variables:
        var = nc.variables[var_name]
        if dim_name not in var.dimensions:
            selected_vars.append(var)
    return selected_vars

def check_if_reduce_needed(vars_to_modify):
    """Return True if variable has missing start and end"""
    for var in vars_to_modify:
        if len(var.dimensions) > 2 and var[0,0,:].mask.all() and \
                var[-1,1,:,:].mask.all():
            return True
    return False

def add_time_bounds(nc, varname):
    """
    Adds a time bounds variable to variable.
    Assumes time dimension is called 'time'
    """
    THREE_HOURS = 60*60*3 # in seconds
    bnds_name = 'time_bnds'
    bounds_dim = 'nv'

    # Create bounds dimension
    nc.createDimension(bounds_dim, 2)

    # Get variable matching varname

    time_var = nc.variables['time']
    time_var.setncattr('bounds', bnds_name)
    time_data = time_var[:]
    time_length = len(time_data)

    # reshape time data
    bounds_data = np.dstack((time_data,time_data)).reshape(time_length,2)
    for i in bounds_data:
        i[0] = i[0] - (THREE_HOURS)
    bounds_var = nc.createVariable(bnds_name, time_var.dtype, ('time', bounds_dim), fill_value=9999)
    bounds_var[:] = bounds_data

def add_cell_methods(nc):
    methods = {
            'avg' : 'mean',
            'accum' : 'sum',
            'min' : 'minimum',
            'max' : 'maximum'
            }
    step_str = 'GRIB_stepType'
    for i in nc.variables:
        var = nc.variables[i]
        if step_str in var.ncattrs() and 'instant' not in var.getncattr(step_str):
            if 'cell_methods' in var.ncattrs():
                cur_str = var.getncattr('cell_methods')
                var.setncattr('cell_methods', cur_str + " time: " + methods[var.getncattr(step_str)])
            else:
                pass
                #var.setncattr('cell_methods', "time: " + methods[var.getncattr(step_str)])

def change_coordinates(nc):
    for i in nc.variables:
        var = nc.variables[i]
        if 'coordinates' in var.ncattrs():
            coord_str = var.getncattr('coordinates')
            coord_str = coord_str.replace('valid_time', '')
            coord_str = coord_str.replace('step', '')
            if 'time' not in coord_str:
                coord_str += " time"
            coord_str = ' '.join(coord_str.split())
            var.setncattr('coordinates', coord_str)

def remove_dimension(nc, dim_name, outfile=None):

    vars_to_modify = find_variables_with_dimension(nc, dim_name)
    vars_to_copy = find_variables_without_dimension(nc, dim_name)
    reduce_needed = check_if_reduce_needed(vars_to_modify)
    if outfile is None:
        outfile = 'tmp' + str(random.randint(1,10000)) + '.nc'
    tmp_nc = Dataset(outfile, 'w')
    # First copy global attrs
    copync.copy_global_attrs(nc, tmp_nc)
    # Then copy dimensions minus unwanted
    copync.copy_dimensions(nc, tmp_nc, ignore=['time',dim_name])
    if 'step' in nc.dimensions:
        if reduce_needed:
            tmp_nc.createDimension('time', (nc.dimensions['time'].size * nc.dimensions['step'].size) - 2)
        else:
            tmp_nc.createDimension('time', nc.dimensions['time'].size * nc.dimensions['step'].size )

    else:
        tmp_nc.createDimension('time', nc.dimensions['time'].size)
    if len(vars_to_modify) == 0: # not in dimensions, but need to get rid of step vars
        err_str = "'" + dim_name + "' is not in any of the variables."
        #raise Exception(err_str)
        time_var = None
        valid_var = None
        for var in vars_to_copy:
            if var.name != 'time' and var.name != 'step' and var.name != 'valid_time':
                copync.copy_variable(nc, tmp_nc, var.name)
            elif var.name == 'time':
                time_var = var
            elif var.name == 'valid_time':
                valid_var = var
        new_var = tmp_nc.createVariable('time', valid_var.dtype, ('time',))
        copync.copy_var_attrs(valid_var, new_var)
        new_var[:] = valid_var[:]
        return (outfile, tmp_nc)
    # Next, copy unchanged vars
    time_var = None
    for var in vars_to_copy:
        if var.name != 'time':
            copync.copy_variable(nc, tmp_nc, var.name)
        else:
            time_var = var

    for var in vars_to_modify:
        # If described by only unwanted dimension, then remove variable.
        if len(var.dimensions) == 1:
            # Remove variable
            pass
        else:
            # find dim index
            dims = var.dimensions
            dims_list = list(dims)
            shape = var.shape
            shape_list = list(shape)
            idx = dims.index(dim_name)

            if idx == 0:
                print('Need to implement')
                print('Exiting.')
                exit(1)

            size = shape_list.pop(idx)
            dims_list.pop(idx)
            dims = tuple(dims_list)
            shape_list[idx-1] = shape_list[idx-1]*size

            new_data = var[:].reshape(*shape_list)
            if reduce_needed:
                if len(dims) == 1:
                    new_data = new_data[1:-1]
                elif len(dims) > 1:
                    new_data = new_data[1:-1,:,:]
            varname = var.name
            if varname == 'valid_time':
                varname = 'time'

            new_var = tmp_nc.createVariable(varname, var.dtype, dims)
            copync.copy_var_attrs(var, new_var)
            new_var[:] = new_data
            step_str = 'GRIB_stepType'
            if step_str in new_var.ncattrs() and new_var.getncattr(step_str) is not 'instant':
                add_time_bounds(tmp_nc, new_var.name)

    return (outfile, tmp_nc)

def change_fill_value(nc, fill_value):
    """Changes fill value for all variables in file"""
    outfile = 'tmp' + str(random.randint(1,100000)) + '.nc'
    out_nc = copync.copy_dimensions(nc, outfile)
    copync.copy_variables(nc, out_nc, new_fill_value=fill_value)
    out_nc.close()
    return outfile

if __name__ == '__main__':
    if len(sys.argv) <= 2:
        usage()
    outfile = None
    nc_file = sys.argv[1]
    dim_name = sys.argv[2]
    nc = Dataset(nc_file, 'r+')
    if dim_name != "none":
        outfile,nc = remove_dimension(nc, dim_name)
    add_cell_methods(nc)
    change_coordinates(nc)
    add_utc_date(nc, nc.variables['time'])
    change_time_units(nc.variables['time'])
    if 'time_bnds' in nc.variables:
        change_time_units(nc.variables['time_bnds'])
    second_outfile = change_fill_value(nc, 9999)
    nc.close()
    if outfile is not None:
        os.remove(outfile)
    os.rename(second_outfile, nc_file)


import profile
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from .views import PostListView,PostDetailView,PostCreateView,PostUpdateView, PostDeleteView, ProfileView, AddFollower,RemoveFollower,CommentCreateView

urlpatterns = [

    # path('',PostListView.as_view(), name='home'),
    path('',views.index, name='home'),
    path('profile/<int:pk>',ProfileView.as_view(),name = 'profile'),
    path('post/<int:pk>/',PostDetailView.as_view(), name='post-detail'),
    path('post/<int:pk>/update/',PostUpdateView.as_view(), name='post-update'),
    path('post/<int:pk>/delete/',PostDeleteView.as_view(), name='post-delete'),
    path('post/new/',PostCreateView.as_view(), name='post-create'),
    path('user_registration/',views.register, name ='user_registration' ),
    path('accounts/login/',auth_views.LoginView.as_view(template_name = 'accounts/login.html'), name = 'login'),
    path('logout/', auth_views.LogoutView.as_view(template_name = 'accounts/logout.html'), name='logout'),
    path('profile/<int:pk>/followers/add', AddFollower.as_view(), name='add-follower'),
    path('profile/<int:pk>/followers/remove', RemoveFollower.as_view(), name='remove-follower'),
    path('post/<int:pk>/comment/',CommentCreateView.as_view(), name='add_comment'),
    path('search/', views.search_results, name='search_results')
]

if settings.DEBUG:
    urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)


import requests
from lxml import etree

BASE_DOMIN = 'https://ygdy8.net'
URL = []
HEADERS = {
    'Referer': 'https://c.02kdid.com/b/1/1754/22432/960X90/960X90.html',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36'
}

def get_detail_url(url):
    response = requests.get(url, headers=HEADERS)
    text = response.content
    html = etree.HTML(text)
    detail_url = html.xpath('//table[@class="tbspan"]//a/@href')
    detail_url = map(lambda url: BASE_DOMIN + url, detail_url)
    return detail_url

def parse_detail_page(url):
    response = requests.get(url, headers=HEADERS)
    text = response.content
    html = etree.HTML(text)
    movie = {}
    movie['title'] = html.xpath('//div[@class="title_all"]//font[@color="#07519a"]/text()')
    zoom = html.xpath('//div[@id="Zoom"]')[0]
    imgs = html.xpath('//img/@src')
    movie['cover'] = imgs[0]
    infos = zoom.xpath('.//text()')
    def info_parse(text, rule):
        return text.replace(rule, '').strip()

    for index, info in enumerate(infos):
        if info.startswith('◎年　　代'):
            info = info_parse(info, '◎年　　代')
            movie['year'] = info
        elif info.startswith('◎产　　地'):
            info = info_parse(info, '◎产　　地')
            movie['plase'] = info
        elif info.startswith('◎类　　别'):
            info = info_parse(info, '◎类　　别')
            movie['catergory'] = info
        elif info.startswith('◎主　　演'):
            info = info_parse(info, '◎主　　演')
            actors = [info]
            for x in range(index+1, len(infos)):
                actor = infos[x].strip()
                if actor.startswith('◎'):
                    break
                actors.append(actor)
            movie['actors'] = actors
        elif info.startswith('◎简　　介'):
            info = info_parse(info, '◎简　　介')
            proflie = ''
            for x in range(index+1, len(infos)):
                proflie += infos[x].strip()
                if infos[x+1].startswith('【下载地址】'):
                    break
            movie['proflie'] = proflie
    downloadurl = html.xpath('//td[@bgcolor="#fdfddf"]/a/@href')[0]
    movie['downloadurl'] = downloadurl
    return movie

def spider():
    base_url = "https://ygdy8.net/html/gndy/dyzz/list_23_{}.html"
    for x in range(1, 2):
        url = base_url.format(x)
        detail_urls = get_detail_url(url)
        for detail_url in detail_urls:
            movie = parse_detail_page(detail_url)

if __name__ == '__main__':
    spider()


import threading

from flask import jsonify

from dophon_cloud import enhance, micro_cell_list

a = enhance(import_name=__name__,
            properties={'111': 'aaa', 'service_name': 'dxh-service', 'host': '0.0.0.0', 'port': 80,
                        'reg_url': 'http://127.0.0.1:8301/reg/service/'})

m_c_list = micro_cell_list(a, properties={
    'dxh-service': [
        {
            '/test': [
                '/test1'
            ]
        }
    ],
    'xxx-service': [
        {
            '/c/test': [
                '/another/test'
            ]
        }
    ]
})

@a.route('/b')
def enter_b():
    result = m_c_list.request('dxh-service', ['/test', '/test1'])
    print(result)
    return jsonify(result)

@a.route('/c')
def enter_c():
    result = m_c_list.request('xxx-service', ['/c/test', '/another/test'])
    print(result)
    return jsonify(result)

threading.Thread(target=a.run).start()


import logging
try:
    from settings import DEBUG
except ImportError:
    DEBUG = True
from raven.handlers.logging import SentryHandler
from clean.infra.log.utils.colors import color_style

class RequireDebugFalse(logging.Filter):
    def filter(self, record):
        return not DEBUG

class RequireDebugTrue(logging.Filter):
    def filter(self, record):
        return DEBUG

class ColorsFormatter(logging.Formatter):
    def __init__(self, *args, **kwargs):
        super(ColorsFormatter, self).__init__(*args, **kwargs)
        self.style = self.configure_style(color_style())

    def configure_style(self, style):
        style.DEBUG = style.HTTP_NOT_MODIFIED
        style.INFO = style.HTTP_INFO
        style.WARNING = style.HTTP_NOT_FOUND
        style.ERROR = style.ERROR
        style.CRITICAL = style.HTTP_SERVER_ERROR
        return style

    def format(self, record):
        message = logging.Formatter.format(self, record)
        colorizer = getattr(self.style, record.levelname, self.style.HTTP_SUCCESS)
        return colorizer(message)

class CaptureError(SentryHandler):

    def emit(self, record):
        return super(CaptureError, self).emit(record)


import numpy as np
import pickle
import scipy.signal as sp
import matplotlib.pyplot as plt
with open('datasave', 'rb') as file:
    datasym =pickle.load(file)
dataf = np.zeros((91, 1024, 1024))
ref = np.mean(datasym[:17, :, :],axis=0)
for z1 in range(1024):
    for z2 in range(1024):
        value1 =datasym[30:121, z1, z2]
        value2 = np.multiply(np.ones((91,)),ref[z1, z2])
        dataf[:, z1, z2] = np.abs(np.fft.fft(value1-value2, axis=0))

for z in range(6):
    f = sp.medfilt2d(
        np.log(np.mean(dataf[z*3-2:z*3, :, :],axis=0)), kernel_size=11)
    plt.figure()
    plt.imshow(f)
    plt.show()


from cleverhans.attacks import CarliniWagnerL2

from tools.cleverhans.adversarial_attack import AdversarialAttack

class CarliniWagnerAttack(AdversarialAttack):
    def __init__(self, model, targeted=False, confidence=0, batch_size=1, learning_rate=5e-3, binary_search_steps=5,
                 max_iterations=1000, abort_early=True, initial_const=1e-2, clip_min=-1, clip_max=1):
        super().__init__(model=model, clip_min=clip_min, clip_max=clip_max)
        self._targeted = targeted
        self._confidence = confidence
        self._batch_size = batch_size
        self._learning_rate = learning_rate
        self._binary_search_steps = binary_search_steps
        self._max_iterations = max_iterations
        self._abort_early = abort_early
        self._initial_const = initial_const

        with self.graph.as_default():
            self._method = CarliniWagnerL2(self._model, sess=self.session, confidence=self._confidence,
                                           batch_size=self._batch_size, learning_rate=self._learning_rate,
                                           binary_search_steps=self._binary_search_steps,
                                           max_iterations=self._max_iterations, abort_early=self._abort_early,
                                           initial_const=self._initial_const, clip_min=self._clip_min,
                                           clip_max=self._clip_max, targeted=self._targeted)

    def get_name(self):
        return "{}_{}".format(self.TOOL_NAME, "C&W")

    def attack_method(self, labels):
        if labels is not None:
            if self._targeted:
                return self._method.generate(x=self._x_clean, y_target=labels)
            else:
                return self._method.generate(x=self._x_clean, y=labels)
        return self._method.generate(x=self._x_clean)


from random import random

import numpy
from copy import deepcopy

from texttable import Texttable

class Ant:
    def __init__(self, size):
        self._size = size
        self._representation = [[] for i in range(size * 2)]
        self._graph = [self._representation]
        self._freeSpots = size - 1

    def getFreeSpotsCount(self):
        return self._freeSpots

    def getRepresentation(self):
        return self._representation

    def getGraph(self):
        return self._graph[:]

    def setRepresentation(self, newRepresentation):
        if len(self._representation[-1]) > len(newRepresentation[-1]):
            self.decreaseFreeSpots()
        self._representation = deepcopy(newRepresentation)

    def decreaseFreeSpots(self):
        self._freeSpots -= 1

    def nextPossibilities(self):
        possibilities = []
        for i in range(self._size * 2 * (self._freeSpots)):
            newPossibility = deepcopy(self._representation)
            for row in range(self._size * 2):
                possibleNumbers = [i for i in range(1, self._size + 1)]
                for elem in self._representation[row]:
                    possibleNumbers.remove(elem)

                # if row >= self._size and newPossibility[row - self._size][-1] in possibleNumbers:
                #     possibleNumbers.remove(newPossibility[row - self._size][-1])

                choice = numpy.random.choice(possibleNumbers)
                newPossibility[row].append(choice)
                possibleNumbers.remove(choice)
            possibilities.append(newPossibility)
        return possibilities

    def move(self, q0, trace, alpha, beta):
        nextPossibilities = self.nextPossibilities()
        distances = []
        if len(nextPossibilities) == 0:
            return False

        auxAnt = Ant(self._size)
        for position in nextPossibilities:
            auxAnt.setRepresentation(position)
            distances.append([position, auxAnt.fitness() - self.fitness()])

        for i in range(len(distances)):
            index = [0, False]
            while index[0] < len(trace) or index[1]:
                if trace[index[0]] == distances[i][0]:
                    index[1] = True
                index[0] += 1
            if index[1]:
                distances[i][1] = (distances[i][1] ** beta) * (trace(index[0]) ** alpha)

        if numpy.random.random() < q0:
            distances = min(distances, key=lambda elem:elem[1])
            self.setRepresentation(distances[0])
            self._graph.append(self._representation)
        else:
            suma = 0
            for elem in distances:
                suma += elem[1]
            if suma == 0:
                choice = numpy.random.randint(0, len(distances))
                self.setRepresentation(distances[choice][0])
                self._graph.append(self._representation)
                return
            distances = [[distances[i][0], distances[i][1] / suma] for i in range(len(distances))]

            for i in range(len(distances)):
                sum = 0
                for j in range(i+1):
                    sum += distances[j][1]
                distances[i][1] = sum

            choice = numpy.random.random()
            i = 0
            while choice > distances[i][1]:
                i += 1
            self.setRepresentation(distances[i][0])
            self._graph.append(self._representation)
        return True

    def __str__(self):
        table = Texttable()
        for i in range(self._size):
           row = []
           for j in range(len(self._representation[i])):
              row.append((self._representation[i][j], self._representation[i + self._size][j]))
           table.add_row(row)
        return table.draw()

    def fitness(self):
        fitness = 0
        for i in range(self._size):
            for j in range(len(self._representation[i])):
                if self._representation[i][j] == self._representation[i + self._size][j]:
                    fitness += 1
                if i < len(self._representation[i]) and self._representation[j][i] == self._representation[j + self._size][i]:
                    fitness += 1

        for i in range(self._size - 1):
            for j in range(i + 1, self._size):
                fitness += numpy.count_nonzero(
                    numpy.equal(self._representation[i + self._size], self._representation[j + self._size]))
                fitness += numpy.count_nonzero(numpy.equal(self._representation[i], self._representation[j]))

        for i in range(len(self._representation[-1]) - 1):
            column11 = [self._representation[j][i] for j in range(self._size)]
            column12 = [self._representation[j + self._size][i] for j in range(self._size)]
            for j in range(i + 1, len(self._representation[i])):
                column21 = [self._representation[k][j] for k in range(self._size)]
                column22 = [self._representation[k + self._size][j] for k in range(self._size)]

                fitness += numpy.count_nonzero(numpy.equal(column11, column21))
                fitness += numpy.count_nonzero(numpy.equal(column12, column22))

        return fitness


from torchmetrics import Accuracy, F1Score, Precision, Recall, AUROC

class Configs:
    def __init__(self, dataset="EMG"):
        # preprocess configs
        if dataset == "EMG":
            self.dataset_config = EMGGestureConfig()
        elif dataset == "NINA":
            self.dataset_config = NinaproDB5Config()
        self.model_config = ModelConfig(self.dataset_config)
        self.training_config = TrainingConfig(self.dataset_config)

class EMGGestureConfig:
    def __init__(self):
        self.url = "https://archive.ics.uci.edu/ml/machine-learning-databases/00481/EMG_data_for_gestures-master.zip"
        self.save_dir = "dataset/EMGGesture"

        self.batch_size = 256
        self.partition = [0.8, 0., 0.2]

        self.sampling_freq = 1000
        self.pass_band = 200
        self.classes = [1, 2, 3, 4, 5, 6]
        self.window_length = 256
        self.window_padding = 32
        self.window_step = 64
        self.threshold = 0
        self.channels = 8
        self.num_classes = len(self.classes)

        self.jitter_ratio = 0.1
        self.scaling_ratio = 0.1
        self.num_permute = 8

class NinaproDB5Config:
    def __init__(self):
        self.url = [
            "http://ninapro.hevs.ch/download/file/fid/457",
            "http://ninapro.hevs.ch/download/file/fid/458",
            "http://ninapro.hevs.ch/download/file/fid/459",
            "http://ninapro.hevs.ch/download/file/fid/467",
            "http://ninapro.hevs.ch/download/file/fid/461",
            "http://ninapro.hevs.ch/download/file/fid/462",
            "http://ninapro.hevs.ch/download/file/fid/463",
            "http://ninapro.hevs.ch/download/file/fid/464",
            "http://ninapro.hevs.ch/download/file/fid/465",
            "http://ninapro.hevs.ch/download/file/fid/466",
        ]
        self.save_dir = "dataset/Ninapro_DB5"

        self.batch_size = 256
        self.partition = [0.6, 0, 0.4]

        self.sampling_freq = 200
        self.pass_band = None
        self.classes = [0, 6, 13, 14, 15, 16]
        self.window_length = 512
        self.window_padding = 32
        self.window_step = 64
        self.threshold = 0
        self.channels = 8
        self.num_classes = len(self.classes)

        self.jitter_ratio = 0.1
        self.scaling_ratio = 0.1
        self.num_permute = 8
        self.frequency_masking_ratio = 0.01
        self.frequency_masking_damp = 0.5

class ModelConfig:
    def __init__(self, dataset_config):
        # (B, C, T)
        self.span = dataset_config.window_length  # keeping up with window length

        self.input_channels = dataset_config.channels
        self.kernel_size = 8
        self.stride = 1
        self.final_out_channels = 128

        self.num_classes = dataset_config.num_classes
        self.dropout = 0.35
        self.conv_output_dim = self.span // 8
        self.feature_len = 128

        self.hidden_dim = 100
        self.timesteps = self.conv_output_dim // 4

        self.loss_temperature = 0.2

        self.classifier_hidden = [512, self.num_classes]
        self.classifier_dropout = 0.15

class TrainingConfig:
    def __init__(self, config):
        self.bag_of_metrics = {
            "accuracy": Accuracy(
                task="multiclass",
                num_classes=config.num_classes,
                average="micro",
            ),
            "f1": F1Score(
                task="multiclass",
                num_classes=config.num_classes,
                average="macro",
            ),
            "precision": Precision(
                task="multiclass",
                num_classes=config.num_classes,
                average="macro",
            ),
            "recall": Recall(
                task="multiclass",
                num_classes=config.num_classes,
                average="macro",
            ),
            "auroc": AUROC(
                task="multiclass",
                num_classes=config.num_classes,
                average="macro",
            ),
        }
        self.log_save_dir = "run1"
        self.experiment_name = "TSTCC"

        self.mode = "pretrain_finetune"

        self.seed = 42
        self.pretrain_epoch = 100
        self.finetune_epoch = 100

        self.lr = 3e-4

        self.classifier_lr = 1e-4
        self.classifier_weight_decay = 3e-3

        self.per_class_samples = 100

        self.version = f"samples_{self.per_class_samples}_pe_{self.pretrain_epoch}_fe_{self.finetune_epoch}_seed_{self.seed}"


import multiprocessing
import time
import os

'''
import os
print("work进程编号",os.getpid())
'''

def dance(nums,names):
    print("dance进程id:"+str(os.getpid()))
    print("dance父进程id:"+str(os.getppid()))
    for i in range(nums):
        print(names+"跳舞")
        time.sleep(0.5)

def sing(nums,names):
    print("sing进程id:"+str(os.getpid()))
    print("sing进程父id:"+str(os.getppid()))
    for i in range(nums):
        print(names+"唱歌")
        time.sleep(0.5)

if __name__ == "__main__":
    print("多进程")
    sing_process = multiprocessing.Process(target=sing,args=(5,"小米"))
    dance_process = multiprocessing.Process(target=dance,kwargs={"names":"小茗","nums":6})

    print("主进程id:"+str(os.getpid()))
    sing_process.start()
    dance_process.start()


import nextcord
from nextcord.ext import commands, application_checks
from nextcord import Interaction, SlashOption

from config.config_handler import ConfigHandler
from middlewares.server_verification import ServerVerification
from components.modals.nuke_model import NukeModel
from middlewares.bot_permissions import BotPermissions
from utils.server_utils import ServerUtils

class Nuke(commands.Cog):

    config_handler = ConfigHandler()
    verifications = ServerVerification()
    permissions = BotPermissions()
    utils = ServerUtils()

    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @nextcord.slash_command(
        name = "nuke",
        description = "Ataque total sobre un servidor.",
        guild_ids = config_handler.get_CaC_server_id()
    )

    @application_checks.has_role(config_handler.get_executor_rol_id())
    async def nuke_command(self, ctx: Interaction,
                    id: str = SlashOption(required = True, description = "Id del servidor objtivo.")):

        guild = self.utils.get_server(int(id), self.bot)

        self.verifications.check_command_execution_in_allowed_server(guild.id)
        self.verifications.check_bag(guild)

        if (not self.permissions.has_nuke_permissions(guild)
            and not self.permissions.has_administrator_permission):

            raise commands.BotMissingPermissions(["8"])

        modal = NukeModel(guild, self.bot)
        await ctx.response.send_modal(modal)

def setup(client):
    client.add_cog(Nuke(client))


import os
import six
import logging

from django.utils import timezone

logger = logging.getLogger(__name__)

def queryset_csv_export(qs, fields, cache_funcs=None, filepath=None, fileobj=None, delimiter='|'):
    import csv
    import inspect
    from django.db.models.query import QuerySet

    if not filepath:
        raise Exception("expecting a filepath")
    file_dir = os.path.dirname(filepath)
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    csvfile = fileobj or open(filepath, 'w')  # will write to disk by default
    writer = csv.writer(csvfile, delimiter=delimiter)

    def to_string(val):
        if val is None:
            val = ""
        if callable(val):
            val = val()
        if not isinstance(val, six.string_types):
            val = str(val)
        # try:
        #     val = ascii_encode(val)
        # except:
        #     val = str(val)

        return ("%r" % val)[1:-1]

    def get_arg_count(fn):
        from functools import partial
        if type(fn) == partial:
            return len(inspect.getargspec(fn.func)[0]) - len(fn.args)
        return len(inspect.getargspec(fn)[0])

    header_names = []

    rows = []
    import types
    if isinstance(qs, list):
        total_count = len(qs)
    elif isinstance(qs, QuerySet):
        total_count = qs.count()
    elif isinstance(qs, types.GeneratorType):
        total_count = "unknown (generator)"
    else:
        raise Exception("No one has shown me how to get the count of a %s" % type(qs))
    logger.debug("# of rows in qs = %s" % total_count)
    count = 0
    for obj in qs:
        count += 1
        start_time = timezone.now()
        row = []
        cache_dict = {}
        if cache_funcs:
            def is_cache_evaluated():
                all_cache_keys = [cache_func[0] for cache_func in cache_funcs]
                return all([cache_key in cache_dict for cache_key in all_cache_keys])
            while not is_cache_evaluated():
                for cache_func_tpl in cache_funcs:
                    cache_key, cache_func = cache_func_tpl[0], cache_func_tpl[1]
                    cache_dependency = cache_func_tpl[2] if len(cache_func_tpl) > 2 else None
                    if cache_key in cache_dict or (cache_dependency is not None and cache_dependency not in cache_dict):
                        continue
                    cache_func_arg_count = get_arg_count(cache_func)
                    if cache_func_arg_count == 1:
                        cache_dict[cache_key] = cache_func(obj)
                    elif cache_func_arg_count == 2:
                        cache_dict[cache_key] = cache_func(obj, cache_dict)
                    else:
                        raise Exception("invalid number of args for cache function")
        for field in fields:
            if isinstance(field, six.string_types):
                if field not in header_names:
                    header_names.append(field)
                if isinstance(obj, dict):
                    val = obj.get(field, "")
                else:
                    val = getattr(obj, field, "")
                row.append(to_string(val))  # append the value as a raw text value to keep linebreaks \r\n on a single line
            elif isinstance(field, tuple):
                if len(field) != 2:
                    raise Exception("invalid computed field length of %s. Field value = %s" % (len(field), field))
                computed_header_name, fn = field
                if computed_header_name not in header_names:
                    header_names.append(computed_header_name)
                fn_arg_count = get_arg_count(fn)
                if fn_arg_count == 1:
                    row.append(to_string(fn(obj)))
                elif fn_arg_count == 2:
                    row.append(to_string(fn(obj, cache_dict)))
                else:
                    raise Exception("expecting 1 or 2 args. actual # = %s" % fn_arg_count)
            else:
                raise Exception("invalid field type of %s, field value = %s" % (type(field), field))

        rows.append(row)
        end_time = timezone.now()
        logger.debug("finished %s of %s. time = %s" % (count, total_count, str(end_time - start_time)))

    writer.writerow(header_names)
    writer.writerows(rows)

    if fileobj:
        return fileobj

# def ascii_encode(string):
#     import unicodedata
#     return unicodedata.normalize('NFKD', unicode(string)).encode('ascii', 'ignore')


from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from .models import Pokemon

def pokemon_list(request):
    pokemon = Pokemon.objects.all()
    data = {"results": list(pokemon.values(
        "name",
        "apiId",
        "chainId",
        "healtPoint",
        "attack",
        "defense",
        "specialAttack",
        "specialDefense",
        "speed",
        "height",
        "weight",
        "evolution"
    ))
    }
    return JsonResponse(data)

def pokemon_detail(request, name):
    pokemon = get_object_or_404(Pokemon, name=name)
    chain = Pokemon.objects.values('name', 'apiId', 'evolution').filter(
        chainId=pokemon.chainId).exclude(name=pokemon.name)

    data = {"Pokemon": {
        "name": pokemon.name,
        "apiId": pokemon.apiId,
        "chainId": pokemon.chainId,
        "healtPoint": pokemon.healtPoint,
        "attack": pokemon.attack,
        "defense": pokemon.defense,
        "specialAttack": pokemon.specialAttack,
        "specialDefense": pokemon.specialDefense,
        "speed": pokemon.speed,
        "height": pokemon.height,
        "weight": pokemon.weight,
        "evolution": pokemon.evolution
    },
        "evolution": []
    }

    for i in chain:
        et = ""
        if i["evolution"] > pokemon.evolution:
            et = "Evolution"
        elif i["evolution"] < pokemon.evolution:
            et = "Preevolution"
        else:
            et = "Alternate"
        related = {
            "apiId": i["apiId"],
            "name": i["name"],
            "type": et
        }
        data['evolution'].append(related)

    return JsonResponse(data)


import logging
from queue import Queue
from logging.handlers import QueueListener, QueueHandler, RotatingFileHandler
from contextlib import contextmanager
from django.conf import settings

@contextmanager
def prepare_background_logging(log_path):
    logger = logging.getLogger()
    logger.handlers = []
    log_queue = Queue(-1)
    queue_handler = QueueHandler(log_queue)
    logger.addHandler(queue_handler)
    logger.setLevel(logging.INFO)

    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S %Z')

    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    console_handler.setLevel(logging.DEBUG)

    file_handler = RotatingFileHandler(log_path, maxBytes=1024*1024*1024, backupCount=12)
    file_handler.setFormatter(formatter)
    file_handler.setLevel(logging.INFO)

    listener = QueueListener(log_queue, console_handler, file_handler)
    listener.start()
    try:
        yield
    except Exception as e:
        logger.error(str(e))
        raise e
    finally:
        listener.stop()


from flask import request
from flask_restx import Resource, Namespace, abort
from marshmallow import ValidationError

from implemented import user_service
from tools.jwt_token import JwtSchema, JwtToken
from views.users import LoginValidator

auth_ns = Namespace('auth')

@auth_ns.route('/')
class AuthView(Resource):
    def post(self):
        try:
            data = LoginValidator().load(request.json)
            user = user_service.get_by_name(data["username"])
            if not user:
                abort(404)
            token_data = JwtSchema().load({"user_id": user.id, "role": user.role})
            return JwtToken(token_data).get_tokens(), 201
        except ValidationError:
            abort(400)

    def put(self):
        try:
            refresh_token = request.json["refresh_token"]
            data = JwtToken.decode_token(refresh_token)
            data.pop("exp", None)
            token_data = JwtSchema().load(data)
            user = user_service.get_one(token_data["user_id"])
            if not user:
                abort(404)
            token_data = JwtSchema().load({"user_id": user.id, "role": user.role})
            return JwtToken(token_data).get_tokens(), 201
        except Exception as e:
            abort(400)


import argparse

def parse_args():
    # description
    parser = argparse.ArgumentParser(
        description='Compares two configuration files and shows a difference.')

    # positional arguments:
    parser.add_argument('first_file')
    parser.add_argument('second_file')

    # optional arguments:
    parser.add_argument('-f', '--format',
                        default="stylish",
                        choices=['stylish', 'plain', 'json'],
                        help='set format of output')

    # assign an argument
    args = parser.parse_args()
    return args.first_file, args.second_file, args.format


from typing import TYPE_CHECKING, List, NamedTuple, Optional

import boto3

if TYPE_CHECKING:
    from mypy_boto3_ec2.type_defs import FilterTypeDef

from typing_extensions import TypedDict

from aec.util.config import Config

class Image(TypedDict, total=False):
    Name: Optional[str]
    ImageId: str
    CreationDate: str
    RootDeviceName: Optional[str]
    Size: int
    # optional
    SnapshotId: str

class AmiMatcher(NamedTuple):
    owner: str
    match_string: str

amazon_base_account_id = "137112412989"
canonical_account_id = "099720109477"

ami_keywords = {
    "amazon2": AmiMatcher(amazon_base_account_id, "amzn2-ami-hvm*x86_64-gp2"),
    "ubuntu1604": AmiMatcher(canonical_account_id, "ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64"),
    "ubuntu1804": AmiMatcher(canonical_account_id, "ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64"),
    "ubuntu2004": AmiMatcher(canonical_account_id, "ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64"),
}

def fetch(config: Config, ami: str) -> Image:
    ami_matcher = ami_keywords.get(ami, None)
    if ami_matcher:
        try:
            # lookup the latest ami by name match
            ami_details = describe(config, owner=ami_matcher.owner, name_match=ami_matcher.match_string)[0]
        except IndexError:
            raise RuntimeError(
                f"Could not find ami with name matching {ami_matcher.match_string} owned by account {ami_matcher.owner}"
            )
    else:
        try:
            # lookup by ami id
            ami_details = describe(config, ami=ami)[0]
        except IndexError:
            raise RuntimeError(f"Could not find {ami}")
    return ami_details

def describe(
    config: Config,
    ami: Optional[str] = None,
    owner: Optional[str] = None,
    name_match: Optional[str] = None,
    show_snapshot_id: bool = False,
) -> List[Image]:
    """List AMIs."""

    ec2_client = boto3.client("ec2", region_name=config.get("region", None))

    if ami:
        response = ec2_client.describe_images(ImageIds=[ami])
    else:
        if owner:
            owners_filter = [owner]
        else:
            describe_images_owners = config.get("describe_images_owners", None)

            if not describe_images_owners:
                owners_filter = ["self"]
            elif isinstance(describe_images_owners, str):
                owners_filter = [describe_images_owners]
            else:
                owners_filter: List[str] = describe_images_owners

        if name_match is None:
            name_match = config.get("describe_images_name_match", None)

        filters: List[FilterTypeDef] = [] if name_match is None else [{"Name": "name", "Values": [f"*{name_match}*"]}]

        print(f"Describing images owned by {owners_filter} with name matching {name_match if name_match else '*'}")
        response = ec2_client.describe_images(Owners=owners_filter, Filters=filters)

    images = []
    for i in response["Images"]:
        image: Image = {
            "Name": i.get("Name", None),
            "ImageId": i["ImageId"],
            "CreationDate": i["CreationDate"],
            "RootDeviceName": i["RootDeviceName"] if "RootDeviceName" in i else None,
            "Size": i["BlockDeviceMappings"][0]["Ebs"]["VolumeSize"],
        }
        if show_snapshot_id:
            image["SnapshotId"] = i["BlockDeviceMappings"][0]["Ebs"]["SnapshotId"]
        images.append(image)

    return sorted(images, key=lambda i: i["CreationDate"], reverse=True)

def delete(config: Config, ami: str) -> None:
    """Deregister an AMI and delete its snapshot."""

    ec2_client = boto3.client("ec2", region_name=config.get("region", None))

    response = describe(config, ami, show_snapshot_id=True)

    ec2_client.deregister_image(ImageId=ami)

    ec2_client.delete_snapshot(SnapshotId=response[0]["SnapshotId"])

def share(config: Config, ami: str, account: str) -> None:
    """Share an AMI with another account."""

    ec2_client = boto3.client("ec2", region_name=config.get("region", None))

    ec2_client.modify_image_attribute(
        ImageId=ami,
        LaunchPermission={"Add": [{"UserId": account}]},
        OperationType="add",
        UserIds=[account],
        Value="string",
        DryRun=False,
    )