import wx, os
from pvg_common import previewPanel, options

import wx.lib.newevent
ThumbnailClickedEvt, EVT_THUMBNAIL_CLICKED = wx.lib.newevent.NewCommandEvent()

from wx.lib.filebrowsebutton import FileBrowseButton, DirBrowseButton

class thumbnailPanel(previewPanel):
    """
    A small preview Panel to be used as thumbnail
    """

    def __init__( self, parent, monitor_number, thumbnailSize=(320,240) ):
        previewPanel.__init__(self, parent, size=thumbnailSize, keymode=False)

        self.number = int(monitor_number)
        self.allowEditing = False

        self.displayNumber()

        self.Bind(wx.EVT_LEFT_UP, self.onLeftClick)

    def displayNumber(self):
        """
        """
        # font type: wx.DEFAULT, wx.DECORATIVE, wx.ROMAN, wx.SCRIPT, wx.SWISS, wx.MODERN
        # slant: wx.NORMAL, wx.SLANT or wx.ITALIC
        # weight: wx.NORMAL, wx.LIGHT or wx.BOLD
        #font1 = wx.Font(10, wx.SWISS, wx.ITALIC, wx.NORMAL)
        # use additional fonts this way ...
        pos = int(self.size[0]/2 - 20), int(self.size[1]/2 - 20),
        font1 = wx.Font(35, wx.SWISS, wx.NORMAL, wx.NORMAL)
        text1 = wx.StaticText( self, wx.ID_ANY, '%s' % (self.number+1), pos)
        text1.SetFont(font1)

    def onLeftClick(self, evt):
        """
        Send signal around that the thumbnail was clicked
        """
        event = ThumbnailClickedEvt(self.GetId())

        event.id = self.GetId()
        event.number = self.number
        event.thumbnail = self

        self.GetEventHandler().ProcessEvent(event)

class panelGridView(wx.ScrolledWindow):
    """
    """
    def __init__(self, parent, gridSize, thumbnailSize=(320,240) ):
        """
        """
        wx.ScrolledWindow.__init__(self, parent, wx.ID_ANY, size=(-1,600))
        self.SetScrollbars(1, 1, 1, 1)
        self.SetScrollRate(10, 10)
        self.parent = parent
        self.thumbnailSize = thumbnailSize

        grid_mainSizer = wx.GridSizer(6,3,2,2)

        #Populate the thumbnail grid
        self.previewPanels = []
        for i in range (int(gridSize)):
            self.previewPanels.append ( thumbnailPanel(self, monitor_number=i, thumbnailSize=self.thumbnailSize) )
            grid_mainSizer.Add(self.previewPanels[i])#, 0, wx.EXPAND|wx.FIXED_MINSIZE, 0)

        self.SetSizer(grid_mainSizer)

        self.Bind(EVT_THUMBNAIL_CLICKED, self.onThumbnailClicked)

    def onThumbnailClicked(self, event):
        """
        Relay event to sibling panel
        """
        wx.PostEvent(self.parent.lowerPanel, event)
        event.Skip()

class panelConfigure(wx.Panel):
    """
    """
    def __init__(self, parent):
        """
        """
        wx.Panel.__init__(self, parent, wx.ID_ANY, size=(-1,300), style=wx.SUNKEN_BORDER|wx.TAB_TRAVERSAL)
        self.parent = parent

        self.thumbnail = None
        self.mask_file = None
        self.source = None
        self.sourceType = None
        self.track = None
        self.trackType = None

        lowerSizer = wx.BoxSizer(wx.HORIZONTAL)

        #Static box1 (LEFT)
        sb_1 = wx.StaticBox(self, -1, "Select Monitor")#, size=(250,-1))
        sbSizer_1 = wx.StaticBoxSizer (sb_1, wx.VERTICAL)

        n_monitors = options.GetOption("Monitors")
        self.MonitorList = ['Monitor %s' % (int(m) + 1) for m in range( n_monitors )]
        self.thumbnailNumber = wx.ComboBox(self, -1, size=(-1,-1) , choices=self.MonitorList, style=wx.CB_DROPDOWN | wx.CB_READONLY | wx.CB_SORT)
        self.Bind ( wx.EVT_COMBOBOX, self.onChangingMonitor, self.thumbnailNumber)

        self.currentSource = wx.TextCtrl (self, -1, "No Source Selected", style=wx.TE_READONLY)

        btnSizer_1 = wx.BoxSizer(wx.HORIZONTAL)
        self.btnPlay = wx.Button( self, wx.ID_FORWARD, label="Play")
        self.btnStop = wx.Button( self, wx.ID_STOP, label="Stop")
        self.Bind(wx.EVT_BUTTON, self.onPlay, self.btnPlay)
        self.Bind(wx.EVT_BUTTON, self.onStop, self.btnStop)
        self.btnPlay.Enable(False); self.btnStop.Enable(False)
        self.applyButton = wx.Button( self, wx.ID_APPLY )
        self.applyButton.SetToolTip(wx.ToolTip("Apply and Save to file"))
        self.Bind(wx.EVT_BUTTON, self.onApplySource, self.applyButton)

        btnSizer_1.Add ( self.btnPlay , 0, wx.ALIGN_LEFT|wx.ALL, 5 )
        btnSizer_1.Add ( self.btnStop , 0, wx.ALIGN_CENTER|wx.LEFT|wx.TOP|wx.DOWN, 5 )
        btnSizer_1.Add ( self.applyButton, 0, wx.ALIGN_RIGHT|wx.LEFT|wx.RIGHT|wx.TOP, 5 )

        sbSizer_1.Add ( self.thumbnailNumber, 0, wx.ALIGN_CENTRE|wx.LEFT|wx.RIGHT|wx.TOP, 5 )
        sbSizer_1.Add ( self.currentSource, 0, wx.EXPAND|wx.ALIGN_CENTRE|wx.LEFT|wx.RIGHT|wx.TOP, 5 )
        sbSizer_1.Add ( btnSizer_1, 0, wx.EXPAND|wx.ALIGN_BOTTOM|wx.TOP, 5 )

        lowerSizer.Add (sbSizer_1, 0, wx.EXPAND|wx.ALL, 5)

        #Static box2 (CENTER)
        sb_2 = wx.StaticBox(self, -1, "Select Video input" )
        sbSizer_2 = wx.StaticBoxSizer (sb_2, wx.VERTICAL)
        grid2 = wx.FlexGridSizer( 0, 2, 0, 0 )

        n_cams = options.GetOption("Webcams")
        self.WebcamsList = [ 'Webcam %s' % (int(w) +1) for w in range( n_cams ) ]
        rb1 = wx.RadioButton(self, -1, 'Camera', style=wx.RB_GROUP)
        source1 = wx.ComboBox(self, -1, size=(285,-1) , choices = self.WebcamsList, style=wx.CB_DROPDOWN | wx.CB_READONLY | wx.CB_SORT)
        self.Bind(wx.EVT_COMBOBOX, self.sourceCallback, source1)

        rb2 = wx.RadioButton(self, -1, 'File' )
        source2 = FileBrowseButton(self, -1, labelText='', size=(300,-1), changeCallback = self.sourceCallback)

        rb3 = wx.RadioButton(self, -1, 'Folder' )
        source3 = DirBrowseButton (self, style=wx.DD_DIR_MUST_EXIST, labelText='', size=(300,-1), changeCallback = self.sourceCallback)

        self.controls = []
        self.controls.append((rb1, source1))
        self.controls.append((rb2, source2))
        self.controls.append((rb3, source3))

        for radio, source in self.controls:
            grid2.Add( radio , 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 2 )
            grid2.Add( source , 0, wx.ALIGN_CENTRE|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 2 )
            self.Bind(wx.EVT_RADIOBUTTON, self.onChangeSource, radio )
            source.Enable(False)

        self.controls[0][1].Enable(True)

        #grid2.Add(wx.StaticText(self, -1, ""))

        sbSizer_2.Add( grid2 )
        lowerSizer.Add(sbSizer_2, 0, wx.EXPAND|wx.ALL, 5)

        #Static box3 (RIGHT)
        sb_3 = wx.StaticBox(self, -1, "Set Tracking Parameters")
        sbSizer_3 = wx.StaticBoxSizer (sb_3, wx.VERTICAL)

        sbSizer_31 = wx.BoxSizer (wx.HORIZONTAL)

        self.activateTracking = wx.CheckBox(self, -1, "Activate Tracking")
        self.activateTracking.SetValue(False)
        self.activateTracking.Bind ( wx.EVT_CHECKBOX, self.onActivateTracking)

        self.isSDMonitor = wx.CheckBox(self, -1, "Sleep Deprivation Monitor")
        self.isSDMonitor.SetValue(False)
        self.isSDMonitor.Bind ( wx.EVT_CHECKBOX, self.onSDMonitor)
        self.isSDMonitor.Enable(False)

        sbSizer_31.Add (self.activateTracking, 0, wx.ALIGN_LEFT|wx.LEFT|wx.RIGHT|wx.TOP, 5 )
        sbSizer_31.Add (self.isSDMonitor, 0, wx.ALIGN_LEFT|wx.LEFT|wx.RIGHT|wx.TOP, 5 )

        self.pickMaskBrowser = FileBrowseButton(self, -1, labelText='Mask File')

        #sbSizer_3.Add ( self.activateTracking , 0, wx.ALIGN_LEFT|wx.LEFT|wx.RIGHT|wx.TOP, 5 )
        sbSizer_3.Add ( sbSizer_31 , 0, wx.ALIGN_LEFT|wx.LEFT|wx.RIGHT|wx.TOP, 5 )
        sbSizer_3.Add ( self.pickMaskBrowser , 0, wx.ALIGN_LEFT|wx.LEFT|wx.RIGHT|wx.TOP|wx.EXPAND, 5 )

        #trackingTypeSizer = wx.Sizer(wx.HORIZONTAL)
        self.trackDistanceRadio = wx.RadioButton(self, -1, "Activity as distance traveled", style=wx.RB_GROUP)
        self.trackVirtualBM = wx.RadioButton(self, -1, "Activity as midline crossings count")
        self.trackPosition = wx.RadioButton(self, -1, "Only position of flies")
        sbSizer_3.Add (wx.StaticText ( self, -1, "Calculate fly activity as..."), 0, wx.ALIGN_LEFT|wx.LEFT|wx.RIGHT|wx.TOP, 5 )
        sbSizer_3.Add (self.trackDistanceRadio, 0, wx.ALIGN_LEFT|wx.LEFT|wx.RIGHT|wx.TOP, 2 )
        sbSizer_3.Add (self.trackVirtualBM, 0, wx.ALIGN_LEFT|wx.LEFT|wx.RIGHT|wx.TOP, 2 )
        sbSizer_3.Add (self.trackPosition, 0, wx.ALIGN_LEFT|wx.LEFT|wx.RIGHT|wx.TOP, 2 )

        lowerSizer.Add(sbSizer_3, -1, wx.EXPAND|wx.ALL, 5)

        self.SetSizer(lowerSizer)
        self.Bind(EVT_THUMBNAIL_CLICKED, self.onThumbnailClicked)

    def __getSource(self):
        """
        check which source is ticked and what is the associated value
        """

        for (r, s), st in zip(self.controls,range(3)):
            if r.GetValue():
                source = s.GetValue()
                sourceType = st

        return source, sourceType

    def __getTrackingType(self):
        """
        return which tracking we are chosing
        ['DISTANCE','VBS','XY_COORDS']
        """
        if self.trackDistanceRadio.GetValue(): trackType = "DISTANCE"
        elif self.trackVirtualBM.GetValue(): trackType = "VBS"
        elif self.trackPosition.GetValue(): trackType = "XY_COORDS"

        return trackType

    def onPlay (self, event=None):
        """
        """
        if self.thumbnail:
            self.thumbnail.Play()
            self.btnStop.Enable(True)

    def onStop (self, event=None):
        """
        """
        if self.thumbnail and self.thumbnail.isPlaying:
            self.thumbnail.Stop()
            self.btnStop.Enable(False)

    def onThumbnailClicked(self, evt):
        """
        Picking thumbnail by clicking on it
        """
        self.monitor_number = evt.number + 1
        self.thumbnail = evt.thumbnail
        self.thumbnailNumber.SetValue(self.MonitorList[self.monitor_number -1 ])
        self.updateThumbnail()

    def onChangingMonitor(self, evt):
        """
        Picking thumbnail by using the dropbox
        """
        sel = evt.GetString()
        self.monitor_number = self.MonitorList.index(sel) + 1
        self.thumbnail = self.parent.scrollThumbnails.previewPanels[self.monitor_number]         #this is not very elegant
        self.updateThumbnail()

    def updateThumbnail(self):
        """
        Refreshing thumbnail data
        """
        if options.HasMonitor(self.monitor_number):
            sourceType, source, track, mask_file, trackType, isSDMonitor = options.GetMonitor(self.monitor_number)
        else:
            sourceType, source, track, mask_file, trackType, isSDMonitor = [0, '', False, '', 1, False]

        if sourceType == 0 and source != '':
            source = self.WebcamsList[source]

        self.source = self.thumbnail.source = source
        self.sourceType = self.thumbnail.sourceType = sourceType
        self.thumbnail.track = track
        if self.thumbnail.hasMonitor():
                self.thumbnail.mon.isSDMonitor = isSDMonitor

        #update first static box
        active = self.thumbnail.hasMonitor()
        self.applyButton.Enable ( active )
        self.btnPlay.Enable ( active )
        self.btnStop.Enable ( active and self.thumbnail.isPlaying )

        text = os.path.split(str(self.source))[1] or "No Source Selected"
        self.currentSource.SetValue( text )

        #update second static box
        for radio, src in self.controls:
            src.Enable(False); src.SetValue('')

        radio, src = self.controls[self.sourceType]
        radio.SetValue(True); src.Enable(True)
        src.SetValue(self.source)

        #update third static box
        self.activateTracking.SetValue(self.thumbnail.track)
        self.isSDMonitor.SetValue(isSDMonitor)
        self.pickMaskBrowser.SetValue(mask_file or '')
        [self.trackDistanceRadio, self.trackVirtualBM, self.trackPosition][trackType].SetValue(True)

    def sourceCallback (self, event):
        """
        """
        self.applyButton.Enable(True)

    def onChangeSource(self, event):
        """

        """

        radio_selected = event.GetEventObject()

        for radio, source in self.controls:
            if radio is radio_selected:
                source.Enable(True)
            else:
                source.Enable(False)

        self.applyButton.Enable(True)

    def onApplySource(self, event):
        """
        """

        source, sourceType = self.__getSource()
        track = self.activateTracking.GetValue()
        self.mask_file = self.pickMaskBrowser.GetValue()
        self.trackType = self.__getTrackingType()

        if self.thumbnail:

            if sourceType > 0: camera = source
            else: camera = self.WebcamsList.index(source)

            self.thumbnail.source = camera
            self.thumbnail.sourceType = sourceType

            #Change the source text
            self.currentSource.SetValue( os.path.split(source)[1] )

            #Set thumbnail's source
            self.thumbnail.setMonitor(camera)

            #Enable buttons
            self.btnPlay.Enable(True)
            self.activateTracking.Enable(True)
            self.pickMaskBrowser.Enable(True)

            self.saveMonitorConfiguration()

    def saveMonitorConfiguration(self):
        """
        """

        options.SetMonitor(self.monitor_number,
                           self.thumbnail.sourceType,
                           self.thumbnail.source+1,
                           self.thumbnail.track,
                           self.mask_file,
                           self.trackType,
                           self.thumbnail.mon.isSDMonitor
                           )
        options.Save()

    def onActivateTracking(self, event):
        """
        """
        if self.thumbnail:
            self.thumbnail.track = event.IsChecked()

    def onSDMonitor(self, event):
        """
        """
        if self.thumbnail:
            self.thumbnail.mon.isSDMonitor = event.IsChecked()

