Example #1
0
class VacalcFrame(object):
    def __init__(self, employees):
        self._frame = JFrame('Vacation Calculator',
                             defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        self._frame.setContentPane(self._create_ui(employees))
        self._frame.pack()

    def _create_ui(self, employees):
        panel = JPanel(layout=FlowLayout())
        self._overview = EmployeeOverview(employees, self)
        self._details = EmployeeDetails(employees)
        self._welcome = Welcome()
        panel.add(self._overview)
        panel.add(self._welcome)
        return panel

    def show(self):
        self._frame.setVisible(True)

    def employee_selected(self, employee):
        self._ensure_details_shown()
        self._details.show_employee(employee)

    def edit_new_employee(self):
        self._ensure_details_shown()
        self._details.edit_new_employee()

    def _ensure_details_shown(self):
        if self._welcome:
            self._frame.contentPane.remove(self._welcome)
            self._frame.contentPane.add(self._details)
            self._frame.pack()
            self._welcome = None
Example #2
0
    def initResultados(self):
        diag = JFrame()
        self.lineas = list()
        self.areaResultados = JTextArea()
        numLineas = self.readResultados()

        panelResultados = JPanel()
        #panelResultados.setAutoscrolls(True)
        panelResultados.setBorder(BorderFactory.createEtchedBorder())
        panelResultados.setLayout(GridLayout(0, 1))

        pane = JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                           JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
        pane.viewport.view = self.areaResultados

        #pane.getViewport().add(panelResultados)

        diag.setTitle("RESULTADOS OBTENIDOS")

        diag.setSize(1000, 450)
        diag.setLayout(BorderLayout())
        diag.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        diag.setLocationRelativeTo(None)
        diag.setVisible(True)

        panelResultados.add(pane)
        diag.add(panelResultados, BorderLayout.CENTER)
Example #3
0
    def run(self):
        frame = JFrame('Table7',
                       size=(300, 150),
                       locationRelativeTo=None,
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        headings = 'T/F,Date,Integer,Float,Double'.split(',')
        model = myTM(self.data, headings)
        table = JTable(model,
                       selectionMode=ListSelectionModel.SINGLE_SELECTION)
        table.getColumnModel().getColumn(model.getColumnCount() -
                                         1  # i.e., last column
                                         ).setCellRenderer(myRenderer())

        #----------------------------------------------------------
        # Adjust the width of the columns using only header text
        #----------------------------------------------------------
        hRenderer = table.getTableHeader().getDefaultRenderer()
        for col in range(model.getColumnCount()):
            column = table.getColumnModel().getColumn(col)
            comp = hRenderer.getTableCellRendererComponent(
                None,  # Table
                column.getHeaderValue(),  # value
                0,  # isSelected = false 
                0,  # hasFocus = false
                -1,  # row #
                col  # col #
            )
            width = comp.getPreferredSize().width
            #           print 'col: %d  previous: %d  current: %d' % ( col, column.getPreferredWidth(), width )
            column.setPreferredWidth(width)

        frame.add(JScrollPane(table))
        frame.setVisible(1)
class CoordinateChooser:
    def buttonPressed(self, event):
        # The OK button was pressed; proceed to compute and plot moment arms
        # relative to the selected coordinate.
        coordIndex = self.cb.selectedIndex
        coordName = self.data[coordIndex]
        self.frame.setVisible(False)
        ComputeAndPlotMomentArms(coordIndex)

    def __init__(self):
        # Populate and display window for selecting a coordinate from the
        # specified motion (kinematics) file.
        self.frame = JFrame("Coordinate chooser")
        self.frame.setSize(350, 100)
        self.frame.setLayout(BorderLayout())
        self.frame.setLocationRelativeTo(None)

        self.data = coordList
        self.cb = JComboBox(self.data, preferredSize=(200, 25))
        self.frame.add(self.cb, BorderLayout.WEST)

        btn = JButton('OK',
                      preferredSize=(75, 25),
                      actionPerformed=self.buttonPressed)
        self.frame.add(btn, BorderLayout.EAST)

        self.label = JLabel('Please select the coordinate to use in the \
			moment arm calculations',
                            preferredSize=(325, 50))
        self.frame.add(self.label, BorderLayout.NORTH)

        self.frame.setVisible(True)
Example #5
0
def show():
    """ adapted from here: http://wiki.gephi.org/index.php/Toolkit_-_Reuse_the_Preview_Applet"""
    from javax.swing import JFrame
    from java.awt import BorderLayout

    pc = PreviewController
    pc.refreshPreview()

    # New Processing target, get the PApplet
    target = pc.getRenderTarget("processing")
    applet = target.getApplet()
    applet.init()

    # Refresh the preview and reset the zoom
    try:
        pc.render(target)
    except Exception:
        # throws sun.dc.pr.PRError: sun.dc.pr.PRError: setPenT4: invalid pen transformation (singular)
        pass
    target.refresh()
    target.resetZoom()

    # Add the applet to a JFrame and display
    frame = JFrame("Preview")
    frame.setLayout(BorderLayout())

    # frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.add(applet, BorderLayout.CENTER)

    frame.pack()
    frame.setVisible(True)
    def run( self ) :
        frame = JFrame(
            'SecConfigReport_02',
            size = ( 300, 300 ),
            locationRelativeTo = None,
            defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        )

        data = []
        text = AdminTask.generateSecConfigReport()
        for line in text.splitlines()[ 2: ] :
            data.append(
                [
                    info.strip() for info in
                    line[ :-2 ].split( ';' )
                ]
            )

        frame.add(
            JScrollPane(
                JTable( data, ';;;'.split( ';' ) )
            )
        )

        frame.pack()
        frame.setVisible( 1 )
Example #7
0
    def bg(self, panel2, e):
        bground = JFrame()
        bground.setTitle("Change Background")
        bground.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
        bground.setSize(350, 100)
        bground.setLocationRelativeTo(None)
        bground.setVisible(True)
        bground.setResizable(False)

        panel = JPanel()
        #panel.setBackground(Color(46, 64, 96))
        bground.getContentPane().add(panel)

        path = JLabel("File:")
        panel.add(path)

        path2 = JTextField()
        path2.setPreferredSize(Dimension(180, 20))
        panel.add(path2)

        browse = JButton("Browse file",
                         actionPerformed=lambda e: self.browse(path2, e))
        panel.add(browse)

        change = JButton(
            "Change",
            actionPerformed=lambda e: self.change(path2.getText(), panel2, e))
        panel.add(change)

        bground.add(panel)
Example #8
0
 def run( self ) :
     frame = JFrame( 'ButtonDemo_03' )
     frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE )
     button = frame.add( JButton( 'Press me' ) )
     button.actionPerformed = self.buttonPressed
     frame.pack()
     frame.setVisible( 1 )
Example #9
0
    def run(self):
        frame = JFrame('FrameMethods',
                       size=(1000, 500),
                       locationRelativeTo=None,
                       layout=GridLayout(0, 2),
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        self.one = self.parse(self.textFile('JFrame Methods.txt'))
        self.left = JTextArea(self.one,
                              20,
                              40,
                              editable=0,
                              font=Font('Courier', Font.PLAIN, 12))

        frame.add(JScrollPane(self.left))

        self.two = self.parse(self.textFile('JInternalFrame Methods.txt'))
        self.right = JTextArea(self.two,
                               20,
                               40,
                               editable=0,
                               font=Font('Courier', Font.PLAIN, 12))
        frame.add(JScrollPane(self.right))

        frame.setJMenuBar(self.makeMenu())

        frame.setVisible(1)
    def run(self):
        frame = JFrame('AbsoluteLayout',
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        # Replace the default Layout Manager
        frame.setLayout(None)

        # Information defining button title, location & size
        data = [['A', 20, 10, 0, 0], ['B', 40, 40, 10, 10],
                ['C', 80, 20, 20, 20]]

        # For each data entry, create & position a button
        insets = frame.getInsets()
        for item in data:
            button = frame.add(JButton(item[0]))
            size = button.getPreferredSize()
            button.setBounds(insets.left + item[1], insets.top + item[2],
                             size.width + item[3], size.height + item[4])

        # Define the application frame size
        frame.setSize(
            300 + insets.left + insets.right,  # frame width
            150 + insets.top + insets.bottom  # frame height
        )

        # Make the frame visible
        frame.setVisible(1)
Example #11
0
 def run(self):
     frame = JFrame('javadocInfo_00',
                    locationRelativeTo=None,
                    size=(250, 250),
                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
     #       frame.pack()
     frame.setVisible(1)
Example #12
0
def makeUI(model):
    table = JTable(model)
    jsp = JScrollPane(table)
    regex_label = JLabel("Search: ")
    regex_field = JTextField(20)
    top = JPanel()
    top.add(regex_label)
    top.add(regex_field)
    top.setLayout(BoxLayout(top, BoxLayout.X_AXIS))
    base_path_label = JLabel("Base path:")
    base_path_field = JTextField(50)
    bottom = JPanel()
    bottom.add(base_path_label)
    bottom.add(base_path_field)
    bottom.setLayout(BoxLayout(bottom, BoxLayout.X_AXIS))
    all = JPanel()
    all.add(top)
    all.add(jsp)
    all.add(bottom)
    all.setLayout(BoxLayout(all, BoxLayout.Y_AXIS))
    frame = JFrame("File paths")
    frame.getContentPane().add(all)
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
    frame.addWindowListener(Closing())
    frame.pack()
    frame.setVisible(True)
    # Listeners
    regex_field.addKeyListener(EnterListener(table, model, frame))
    table.addMouseListener(RowClickListener(base_path_field))
    #
    return model, table, regex_field, frame
Example #13
0
    def run(self):
        frame = JFrame('List6',
                       size=(200, 220),
                       layout=GridLayout(1, 2),
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        panel = JPanel(layout=GridLayout(0, 1))
        self.buttons = {}
        for name in 'First,Last,Before,After,Remove'.split(','):
            self.buttons[name] = panel.add(self.button(name))

        self.text = panel.add(JTextField(10))
        self.addInputMethodListener(self)
        #       self.addTextListener( self )
        frame.add(panel)

        data = ('Now is the time for all good spam ' +
                'to come to the aid of their eggs').split(' ')
        model = DefaultListModel()
        for word in data:
            model.addElement(word)
        self.info = JList(model,
                          valueChanged=self.selection,
                          selectionMode=ListSelectionModel.SINGLE_SELECTION)
        frame.add(JScrollPane(self.info, preferredSize=(200, 100)))
        frame.setVisible(1)
Example #14
0
 def gui_open(path):
     label = JLabel(ImageIcon(ImageIO.read(File(URL(path).getFile()))))
     frame = JFrame()
     frame.getContentPane().add(label)
     frame.pack()
     frame.setLocation(200, 200)
     frame.setVisible(True)
Example #15
0
    def run(self):
        frame = JFrame('flexible Box',
                       locationRelativeTo=None,
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        print '\nscreenSize:', Toolkit.getDefaultToolkit().getScreenSize()

        box = Box.createHorizontalBox()
        box.add(Box.createGlue())
        box.add(Box.createRigidArea(Dimension(5, 5)))
        box.add(JLabel('Name:'))
        box.add(Box.createRigidArea(Dimension(5, 5)))
        self.tf = box.add(
            JTextField(
                10  # ,
                #               maximumSize = Dimension(   2000, 20 )
                #               maximumSize = Dimension(  20000, 20 )
                #               maximumSize = Dimension( 200000, 20 )
            ))
        box.add(Box.createRigidArea(Dimension(5, 5)))
        box.add(JButton('Submit', actionPerformed=self.buttonPress))
        box.add(Box.createRigidArea(Dimension(5, 5)))
        box.add(Box.createGlue())

        frame.add(box)
        frame.pack()
        frame.setVisible(1)
Example #16
0
    def run(self):

        #-----------------------------------------------------------------------
        # Name: isEven()
        # Role: Return true (1) if the specified value is an even integer
        #-----------------------------------------------------------------------
        def isEven(num):
            return not (num & 1)

        #-----------------------------------------------------------------------
        # Name: isOdd()
        # Role: Return true (1) if the specified value is an odd integer
        #-----------------------------------------------------------------------
        def isOdd(num):
            return num & 1

        #-----------------------------------------------------------------------
        # Name: isPrime()
        # Role: Return true (1) if and only if the specified value is a prime
        #       integer
        #-----------------------------------------------------------------------
        def isPrime(num):
            result = 0  # Default = False
            if num == abs(int(num)):  # Only integers allowed
                if num == 1:  # Special case
                    pass  #   use default (false)
                elif num == 2:  # Special case
                    result = 1  #
                elif num & 1:  # Only odd numbers...
                    for f in xrange(3, int(num**0.5) + 1, 2):
                        if not num % f:
                            break  # f is a factor...
                    else:
                        result = 1  # we found a prime
            return result

        #---------------------------------------------------------------------------
        # Name: label()
        # Role: Instantiate a Right aligned label with the specified text
        #---------------------------------------------------------------------------
        def label(text):
            return JLabel(text + ' ', horizontalAlignment=SwingConstants.RIGHT)

        frame = JFrame('Listen4',
                       layout=GridLayout(0, 2),
                       locationRelativeTo=None,
                       size=(200, 128),
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        frame.add(label('Integer:'))
        text = frame.add(JTextField(10))
        frame.add(label('Even?'))
        even = frame.add(JLabel(''))
        text.addKeyListener(listener(text, even, isEven))
        frame.add(label('Odd?'))
        odd = frame.add(JLabel(''))
        text.addKeyListener(listener(text, odd, isOdd))
        frame.add(label('Prime?'))
        prime = frame.add(JLabel(''))
        text.addKeyListener(listener(text, prime, isPrime))
        frame.setVisible(1)
Example #17
0
 def run( self ) :
     frame = JFrame( 'ButtonDemo_02' )
     frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE )
     button = frame.add( JButton( 'Press me' ) )
     button.addActionListener( self )
     frame.pack()
     frame.setVisible( 1 )
 def run(self):
     frame = JFrame('LayeredPaneDemo',
                    locationRelativeTo=None,
                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
     frame.setContentPane(self.createLayeredPane())
     frame.pack()
     frame.setVisible(1)
Example #19
0
def main_menu():
    """ Main menu which is always open

    Parameters
    ----------
    None

    Returns
    -------
    JFrame
        Main menu with JButtons calling other functions
    """
    frame = JFrame("GMM Image Quality Calculator")
    nButtons = 4
    frame.setSize(100 * nButtons, 300)
    frame.setLayout(GridLayout(nButtons, 1))

    # Define JButtons
    get_user_params_JB = JButton("Load image and settings", actionPerformed = User_Dialogs.get_user_params)
    fit_GMM_JB = JButton("Fit Gaussian Mixture Model", actionPerformed = User_Dialogs.fit_GMM)
    show_as_RT_JB = JButton("Show SNR and CNR as Results Table", actionPerformed = User_Dialogs.show_as_RT)
    show_thresholded_JB = JButton("Show thresholded stack", actionPerformed = User_Dialogs.show_thresholded)

    # Add JButtons to frame
    frame.add(get_user_params_JB)
    frame.add(fit_GMM_JB)
    frame.add(show_as_RT_JB)
    frame.add(show_thresholded_JB)
    frame.setVisible(True)
Example #20
0
 def run(self):
     frame = JFrame('List1',
                    size=(250, 200),
                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
     data = 'Now is the time for all good spam'.split(' ')
     frame.add(JList(data))
     frame.setVisible(1)
Example #21
0
    def run(self):
        frame = JFrame('SecConfigReport_09',
                       size=(500, 300),
                       locationRelativeTo=None,
                       componentResized=self.frameResized,
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        data = []
        text = AdminTask.generateSecConfigReport()
        #-----------------------------------------------------------------------
        # The RegExp was added to replace multiple blanks with a single one
        #-----------------------------------------------------------------------
        for line in text.splitlines()[2:]:
            data.append([
                re.sub('  +', ' ', info.strip())
                for info in line[:-2].split(';')
            ])

        self.table = table = JTable(
            reportTableModel(
                data,
                ';;;'.split(';'),
            ),
            selectionMode=ListSelectionModel.SINGLE_SELECTION)
        table.setDefaultRenderer(String, reportRenderer())
        self.setColumnWidths(table)
        scroller = JScrollPane(table)
        scroller.getViewport().addChangeListener(rowFinder(table))
        frame.add(scroller)

        frame.pack()
        frame.setVisible(1)
        frame.setMinimumSize(frame.getSize())
Example #22
0
    def onInfo(self, e):
        info = JFrame()
        info.setTitle("Info")
        info.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
        info.setSize(410, 400)
        info.setLocationRelativeTo(None)
        info.setResizable(False)
        info.setVisible(True)

        panel = JPanel()
        #panel.setBackground(Color(46, 64, 96))
        #panel.setLayout(GridLayout(0, 2))

        logo = JLabel(ImageIcon("/icons/logo.jpg"))
        panel.add(logo)

        f = Font("", Font.ITALIC, 40)
        title = JLabel("Stylus OS 1.0 beta")
        title.setFont(f)
        panel.add(title)

        f = Font("", Font.ITALIC, 14)
        copyright = JLabel(
            "Copyright (c) 2016 Niccolo' Ciavarella. All rights reserved.")
        copyright.setFont(f)
        panel.add(copyright)

        info.getContentPane().add(panel)
        info.add(panel)
Example #23
0
    def run(self):
        frame = JFrame('MethodTable2',
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        #-----------------------------------------------------------------------
        # Get the text to be processed
        #-----------------------------------------------------------------------
        helpText = Help.help().expandtabs()

        #-----------------------------------------------------------------------
        # Verify our help text parsing routine
        #-----------------------------------------------------------------------
        headings = ['Method', 'Description / Abstract']

        #-----------------------------------------------------------------------
        # Let's try to highlight every instance of "help" in the table
        #-----------------------------------------------------------------------
        data = self.parseMethodHelp(helpText)
        for r in range(len(data)):
            for c in range(len(data[r])):
                data[r][c] = self.hiliteText(data[r][c], 'help')

        #-----------------------------------------------------------------------
        # Create the JTable using the massaged data and column headings
        #-----------------------------------------------------------------------
        table = JTable(data, headings, font=Font('Courier', Font.PLAIN, 12))
        frame.add(JScrollPane(table), 'Center')

        frame.pack()
        self.center(frame)
        frame.setVisible(1)
Example #24
0
    def run(self):
        frame = JFrame('Console timeout',
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        #-----------------------------------------------------------------------
        # The frame (i.e., it's ContentPane) should use a vertically aligned
        # BoxLayout layout manager (i.e., along the Y_AXIS)
        #-----------------------------------------------------------------------
        cp = frame.getContentPane()
        cp.setLayout(BoxLayout(cp, BoxLayout.Y_AXIS))

        #-----------------------------------------------------------------------
        # The JTextField will be preceeded, and followed by JLabel components
        # identifying the value being displayed, and the associated time units.
        # However, we want them displayed horizontally, so we put them into a
        # single JPanel instance using a FlowLayout layout manager
        #-----------------------------------------------------------------------
        input = JPanel(layout=FlowLayout())
        input.add(JLabel('Timeout:'))
        self.text = JTextField(3, actionPerformed=self.update)
        input.add(self.text)
        self.text.setText(getTimeout())
        input.add(JLabel('minutes'))
        cp.add(input)

        #-----------------------------------------------------------------------
        # Then, we add a message area beneath
        #-----------------------------------------------------------------------
        self.msg = cp.add(JLabel())

        frame.setSize(290, 100)
        frame.setVisible(1)
Example #25
0
 def run(self):
     frame = JFrame('Spinner4',
                    layout=FlowLayout(),
                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
     frame.add(JSpinner(SpinnerDateModel()))
     frame.pack()
     frame.setVisible(1)
Example #26
0
    def run(self):
        frame = JFrame('horizontalBox',
                       locationRelativeTo=None,
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        vert = Box.createVerticalBox()
        vert.add(Box.createGlue())
        vert.add(JButton('<>'))
        vert.add(Box.createVerticalStrut(5))
        vert.add(JButton('<>'))
        vert.add(Box.createVerticalStrut(5))
        vert.add(JButton('<>'))
        vert.add(Box.createGlue())

        hor = Box.createHorizontalBox()
        hor.add(Box.createGlue())
        hor.add(JButton('<>'))
        hor.add(Box.createHorizontalStrut(5))

        hor.add(vert)

        hor.add(Box.createHorizontalStrut(5))
        hor.add(JButton('<>'))
        hor.add(Box.createGlue())

        frame.add(hor)
        frame.pack()
        frame.setVisible(1)
Example #27
0
def tree():
  """
  tree(xmlfile="dsm2.xml")
    creates a tree view on a given xml file of dsm2 input data
  """
  tv = TreeViewer()
  mp2 = JPanel()
  mp2.setLayout(BorderLayout())
  tf = JTextField("dsm2.inp")
  pb = JButton("parse")
  mp2.add(tf,BorderLayout.CENTER)
  mp2.add(pb,BorderLayout.EAST)
  class ParseListener(ActionListener):
    def __init__(self,tf,tv,fr):
      self.tf = tf
      self.tv = tv
      self.fr = fr
    def actionPerformed(self,evt):
      dsm2file = self.tf.getText()
      parser = DSM2Parser(dsm2file)
      self.tv.xdoc = parser.dsm2_data.toXml()
      self.fr.getContentPane().add(self.tv.gui(),BorderLayout.CENTER)
      self.fr.pack()
      self.fr.setVisible(1)
  fr = JFrame()
  fr.setTitle("DSM2Tree")
  fr.setLocation(100,100)
  fr.setSize(600,60)
  fr.getContentPane().setLayout(BorderLayout())
  fr.getContentPane().add(mp2,BorderLayout.NORTH)
  al = ParseListener(tf,tv,fr)
  pb.addActionListener(al)
  fr.pack()
  fr.setVisible(1)
Example #28
0
    def run( self ) :
        frame = JFrame(
            'WSAShelp_01',
            locationRelativeTo = None,
            defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        )
#       text = Help.help()
#       tabs = text.count( '\t' )
#       text = Help.help().expandtabs()
#       rows = text.count( '\n' ) + 1
#       cols = max( [ len( x ) for x in text.splitlines() ] )
#       cols = max( [ len( x.expandtabs() ) for x in text.splitlines() ] )
#       print '\nrows: %d  cols: %d  tabs: %d' % ( rows, cols, tabs )
        frame.add(
            JScrollPane(
                JTextArea(
#                   text,
                    Help.help().expandtabs(),
                    20,
                    80,
                    font = Font( 'Courier' , Font.PLAIN, 12 )
                )
            )
        )
        frame.pack()
        size = frame.getSize()
#       print 'frame.getSize():', size
        loc = frame.getLocation()
#       print 'frame.getLocation():', loc
        loc.x -= ( size.width  >> 1 )
        loc.y -= ( size.height >> 1 )
        frame.setLocation( loc )
        frame.setVisible( 1 )
class VacalcFrame(object):
    def __init__(self, employees, dateprovider):
        self._frame = JFrame("Vacation Calculator", defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        self._frame.setContentPane(self._create_ui(employees, dateprovider))
        self._frame.pack()

    def _create_ui(self, employees, dateprovider):
        panel = JPanel(layout=FlowLayout())
        self._overview = EmployeeOverview(employees, self)
        self._details = EmployeeDetails(employees, dateprovider)
        self._welcome = Welcome()
        panel.add(self._overview)
        panel.add(self._welcome)
        return panel

    def show(self):
        self._frame.setVisible(True)

    def employee_selected(self, employee):
        self._ensure_details_shown()
        self._details.show_employee(employee)

    def edit_new_employee(self):
        self._ensure_details_shown()
        self._details.edit_new_employee()

    def _ensure_details_shown(self):
        if self._welcome:
            self._frame.contentPane.remove(self._welcome)
            self._frame.contentPane.add(self._details)
            self._frame.pack()
            self._welcome = None
Example #30
0
 def run(self):
     #-----------------------------------------------------------------------
     # First, we determine the size & location of the application frame
     #-----------------------------------------------------------------------
     screenSize = Toolkit.getDefaultToolkit().getScreenSize()
     w = screenSize.width >> 1  # 1/2 screen width
     h = screenSize.height >> 1  # 1/2 screen height
     x = (screenSize.width - w) >> 1
     y = (screenSize.height - h) >> 1
     frame = JFrame(
         'iFrameEvents2',
         bounds=(x, y, w, h),  # location & size
         defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
     #-----------------------------------------------------------------------
     # Next, we create, and add the menubar
     #-----------------------------------------------------------------------
     frame.setJMenuBar(self.menuBar())
     #-----------------------------------------------------------------------
     # Then, we replace the frame ContentPane with a JDesktopPane instance
     # for all of the inner frames, and populate it with our eventLogger
     # inner frame instance.
     #-----------------------------------------------------------------------
     self.desktop = desktop = JDesktopPane()
     self.logger = eventLogger()
     desktop.add(self.logger, 0, 0)
     frame.setContentPane(desktop)
     #-----------------------------------------------------------------------
     # Initialize the number of inner frames created
     #-----------------------------------------------------------------------
     self.iFrameCount = 0
     frame.setVisible(1)
Example #31
0
def initial():
    global f  ##文件
    global txt
    global number_of_occurrence
    reload(sys)
    sys.setdefaultencoding('utf-8')
    ctr.init()
    ctr.set_value('flag', 0)
    ctr.set_value('reload_check', 0)
    ctr.set_value('world_boss_check', 0)
    ctr.set_value('raid_check', 0)
    #ctr.set_value('raid_check',None)
    number_of_occurrence = 0
    ctr.set_value('max_level_check', None)
    ctr.set_value('return_check', 0)
    ticks = time.time()
    date = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime(ticks)) + '_日誌'
    f = open(date + '.txt', 'w', 0)

    frame = JFrame("Log")
    txt = JTextArea(19, 55)
    scrollPane = JScrollPane(txt)
    ##frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.setLocation(2000, 100)
    frame.setSize(480, 450)
    frame.setLayout(FlowLayout())
    ##label = JLabel('記錄:')
    scrollPane.setHorizontalScrollBarPolicy(
        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER)
    ##frame.add(label)
    frame.add(scrollPane)
    frame.setVisible(True)
def show():
    """ adapted from here: http://wiki.gephi.org/index.php/Toolkit_-_Reuse_the_Preview_Applet"""
    from javax.swing import JFrame
    from java.awt import BorderLayout

    pc = PreviewController
    pc.refreshPreview();
     
    # New Processing target, get the PApplet
    target = pc.getRenderTarget("processing")
    applet = target.getApplet()
    applet.init()
     
    # Refresh the preview and reset the zoom
    try:
        pc.render(target) 
    except Exception:
        # throws sun.dc.pr.PRError: sun.dc.pr.PRError: setPenT4: invalid pen transformation (singular)
        pass
    target.refresh()
    target.resetZoom()
     
    # Add the applet to a JFrame and display
    frame = JFrame("Preview")
    frame.setLayout(BorderLayout())
     
    # frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.add(applet, BorderLayout.CENTER)
     
    frame.pack()
    frame.setVisible(True)
Example #33
0
def startGui():
    frame = JFrame("MonkeyPySon")
    frame.setContentPane(getContentPane())
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.pack()
    frame.setVisible(True)
    frame.addWindowFocusListener(GuiWindowFocusListener())
    startLookingDevices()
Example #34
0
class ApplicationTestCase(unittest.TestCase):
	def setUp(self):
		Robot().mouseMove(800, 600)
		self.launch_app()
		self.app = ApplicationTestApp()

	def tearDown(self):
		self.frame.setVisible(False)
		self.frame.dispose()

	def launch_app(self):
		self.frame = JFrame("Test Window", defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
		pane = self.frame.getContentPane()
		layout = SpringLayout()
		pane.setLayout(layout)
		label = JLabel("Test Label")
		pane.add(label)
		layout.putConstraint(SpringLayout.WEST, label, 20, SpringLayout.WEST, pane)
		layout.putConstraint(SpringLayout.NORTH, label, 20, SpringLayout.NORTH, pane)
		self.frame.pack()
		self.frame.setVisible(True)
		self.frame.setSize(800, 600)

	def test_init_window(self):
		window = self.app.init_window(ApplicationTestWindow)
		self.assertNotEqual(window, None)
		self.assertTrue(isinstance(window, ApplicationTestWindow))
		self.assertEqual((window.region.getW(), window.region.getH()), (800, 600))

	def test_create_image_folders(self):
		path = os.path.join('images', 'application_test_window', 'test_label')
		shutil.move(os.path.join(path, 'enabled.png'), os.path.join('images', '.enabled.png.tmp'))
		shutil.rmtree(os.path.join('images', 'application_test_window'))
		self.app.create_image_folders()
		self.assertTrue(os.path.exists(path))
		shutil.move(os.path.join('images', '.enabled.png.tmp'), os.path.join(path, 'enabled.png'))

	# TODO: test_capture_screenshots
	# TODO: test_open

	def test_find_focused_window(self):
		window = self.app.find_focused_window()
		self.assertNotEqual(window, None)
		self.assertTrue(isinstance(window, ApplicationTestWindow))

	def test_focused_window(self):
		before_time = time.time()
		window = self.app.focused_window(10)
		after_time = time.time()
		self.assertTrue(after_time >= before_time + 10)
		self.assertNotEqual(window, None)
		self.assertTrue(isinstance(window, ApplicationTestWindow))
def readSVG(svgPath):
	#parser = XMLResourceDescriptor.getXMLParserClassName()
	#f = SAXSVGDocumentFactory(parser)
	#print(svgPath)
	#doc = f.createDocument(svgPath.toURI().toString())
	#print(doc)
	svgCanvas = JSVGCanvas()
	svgCanvas.setURI(svgPath.toURI().toString())
	f = JFrame('SVG image', size=(1000, 1000), locationRelativeTo=None)
	p = JPanel()
	p.add(svgCanvas)
	f.getContentPane().add(p)
	f.setVisible(True)
Example #36
0
File: ashdi.py Project: sjp38/ash
def start_ashdi():
    loadKeyLayout("data_2.0/ashdi_keylayout.xml")

    global frame
    frame = JFrame(FRAME_TITLE)
    frame.setContentPane(getContentPane())
    frame.windowClosing = lambda x: windowClosing()
    frame.pack()
    frame.setVisible(True)
    frame.addWindowFocusListener(GuiWindowFocusListener())
    start_android_waker()
    handleConnectedDevBtn(True)
    check_move_support()
Example #37
0
def createFrame():
    global isDominant
    manager = doAction()
    if isTemporal:
        frame = JFrame("LosiTemp - LOoking for Selection In TEMPoral datasets")
    elif isDominant:
        frame = JFrame("Mcheza - Dominant Selection Workbench")
    else:
        frame = JFrame("LOSITAN - Selection Workbench")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    doPrettyType(frame, manager)
    frame.setVisible(1)
    frame.setResizable(0)
    return frame
def install(helper):
  	print('install called'); 
	
	frame = JFrame("Please Input Values")
	frame.setLocation(100,100)
	frame.setSize(500,400)
	frame.setLayout(None)

	lbl1 = JLabel("Input1: ")
	lbl1.setBounds(60,20,60,20)
	txt1 = JTextField(100)
	txt1.setBounds(130,20,200,20)
	lbl2 = JLabel("Input2: ")
	lbl2.setBounds(60,50,100,20)
	txt2 = JTextField(100)
	txt2.setBounds(130,50,200,20)
	lbl3 = JLabel("Input3: ")
	lbl3.setBounds(60,80,140,20)
	txt3 = JTextField(100)
	txt3.setBounds(130,80,200,20)
	lbl4 = JLabel("Input4: ")
	lbl4.setBounds(60,110,180,20)
	txt4 = JTextField(100)
	txt4.setBounds(130,110,200,20)
	
	def getValues(event):
		print "clicked"
		ScriptVars.setGlobalVar("Input1",str(txt1.getText()))
		print(ScriptVars.getGlobalVar("Input1"))
		ScriptVars.setGlobalVar("Input2",str(txt2.getText()))
		print(ScriptVars.getGlobalVar("Input2"))
		ScriptVars.setGlobalVar("Input3",str(txt3.getText()))
		print(ScriptVars.getGlobalVar("Input3"))
		ScriptVars.setGlobalVar("Input4",str(txt4.getText()))
		print(ScriptVars.getGlobalVar("Input4"))		
		
	btn = JButton("Submit", actionPerformed = getValues)
	btn.setBounds(160,150,100,20)
		
	frame.add(lbl1)
	frame.add(txt1)
	frame.add(lbl2)
	frame.add(txt2)
	frame.add(btn)
	frame.add(lbl3)
	frame.add(txt3)
	frame.add(lbl4)
	frame.add(txt4)
	frame.setVisible(True)
Example #39
0
  def __init__(self, title, display, panel):
    from java.awt import Toolkit
    from javax.swing import JFrame
    self.display = display

    frame = JFrame(title, windowClosing=self.desty)
    frame.getContentPane().add(panel)
    frame.pack()
    frame.invalidate()

    fSize = frame.getSize()
    screensize = Toolkit.getDefaultToolkit().getScreenSize()
    frame.setLocation((screensize.width - fSize.width)/2,
                      (screensize.height - fSize.height)/2)
    frame.setVisible(1)
Example #40
0
class ShowImageViewer:
    def __init__(self):
        self.frame = JFrame("Display Image")

        btn = JButton("Switch",actionPerformed=self.switchPic)
        #self.frame.getContentPane().add(btn)
        self.switchPic('/home/jack/Desktop/mgarvin.jpg')
        self.frame.setSize(500,500)
        self.frame.setVisible(True)

    def callSwitchPic(self,event):
        self.switchPic('/home/jack/Desktop/mteam.jpg')
    
    def switchPic(self,image):
        panel = ShowImage(image)
        self.frame.getContentPane().add(panel)        
Example #41
0
def geom_viewer(dsm2file = "dsm2.inp"):
  """
  geom_viewer(dsm2file = "dsm2.inp")
  starts off a dsm2 geometry viewer for dsm2 input data
  Irregular xsections are plotted if available otherwise
  regular xsections are plotted.
  """
  dgv = DSM2GeomViewer(dsm2file)
  mp = dgv.gui()
  fr = JFrame()
  fr.setTitle('Geom Viewer')
  fr.getContentPane().add(mp)
  fr.setLocation(300,100)
  fr.pack()
  sz = fr.getSize()
  fr.setSize(250,sz.height)
  fr.setVisible(1)
Example #42
0
def createAndShowGUI():
    # Create the GUI and show it. As with all GUI code, this must run
    # on the event-dispatching thread.
    frame = JFrame("GUI Development ")
    frame.setSize(500, 600)
    frame.setLayout(BorderLayout())
    splitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
    
    #Create and set up the content pane.
    psimures= ResourcePanel()
    psimures.setOpaque(True)
    pconfig = ConfigurationPanel()
    pconfig.setOpaque(True)      #content panes must be opaque

    # show the GUI
    splitPane.add(psimures)
    splitPane.add(pconfig)
    frame.add(splitPane)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
    frame.setVisible(True)
Example #43
0
def createAndShowGUI():
    # Create the GUI and show it. As with all GUI code, this must run
    # on the event-dispatching thread.
    frame = JFrame("MAE ")
    frame.setSize(1024, 768)
    panel= JPanel()
    panel.setLayout(GridBagLayout())
    
    #Create and set up the content pane.
    psimures= SimoutPanel()
    psimures.setOpaque(True)
    c = GridBagConstraints()
    c.fill = GridBagConstraints.HORIZONTAL
    c.weightx = 1
    c.gridx = 0
    c.gridy = 0
    panel.add(psimures, c);
    pmeasure= MeasPanel()
    pmeasure.setOpaque(True)
    c = GridBagConstraints()
    c.fill = GridBagConstraints.HORIZONTAL
    c.weightx = 1
    c.gridx = 0
    c.gridy = 1
    panel.add(pmeasure, c);
    preport = ReportPanel()
    preport.setOpaque(True)
    c = GridBagConstraints()
    c.fill = GridBagConstraints.VERTICAL
    c.weighty = 1
    c.gridx = 1
    c.gridy = 0
    c.gridheight= 2
    panel.add(preport,c)
    # show the GUI
    
    frame.add(panel)
#     frame.add(pmeasure)
#     frame.add(preport)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
    frame.setVisible(True)
Example #44
0
class StopWatch(Runnable):
    def __init__(self):
        self.frame = JFrame("StopWatch", defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        self.start = JButton("Start", actionPerformed=self.start)
        self.frame.add(self.start, BorderLayout.WEST)
        self.stop = JButton("Stop", actionPerformed=self.stop)
        self.frame.add(self.stop, BorderLayout.EAST)
        self.label = JLabel(" " * 45)
        self.frame.add(self.label, BorderLayout.SOUTH)
        self.frame.pack()

    def start(self, event):
        self.started = Calendar.getInstance().getTimeInMillis()
        self.label.setText("Running")

    def stop(self, event):
        elapsed = Calendar.getInstance().getTimeInMillis() - self.started
        self.label.setText("Elapsed: %.2f seconds" % (float(elapsed) / 1000.0))

    def run(self):
        self.frame.setVisible(1)
  def __init__(self):
    frame = JFrame("Jython JTable Example")
    frame.setSize(500, 250)
    frame.setLayout(BorderLayout())

    self.tableData = [
      ['Mouse 1', eventNames[0], eventScriptType[0]],
      ['Mouse 2', eventNames[1] , eventScriptType[1]],
      ['Mouse 3', eventNames[2], eventScriptType[2]],
      ['Mouse 1 Shift', eventNames[3], eventScriptType[3]],
      ['Mouse 2 Shift',eventNames[4], eventScriptType[4]],
      ['Mouse 3 Shift',eventNames[5], eventScriptType[5]],
      ['Mouse 1 Control',eventNames[6], eventScriptType[6]],
      ['Mouse 2 Control',eventNames[7], eventScriptType[7]],
      ['Mouse 3 Control',eventNames[8], eventScriptType[8]],
       ]
    colNames = ('Script/Event','Name','Type')
    dataModel = DefaultTableModel(self.tableData, colNames)
    self.table = JTable(dataModel)

    scrollPane = JScrollPane()
    scrollPane.setPreferredSize(Dimension(400,200))
    scrollPane.getViewport().setView((self.table))

    panel = JPanel()
    panel.add(scrollPane)

    frame.add(panel, BorderLayout.CENTER)

    self.label = JLabel('Hello from Jython')
    frame.add(self.label, BorderLayout.NORTH)
    button = JButton('Save Settings',actionPerformed=self.setText)
    frame.add(button, BorderLayout.SOUTH)
    exitButton = JButton('Exit',actionPerformed=self.myExit)
    frame.add(exitButton, BorderLayout.EAST)

    frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
    frame.setVisible(True)
Example #46
0
def main(args):
  _WIDTH = 300
  _HEIGHT = 300
  fps = 20#frames per second
  bgColor = Color.white
  frame = JFrame("Graphics!")
  frame.setBackground(bgColor);
  frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)

  drawgraphics = DrawGraphics()
  content = Animator(drawgraphics, _WIDTH, _HEIGHT, fps)
  content.setBackground(bgColor)
  content.setSize(_WIDTH, _HEIGHT)
  content.setMinimumSize(Dimension(_WIDTH, _HEIGHT))
  content.setPreferredSize(Dimension(_WIDTH, _HEIGHT))

  frame.setSize(_WIDTH, _HEIGHT)
  frame.setContentPane(content)
  frame.setResizable(True)
  frame.pack()

  Thread(content).start()
  frame.setVisible(True)
    def __init__(self, imgData):
        n = imgData.size()
        win = JFrame("Point Marker Panel")
        win.setPreferredSize(Dimension(350, 590))
        win.setSize(win.getPreferredSize())
        pan = JPanel()
        pan.setLayout(BoxLayout(pan, BoxLayout.Y_AXIS))
        win.getContentPane().add(pan)

        progressPanel = JPanel()
        progressPanel.setLayout(BoxLayout(progressPanel, BoxLayout.Y_AXIS))
        positionBar = JProgressBar()
        positionBar.setMinimum(0)
        positionBar.setMaximum(n)
        positionBar.setStringPainted(True)
        progressPanel.add(Box.createGlue())
        progressPanel.add(positionBar)

        progressBar = JProgressBar()
        progressBar.setMinimum(0)
        progressBar.setMaximum(n)
        progressBar.setStringPainted(True)
        progressPanel.add(progressBar)
        progressPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(progressPanel)

        pan.add(Box.createRigidArea(Dimension(5,5)))
        savePanel = JPanel()
        savePanel.setLayout(BoxLayout(savePanel, BoxLayout.Y_AXIS))
        saveMessageLabel = JLabel("<html><u>Save Often</u></html>")
        savePanel.add(saveMessageLabel)
        savePanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        savePanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(savePanel)
        # pan.add(saveMessageLabel)

        pan.add(Box.createRigidArea(Dimension(5,5)))
        calPanel = JPanel()
        calPanel.setLayout(BoxLayout(calPanel, BoxLayout.Y_AXIS))
        calPanelIn = JPanel()
        calPanelIn.setLayout(BoxLayout(calPanelIn, BoxLayout.X_AXIS))
        pixelSizeText = JTextField(12)
        pixelSizeText.setHorizontalAlignment(JTextField.RIGHT)
        # pixelSizeText.setMaximumSize(pixelSizeText.getPreferredSize())
        unitText = JTextField(10)
        # unitText.setMaximumSize(unitText.getPreferredSize())
        pixelSizeText.setText("Enter Pixel Size Here")
        calPanelIn.add(pixelSizeText)
        unitText.setText("Unit")
        calPanelIn.add(unitText)
        calPanelIn.setAlignmentX(Component.CENTER_ALIGNMENT)
        calPanelIn.setBorder(BorderFactory.createTitledBorder("Custom Calibration"))
        calPanel.add(calPanelIn)
        calPanelIn.setAlignmentX(Component.CENTER_ALIGNMENT)
        calPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(calPanel)

        pan.add(Box.createRigidArea(Dimension(5,5)))
        helpPanel = JPanel()
        helpPanel.setLayout(BoxLayout(helpPanel, BoxLayout.Y_AXIS))
        helpLable = JLabel("<html><ul>\
                            <li>Focus on Image Window</li>\
                            <li>Select multi-point Tool</li>\
                            <li>Click to Draw Points</li>\
                            <li>Drag to Move Points</li>\
                            <li>\"Alt\" + Click to Erase Points</li>\
                            <li>Optional: Customize Calibration Above\
                                 and Refresh Images\
                                (won't be written to files)</li>\
                            </html>")
        helpLable.setBorder(BorderFactory.createTitledBorder("Usage"))
        keyTagOpen = "<span style=\"background-color: #FFFFFF\"><b><kbd>"
        keyTagClose = "</kbd></b></span>"
        keyLable = JLabel("<html><ul>\
                            <li>Next Image --- " + keyTagOpen + "&lt" + \
                                keyTagClose + "</li>\
                            <li>Previous Image --- " + keyTagOpen + ">" + \
                                keyTagClose + "</li>\
                            <li>Save --- " + keyTagOpen + "`" + keyTagClose + \
                                " (upper-left to TAB key)</li>\
                            <li>Next Unmarked Image --- " + keyTagOpen + \
                                "TAB" + keyTagClose + "</li></ul>\
                            </html>")
        keyLable.setBorder(BorderFactory.createTitledBorder("Keyboard Shortcuts"))
        helpPanel.add(helpLable)
        helpPanel.add(keyLable)
        helpPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        helpPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(helpPanel)

        # pan.add(Box.createRigidArea(Dimension(0, 10)))
        infoPanel = JPanel()
        infoPanel.setLayout(BoxLayout(infoPanel, BoxLayout.Y_AXIS))
        infoLabel = JLabel()
        infoLabel.setBorder(BorderFactory.createTitledBorder("Project Info"))
        infoPanel.add(infoLabel)
        infoPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        infoPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(infoPanel)

        win.setVisible(True)

        self.imgData = imgData
        self.win = win
        # self.progressPanel = progressPanel
        self.positionBar = positionBar
        self.progressBar = progressBar
        self.saveMessageLabel = saveMessageLabel
        self.infoLabel = infoLabel
        self.pixelSizeText = pixelSizeText
        self.unitText = unitText
        self.update()
def test():
    mainFrame = JFrame()
    mainFrame.setSize(208, 227)
    mainCanvas = teapotCanvas()
    mainFrame.add(mainCanvas)
    mainFrame.setVisible(1)
Example #49
0
d1 = ClientServer.getClientDisplay(client, 0)
d2 = ClientServer.getClientDisplay(client, 1)
refimg = client.getDataReference(0)
userline = client.getDataReference(1)

# get image in order to get its size and type schema
image = refimg.getData()
dom = getDomain(image)
LINES = dom.getY().getLength()
d = domainType(image)

# create line slider for client user
slide = VisADSlider("imgline",0,LINES,0,1.0,userline,d[1])

showAxesScales(d2,1)

# display everything...
frame = JFrame("Test T8 Client")
pane = frame.getContentPane()
pane.setLayout(BorderLayout())

# GridLayout with 1 row, 2 columns, 5 pixel horiz and vert gaps
panel = JPanel(GridLayout(1,2,5,5))
panel.add(d1.getComponent())
panel.add(d2.getComponent())
pane.add("Center",panel)
pane.add("North",slide)
frame.setSize(800,500)
frame.setVisible(1)

Example #50
0
        while results.next():
            i += 1
            #logger.debug("%s" % results)

            logger.debug("%s : %s" % (results.getString("TABLE_NAME"), results.getString("TABLE_TEXT")))

            #logger.debug("%s : %s [%s]" % (results.getString("COLUMN_NAME"), results.getString("COLUMN_TEXT"), results.getString("TYPE_NAME")))

            if i == 1000:
                exit()

        logger.debug("Success!")

def exit_all(event):
    exit

if __name__ == "__main__":
    f = JFrame('Hello, Jython!', defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size = (550, 200))

    f.setResizable(True)

    b = JButton('Connect!', actionPerformed=change_text)
    #d = JButton('Exit!!', actionPerformed=exit_all)

    c = f.getContentPane()
    c.setBackground(Color.DARK_GRAY)
    c.add(b)
    #c.add(d)

    f.setVisible(True)
Example #51
0
def makeEditorFrame(ldPath, compiler):
    mb = JMenuBar()
    
    file = JMenu("File")
    edit = JMenu("Edit")
    run = JMenu("Run")
    
    newMenu = menu_with_accelerator("New",(KeyEvent.VK_N,ActionEvent.META_MASK))
    file.add(newMenu)
           
    open = menu_with_accelerator("Open",(KeyEvent.VK_O,ActionEvent.META_MASK))
    file.add(open)
    
    save = menu_with_accelerator("Save",(KeyEvent.VK_S,ActionEvent.META_MASK))
    file.add(save)
    
    file.add(JSeparator());
    
    resetPipe = menu_with_accelerator("Reset Pipeline",(KeyEvent.VK_N,ActionEvent.META_MASK | ActionEvent.SHIFT_MASK))
    file.add(resetPipe)
            
    openPipe = menu_with_accelerator("Open Pipeline",(KeyEvent.VK_O,ActionEvent.META_MASK | ActionEvent.SHIFT_MASK))
    file.add(openPipe)
            
    compile = menu_with_accelerator("Compile",(KeyEvent.VK_ENTER, ActionEvent.META_MASK))
    run.add(compile)
            
    mb.add(file)
    mb.add(edit)
    mb.add(run)
            
    f = JFrame("SFGP Shader Editor")
    f.setJMenuBar(mb)
    c = f.getContentPane()
    c.setLayout(BorderLayout())
    editor = GLSLEditorPane("",ldPath,compiler)
    c.add(editor, BorderLayout.CENTER)
    c.doLayout()
    
    f.setSize(1000, 700);
    f.setVisible(True);
    f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            
    class EditorActionListener(ActionListener):
        def makeRelay(srcObj):
            return (lambda e: editor.actionPerformed(ActionEvent(srcObj, e.getID(), e.getActionCommand())))
        editorActions = {
            save : (lambda e: editor.saveCurrent()),
            compile : (lambda e: editor.compileCurrent()),
            open : makeRelay(editor.openShader),
            newMenu : makeRelay(editor.newShader),
            openPipe : makeRelay(editor.openPipeline),
            resetPipe : makeRelay(editor.resetPipeline)
                        }
        def actionPerformed(self, e):
            editorActions = EditorActionListener.editorActions
            evtSrc = e.getSource()
            if evtSrc in editorActions:
                editorActions[evtSrc](e)
            else:
                raise IllegalStateException("Imaginary menu item registered an ActionEvent: " + evtSrc)
    menuListener = EditorActionListener()
    compile.addActionListener(menuListener);
    newMenu.addActionListener(menuListener);
    open.addActionListener(menuListener);
    save.addActionListener(menuListener);
    resetPipe.addActionListener(menuListener);
    openPipe.addActionListener(menuListener);
def gui():
    fr = JFrame('Calibration Compare Tool',defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
    fr.add(InputPanel())
    fr.pack()
    fr.setVisible(True)
class FilamentGame_ModelEditor(EditorExtension, JPanel, MouseListener, MouseMotionListener):
    def getExtensionName(self):
        return "Filament Model Tool"

    def initializeExtension(self, manager):
        self.manager = manager
        self.frame = JFrame(self.getExtensionName())
        self.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

        # instance setup
        self.state = State.NOTHING
        self.entity = Entity()

        # Setupgui
        self.setupGui()
        self.addMouseListener(self)
        self.addMouseMotionListener(self)
        self.setPreferredSize(Dimension(500, 500))
        self.frame.pack()
        self.frame.setResizable(False)
        self.frame.setVisible(True)
        self.cameraPos = [0, 0]

    def setupGui(self):

        cPanel = JPanel()

        # Draw Shape Button
        self.drawShapeButton = JButton("Draw", actionPerformed=self.drawShapeButtonAction)
        cPanel.add(self.drawShapeButton)

        drawShapeButton = JButton("Clear", actionPerformed=self.clearShapeButtonAction)
        cPanel.add(drawShapeButton)

        # Label
        self.infoLabel = JLabel("Shape Editor")
        cPanel.add(self.infoLabel)

        self.frame.add(BorderLayout.NORTH, cPanel)
        self.frame.add(BorderLayout.CENTER, self)

    def entitySelected(self, entity):
        self.entity = entity
        self.repaint()

    def sceneChanged(self, scene):
        self.scene = scene
        self.entity = Entity()
        self.repaint()

    # BUTTONS
    def drawShapeButtonAction(self, e):
        if self.state == State.NOTHING:
            self.state = State.DRAW_SHAPE
            self.infoLabel.setText("Click to Draw Shape")
            self.drawShapeButton.setText("Stop Drawing")
        elif self.state != State.NOTHING:
            self.state = State.NOTHING
            self.infoLabel.setText("")
            self.drawShapeButton.setText("Draw")
        self.revalidate()

    def clearShapeButtonAction(self, e):
        if self.state != State.NOTHING:
            self.drawShapeButtonAction(e)
        self.state = State.NOTHING
        polygon = self.entity.getModel().pol
        polygon.reset()
        self.repaint()

    # DRAWING
    def paintComponent(self, g):
        self.super__paintComponent(g)
        g.scale(1, -1)
        g.translate(-self.cameraPos[0] + self.getWidth() / 2, -self.cameraPos[1] - self.getHeight() / 2)
        self.drawGrid(g)
        polygon = self.entity.getModel().pol
        x = []
        y = []
        g.setColor(Color.BLACK)
        for i in range(polygon.npoints):
            x = x + [int(polygon.xpoints[i])]
            y = y + [int(polygon.ypoints[i])]
            g.drawRect(int(polygon.xpoints[i]) - 2, int(polygon.ypoints[i]) - 2, 4, 4)
        g.fillPolygon(x, y, polygon.npoints)

    def drawGrid(self, g):
        g.setColor(Color.RED)
        g.drawLine(50, 0, -50, 0)
        g.drawLine(0, 50, 0, -50)

    # MOUSE LISTENER
    def mouseCicked(self, e):
        return

    def mouseEntered(self, e):
        return

    def mouseExited(self, e):
        return

    def mousePressed(self, e):
        self.anchor = e.getPoint()
        self.oldCamPos = self.cameraPos

    def findMousePos(self, p):
        w = self.getWidth()
        h = self.getHeight()
        cX = self.cameraPos[0]
        cY = self.cameraPos[1]

        y = h - p.y

        x = p.x - w / 2 + cX
        y = y - h / 2 + cY

        return [x, y]

    def mouseReleased(self, e):
        if self.state == State.DRAW_SHAPE:
            try:
                p = self.findMousePos(e.getPoint())
                self.entity.getModel().pol.addPoint(p[0], p[1])
            except IllegalPathStateException:
                print "Error Building Polygon path!"
        self.repaint()

    def mouseMoved(self, e):
        return

    def mouseDragged(self, e):
        if self.state == State.NOTHING:
            self.cameraPos = [
                self.oldCamPos[0] + self.anchor.x - e.getX(),
                self.oldCamPos[1] - self.anchor.y + e.getY(),
            ]
            print str(self.cameraPos)
            self.repaint()

    def update(self, delta):
        return
Example #54
0
class Pipeline():
  def __init__(self):
    #If a swing interface is asked for this will be the JFrame.
    self.frame = None
    #Keeps track of the number of queries processed.
    self.jobCount = 0
    #Keeps track of the query currently being processed.
    self.currentJob = ""
    #Keeps track of the massage to be displayed.
    self.message = 0
    #Messages to be displayed at each stage in the processing of a single query.
    self.messages = ["Searching for genes via genemark",
                     "Extending genes found via genemark",
                     "Searching for intergenic genes",
                     "Removing overlapping genes",
                     "Searching for promoters",
                     "Using transterm to find terminators",
                     "Removing transcription signals which conflict with genes",
                     "Using tRNAscan to find transfer RNAs",
                     "Writing Artemis file",
                     "Writing summary .xml, .html, and .xls files"]
    self.exception = None

  def initializeDisplay(self, queries, swing):
    """
    queries: A list of the fasts files to be processed.
    swing:   If true then updates about progress will be displayed in a swing window, otherwise they will be written to stdout.
    
    Initializes the interface for telling the user about progress in the pipeline.  Queries is used to count the
    number of queries the pipeline will process and to size the swing display(if it is used) so that text
    isn't cutoff at the edge of the window.  The swing display is setup if swing is true.
    """
  
    self.numJobs = len(queries)
    if swing:
      self.frame = JFrame("Neofelis")
      self.frame.addWindowListener(PipelineWindowAdapter(self))
      contentPane = JPanel(GridBagLayout())
      self.frame.setContentPane(contentPane)
      self.globalLabel = JLabel(max(queries, key = len))
      self.globalProgress = JProgressBar(0, self.numJobs)
      self.currentLabel = JLabel(max(self.messages, key = len))
      self.currentProgress = JProgressBar(0, len(self.messages))
      self.doneButton = JButton(DoneAction(self.frame))
      self.doneButton.setEnabled(False)

      constraints = GridBagConstraints()
      
      constraints.gridx, constraints.gridy = 0, 0
      constraints.gridwidth, constraints.gridheight = 1, 1
      constraints.weightx = 1
      constraints.fill = GridBagConstraints.HORIZONTAL
      contentPane.add(self.globalLabel, constraints)
      constraints.gridy = 1
      contentPane.add(self.globalProgress, constraints)
      constraints.gridy = 2
      contentPane.add(self.currentLabel, constraints)
      constraints.gridy = 3
      contentPane.add(self.currentProgress, constraints)
      constraints.gridy = 4
      constraints.weightx = 0
      constraints.fill = GridBagConstraints.NONE
      constraints.anchor = GridBagConstraints.LINE_END
      contentPane.add(self.doneButton, constraints)
    
      self.frame.pack()
      self.frame.setResizable(False)
      self.globalLabel.setText(" ")
      self.currentLabel.setText(" ")
      self.frame.setLocationRelativeTo(None)
      self.frame.setVisible(True)

  def updateProgress(self, job):
    """
    query: Name of the query currently being processed.
    
    This function use used for updating the progress shown in the interface.  If job is not equal to currentJob then
    global progress is incremented and shown and the currentProgress is reset and shown.  If job is equal to currentJob
    then the globalProgress does not change and currentProgress is increased.
    """
    if self.exception:
      raise self.exception
    
    if self.frame:
      if job != self.currentJob:
        self.currentProgress.setValue(self.currentProgress.getMaximum())
        self.globalLabel.setText(job)
        self.globalProgress.setValue(self.jobCount)
        print "Processing %s, %.2f%% done" % (job, 100.0*self.jobCount/self.numJobs)
        self.jobCount += 1
        self.currentJob = job
        self.message = -1
      self.message += 1
      print "    %s, %.2f%% done" % (self.messages[self.message], 100.0*self.message/len(self.messages))
      self.currentProgress.setValue(self.message)
      self.currentLabel.setText(self.messages[self.message])
    else:
      if job != self.currentJob:
        print "Processing %s, %.2f%% done" % (job, 100.0*self.jobCount/self.numJobs)
        self.jobCount += 1
        self.currentJob = job
        self.message = -1
      self.message += 1
      print "    %s, %.2f%% done" % (self.messages[self.message], 100.0*self.message/len(self.messages))

  def finished(self):
    """
    This function is to be called at the end of the pipeline.  Informs the user that the pipeline is finished
    and if a swing interface is being used the Done button is enabled.
    """
    print "Processing 100.00% done"
    if self.frame:
      self.globalLabel.setText("Finished")
      self.globalProgress.setValue(self.globalProgress.getMaximum())
      self.currentLabel.setText(" ")
      self.currentProgress.setValue(self.currentProgress.getMaximum())
      self.doneButton.setEnabled(True)
      while self.frame.isVisible():
        pass

  def run(self, blastLocation, genemarkLocation, transtermLocation, tRNAscanLocation, database, eValue, matrix, minLength, scaffoldingDistance, promoterScoreCutoff, queries, swing = False, email = ""):
    """
    blastLocation:       Directory blast was installed in.
    genemarkLocation:    Directory genemark was installed in.
    transtermLocation:   Directory transterm was installed in.
    tRNAscanLocation:    Directory tRNAscan was installed in.
    database:            Name of the blast database to use.
    eValue:              The e value used whenever a blast search is done.
    matrix:              The matrix to use when running genemark.  If None then genemark is run heuristically.
    minLength:           Minimum length of any genes included in the resulting annotation.
    scaffoldingDistance: The maximum length allowed between genes when contiguous regions of genes are being identified
    promoterScoreCutoff: Minimum score allowed for any promoters included in the resulting annotation
    queries:             A list of faster files to process.
    swing:               If true a swing window will be used to updated the user about the pipeline's progress.
    email:               If this is a non-empty string an email will be sent to the address in the string when the pipeline is done.  This will be attempted with the sendmail command on the local computer.
    
    The main pipeline function.  For every query genemark is used to predict genes, these genes are then extended to any preferable starts.  Then the pipeline searches
    for any intergenic genes(genes between those found by genemark) and these are combined with the extended genemark genes.  Then the genes are pruned to remove
    any undesirable genes found in the intergenic stage.  BPROM and Transterm are used to find promoters and terminators, which are then pruned to remove any
    signals which are inside or too far away from any genes.  Next, tRNAscan is used to find any transfer RNAs in the genome.  Finally, all the remaining genes,
    promoters, and terminators are written to an artemis file in the directory of the query with the same name but with a .art extension, and .xml, .html, and
    .xls files will be generating describing the blast results of the final genes.
    """
    self.initializeDisplay(queries, swing)

    try:
      for query in queries:
        name = os.path.splitext(query)[0]
        queryDirectory, name = os.path.split(name)
        
        genome = utils.loadGenome(query)
        swapFileName = "query" + str(id(self)) + ".fas"
        queryFile = open(swapFileName, "w")
        queryFile.write(">" + name + "\n")
        for i in range(0, len(genome), 50):
          queryFile.write(genome[i:min(i+50, len(genome))] + "\n")
        queryFile.close()

        self.updateProgress(query)
        initialGenes = genemark.findGenes(swapFileName, name, blastLocation, database, eValue, genemarkLocation, matrix, self)
      
        self.updateProgress(query)
        extendedGenes = extend.extendGenes(swapFileName, initialGenes, name, blastLocation, database, eValue, self)
    
        self.updateProgress(query)
        intergenicGenes = intergenic.findIntergenics(swapFileName, extendedGenes, name, minLength, blastLocation, database, eValue, self)

        genes = {}
        for k, v in extendedGenes.items() + intergenicGenes.items():
          genes[k] = v
        
        self.updateProgress(query)
        scaffolded = scaffolds.refineScaffolds(genes, scaffoldingDistance)
 
        self.updateProgress(query)
        initialPromoters = promoters.findPromoters(swapFileName, name, promoterScoreCutoff, self.frame)
    
        self.updateProgress(query)
        initialTerminators = terminators.findTerminators(swapFileName, name, genes.values(), transtermLocation)
      
        self.updateProgress(query)
        filteredSignals = signals.filterSignals(scaffolded.values(), initialPromoters + initialTerminators)
        filteredPromoters = filter(lambda x: isinstance(x, promoters.Promoter), filteredSignals)
        filteredTerminators = filter(lambda x: isinstance(x, terminators.Terminator), filteredSignals)

        self.updateProgress(query)
        transferRNAs = rna.findtRNAs(tRNAscanLocation, swapFileName)

        os.remove(swapFileName)

        self.updateProgress(query)
        artemis.writeArtemisFile(os.path.splitext(query)[0] + ".art", genome, scaffolded.values(), filteredPromoters, filteredTerminators, transferRNAs)

        self.updateProgress(query)
        report.report(name, scaffolded, os.path.splitext(query)[0])

      if email:
        if not os.path.isfile("EMAIL_MESSAGE"):
          message = open("EMAIL_MESSAGE", "w")
          message.write("Subject: Annotation Complete\nYour genome has been annotated.\n")
          message.close()
        
        sent = False
        while not sent:
          message = open("EMAIL_MESSAGE", "r")
          sendmailProcess = subprocess.Popen(["/usr/sbin/sendmail", "-F", "Neofelis", "-f", "*****@*****.**", email],
                                             stdin = message,
                                             stdout = subprocess.PIPE)
          result = ""
          nextRead = sendmailProcess.stdout.read()
          while nextRead:
            result += nextRead
            nextRead = sendmailProcess.stdout.read()
          sent = not result.strip()
          message.close()
    
      self.finished()
    except PipelineException:
      return
Example #55
0
main_panel = JPanel()

### panel 1
panel1 = JPanel()
panel1.add(lbl1)
cb1 = JComboBox(choice_list)
btn1 = JButton("Accept")
btn1.addActionListener(ButtonListener(btn1))
panel1.add(cb1)
panel1.add(btn1)

### panel 2
panel2 = JPanel()
panel2.add(lbl2)
cb2 = JComboBox(sorted(roi_ni.keys()))
cb2.addActionListener(Listener(lbl2, cb2))
panel2.add(cb2)

### panel 3
pnl3 = JPanel()
lst1 = JList(listmodel)
pnl3.add(lst1)

frame = JFrame("Swing GUI Test Frame")
frame.getContentPane().add(main_panel)
main_panel.add(panel1)
main_panel.add(panel2)
main_panel.add(pnl3)
frame.pack()
frame.setVisible(True)
Example #56
0
def main():
	
	binNaviProxy = StandAlone.getPluginInterface()
	binNaviProxy.databaseManager.addDatabase("","com.mysql.jdbc.Driver","localhost","BINNAVI1","binnavi","binnavi",False,False)
	db=binNaviProxy.databaseManager.databases[0]
	db.connect()
	db.load()
	mods=db.getModules()
	
	### initiate dialogBox to setect the module that should be used.
	
	######################################################
	
	
	frame = JFrame('BinNavi Module Selector',layout=BorderLayout(),		
				defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
				size = (1500, 800)
			)
	frame2 = JFrame('Function Selector',layout=BorderLayout(),		
				defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
				size = (30, 30)
			)
			
	frame2.setFocusableWindowState(False)
	frame2.setFocusable(False)
	frame2.setAlwaysOnTop(False)
	#convert the module list into the string to be used in the TextBox.
	textTemp = map((lambda x,y:"[%d]%s"%(x,y)),range(len(mods)),mods) 
	textStr=''.join(textTemp)

	tx=JTextArea(textStr)
	tx.setLineWrap(True);
	tx.setWrapStyleWord(True);
	frame.add(tx,BorderLayout.PAGE_START)
	frame.visible = True
	modInd = JOptionPane.showInputDialog(frame2, "Enter the index of the chosen module", 
			 "Module selector");
	
	#Open the module returned by the index 
	bfname=mods[int(modInd)] # this modules correxponds to the chosen module
	bfname.load()
	funcViews=bfname.views
	#textTemp2 = ["[%d]%s"%(i,j) for i in range(len(funcViews)) for j in funcViews]
	textTemp2=map((lambda x,y:"[%d]%s"%(x,y.toString()[5:18])),range(len(funcViews)),funcViews)
	textStr1=''.join(textTemp2)
	## remove the older text from the frame view
	frame.remove(tx)
	frame.update(frame.getGraphics())
	frame.visible = False
	## create a new textArea with the string made from all the functions' name
	txStr=JTextArea(textStr1)
	#tx.setsrcollOffset(20)
	txStr.setLineWrap(True);
	txStr.setWrapStyleWord(True);
	frame.add(txStr,BorderLayout.PAGE_START)
	frame.update(frame.getGraphics())
	frame.visible = True
	funcInd = JOptionPane.showInputDialog(frame2, "Enter the index of the function", 
			 "Function selector");
   
 ######################################################
	
	
	bffunc=bfname.views[int(funcInd)] #this is the view of the buildfname function
	bffunc.load()
	
	frame2.setVisible(False)
	dispose(frame2)
	
	bfReil=bffunc.getReilCode() # this is the REIL code of the function
	bfReilGraph=bfReil.getGraph()
			
	instGraph = InstructionGraph.create(bfReilGraph)
	time.clock()
	results=doAnalysis(instGraph)
	totalTime=time.clock()
	#print "resultsLen", len([r for r in results])
			
	print "**** printing results *******\n"
	print "Total time:", totalTime, '\n'
	numNode=0
	for n in instGraph:
		numNode+=numNode
		
		nIn=list(results.getState(n).inVal)
		nIn.sort(key=itemgetter(0))
		nOut=list(results.getState(n).out)
		nOut.sort(key=itemgetter(0))
		print '@@ ',n.getInstruction(),'\n'
		print '\t In', nIn, '\n'
		print '\t OUT', nOut, '\n'
		print '\t memory: ',results.getState(n).memoryWritten, '\n'
	print "++++ Total instructions: %d +++++\n"%numNode		 
	#finally close the view of the function
	bffunc.close()
	#print bffunc.isLoaded()
	#junky=raw_input("function closed. enter any charater")
	


	print "Done! Closing the module selector window"
	frame.setVisible(False)
	dispose(frame)
class ToBeDetermined( Runnable ) :
    def __init__( self ) :
        self.frame = JFrame( 'ToBeDetermined' , defaultCloseOperation = JFrame.EXIT_ON_CLOSE );        
    def run( self ) :
        self.frame.setVisible( 1 );   # Have the application make itself visible
def main():
    '''
    Main function that implements main algorithm
    
    '''
    # a file where some log will be created which says how many functions are discovered etc.
    logFile=raw_input("Enter the name of log file")
    # this is provided as an extra file which is a pickled file comtains a list of functions
    # that are found to be BOP. Its main purpose is: if you want to use these functions for some
    # other analysis, just load this file and viola!!!
    fileBOP=raw_input("Enter the file name (full path) to store (Pickled) BOP function's name: ")
    
    interestingFuncs={} # dictionary of interesting functions
    interestingFuncsLOC={} # dictionary of LOC in interesting functions

    binNaviProxy = StandAlone.getPluginInterface()
    
    ################## place to set database connectivity parameter ######### 
    binNaviProxy.databaseManager.addDatabase("","org.postgresql.Driver","localhost","DataBase_name","user","password",False,False)
    ########################################################################
    db=binNaviProxy.databaseManager.databases[0]
    db.connect()
    db.load()
    mods=db.getModules()

    ### initiate dialogBox to setect the module that should be used.

    ######################################################


    frame = JFrame('BinNavi Module Selector',layout=BorderLayout(),
                defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
                size = (500, 500)
            )
    frame2 = JFrame('Function Selector',layout=BorderLayout(),
                defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
                size = (30, 30)
            )


    #convert the module list into the string to be used in the TextBox.
    ## This gives a very ugly box to select the required function (yes, I am bit lazy to learn Java Swing!!). 
    textTemp = map((lambda x,y:"[%d]%s"%(x,y)),range(len(mods)),mods)
    textStr=''.join(textTemp)

    tx=JTextArea(textStr)
    tx.setLineWrap(True);
    tx.setWrapStyleWord(True);
    frame.add(tx,BorderLayout.PAGE_START)
    frame.visible = True
    modInd = JOptionPane.showInputDialog(frame2, "Enter the index of the chosen module",
             "Module selector");

    #Open the module returned by the index
    bfname=mods[int(modInd)] # this modules correxponds to the chosen module
    bfname.load()
    funcViews=bfname.views

    frame2.setVisible(False)
    dispose(frame2)

 ######################################################
    analyzedFunctions = 0
    totalDiscoveredLoops=0
    totalInterestingLoops=0
    time.clock()
    for funcInd in range(1,len(funcViews)):
        
        BBnum=funcViews[funcInd].getNodeCount()
        
        if BBnum <4:
            print "skipped"
            continue #do not analyse function if num of BB less than 4
        
        print 'analyzing %s'%funcViews[funcInd].getName()

        dominatingSets={}#dictionary to keep dominating nodes of a node

        bffunc=bfname.views[int(funcInd)] #this is the view of the buildfname function
        bffunc.load()
        try:
            bfReil=bffunc.getReilCode() # this is the REIL code of the function
        except:
            print "error in getReilCode()"
            bffunc.close()
            gc.collect()
            continue

        bfReilGraph=bfReil.getGraph()
        try:
            #dominatorTree = GraphAlgorithms.getDominatorTree(bfReilGraph, findRoot(bfReilGraph.getNodes())) #only for BinNavi v 3.0
            dominatorTree = GraphAlgorithms.getDominatorTree(bfReilGraph, findRoot(bfReilGraph.getNodes()),None)
        except:
            print "dominator tree problem.. continue with the next function"
            bffunc.close()
            gc.collect()
            continue

        fillDominatingSets(dominatorTree.getRootNode(), dominatingSets, None)

        # let us find loops in this function
        finalLoops=findLoops(bfReilGraph,dominatingSets)
        if finalLoops ==None:
            bffunc.close()
            gc.collect()
            continue
        analyzedFunctions = analyzedFunctions +1
        totalDiscoveredLoops = totalDiscoveredLoops + len(finalLoops)
        # check if the loops are potential candidates for being interesting.
        # this is done by checking if there are atleast 2 STM statements in each loop.
        #print "privious length", len(finalLoops)
        if len(finalLoops)== 0:
            bffunc.close()
            gc.collect()
            continue
        for lp in finalLoops.keys():
            countSTM=0
            for lpn in finalLoops[lp]:
                inst=lpn.getInstructions()
                for i in inst:

                    if i.getMnemonic() == 'stm':
                        countSTM=countSTM+1
                if countSTM >0:
                    break


            if countSTM <= 0:
                del finalLoops[lp]

        #print "latest length", len(finalLoops)

        if len(finalLoops)== 0:
            bffunc.close()
            gc.collect()
            continue


        instGraph = InstructionGraph.create(bfReilGraph)
        
        interestingFuncs[funcViews[funcInd].getName()]=[]
        
        for k in finalLoops.keys():
            print 'analysing loop at %s-%s'%(k[0],k[1])
            if k[0] == k[1]:
                print "skipping this loop as src= dest"
                continue
            #check to skip very big loops i.e. loops having 100 BB
            if len(finalLoops[k]) > 100:
                print "very big loop, skipping!"
                continue
            if isInteresting(finalLoops[k],instGraph) ==True:
                totalInterestingLoops = totalInterestingLoops + 1
                interestingFuncs[funcViews[funcInd].getName()].append(k)
                interestingFuncsLOC[str(funcViews[funcInd].getName())]=sum([len(x.getInstructions()) for x in (getCodeNodes(bffunc.getGraph()))])
                print 'loop at %s IS interesting.'%k[0]
            else:
                print 'loop at %s is NOT interesting.'%k[0]

        #finally close the view of the function
        bffunc.close()
        gc.collect()
        #print bffunc.isLoaded()
        #junky=raw_input("function closed. enter any charater")
    totalTime=time.clock()

# remove the function entries that do not have any interesting loops
    for ky in interestingFuncs.keys():
        if len(interestingFuncs[ky]) == 0:
            del interestingFuncs[ky]

    # write the results in a file
    #


    outFile=open(logFile,'w')
    outFile.write('########## Global Results ###########\n')
    outFile.write('Total Functions in the module: ')
    outFile.write(str(len(funcViews)))
    outFile.write('\nTotal Analyzed Functions in the module: ')
    outFile.write(str(analyzedFunctions))
    outFile.write('\nTotal Interesting Functions in the module: ')
    outFile.write(str(len(interestingFuncs)))
    outFile.write('\nTotal loops discovered in the module: ')
    outFile.write(str(totalDiscoveredLoops))
    outFile.write('\nTotal INTERESTING loops discovered in the module: ')
    outFile.write(str(totalInterestingLoops))
    outFile.write('\nTotal Time: ')
    outFile.write(str(totalTime))
    outFile.write('\n')
    outFile.write('########## Global Results ###########\n')
    for k in interestingFuncs.keys():
        outFile.write("%s: %s: %d"%(str(k), "LOC", interestingFuncsLOC[k]))
        outFile.write('\n')
        for l in interestingFuncs[k]:
            outFile.write('\t')
            outFile.write(str(l))
            outFile.write('\n')
    outFile.close()
    # before we save these BOPS, we include few widely known BOPs which are given int eh following list

    knownBOPs = ['strcpy', 'strncpy', 'memcpy','wcscpy']
    for fn in knownBOPs:
        interestingFuncs[fn] = []


    # save the function name as pickled objects
    fileBOPFd=open(fileBOP+'.pkl', 'w')
    pickle.dump(interestingFuncs.keys(), fileBOPFd)
    fileBOPFd.close()
    print "[*] Pickled in the file %s"%fileBOP+'.pkl'
    print "Done! Closing the module selector window"
    frame.setVisible(False)
    dispose(frame)