class panelOne(wx.Panel):
    """
    Panel number One
    All the thumbnails
    """
    def __init__(self, parent):

        wx.Panel.__init__(self, parent)

        monitor_number = options.GetOption("Monitors")
        tn_size = options.GetOption("ThumbnailSize")

        self.temp_source  = ''
        self.source = ''
        self.sourceType = -1

        self.scrollThumbnails = panelGridView(self, gridSize=monitor_number, thumbnailSize=tn_size)
        self.lowerPanel = panelConfigure(self)

        self.PanelOneSizer = wx.BoxSizer(wx.VERTICAL)
        self.PanelOneSizer.Add(self.scrollThumbnails, 1, wx.EXPAND, 0)
        self.PanelOneSizer.Add(self.lowerPanel, 0, wx.EXPAND, 0)
        self.SetSizer(self.PanelOneSizer)

    def StopPlaying(self):
        """
        """
        self.lowerPanel.onStop()


import subprocess

arguments = [
        ["one", "Error\n"],
        ["2147483648", "Error\n"],
        ["-2147483649", "Error\n"],
        ["1 1", "Error\n"],
        ["1", ""],
        ["1 2", ""],
        ]

def main():

    for x in range(0, len(arguments)):
        expected = arguments[x][1]

        sp = subprocess.Popen(["./push_swap", arguments[x][0]], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = sp.communicate()

        if (err == ""):
            cmd_output = out.decode('utf-8')
        else:
            cmd_output = err.decode('utf-8')

        if (expected != cmd_output):
            print("expected [{0}] | input [{1}] != output [{2}]".format(expected.rstrip('\n'), arguments[x][0].rstrip('\n'), cmd_output.rstrip('\n')))
        else:
            print("passed")

if __name__ == "__main__":
    main()


# When you are done, this program will draw an ellipse
# that travels across the screen when the mouse is pressed.

# ***********  SOUND ***************
# Some computers are unable to play sounds.
# If you cannot play sound on this computer, set canPlaySounds to false.
# If you are not sure, ask your teacher

can_play_sounds = True

def setup():
    global u
    global x
    global a
    global b
    global c
    global d
    global e
    global f
    global g
    global h
    global i
    global j
    global k
    global l
    global m
    global n
    global o
    a=50
    b=50
    c=50
    d=50
    e=50
    f=50
    g=50
    h=50
    i=50
    j=50
    k=50
    l=50
    m=50
    n=50
    o=50

    size(2000, 800)
    x=50
    u=random(800)

    # 1. Set the variable named x to 50.

def draw():
    global x
    global a
    global b
    global c
    global d
    global e
    global f
    global g
    global h
    global i
    global j
    global k
    global l
    global m
    global n
    global o
    background(200, 200, 200)

    # 2. Draw an ellipse of height and width 50. Make sure to use the x variable
    # for its X position. Pick a y value that places it half way down the window.

    fill("#0EE5EA")

    #ellipse(x, 400, 50, 50)
    #ellipse(a, 400, 50, 50)
    #ellipse(b, 400, 50, 50)
    #ellipse(c, 400, 50, 50)
    #ellipse(d, 400, 50, 50)
    #ellipse(e, 400, 50, 50)
    #ellipse(f, 400, 50, 50)
    #ellipse(g, 400, 50, 50)
    #ellipse(h, 400, 50, 50)
    #ellipse(i, 400, 50, 50)
    #ellipse(j, 400, 50, 50)
    #ellipse(k, 400, 50, 50)
    #ellipse(l, 400, 50, 50)
    #ellipse(n, 400, 50, 50)
    #ellipse(m, 400, 50, 50)
    #ellipse(o, 400, 50, 50)

    ellipse(x, 100, 50, 50)

    ellipse(a, 50, 50, 50)
    ellipse(b, 150, 50, 50)
    ellipse(c, 200, 50, 50)
    ellipse(d, 250, 50, 50)
    ellipse(e, 800, 50, 50)
    ellipse(f, 300, 50, 50)
    ellipse(g, u, 50, 50)
    ellipse(h, 400, 50, 50)
    ellipse(i, 450, 50, 50)
    ellipse(j, 500, 50, 50)
    ellipse(k, 550, 50, 50)
    ellipse(l, 600, 50, 50)
    ellipse(n, 650, 50, 50)
    ellipse(m, 700, 50, 50)
    ellipse(o, 750, 50, 50)

    # 3. Fill in the ellipse with a nice color. Remember to put it above the code
    # where you draw the ellipse.
    #if mousePressed:
    x = x + 3.918356
    a = a + 2.19847394813274984
    b=b+2.98275984375439857
    c = c + 5.2
    d=d+4.0194732948123
    e=e+3.120394820394
    f=f+8.199999999999999
    g=g+9.994829304
    h=h+8.19
    i=i+8.11111111
    j=j+3.90956999999999999
    k=k+2.2425
    l=l+2.1982374
    m=m+8.8943
    n=n+8.234789
    o=o+5.324879

    # 4. If the mouse is pressed change the x value so that the dot moves to the right

    # 5. If your dot moves slowly, make it move faster. If it moves too quickly,
    # slow it down (you have to figure out what part of your code to change)

    # 6. Use an if statement to play a sound (ding) when your dot crosses the finish
    if g >= 2000:
        play_sound()
    # line (right side of window). A playSound() method is provided (you have to
    # uncomment the code at the bottom of this program to get this to work)

    sound_played = True

def play_sound():

    # if can_play_sounds:
    #     if sound_played:
    #         Minim minim = new Minim(this)
    #         AudioSample sound = minim.loadSample("ding.wav")
    #         sound.trigger()
    #         soundPlayed = true
    #         pass
    fill(0)
    textSize(36)
    text("WINNER!!", width/2, height/2)


# -*- coding: utf-8 -*-
"""
Created on Sat Jun 20 12:11:45 2020

@author: Syamanthaka
"""

from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from app import app
# import layouts as lyt
import data_n_graphs as grf

@app.callback([Output('output-data-upload', 'children'),
               Output('x-dropdown', 'options'),
               Output('y-dropdown', 'options'),
               Output('data_df', 'children')],
              [Input('upload-data', 'contents')],
              [State('upload-data', 'filename')])
def update_output(contents, filename):
    if contents is not None:
        contents_df, cols, the_df = grf.parse_contents(contents, filename)
        return contents_df, cols, cols, the_df

@app.callback([Output('selected_cols', 'children'),
               Output('output_grf', 'children'),
               Output('main_title', 'placeholder'),
               Output('xtitle', 'placeholder'),
               Output('ytitle', 'placeholder'),
               Output('dd_val', 'value')
               ],
              [Input('data_df', 'children'),
               Input('x-dropdown', 'value'),
               Input('y-dropdown', 'value'),
               Input('grf_typ', 'value'),
               Input('my-color-picker', 'value'),
               Input('main_title', 'value'),
               Input('xtitle', 'value'),
               Input('ytitle', 'value')
              ],
              [State('x-dropdown', 'value'),
               State('y-dropdown', 'value')
              ])
def update_dds(df, x, y, gtyp, sel_color, mtitle_val, xtitle_val, ytitle_val, x_state, y_state):
    if not (x_state and y_state):
        raise PreventUpdate

    main_title = mtitle_val if mtitle_val != '' else x + ' vs ' + y
    xtitle = xtitle_val if xtitle_val != '' else x
    ytitle = ytitle_val if ytitle_val != '' else y

    grf_obj, grf_typ_new =  grf.plot_grf(df, x, y, gtyp, sel_color, main_title, xtitle, ytitle)
    sel_txt = 'You have selected ' + x + ' and ' + y

    return sel_txt, grf_obj, main_title, xtitle, ytitle, grf_typ_new

@app.callback(Output('grf_typ', 'value'),
              [Input('dd_val', 'value')])
def update_bar_type(hidden_val):
    return hidden_val


# coding: utf-8
from typing import List, Dict
from ...dataclass.area import Area
from ...dataclass.area_info import AreaInfo
from .i_rules_area import IRulesArea
from .rule_area_base import RuleAreaBase

class RuleAreaVertical(RuleAreaBase):
    """Matches when there is a vertical parent"""

    def __init__(self, rules: IRulesArea) -> None:
        """constructor"""
        super().__init__(rules=rules)
    # region IRuleArea Methods

    def get_is_match(self, ai: AreaInfo, alst: List[Area]) -> bool:
        """
        Gets if rule is a match

        Args:
            alst (List[Area]): Areas to match
        """
        # vertical matches are when all areas have the sam x1 value:
        # see: https://api.libreoffice.org/docs/idl/ref/servicecom_1_1sun_1_1star_1_1ucb_1_1ContentResultSet.html
        if len(alst) < 2:
            return False
        first = self._get_first_y1(ai=ai, alst=alst)
        if ai.shape:
            # vertical are ofset left or right on x1, Usually right
            # more likley this is a single
            if first.x1 == ai.shape.x1:
                return False
        is_vert = True
        d_lst: Dict[int, List[Area]] = self._list_dict_x1(
            lst=alst)  # grouped by y1
        for area in d_lst[first.x1]:
            if area.x1 != first.x1:
                is_vert = False
                break

        return is_vert

    def get_area(self, ai: AreaInfo, alst: List[Area]) -> List[Area]:
        """
        Gets filtered Area list

        Args:
            alst (List[Area]): Areas to filter

         Returns:
            List[Area]: Filtered Area List
        """
        # remove any duplicates and return list.
        # is it unlikely there would ever be duplicates, but just in case.
        first = self._get_first_y1(ai=ai, alst=alst)
        d_lst: Dict[int, List[Area]] = self._list_dict_x1(
            lst=alst)  # grouped by y1
        # filtering upper by shape or first is a bug fix.
        # in cases such as https://tinyurl.com/yaqul3gs
        # some of child classes have the exact same y1 as the parrent classes
        if ai.shape:
            upper: List[Area] = [
                a for a in d_lst[first.x1] if a.y1 < ai.shape.y1]
        else:
            upper: List[Area] = [
                a for a in d_lst[first.x1] if a.y1 <= first.y1]
        sorted_u = sorted(upper, key=lambda a: a.y1)
        if self.rules.remove_parent_inherited:
            self._remove_duplicates_lst(sorted_u)
        return sorted_u


'''
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.
'''

def largest_palindrome_product(num1, num2):
    i = 0
    result = 0
    isFind = False
    while i < num1:
        for j in range(i // 2 + 1):
            p = (num1 - j) * (num2 - (i - j))
            if p == reverse_int(p):
                result = max(result, p)
                isFind = True
        if isFind:
            break
        i += 1
    return result

def reverse_int(n):
    return int(str(n)[::-1])

print(largest_palindrome_product(999, 999))


#! -*- coding: utf-8 -*-

def keeptags(value, tags):
    """
    Strips all [X]HTML tags except the space seperated list of tags
    from the output.

    Usage example: keeptags(html, "strong em ul li")
    """
    import re
    from django.utils.html import strip_tags, escape
    tags = [re.escape(tag) for tag in tags.split()]
    tags_re = '(%s)' % '|'.join(tags)
    singletag_re = re.compile(r'<(%s\s*/?)>' % tags_re)
    starttag_re = re.compile(r'<(%s)(\s+[^>]+)>' % tags_re)
    endtag_re = re.compile(r'<(/%s)>' % tags_re)
    value = singletag_re.sub('##~~~\g<1>~~~##', value)
    value = starttag_re.sub('##~~~\g<1>\g<3>~~~##', value)
    value = endtag_re.sub('##~~~\g<1>~~~##', value)
    value = strip_tags(value)
    recreate_re = re.compile('##~~~([^~]+)~~~##')
    value = recreate_re.sub('<\g<1>>', value)
    return value


from flask import Flask, request, jsonify

app = Flask(__name__)

from filterLib.curse_detector import CurseDetector

@app.route('/')
def hello_world():
    return 'Hello World!'

@app.route('/text', methods=["POST"])
def check_text():
    curse = CurseDetector()
    body = request.json
    text = body['text']

    result = curse.predict(text)
    returnArr = []
    cnt = 0

    for i in result:
        if i[1] > 0.9:
            returnArr.append('true')
            cnt += 1
            continue

        returnArr.append('false')
        cnt += 1

    return jsonify(
        data=returnArr
    )

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


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

import os
import sys
import time
import numpy as np

from utils import parse_listfile

def parse_pairwise_score(pairwise_score):
    lines = parse_listfile(pairwise_score, [1, 2, 3])
    pairs, scores = [], []
    for i in lines:
        pairs.append((i[0], i[1]))
        scores.append(i[2])
    return pairs, scores

def parse_pair(pairlist):
    return parse_listfile(pairlist, [1, 2])

def main(lindahl_pairwise_score, lindahl_family, lindahl_superfamily, lindahl_fold):
    start = time.clock()
    # score dict
    pairs, scores = parse_pairwise_score(lindahl_pairwise_score)

    # lindahl data
    lindahl_family = parse_pair(lindahl_family)
    lindahl_superfamily = parse_pair(lindahl_superfamily)
    lindahl_fold = parse_pair(lindahl_fold)
    assert len(lindahl_family) == 1646 and len(lindahl_superfamily) == 2130 and len(lindahl_fold) == 3662

    # label +1 or -1 for scores
    fout_family = open('value-family', 'w')
    fout_superfamily = open('value-superfamily', 'w')
    fout_fold = open('value-fold', 'w')
    for i, p in enumerate(pairs):
        if not (i+1) % 100:
            print('.', end='', file=sys.stderr)
        if not (i+1) % 10000:
            print(i+1, file=sys.stderr)
        if p in lindahl_family:
            print('+1', scores[i], file=fout_family)
        elif p in lindahl_superfamily:
            print('+1', scores[i], file=fout_superfamily)
        elif p in lindahl_fold:
            print('+1', scores[i], file=fout_fold)
        else:
            print('-1', scores[i], file=fout_family)
            print('-1', scores[i], file=fout_superfamily)
            print('-1', scores[i], file=fout_fold)
    fout_family.close()
    fout_superfamily.close()
    fout_fold.close()

    stop = time.clock()
    print('Time Spent =', stop - start)

if __name__ == '__main__':
    if len(sys.argv) != 2:
        sys.exit('Usage: %s <lindahl_pairwise_score>' % sys.argv[0])
    lindahl_pairwise_score = sys.argv[1]

    prefix = os.path.dirname(sys.argv[0])
    lindahl_family = '%s/list/lindahl_family' % prefix
    lindahl_superfamily = '%s/list/lindahl_superfamily' % prefix
    lindahl_fold = '%s/list/lindahl_fold' % prefix

    main(lindahl_pairwise_score, lindahl_family, lindahl_superfamily, lindahl_fold)


import urllib.request, json
from bs4 import BeautifulSoup

user_id = list()

def get_id():

    username = str(input('Enter username: '))

    data = urllib.request.urlopen(f'https://users.roblox.com/v1/users/search?keyword={username}&limit=10')
    data_load = json.loads(data.read().decode())

    for dic in data_load['data']:
        user_id.append(dic['id'])

def get_info():

    data = urllib.request.urlopen(f'https://users.roblox.com/v1/users/{user_id[0]}')
    data_load = json.loads(data.read().decode())


import io
import sys

_INPUT = """\
6
4 10
4 2 3 2
20 100
29 31 68 20 83 66 23 84 69 96 41 61 83 37 52 71 18 55 40 8
"""

sys.stdin = io.StringIO(_INPUT)
case_no=int(input())
for __ in range(case_no):
  #Kruskal法 max_vに頂点数,edgesに辺(重み、結んでいる２つの頂点（順不同）で入れる)
  class UnionFind():
    def __init__(self, n):
      self.n = n
      self.parents = [-1] * n
    def find(self, x):
      if self.parents[x] < 0:
        return x
      else:
        self.parents[x] = self.find(self.parents[x])
        return self.parents[x]
    def union(self, x, y):
      x = self.find(x)
      y = self.find(y)
      if x == y:
        return
      if self.parents[x] > self.parents[y]:
        x, y = y, x
      self.parents[x] += self.parents[y]
      self.parents[y] = x
    def size(self, x):
      return -self.parents[self.find(x)]
    def same(self, x, y):
      return self.find(x) == self.find(y)
    def members(self, x):
      root = self.find(x)
      return [i for i in range(self.n) if self.find(i) == root]
    def roots(self):
      return [i for i, x in enumerate(self.parents) if x < 0]
    def group_count(self):
      return len(self.roots())
    def all_group_members(self):
      return {r: self.members(r) for r in self.roots()}
    def __str__(self):
      return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
  def Kruskal(G):
    edges=set()
    for i in range(len(G)):
      for j in range(len(G[i])):
        c,k=G[i][j]
        l,m=min(i,k),max(i,k)
        edges.add((c,l,m))
    edges=list(edges)
    edges.sort()
    uf = UnionFind(len(G))
    mst = [] #最小全域木の辺すべて
    weight=0 #最小全域木の重さ
    for edge in edges:
      if not uf.same(edge[1], edge[2]):
        uf.union(edge[1], edge[2])
        mst.append(edge)
        weight+=edge[0]
    return mst,weight

  N,M=map(int,input().split())
  A=list(map(int,input().split()))
  score=[(pow(A[i],A[j],M)+pow(A[j],A[i],M))%M for i in range(N) for j in range(N)]
  G=[[] for _ in range(N)]
  for i in range(N):
    for j in range(i+1,N):
      G[i].append((-score[i*N+j],j))
      G[j].append((-score[i*N+j],i))
  print(-Kruskal(G)[1])


# this is a line comment

'''
this is a docstring
'''

"""
python is space sensative

Errors
syntaxerror is something wrong with the way your program is written
a nameerror occurs when the python interpreter sees a word it does not recognize
typeerror is an error thrown when an operation is applied to an object of an inappropriate type
logic error is an error found by the programmer when the program isn’t doing what it is intending to do
"""

# STRINGS
string_variable = "string 1"
string_variable_2 = 'string 1'
string_variable_2+=" and string 2"
# print(string_variable_2)

# NUMBERS
integer_variable = 5
float_variable = 4.1

# TYPES AND CASTING
# python has the following data types built-in by default, in these categories:
# text type:	str
# numeric types:	int, float, complex
# sequence types:	list, tuple, range
# mapping type:	dict
# set types:	set, frozenset
# boolean type:	bool
# binary types:	bytes, bytearray, memoryview
# none type:	nonetype

type_variable = 9
# print(type(type_variable))
# print(type_variable)
type_variable = str(type_variable)
# print(type(type_variable))
# print(type_variable)
type_variable = float(type_variable)
# print(type(type_variable))
# print(type_variable)

# CALULATIONS
# +, -, *, **, /, //, %,
# print("5 + 2")
# print(5 + 2)
# print("5 - 2")
# print(5 - 2)
# print("5 * 2")
# print(5 * 2)
# print("5 ** 2")
# print(5 ** 2)
# print("10 / 7")  # python converts all ints to floats before performing division
# print(10 / 7)
# print("10 // 7")  # floor division
# print(10 // 7)
# print("12 % 10")
# print(12 % 10)

# BOOLEAN VARIABLES
boolean_true = True
boolean_false = False

# BOOLEAN EXPRESSIONS
boolean_var_1 = 3 != 3
boolean_var_2 = (3 - 3) == 0
boolean_var_3 = 1
boolean_var_4 = 0

# PYTHON OPERATORS PRECEDENCE RULE
# P – Parentheses
# E – Exponentiation
# M – Multiplication
# D – Division
# A – Addition
# S – Subtraction

# RELATIONAL OPERATORS
# == , !=, >, <, >=, <=

# CONTROL FLOW
# if, elif, else statement
# if (5 > 5):
#     print(5)
# if (10 > 5):
#     print(10)
# if (10 != 5):
#     print(10)

user_name = "Foo"
# if user_name == "Foo":
#     print("user_name was true")
# elif user_name == "Bar":
#     print("Bar was True")
# elif user_name == "Baz":
#     print("Baz was True")
# else:
#     print("All False")

# BOOLEAN OPERATORS
# if user_name == "Foo" and 3 == 3:
#     print("true")
#
# if user_name == "Bar" or 3 == 3:
#     print("true")

not_boolean = not 1 + 1 == 2  # prints opposite
# print(not_boolean)

little_string = "and"
big_string = 'amanda'
# if little_string in big_string:
    # print(True)


from datetime import datetime
import logging
from os import path

from flask import current_app as app
from saml2 import BINDING_HTTP_POST
from saml2 import xmldsig
from saml2.client import Saml2Client
from saml2.config import Config as Saml2Config
from saml2.validate import ResponseLifetimeExceed

from pcapi import settings
from pcapi.core.users import constants
from pcapi.core.users import models as user_models

from . import exceptions
from . import models

logger = logging.getLogger(__name__)

BASEDIR = path.dirname(path.abspath(__file__))
FILES_DIR = "files"
PRIVATE_KEY_FILE_PATH = path.join(BASEDIR, f"{FILES_DIR}/private.key")
PUBLIC_CERTIFICATE_FILE_PATH = path.join(BASEDIR, f"{FILES_DIR}/public.cert")

with open(PUBLIC_CERTIFICATE_FILE_PATH, "w") as certificate_file:
    certificate_file.write(settings.EDUCONNECT_SP_CERTIFICATE)
with open(PRIVATE_KEY_FILE_PATH, "w") as key_file:
    key_file.write(settings.EDUCONNECT_SP_PRIVATE_KEY)

def get_saml_client() -> Saml2Client:
    entityid = f"{settings.API_URL_FOR_EDUCONNECT}/saml/metadata.xml"
    https_acs_url = f"{settings.API_URL_FOR_EDUCONNECT}/saml/acs/"

    config = {
        "entityid": entityid,
        "metadata": {
            "local": [
                path.join(BASEDIR, f"{FILES_DIR}/educonnect.{'production' if settings.IS_PROD else 'pr4'}.metadata.xml")
            ],
        },
        "service": {
            "sp": {
                "endpoints": {
                    "assertion_consumer_service": [(https_acs_url, BINDING_HTTP_POST)],
                },
                "allow_unsolicited": True,
                "authn_requests_signed": True,
                "logout_requests_signed": True,
                "want_assertions_signed": True,
                "want_response_signed": True,
            }
        },
        "signing_algorithm": xmldsig.SIG_RSA_SHA256,
        "digest_algorithm": xmldsig.DIGEST_SHA256,
        "cert_file": PUBLIC_CERTIFICATE_FILE_PATH,
        "key_file": PRIVATE_KEY_FILE_PATH,
        "encryption_keypairs": [
            {"key_file": PRIVATE_KEY_FILE_PATH, "cert_file": PUBLIC_CERTIFICATE_FILE_PATH}  # private part
        ],
    }

    saml2_config = Saml2Config()
    saml2_config.load(config)
    saml2_config.allow_unknown_attributes = True

    saml2_client = Saml2Client(config=saml2_config)

    return saml2_client

def get_login_redirect_url(user: user_models.User) -> str:
    saml_client = get_saml_client()
    saml_request_id, info = saml_client.prepare_for_authenticate()

    logger.info(
        "Sending saml login request with educonnect request_id = %s", saml_request_id, extra={"user_id": user.id}
    )
    key = build_saml_request_id_key(saml_request_id)
    app.redis_client.set(name=key, value=user.id, ex=constants.EDUCONNECT_SAML_REQUEST_ID_TTL)

    redirect_url = next(header[1] for header in info["headers"] if header[0] == "Location")
    return redirect_url

def get_educonnect_user(saml_response: str) -> models.EduconnectUser:
    saml_client = get_saml_client()
    try:
        authn_response = saml_client.parse_authn_request_response(saml_response, BINDING_HTTP_POST)
    except ResponseLifetimeExceed as exception:
        logger.error("Educonnect response more than 10 minutes old: %s", exception)
        raise exceptions.ResponseTooOld()
    except Exception as exception:
        logger.error("Impossible to parse educonnect saml response: %s", exception)
        raise exceptions.EduconnectAuthenticationException()

    educonnect_identity = authn_response.get_identity()

    saml_request_id = authn_response.in_response_to

    try:
        return models.EduconnectUser(
            connection_datetime=datetime.strptime(educonnect_identity[_get_field_oid("6")][0], "%Y-%m-%d %H:%M:%S.%f"),
            birth_date=datetime.strptime(educonnect_identity[_get_field_oid("67")][0], "%Y-%m-%d").date(),
            educonnect_id=educonnect_identity[_get_field_oid("57")][0],
            first_name=educonnect_identity["givenName"][0],
            ine_hash=educonnect_identity[_get_field_oid("64")][0],
            last_name=educonnect_identity["sn"][0],
            logout_url=educonnect_identity[_get_field_oid("5")][0],
            saml_request_id=saml_request_id,
            student_level=educonnect_identity.get(_get_field_oid("73"), [None])[0],
        )
    except KeyError as exception:
        logger.error(
            "Key error raised when parsing educonnect saml response: %s",
            repr(exception),
            extra={"saml_request_id": saml_request_id},
        )
        raise exceptions.ParsingError()
    except Exception as exception:
        logger.error(
            "Error when parsing educonnect saml response: %s",
            repr(exception),
            extra={"saml_request_id": saml_request_id},
        )
        raise exceptions.ParsingError()

def _get_field_oid(oid_key: str) -> str:
    return f"urn:oid:1.3.6.1.4.1.20326.10.999.1.{oid_key}"

def build_saml_request_id_key(saml_request_id: str) -> str:
    return f"educonnect-saml-request-{saml_request_id}"


from django.template import Library

from snpdb.forms import ProjectChoiceForm, VariantsTypeMultipleChoiceForm
from snpdb.models import GenomeBuild, VariantsType
from snpdb.templatetags.jqgrid_tags import get_grid_id

register = Library()

@register.inclusion_tag("snpdb/tags/vcf_grid_filter_tags.html", takes_context=True)
def vcf_grid_filter(context, grid_id_suffix, variants_type=False):
    grid_id = get_grid_id(grid_id_suffix)
    # ProjectChoiceForm is shown twice (Samples and VCF) so we need to alter the IDs
    project_form = ProjectChoiceForm()
    project_form.fields["project"].widget.attrs["id"] = f"id_project_{grid_id}"

    context = {
        'grid_id': grid_id,
        "project_form": project_form,
        "genome_builds": GenomeBuild.builds_with_annotation(),
    }

    if variants_type:
        vt_initial = {"variants_type": [c[0] for c in VariantsType.choices]}
        context["variants_type_form"] = VariantsTypeMultipleChoiceForm(initial=vt_initial)
        context["variants_type_labels"] = dict(VariantsType.choices)

    return context


"""
QML task on noisy PQC with vmapped Monte Carlo noise simulation
"""

import os

os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"
# one need this for jax+gpu combination in some cases
import time
import tensorflow as tf
import numpy as np
import optax
import tensorcircuit as tc

K = tc.set_backend("jax")

# numpy data
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train[..., np.newaxis] / 255.0

def filter_pair(x, y, a, b):
    keep = (y == a) | (y == b)
    x, y = x[keep], y[keep]
    y = y == a
    return x, y

datapoints = 200
batch = 32
logfile = "qml_param_v2.npy"
n = 9
m = 4
maxiter = 5000
data_preparation = "v1"

x_train, y_train = filter_pair(x_train, y_train, 0, 1)

if data_preparation == "v1":
    x_train = tf.image.resize(x_train, (int(np.sqrt(n)), int(np.sqrt(n)))).numpy()
    x_train = np.array(x_train > 0.5, dtype=np.float32)
    x_train = np.squeeze(x_train).reshape([-1, n])

else:  # "v2"
    from sklearn.decomposition import PCA

    x_train = PCA(n).fit_transform(x_train.reshape([-1, 28 * 28]))

mnist_data = (
    tf.data.Dataset.from_tensor_slices((x_train[:datapoints], y_train[:datapoints]))
    .repeat(maxiter)
    .shuffle(datapoints)
    .batch(batch)
)

def f(param, seed, x, pn):
    c = tc.Circuit(n)
    px, py, pz = pn, pn, pn
    for i in range(n):
        if data_preparation == "v1":
            c.rx(i, theta=x[i] * np.pi / 2)
        else:
            c.rx(i, theta=K.atan(x[i]))
    for j in range(m):
        for i in range(n - 1):
            c.cx(i, i + 1)
            c.depolarizing(i, px=px, py=py, pz=pz, status=seed[j, i, 0])
            c.depolarizing(i + 1, px=px, py=py, pz=pz, status=seed[j, i, 1])
        for i in range(n):
            c.rz(i, theta=param[j, i, 0])
        for i in range(n):
            c.rx(i, theta=param[j, i, 1])

    ypreds = K.convert_to_tensor([K.real(c.expectation_ps(z=[i])) for i in range(n)])

    return K.mean(ypreds)

vf = tc.utils.append(K.vmap(f, vectorized_argnums=1), K.mean)

def loss(param, scale, seeds, x, y, pn):
    ypred = vf(param, seeds, x, pn)
    ypred = K.sigmoid(scale * ypred)
    y = K.cast(y, "float32")
    return (
        K.real(-y * K.log(ypred) - (1 - y) * K.log(1 - ypred)),
        ypred,
    )

def acc(yps, ys):
    yps = K.numpy(yps)
    ys = K.numpy(ys)
    yps = (np.sign(yps - 0.5) + 1) / 2
    return 1 - np.mean(np.logical_xor(ys, yps))

vgloss = K.jit(K.vvag(loss, argnums=(0, 1), vectorized_argnums=(3, 4), has_aux=True))
vloss = K.jit(K.vmap(loss, vectorized_argnums=(3, 4)))

def train(param=None, scale=None, noise=0, noc=1, fixed=True, val_step=40):
    times = []
    val_times = []
    if param is None:
        param = K.implicit_randn([m, n, 2])
    if scale is None:
        scale = 15.0 * K.ones([], dtype="float32")
    else:
        scale *= K.ones([], dtype="float32")
    if K.name == "jax":
        opt = K.optimizer(optax.adam(1e-2))
        opt2 = K.optimizer(optax.adam(5e-2))
    else:
        opt = K.optimizer(tf.keras.optimizers.Adam(1e-2))
        opt2 = K.optimizer(tf.keras.optimizers.Adam(5e-2))
    pn = noise * K.ones([], dtype="float32")

    try:
        for i, (xs, ys) in zip(range(maxiter), mnist_data):  # using tf data loader here
            xs, ys = tc.array_to_tensor(xs.numpy(), ys.numpy())
            seeds = K.implicit_randu([noc, m, n, 2])
            time0 = time.time()
            _, grads = vgloss(param, scale, seeds, xs, ys, pn)
            time1 = time.time()
            times.append(time1 - time0)
            param = opt.update(grads[0], param)
            if fixed is False:
                scale = opt2.update(grads[1], scale)
            if i % val_step == 0:
                print("%s round" % str(i))
                print("scale: ", K.numpy(scale))
                time0 = time.time()
                inference(param)
                time1 = time.time()
                val_times.append(time1 - time0)
                if len(times) > 1:
                    print("batch running time est.: ", np.mean(times[1:]))
                    print("batch staging time est.: ", times[0])
                if len(val_times) > 1:
                    print("full set running time est.: ", np.mean(val_times[1:]))
                    print("full set staging time est.: ", val_times[0])
    except KeyboardInterrupt:
        pass

    np.save(logfile, K.numpy(param))
    return param

def inference(param=None, scale=None, noise=0, noc=1, debug=False):
    pn = noise * K.ones([], dtype="float32")
    if param is None:
        param = np.load(logfile)
    if scale is None:
        scale = 15.0 * K.ones([], dtype="float32")
    else:
        scale *= K.ones([], dtype="float32")
    seeds = K.implicit_randu([noc, m, n, 2])
    vs, yps = vloss(
        param,
        scale,
        seeds,
        tc.array_to_tensor(x_train[:datapoints]),
        tc.array_to_tensor(y_train[:datapoints]),
        pn,
    )
    if debug:
        print(yps)
    print("loss: ", K.mean(vs))
    print("acc on training: %.4f" % acc(yps, y_train[:datapoints]))

if __name__ == "__main__":
    train(noise=0.005, scale=30, noc=100, fixed=False)
    # inference(noise=0.01, noc=1000, scale=40, debug=True)


# Dump the schema of a database created by using sqlalchemy
# code modified from:
# https://stackoverflow.com/questions/40619434/dump-postgresql-database-schema-with-python
# You can visualize the schema by using MySQLWorkbench:
# https://dev.mysql.com/downloads/workbench/
import io
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import sessionmaker

class SchemaDump(object):
    def __init__(self, db_url, schema_file_path):
        self.db_url = db_url
        self.schema_file_path = schema_file_path
        self.buf = io.BytesIO()

    def dump_shema(self):
        engine = create_engine(self.db_url)
        metadata = MetaData()
        metadata.reflect(engine)

        def dump(sql, *multiparams, **params):
            f = sql.compile(dialect=engine.dialect)
            self.buf.write(str(f).strip().encode())
            self.buf.write(str(';\n').encode())

        new_engine = create_engine(self.db_url, strategy='mock', executor=dump)
        metadata.create_all(new_engine, checkfirst=True)

        with io.open(self.schema_file_path, 'wb+') as schema:
            schema.write(self.buf.getvalue())

sd = SchemaDump("sqlite:///database.db", "schema.sql")
sd.dump_shema()
print("Schema created.")


import os
import sys
import click

import pandas as pd

from plotnine import ggplot, aes, geom_point, labs, ggsave
from sklearn.decomposition import PCA
from mlhub.pkg import get_cmd_cwd

# Ensure paths are relative to the user's cwd

os.chdir(get_cmd_cwd())

@click.command()
@click.argument('csvfile',
                type=click.File('r'),
                default=sys.stdin)
@click.option("-l", "--label",
              default="label",
              help="identify the label column")
@click.option("-o", "--output",
              default="output not given",
              help="png/pdf to save output, will print if none given")
def cli(csvfile, label, output):
    # Quit if there is no data to read

    try:
        df = pd.read_csv(csvfile)
    except pd.errors.EmptyDataError:
        click.echo("No data available.")
        sys.exit(1)

    # Return error and quit if label column is not able to be found

    if label not in df.columns:
        click.echo("Column with label not identified")
        sys.exit(1)

    # Line of dots if data is one dimension

    if len(df.columns) == 2:
        # Find the non-label column

        header_1_col = list(df.columns.values)
        header_1_col.remove(label)
        p = (ggplot(df) +
             aes(x=header_1_col[0], y=label, color=f"factor({label})") +
             labs(color="Cluster") +
             geom_point())

    # Scatter plot if data is two dimensions

    elif len(df.columns) == 3:

        # Find the non-label columns

        header_2_col = list(df.columns.values)
        header_2_col.remove(label)
        p = (ggplot(df) +
             aes(x=header_2_col[0],
                 y=header_2_col[1],
                 color=f"factor({label})") +
             labs(color="Cluster") +
             geom_point())

    # Perform PCA if there are 2+ dimensions and visualise the 2 most
    # significant components

    else:
        pca = PCA(n_components=2)

        # Remove the label column for PCA

        df_for_pca = df.drop([label], axis=1)
        principal_components = pca.fit_transform(df_for_pca)
        principal_components
        principal_df = pd.DataFrame(data=principal_components,
                                    columns=['PC 1', 'PC 2'])
        principal_label_df = pd.concat([principal_df,
                                        df[[label]]],
                                       axis=1)
        p = (ggplot(principal_label_df) +
             aes(x="PC 1", y="PC 2", color=f"factor({label})") +
             labs(color="Cluster") +
             geom_point())

    if output == "output not given":
        print(p)
    else:
        if output[-3] == '.png':
            ggsave(plot=p, filename=output)
        if output[-3] == '.pdf':
            ggsave(plot=p, filename=output)
        else:
            ggsave(plot=p, filename=output + '.png')

if __name__ == "__main__":
    cli(prog_name="visualise")


'''
https://adventofcode.com/2021/day/6
'''
DAY = 6

from utils import *
from collections import Counter, deque

def parser(test=False):
    input = Input(DAY, 2021, test=test, line_parser=integers)[0]
    return Counter(input)

def part1(input, N_days=80):
    fish_stages = deque([])
    for i in range(9):
        fish_stages.append(input[i])

    for _ in range(N_days):
        born = fish_stages.popleft()
        # Add the recent parents to stage 6
        fish_stages[6] += born
        # Add the newborns to stage 8
        fish_stages.append(born)

    return sum(fish_stages)

def part2(input):
    return part1(input, N_days=256)

def main():
    input = parser()
    print('RESULTS')

    result_1 = part1(input)
    print(f'Part 1: {result_1}')

    result_2 = part2(input)
    print(f'Part 2: {result_2}')

if __name__ == "__main__":
    test(DAY, parser, part1, [5934], part2, [26984457539])
    main()


import sys
if "win" in sys.platform:
    IS_ON_RASPI = False  # 运行在windows上
else:
    IS_ON_RASPI = True  # 运行在raspi上

if IS_ON_RASPI:
    import os, sys
    # os.close(sys.stderr.fileno())  # 关闭错误std流

CHIRP_LENGTH = 0.1
KWS_FRAME_LENGTH = 0.2  # 关键词识别长度
MUTE_PERIOD_LENGTH = 5  # 停止干扰时长
LOWEST_F = 100  # 最低频率
NOISE_NUM = 200  # 噪声组合个数

IN_FS = 48000  # 麦克风采样率
IN_CHANNEL = 1  # 麦克风输入通道数，这里先不要改
IN_BIT_DEPTH = 16  # 麦克风采样位深
IN_DEVICE_KEYWORD = "snd_rpi_i2s_card" if IS_ON_RASPI else "WO Mic"  # 声卡名称，None表示使用默认输入设备
IN_HOST_API = 0 if IS_ON_RASPI else 1  # 输入设备的host api
IN_FRAMES_PER_BUFFER = 2048 * 8  # 每次输入声音长度

OUT_FS = 96000  # 扬声器采样率
OUT_CHANNEL = 1  # 扬声器输出通道数
OUT_BIT_DEPTH = 16  # 扬声器采样位深
OUT_DEVICE_KEYWORD = "USB Audio" if IS_ON_RASPI else "USB-C"  # 声卡名称
OUT_HOST_API = 0 if IS_ON_RASPI else 1  # 输出设备的host api
OUT_FRAMES_PER_BUFFER = int((CHIRP_LENGTH +
                         1 / LOWEST_F * NOISE_NUM) * OUT_FS)  # 每次输出声音长度


'''
날짜:  2022.09.11
시간복잡도: O(N+M)

문제:
풀이:
16:55 ~ 17:05

1. dict로 선언해두고 있는지 없는지 봐도 될듯? O(N+M)
2. set()에 넣어서 보면될듯 O(N)
3. 이진탐색은 정렬해야하므로 O(NlogN)
    + 탐색(logN)xM개
    = NlogN + MlogN = (N+M)logN

set -> dictionary -> 이진탐색

테스트 값
5
8 3 7 9 2
3
5 7 9
'''
import sys
input = sys.stdin.readline

n = int(input())
arr = list(map(int, input().split()))
m = int(input())
find_num = list(map(int,input().split()))

dict_num = dict()
for i in arr:
    if i not in dict_num:
        dict_num[i] = 1

for i in find_num:
    if i in dict_num:
        print("yes", end=' ')
    else:
        print("no",end=' ')


"""Test support code for testing gomill GTP engines.

(Which includes proxy engines.)

"""

def check_engine(tc, engine, command, args, expected,
                 expect_failure=False, expect_end=False,
                 expect_internal_error=False):
    """Send a command to an engine and check its response.

    tc                    -- TestCase
    engine                -- Gtp_engine_protocol
    command               -- GTP command to send
    args                  -- list of GTP arguments to send
    expected              -- expected response string (None to skip check)
    expect_failure        -- expect a GTP failure response
    expect_end            -- expect the engine to report 'end session'
    expect_internal_error -- see below

    If the response isn't as expected, uses 'tc' to report this.

    If expect_internal_error is true, expect_failure is forced true, and the
    check for expected (if specified) is that it's included in the response,
    rather than equal to the response.

    """
    failure, response, end = engine.run_command(command, args)
    if expect_internal_error:
        expect_failure = True
    if expect_failure:
        tc.assertTrue(failure,
                      "unexpected GTP success response: %s" % response)
    else:
        tc.assertFalse(failure,
                       "unexpected GTP failure response: %s" % response)
    if expect_internal_error:
        tc.assertTrue(response.startswith("internal error\n"), response)
        if expected is not None:
            tc.assertTrue(expected in response, response)
    elif expected is not None:
        if command == "showboard":
            tc.assertDiagramEqual(response, expected,
                                  "showboard response not as expected")
        else:
            tc.assertEqual(response, expected, "GTP response not as expected")
    if expect_end:
        tc.assertTrue(end, "expected end-session not seen")
    else:
        tc.assertFalse(end, "unexpected end-session")


# Write a function to calculate the area of a rectangle where length and breadth are passed to the function as argument.

def areaofrect(l,b):

    area = l*b
    return area

l = int(input("length: "))
b = int((input("breadth: ")))

print(areaofrect(l,b))


import copy
import json
import os
import warnings
from absl import app, flags

import torch
from tensorboardX import SummaryWriter
from torchvision.datasets import CIFAR10
from torchvision.datasets import ImageFolder
from torchvision.utils import make_grid, save_image
from torchvision import transforms
from tqdm import trange
import torch.distributed as dist

from diffusion import GaussianDiffusionTrainer, GaussianDiffusionSampler
from model import UNet

FLAGS = flags.FLAGS
flags.DEFINE_enum('dataset', 'cifar10', ['cifar10', 'imagenet64'], help='dataset')
# UNet
flags.DEFINE_integer('ch', 128, help='base channel of UNet')
flags.DEFINE_multi_integer('ch_mult', [1, 2, 2, 2], help='channel multiplier')
flags.DEFINE_multi_integer('attn', [1], help='add attention to these levels')
flags.DEFINE_integer('num_res_blocks', 2, help='# resblock in each level')
flags.DEFINE_float('dropout', 0.1, help='dropout rate of resblock')
# Gaussian Diffusion
flags.DEFINE_integer('T', 1024, help='total diffusion steps')
flags.DEFINE_integer('time_scale', 1, help='total diffusion steps')
flags.DEFINE_enum('mean_type', 'xstart', ['xstart', 'epsilon'], help='predict variable')
flags.DEFINE_enum('var_type', 'fixedlarge', ['fixedlarge', 'fixedsmall'], help='variance type')
flags.DEFINE_enum('loss_type', 'both', ['x', 'eps', 'both'], help='loss type')
# Training
flags.DEFINE_float('lr', 2e-4, help='target learning rate')
flags.DEFINE_float('wd', 0.001, help='target learning rate')
flags.DEFINE_float('grad_clip', 1., help="gradient norm clipping")
flags.DEFINE_integer('total_steps', 800000, help='total training steps')
flags.DEFINE_integer('img_size', 32, help='image size')
flags.DEFINE_integer('warmup', 5000, help='learning rate warmup')
flags.DEFINE_integer('batch_size', 128, help='batch size')
flags.DEFINE_integer('num_workers', 4, help='workers of Dataloader')
flags.DEFINE_float('ema_decay', 0.9999, help="ema decay rate")
flags.DEFINE_string('gpu_id', '4,5,6,7', help='multi gpu training')
flags.DEFINE_integer('local_rank', 0, help='local rank')
flags.DEFINE_bool('distributed', False, help='multi gpu training')
flags.DEFINE_integer('num_gpus', 4, help='multi gpu training')
flags.DEFINE_bool('conditional', False, help='use conditional or not')
flags.DEFINE_integer('class_num', 10, help='class num')
# Logging & Sampling
flags.DEFINE_string('logdir', './logs/CIFAR10/1024', help='log directory')
flags.DEFINE_integer('sample_size', 64, "sampling size of images")
flags.DEFINE_integer('sample_step', 1000, help='frequency of sampling')
flags.DEFINE_integer('save_step', 1000, help='frequency of saving checkpoints, 0 to disable during training')

def ema(source, target, decay):
    source_dict = source.state_dict()
    target_dict = target.state_dict()
    for key in source_dict.keys():
        target_dict[key].data.copy_(
            target_dict[key].data * decay +
            source_dict[key].data * (1 - decay))

def infiniteloop(dataloader):
    while True:
        for x, y in iter(dataloader):
            yield x, y

def get_rank():
    if not dist.is_available():
        return 0
    if not dist.is_initialized():
        return 0
    return dist.get_rank()

def warmup_lr(step):
    return min(step, FLAGS.warmup) / FLAGS.warmup

def train():
    if get_rank() == 0:
        if not os.path.exists(os.path.join(FLAGS.logdir, 'ddim_clip')):
            os.makedirs(os.path.join(FLAGS.logdir, 'ddim_clip'))
    # dataset
    if FLAGS.dataset == 'cifar10':
        dataset = CIFAR10(
            root='../../data', train=True, download=True,
            transform=transforms.Compose([
                transforms.RandomHorizontalFlip(),
                transforms.ToTensor(),
                transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
            ]))
    elif FLAGS.dataset == 'imagenet64':
        dataset = ImageFolder(
            '../../data/ImageNet64/train',
            transforms.Compose([
                transforms.RandomHorizontalFlip(),
                transforms.ToTensor(),
                transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
            ]))

    batch_size = int(FLAGS.batch_size / FLAGS.num_gpus)
    if FLAGS.distributed:
        train_sampler = torch.utils.data.distributed.DistributedSampler(dataset)
        train_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,
                                               num_workers=FLAGS.num_workers, pin_memory=True, sampler=train_sampler, drop_last=True)
    else:
        train_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True,
                                                num_workers=FLAGS.num_workers, drop_last=True)
    train_looper = infiniteloop(train_loader)

    # model setup
    net_model = UNet(
        T=FLAGS.T*FLAGS.time_scale, ch=FLAGS.ch, ch_mult=FLAGS.ch_mult, attn=FLAGS.attn,
        num_res_blocks=FLAGS.num_res_blocks, dropout=FLAGS.dropout,
        conditional=FLAGS.conditional, class_num=FLAGS.class_num)
    ema_model = copy.deepcopy(net_model)

    trainer = GaussianDiffusionTrainer(
        net_model, FLAGS.T, FLAGS.time_scale, FLAGS.loss_type, FLAGS.mean_type).cuda(FLAGS.local_rank)
    net_sampler = GaussianDiffusionSampler(
        net_model, FLAGS.T, FLAGS.time_scale, img_size=FLAGS.img_size,
        mean_type=FLAGS.mean_type, var_type=FLAGS.var_type).cuda(FLAGS.local_rank)
    ema_sampler = GaussianDiffusionSampler(
        ema_model, FLAGS.T, FLAGS.time_scale, img_size=FLAGS.img_size,
        mean_type=FLAGS.mean_type, var_type=FLAGS.var_type).cuda(FLAGS.local_rank)
    if FLAGS.distributed:
        trainer = torch.nn.parallel.DistributedDataParallel(trainer, device_ids=[FLAGS.local_rank], output_device=FLAGS.local_rank)
        net_sampler = torch.nn.parallel.DistributedDataParallel(net_sampler, device_ids=[FLAGS.local_rank], output_device=FLAGS.local_rank)
        ema_sampler = torch.nn.parallel.DistributedDataParallel(ema_sampler, device_ids=[FLAGS.local_rank], output_device=FLAGS.local_rank)

    optim = torch.optim.Adam(net_model.parameters(), lr=FLAGS.lr, weight_decay=FLAGS.wd)
    sched = torch.optim.lr_scheduler.LambdaLR(optim, lr_lambda=warmup_lr)

    # log setup
    x_T = torch.randn(int(FLAGS.sample_size / FLAGS.num_gpus), 3, FLAGS.img_size, FLAGS.img_size)
    x_T = x_T.cuda(FLAGS.local_rank)
    grid = (make_grid(next(iter(train_loader))[0][:int(FLAGS.sample_size / FLAGS.num_gpus)]) + 1) / 2
    if get_rank() == 0:
        writer = SummaryWriter(FLAGS.logdir)
        writer.add_image('real_sample', grid)
        writer.flush()
        # backup all arguments
        with open(os.path.join(FLAGS.logdir, "flagfile.txt"), 'w') as f:
            f.write(FLAGS.flags_into_string())
    # show model size
    model_size = 0
    for param in net_model.parameters():
        model_size += param.data.nelement()
    if get_rank() == 0:
        print('Model params: %.2f M' % (model_size / 1024 / 1024))

    # start training
    for step in range(1, FLAGS.total_steps + 1):
        if FLAGS.distributed:
            train_sampler.set_epoch(step)
        # train
        samples = next(train_looper)
        x_0, y = samples[0].cuda(FLAGS.local_rank), samples[1].cuda(FLAGS.local_rank)
        loss = trainer(x_0, y)
        optim.zero_grad()
        loss.backward()
        torch.nn.utils.clip_grad_norm_(net_model.parameters(), FLAGS.grad_clip)
        optim.step()
        sched.step()
        ema(net_model, ema_model, FLAGS.ema_decay)

        # log
        if get_rank() == 0:
            writer.add_scalar('loss', loss, step)

        # sample
        if FLAGS.sample_step > 0 and (step % FLAGS.sample_step == 0 or step == 1):
            ema_model.eval()
            with torch.no_grad():
                y_target = torch.randint(FLAGS.class_num, size=(x_T.shape[0],), device=x_T.device)
                x_0 = ema_sampler.module.ddim(x_T, 1, True, y=y_target)
                grid = (make_grid(x_0) + 1) / 2
                path = os.path.join(FLAGS.logdir, 'ddim_clip', '%d.png' % step)
                if get_rank() == 0:
                    save_image(grid, path)
                    writer.add_image('ddim_clip', grid, step)
            ema_model.train()

        # save
        if FLAGS.save_step > 0 and step % FLAGS.save_step == 0:
            if get_rank() == 0:
                ckpt = {
                    'net_model': net_model.state_dict(),
                    'ema_model': ema_model.state_dict(),
                    'x_T': x_T,
                    'T': trainer.module.T,
                    'time_scale': trainer.module.time_scale,
                }
                torch.save(ckpt, os.path.join(FLAGS.logdir, 'ckpt.pt'))
    torch.distributed.barrier()
    if get_rank() == 0:
        writer.close()

def main(argv):
    os.environ["CUDA_VISIBLE_DEVICES"] = FLAGS.gpu_id
    FLAGS.num_gpus = int(os.environ["WORLD_SIZE"]) if "WORLD_SIZE" in os.environ else 1
    FLAGS.distributed = FLAGS.num_gpus > 1
    if FLAGS.distributed:
        torch.cuda.set_device(FLAGS.local_rank)
        torch.distributed.init_process_group(backend="nccl", init_method="env://")
    # suppress annoying inception_v3 initialization warning
    warnings.simplefilter(action='ignore', category=FutureWarning)
    train()

if __name__ == '__main__':
    app.run(main)


from datetime import datetime

import numpy as np
import scipy as sp
from scipy import io
import netCDF4 as nc

import pyroms
import pyroms_toolbox

# ----------------- functionals ---------------------------------------------
def get_z(h, hc, N, s_rho, Cs_r, zeta, Vtrans, zice):

    hwater = h - np.abs(zice)
    z_r = np.empty((N,) + h.shape, 'd')
    if Vtrans == 1:
        for k in range(N):
            z0 = hc * s_rho[k] + (hwater - hc) * Cs_r[k]
            z_r[k, :] = z0 + zeta * (1.0 + z0 / hwater)
            z_r[k, :] = z_r[k, :] - np.abs(zice)
    elif Vtrans == 2 or Vtrans == 4 or Vtrans == 5:
        for  k in range(N):
            z0 = (hc * s_rho[k] + hwater * Cs_r[k]) / (hc + hwater)
            z_r[k, :] = zeta + (zeta + hwater) * z0
            z_r[k, :] = z_r[k, :] - np.abs(zice)
    return z_r

# ------------ read grid -----------------------------------------------
grd = pyroms.grid.get_ROMS_grid('fjord_test')
msk = grd.hgrid.mask
zr = grd.vgrid.z_r[:]
N, eta, xi = zr.shape

fh = nc.Dataset('./fjord_grd_test.nc')
zice = fh.variables['zice'][:]
fh.close()

zr = get_z(grd.vgrid.h,
           grd.vgrid.hc, grd.vgrid.N, grd.vgrid.s_rho, grd.vgrid.Cs_r,
           np.zeros(zice.shape), grd.vgrid.Vtrans,
           zice)

# ------------ generate ic file ----------------------------------------
ic_file = './fjord_ic_test.nc'
class ocean_time_info(object):
    pass
ocean_time = ocean_time_info()
ocean_time.long_name = 'seconds since 00-00-00'
ocean_time.units = 'second'

pyroms_toolbox.nc_create_roms_file(ic_file, grd, ocean_time, geogrid=False)

# ------------ write ic values -----------------------------------------
z_pyc = 10.
zeta = 0.
ubar = 0.
vbar = 0.
u = 0.
v = 0.
temp = np.zeros((1, grd.vgrid.N) + grd.vgrid.h.shape)
salt = np.zeros((1, grd.vgrid.N) + grd.vgrid.h.shape)
temp[0, :] = 4. + 2.*(np.tanh(0.025*np.pi*(zr+z_pyc))+1)
salt[0, :] = 30. - 10.*(np.tanh(0.025*np.pi*(zr+z_pyc))+1)
dye_01 = 0.
spval = -1.0e20

# zeta = 0
# ubar = 0
# vbar = 0
# u = 0
# v = 0
# dye_01 = 0
#
# data = io.loadmat('../data/carroll_2017_JGR_oceans_initialTS.mat')
# depth_raw = np.array(data['depth']).squeeze()
# temp_raw = np.array(data['temperature']).squeeze()
# salt_raw = np.array(data['salinity']).squeeze()
# depth_raw = depth_raw[::-1]
# temp_raw = temp_raw[::-1]
# salt_raw = salt_raw[::-1]
#
# temp = np.zeros((1, N, eta, xi))
# salt = np.zeros((1, N, eta, xi))
# for ieta in range(eta):
#     for ixi in range(xi):
#         temp[0, :, ieta, ixi] = np.interp(zr[:, ieta, ixi], depth_raw, temp_raw)
#         salt[0, :, ieta, ixi] = np.interp(zr[:, ieta, ixi], depth_raw, salt_raw)
#
# spval = -1.0e20
# ------------ write to ic file ----------------------------------------
fh = nc.Dataset(ic_file, 'r+')

fh.variables['ocean_time'][:] = 0

fh.createVariable('zeta', 'f8', ('ocean_time', 's_rho', 'eta_rho', 'xi_rho'), fill_value=spval)
fh.variables['zeta'].long_name = 'free-surface'
fh.variables['zeta'].units = 'meter'
fh.variables['zeta'].field = 'free-surface, scalar, series'
fh.variables['zeta'][:] = zeta

fh.createVariable('temp', 'f8', ('ocean_time', 's_rho', 'eta_rho', 'xi_rho'), fill_value=spval)
fh.variables['temp'].long_name = 'potential temperature'
fh.variables['temp'].units = 'Celsius'
fh.variables['temp'].field = 'temperature, scalar, series'
fh.variables['temp'][:] = temp

fh.createVariable('salt', 'f8', ('ocean_time', 's_rho', 'eta_rho', 'xi_rho'), fill_value=spval)
fh.variables['salt'].long_name = 'salinity'
fh.variables['salt'].units = 'PSU'
fh.variables['salt'].field = 'salinity, scalar, series'
fh.variables['salt'][:] = salt

fh.createVariable('dye_01', 'f8', ('ocean_time', 's_rho', 'eta_rho', 'xi_rho'), fill_value=spval)
fh.variables['dye_01'].long_name = 'river dye concentration'
fh.variables['dye_01'].units = ' '
fh.variables['dye_01'].field = 'dye_01, scalar, series'
fh.variables['dye_01'][:] = dye_01

fh.createVariable('u', 'f8', ('ocean_time', 's_rho', 'eta_u', 'xi_u'), fill_value=spval)
fh.variables['u'].long_name = '3D u-momentum component'
fh.variables['u'].units = 'meter second-1'
fh.variables['u'].field = 'u-velocity, scalar, series'
fh.variables['u'][:] = u

fh.createVariable('v', 'f8', ('ocean_time', 's_rho', 'eta_v', 'xi_v'), fill_value=spval)
fh.variables['v'].long_name = '3D v-momentum component'
fh.variables['v'].units = 'meter second-1'
fh.variables['v'].field = 'v-velocity, scalar, series'
fh.variables['v'][:] = v

fh.createVariable('ubar', 'f8', ('ocean_time', 'eta_u', 'xi_u'), fill_value=spval)
fh.variables['ubar'].long_name = '2D u-momentum component'
fh.variables['ubar'].units = 'meter second-1'
fh.variables['ubar'].field = 'ubar-velocity, scalar, series'
fh.variables['ubar'][:] = ubar

fh.createVariable('vbar', 'f8', ('ocean_time', 'eta_v', 'xi_v'), fill_value=spval)
fh.variables['vbar'].long_name = '2D v-momentum component'
fh.variables['vbar'].units = 'meter second-1'
fh.variables['vbar'].field = 'vbar-velocity, scalar, series'
fh.variables['vbar'][:] = vbar

fh.close()


'''
SystemLab-Design 20.01
Configuration file for functional block library & scripts
Version: 1.0 (27-Feb-2018)
Version: 2.0 (7-Sep-2019)
Version: 3.0 (5-Mar-2020)
'''

'''Functional block scripts====================================================
    New folders can be added as needed to the syslab_fb_scripts folders
    and must be added below to the scripts_path list. Otherwise, any fb_script
    names contained in these folders will not be found during a simulation.

    IMPORTANT: Do not change the name or location of the "syslab_fb_scripts"
    folder! To access fb_scripts from another file/folder location,
    use the File path fields in Project Settings
'''

# MV 20.01.r3 28-May-20
# 1 - Removed "syslab_fb_scripts" from root path (now part of main code)
# 2 - Added new folder for custom components/functional blocks
scripts_path_list = []
optical_scripts = 'optical'
electrical_scripts = 'electrical'
digital_scripts = 'digital'
custom_scripts = 'custom'
custom_scripts_aeponyx = 'ng_pon2_aeponyx'

#optical_scripts = '\\syslab_fb_scripts\\optical\\'
#electrical_scripts = '\\syslab_fb_scripts\\electrical\\'
#digital_scripts = '\\syslab_fb_scripts\\digital\\'

scripts_path_list.append(optical_scripts)
scripts_path_list.append(electrical_scripts)
scripts_path_list.append(digital_scripts)
scripts_path_list.append(custom_scripts)
scripts_path_list.append(custom_scripts_aeponyx)

'''Functional block library====================================================
    The baseline sections are optical, electrical & digital. Sections,
    groups and members can be modified (incl. addition or deletion of any of
    these items)
'''
fb_library_group = []
fb_library_group_properties = []
fb_library_group_settings = []

library_title = 'Functional block library (1)'
library_title_background_color = '#dddddd'
library_main_w = 250 #Height of menu tree window
library_main_h = 400 #Width of menu tree window
lib_settings_1 = [library_title, library_title_background_color,
                  library_main_w, library_main_h]
fb_library_group_settings.append(lib_settings_1)

''' OPTICAL-----------------------------------------------------------------'''
# Section title, RGBT numbers, Expanding (boolean)
optical_group_properties = ['Optical', 170, 0, 0, 25, True]
optical_group  = []
optical_titles = ['Sources/Transmitters',
                        'Modulators',
                        'Signal processing/routing',
                        'Fibers',
                        'Couplers/splitters/attenuators',
                        'Polarization devices',
                        'Amplifiers',
                        'Detectors/Receivers',
                        'Analyzers']

opt_sources_transmitters = [ 'WDM Transmitter',
                                            'CW Laser',
                                            'CW Laser Array',
                                            'Gaussian Pulse (Optical)',
                                            'Noise Source - Optical']

opt_modulators = ['Mach-Zehnder Modulator']

opt_signal_processing = [  'Branching node (Optical)',
                                        'Optical Adder',
                                        'Optical Circulator',
                                        'Optical Filter (Band Pass)',
                                        'Fiber Bragg Grating',
                                        'Optical Phase Shift']

opt_passive_devices_fiber = ['Optical Fiber (Linear)']

opt_passive_devices_couplers = ['Optical Attenuator',
                                                'X-Coupler (uni-dir)',
                                                'Optical Splitter',
                                                'Optical Splitter (4 Port)']

opt_pol_devices = [   'Polarization Beam Splitter',
                                'Polarization Beam Combiner',
                                'Jones Matrix']

opt_active_devices = ['Optical Amplifier']

opt_detectors_receivers = ['PIN-APD Detector',
                                        '90 Deg Optical Hybrid']

opt_analyzers = ['Measurement Node (Optical)']

optical_group.append(optical_titles)
optical_group.append(opt_sources_transmitters)
optical_group.append(opt_modulators)
optical_group.append(opt_signal_processing)
optical_group.append(opt_passive_devices_fiber)
optical_group.append(opt_passive_devices_couplers)
optical_group.append(opt_pol_devices)
optical_group.append(opt_active_devices)
optical_group.append(opt_detectors_receivers)
optical_group.append(opt_analyzers)

''' ELECTRICAL--------------------------------------------------------------'''
electrical_group_properties = ['Electrical', 0, 0, 255, 25, True]
electrical_group = []
electrical_titles = ['Waveform generators',
                            'Mathematical operators',
                            'Splitters',
                            'Amplifiers',
                            'Signal processing',
                            'Receivers',
                            'Analyzers']

elec_waveform_gen = [  'Sine Generator',
                                    'Cosine Generator',
                                    'Function Generator',
                                    'Gaussian Pulse Generator',
                                    'DC Source',
                                    'Noise Source']

elec_math_operators = ['Branching Node (Electrical)',
                                    'Adder',
                                    'Subtractor',
                                    'Multiplier',
                                    'Sign Inverter',
                                    'Vertical Shift',
                                    'Phase Shift (Electrical)',
                                    'Time Shift (Electrical)']

elec_passives = ['Power Splitter']

elec_actives = ['Electrical Amplifier',
                        'TIA-LA']

elec_sig_processing = ['Analog Filter']

elec_receivers = [ 'Decision Circuit',
                            'Integrate and Dump',
                            'Comparator',
                            'Analog to Digital Converter']

elec_analyzers = ['Measurement Node (Electrical)',
                            'Multiple Port Viewer (Electrical)']

electrical_group.append(electrical_titles)
electrical_group.append(elec_waveform_gen)
electrical_group.append(elec_math_operators)
electrical_group.append(elec_passives)
electrical_group.append(elec_actives)
electrical_group.append(elec_sig_processing)
electrical_group.append(elec_receivers)
electrical_group.append(elec_analyzers)

''' DIGITAL-----------------------------------------------------------------'''
digital_group_properties = ['Digital', 200, 200, 200, 50, True]
digital_group = []
digital_titles = ['Binary functional blocks',
                        'Symbol functional blocks',
                        'Analyzers']

dgtl_binary = [  'PRBS',
                        '2-bit P-S Conv',
                        '2-bit S-P Conv',
                        'Branching Node (Digital)']

dgtl_symbol = ['IQ generator']

dgtl_analyzers = ['BER Analyzer']

digital_group.append(digital_titles)
digital_group.append(dgtl_binary)
digital_group.append(dgtl_symbol)
digital_group.append(dgtl_analyzers)

'''Combine all groups-------------------------------------------------------'''
fb_sections = [optical_group, electrical_group, digital_group]
fb_sections_properties = [optical_group_properties,
                          electrical_group_properties,
                          digital_group_properties]

fb_library_group.append(fb_sections)
fb_library_group_properties.append(fb_sections_properties)

'''Functional block library (2)================================================
'''
library_title = 'Functional block library (2)'
library_title_background_color = '#dddddd'
library_main_w = 250 #Width of menu tree window
library_main_h = 130 #Height of menu tree window
lib_settings_2 = [library_title, library_title_background_color,
                  library_main_w, library_main_h]

## Section title, RGBT numbers, Expanding (boolean)
custom_group_properties = ['Device List', 170, 0, 0, 25, True]
custom_group  = []
custom_titles = ['Devices']

cust_1 = ['Device 1', 'Device 2']

custom_group.append(custom_titles)
custom_group.append(cust_1)

fb_sections_2 = [custom_group]
fb_sections_properties_2 = [custom_group_properties]

# To view and access fb library 2 elements, uncomment the code below
#fb_library_group_settings.append(lib_settings_2)
#fb_library_group.append(fb_sections_2)
#fb_library_group_properties.append(fb_sections_properties_2)


import torch.nn as nn
import torch
from models.util import MyResNet34

class audio2poseLSTM(nn.Module):
    def __init__(self):
        super(audio2poseLSTM,self).__init__()

        self.em_pose = MyResNet34(256, 1)
        self.em_audio = MyResNet34(256, 1)
        self.lstm = nn.LSTM(512,256,num_layers=2,bias=True,batch_first=True)

        self.output = nn.Linear(256,6)

    def forward(self,x):
        pose_em = self.em_pose(x["img"])
        bs = pose_em.shape[0]
        zero_state = torch.zeros((2, bs, 256), requires_grad=True).to(pose_em.device)
        cur_state = (zero_state, zero_state)
        img_em = pose_em
        bs,seqlen,num,dims = x["audio"].shape

        audio = x["audio"].reshape(-1, 1, num, dims)
        audio_em = self.em_audio(audio).reshape(bs, seqlen, 256)

        result = [self.output(img_em).unsqueeze(1)]

        for i in range(seqlen):

            img_em,cur_state = self.lstm(torch.cat((audio_em[:,i:i+1],img_em.unsqueeze(1)),dim=2),cur_state)
            img_em = img_em.reshape(-1, 256)

            result.append(self.output(img_em).unsqueeze(1))
        res = torch.cat(result,dim=1)
        return res


from tkinter import *
from tkinter import ttk

root=Tk()
root.title("Adding Scroll Bar to Screen")
root.geometry("500x500")

#create a main frame
main_frame=Frame(root,bg="white")
main_frame.pack(fill=BOTH,expand=1)

#create a canvas
my_canvas=Canvas(main_frame,bg="red")
my_canvas.pack(side=LEFT,fill=BOTH,expand=1)
#add a scrollbar to the canvas
my_scrollbar=ttk.Scrollbar(main_frame,orient=VERTICAL,command=my_canvas.yview)
my_scrollbar.pack(side=RIGHT,fill=Y)

#configure the canvas
my_canvas.config(yscrollcommand=my_scrollbar.set)
my_canvas.bind('<Configure>',lambda e:my_canvas.configure(scrollregion=my_canvas.bbox("all")))

#create another frame to a window in the canvas
second_frame=Frame(my_canvas,bg="cyan")

#add that new frame to a window in the canvas
my_canvas.create_window((0,0),window=second_frame,anchor=NW)

# creating 100 buttons
for i in range(100):
    button=Button(second_frame,text="button " + str(i))
    button.pack(pady=5)

root.mainloop()


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

# In[1]:

import pandas as pd
import numpy as np
import math
import os

# In[2]:

##創資料夾
def mkdir(path):
    folder = os.path.exists(path)
    #判斷結果
    if not folder:
        #如果不存在，則建立新目錄
        os.makedirs(path)
        print('-----建立成功-----')
    else:
        #如果目錄已存在，則不建立，提示目錄已存在
        print(path+'目錄已存在')

## 資料匯出
def OutputCSV(df):
    dir_path = 'Rank'
    csv_name = 'Rank'
    Result = dir_path + '/' + csv_name + '.csv'
    df_SAMPLE = pd.DataFrame.from_dict(df)
    df_SAMPLE.to_csv(Result, index=False)
    print('成功產出'+ Result)

def insert_df(name, buy_percentage, sell_trade_num, stop_loss, take_profit, profit):
    dir_path = 'Rank'
    csv_name = 'Rank'
    mkdir(dir_path)
    path = dir_path + '/' + csv_name + '.csv'
    try:
        df = pd.read_csv(path)
        temp=pd.DataFrame({'name':name,
                  'buy_percentage':buy_percentage,
                  'sell_trade_num':sell_trade_num,
                  'stop_loss':stop_loss,
                  'take_profit':take_profit,
                  'profit':profit},
                index=[0])
        df=df.append(temp, ignore_index=True)
        OutputCSV(df)
    except OSError:
        df = pd.DataFrame(columns=['name','buy_percentage','sell_trade_num','stop_loss','take_profit','profit'])
        OutputCSV(df)
        df = pd.read_csv(path)
        temp=pd.DataFrame({'name':name,
                  'buy_percentage':buy_percentage,
                  'sell_trade_num':sell_trade_num,
                  'stop_loss':stop_loss,
                  'take_profit':take_profit,
                  'profit':profit},
                index=[0])
        df=df.append(temp, ignore_index=True)
        OutputCSV(df)

# In[3]:

class Trade():
    trade_count = 0

    # 建構式
    def __init__(self, price, num):
        Trade.trade_count += 1
        self.price = price #買進價格
        self.num = num #買幾張
        self.total_cost = price*num*1000 #尚未考慮手續費

    def get_sell_profit(self, sell_price):
        return sell_price*self.num*1000 - self.total_cost

    def get_current_profit_pc(self, current_price):
        profit = self.get_sell_profit(current_price)
        profit_pc = profit / self.total_cost
        return profit_pc*100

def buy(buy_price):
    global cash
    cash_ = principal * buy_percentage/100
    if cash < cash_:
        cash_ = cash
    can_buy_num = cash_ // (buy_price*1000)
    if can_buy_num > 0:
        buy_trade = Trade(buy_price,can_buy_num)
        portfolio.append(buy_trade)
        cash -= buy_trade.total_cost #尚未考慮手續費
        print('以 %.1f元，買進 %d 張 2330，現金餘額 %.2f 元' % (buy_price,can_buy_num, cash))
    else:
        print('有買進訊號，但無法購買')

def sell(trade, sell_price):
    global cash, profit_count, loss_count, total_profit_rate
    sell_gain = trade.num*1000*sell_price #尚未考慮手續費
    cash += sell_gain
    profit_loss = trade.get_sell_profit(sell_price)
    profit_rate = trade.get_current_profit_pc(sell_price)
    total_profit_rate += profit_rate

    if profit_loss >= 0:
        profit_count += 1
    else:
        loss_count += 1

    portfolio.remove(trade)
    print('以 %.1f元，賣出 %d 張 2330，利損：%.2f元，現金餘額 %.2f 元'          % (sell_price,trade.num,profit_loss,cash))

def meet_strategy_sell(sell_price):
    if sell_trade_num == 'all':
        for _ in range(len(portfolio)):
            sell(portfolio[0], sell_price)
    else:
        tmp = min(sell_trade_num, len(portfolio))
        for _ in range(tmp):
            sell(portfolio[0], sell_price)

def cross_over(col1, col2, idx):
    # col1向上突破col2
    if idx == 0: return False
    return bt_data[col1][idx] > bt_data[col2][idx] and bt_data[col1][idx-1] < bt_data[col2][idx-1]

def cross_under(col1, col2, idx):
    # col1向上突破col2
    if idx == 0: return False
    return bt_data[col1][idx] < bt_data[col2][idx] and bt_data[col1][idx-1] > bt_data[col2][idx-1]

# In[4]:

def backtest(take_profit, stop_loss, buy_pc, sell_trade_n):
    global buy_percentage, sell_trade_num, ROI
    buy_percentage = buy_pc
    sell_trade_num = sell_trade_n
#     stop_loss = 5  # (%)  不停損 math.inf
#     take_profit = 10 # (%) 不停利 math.inf
    stock_num_2330 = 0
    principal = 1000000 * 10

    # 計算交易策略績效
    Trade.trade_count = 0

    for i in range(len(bt_data)-1):
        close = bt_data['Close'][i]
        next_close = bt_data['Close'][i+1]
        next_open = bt_data['Open'][i+1]
        rsi6 = bt_data['RSI6'][i]
        uprate_1day = bt_data['predict_1day_uprate'][i]

        # new
        msg = 'day:{}\n'.format(i)

        ### 先檢查有無 達到停利停損標準的 Trade
        for trade in portfolio:
            if trade.get_current_profit_pc(next_open) <= -stop_loss:
                msg += '(賣出)[停損賣出]\n'
                sell(trade, next_open)
            elif trade.get_current_profit_pc(next_open) >= take_profit:
                msg += '(買入)[停利賣出]\n'
                sell(trade, next_open)

        ### 買進策略
        if uprate_1day == 2 and next_open <= close:
            msg += '(買入)[Model 預測說要漲]\n'
            buy(next_close)

        if cross_over('K_value', 'D_value', i):
            msg += '(買入)[KD 黃金交叉]\n'
            buy(next_open)

        if cross_over('MA_5days', 'MA_20days', i):
            msg += '(買入)[MA 黃金交叉]\n'
            buy(next_open)

        if rsi6 <= 25:
            msg += '(買入)[RSI6 <= 25]\n'
            buy(next_open)

        ### 賣出策略

            #模型預測跌，當沖
        if len(portfolio)>0 and uprate_1day == 0 and next_open >= close:
            msg += '(當沖)[Model 預測說要跌，隔日開盤買進，收盤賣出]\n'
            buy(next_open)
            sell(portfolio[-1], next_close)

        if len(portfolio)>0 and cross_under('K_value', 'D_value', i):
            msg += '(賣出)[KD 死亡交叉]\n'
            meet_strategy_sell(next_open)

        if len(portfolio)>0 and cross_under('MA_5days', 'MA_20days', i):
            msg += '(賣出)[MA 死亡交叉]\n'
            meet_strategy_sell(next_open)

        if len(portfolio)>0 and rsi6 >= 70:
            msg += '(賣出)[RSI6 >= 70]\n'
            meet_strategy_sell(next_open)

        # new
        fornt_end_json['line_bot_push_msg'].append(msg)

        value_of_current_stock = np.sum([x.num*1000*next_open for x in portfolio])
        total_asset = value_of_current_stock + cash
        fornt_end_json['total_asset'].append(total_asset)

        print(msg)
        print('目前總資產 %d' % total_asset)

#         time.sleep(0.1)

    print('*'*25, '最後一天，全部平倉', '*'*25)
    last_close = bt_data['Close'][len(bt_data)-1]
    for _ in range(len(portfolio)):
        sell(portfolio[0], last_close)

    ROI = (cash/principal-1)*100

# In[7]:

bt_data = pd.read_csv('backtest_2330_data.csv')
# bt_data = bt_data[:120]

profit_count, loss_count, total_profit_rate, ROI = 0,0,0,0
principal = 1000000 * 10
cash = principal
portfolio = []
sell_trade_num = None

# new
fornt_end_json = dict()
fornt_end_json['total_asset'] = []
fornt_end_json['line_bot_push_msg'] = []

import json
def start_backtest_and_save_record(name, take_profit, stop_loss, buy_pc, sell_trade_num):
    ### buy_pc 0~100
    global profit_count, loss_count, total_profit_rate, ROI, fornt_end_json, principal, cash
    #init
    profit_count, loss_count, total_profit_rate, ROI = 0,0,0,0
    fornt_end_json = dict()
    fornt_end_json['total_asset'] = []
    fornt_end_json['line_bot_push_msg'] = []
    cash = principal

    Trade.trade_count = 0

    if take_profit == 0:
        # 不停利
        take_profit = math.inf

    if stop_loss == 0:
        # 不停損
        stop_loss = math.inf

    if sell_trade_num == 0:
        # 符合交易策略，一次全賣
        sell_trade_num = 'all'

    backtest(take_profit, stop_loss, buy_pc, sell_trade_num)

    trade_count = profit_count + loss_count
    win_rate = round(profit_count / trade_count*100,2)

    fornt_end_json['backtest_metric'] = dict()
    fornt_end_json['backtest_metric']['total_profit'] = round(ROI,2)
    fornt_end_json['backtest_metric']['avg_profit'] = round(total_profit_rate / trade_count,2)
    fornt_end_json['backtest_metric']['win_rate'] = win_rate

    fornt_end_json['backtest_metric']['trade'] = trade_count
    fornt_end_json['backtest_metric']['profit_trade'] = profit_count
    fornt_end_json['backtest_metric']['loss_trade'] = loss_count

    print('總報酬率: %.2f%%' % fornt_end_json['backtest_metric']['total_profit'])
    print('平均報酬率: %.2f%%' % fornt_end_json['backtest_metric']['avg_profit'])
    print('勝率: %.2f%%' % (fornt_end_json['backtest_metric']['win_rate']))

    print('總交易次數: %d次' % fornt_end_json['backtest_metric']['trade'])
    print('獲利次數: %d次' % fornt_end_json['backtest_metric']['profit_trade'])
    print('虧損次數: %d次' % fornt_end_json['backtest_metric']['loss_trade'])

#     print('總報酬率:', ROI)

    tmp_msg = fornt_end_json['line_bot_push_msg']
    # fornt_end_json['line_bot_push_msg'] = [m.replace('\n', '<br/>') for m in tmp_msg]
    return json.dumps(fornt_end_json)


from datetime import datetime

import base64
import MySQLdb
import MySQLdb.cursors
import logging
import eventlet
import hashlib
import requests

import xml.etree.ElementTree as ET

logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.client').setLevel(logging.DEBUG)

class MySQL():

    def execute_query(self, db_connection, sql, params):
        """ Insert data into the database
        Keyword arguments:
            db_connection -- The connection to the database.
            sql -- The sql to be executed.
            params -- A parameter list holding values to be used in the sql.
        """
        try:
            cursor = db_connection.cursor()
            cursor.execute(sql, params)
        except MySQLdb.DatabaseError:
            raise
        except TypeError:
            raise

    def retrieve_all_data_params(self, db_connection, sql, params):
        """ Retrieve Data from the database

            Retrieve data from the database, returns a dictionary that
            holds the results.

            Keyword arguments:
            db_connection -- The connection to the database.
            sql -- The sql to be executed.
            params -- A parameter list holding values to be used in the sql.

        """
        results = None
        try:
            cursor = db_connection.cursor()
            cursor.execute(sql, params)
            results = cursor.fetchall()
        except MySQLdb.DatabaseError:
            raise
        return results

    def retrieve_all_data(self, db_connection, sql):
        """ Retrieve Data from the database

            Retrieve data from the database, returns a dictionary that
            holds the results.

            Keyword arguments:
            db_connection -- The connection to the database.
            sql -- The sql to be executed.
        """
        results = None
        try:
            cursor = db_connection.cursor()
            cursor.execute(sql)
            results = cursor.fetchall()
        except MySQLdb.DatabaseError:
            raise
        return results


arr = []
size = int(input())
for i in range(size):
    arr.append(list(map(int, input().split())))

# 덩치는 키 몸무게가 큰사람을 의미
# 둘의 값이 다르면 비교 불가

result = []

# 1 2 3 4 5
for i in range(size):
    step = size

    for j in range(size):
        if i != j and (arr[i][1] >= arr[j][1] or arr[i][0] >= arr[j][0]):
            step -= 1

    result.append(step)

print(*result)

SSAFY 대비 스터디/SSAFY 코테대비(Pycham)/test/7568.py


import os
import sys
from typing import Optional, Tuple

def glibc_version_string() -> Optional[str]:
    "Returns glibc version string, or None if not using glibc."
    return glibc_version_string_confstr() or glibc_version_string_ctypes()

def glibc_version_string_confstr() -> Optional[str]:
    "Primary implementation of glibc_version_string using os.confstr."
    # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
    # to be broken or missing. This strategy is used in the standard library
    # platform module:
    # https://github.com/python/cpython/blob/fcf1d003bf4f0100c9d0921ff3d70e1127ca1b71/Lib/platform.py#L175-L183
    if sys.platform == "win32":
        return None
    try:
        gnu_libc_version = os.confstr("CS_GNU_LIBC_VERSION")
        if gnu_libc_version is None:
            return None
        # os.confstr("CS_GNU_LIBC_VERSION") returns a string like "glibc 2.17":
        _, version = gnu_libc_version.split()
    except (AttributeError, OSError, ValueError):
        # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...
        return None
    return version

def glibc_version_string_ctypes() -> Optional[str]:
    "Fallback implementation of glibc_version_string using ctypes."

    try:
        import ctypes
    except ImportError:
        return None

    # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
    # manpage says, "If filename is NULL, then the returned handle is for the
    # main program". This way we can let the linker do the work to figure out
    # which libc our process is actually using.
    process_namespace = ctypes.CDLL(None)
    try:
        gnu_get_libc_version = process_namespace.gnu_get_libc_version
    except AttributeError:
        # Symbol doesn't exist -> therefore, we are not linked to
        # glibc.
        return None

    # Call gnu_get_libc_version, which returns a string like "2.5"
    gnu_get_libc_version.restype = ctypes.c_char_p
    version_str = gnu_get_libc_version()
    # py2 / py3 compatibility:
    if not isinstance(version_str, str):
        version_str = version_str.decode("ascii")

    return version_str

# platform.libc_ver regularly returns completely nonsensical glibc
# versions. E.g. on my computer, platform says:
#
#   ~$ python2.7 -c 'import platform; print(platform.libc_ver())'
#   ('glibc', '2.7')
#   ~$ python3.5 -c 'import platform; print(platform.libc_ver())'
#   ('glibc', '2.9')
#
# But the truth is:
#
#   ~$ ldd --version
#   ldd (Debian GLIBC 2.22-11) 2.22
#
# This is unfortunate, because it means that the linehaul data on libc
# versions that was generated by pip 8.1.2 and earlier is useless and
# misleading. Solution: instead of using platform, use our code that actually
# works.
def libc_ver() -> Tuple[str, str]:
    """Try to determine the glibc version

    Returns a tuple of strings (lib, version) which default to empty strings
    in case the lookup fails.
    """
    glibc_version = glibc_version_string()
    if glibc_version is None:
        return ("", "")
    else:
        return ("glibc", glibc_version)