text:
Q: Serial port access application using jSerialComm library is not getting LISTENING_EVENT_DATA_AVAILABLE events I am trying to communicate with a BLE module over a serial port connection.  The hardware is implemented by a USB-to-Serial device which makes it difficult to probe the interface pins.
The problem is that while I can "see" the writes to the BLE device in a software package that displays the USB traffic I do not see any responses from the BLE device.  I can send and receive data to the BLE device using teraTerm.
(Note:  I suspect the USB sniffer program will only "see" data from the BLE or loop-back device if my Java application calls a read function.)
I switched the serial port from the BLE device to a generic USB-to-Serial device with transmit wired to receive and RTS wired to CTS.  Any data sent to the port should be echoed back.  It works with a serial port emulator (teraTerm) so I know the hardware is ok but my Java application does not respond.
I set breakpoints in the getListeningEvents() and serialEvent() methods but they do not get called.  It looks like I have not setup the code properly to get events.  Unfortunately the examples for the jSerialComm library are all code snippets and do not include a full functional program so I suspect some detail about the overall application structure might be my problem.
The code was originally separated between GUI-related code and serial port related code but I had problems with static and non-static objects.  I have 30+ years of C experience and about 6 weeks of Java use.  Putting it all in one class was the sledgehammer approach but I couldn't find a better solution.  Although just because it compiles doesn't mean it's right...
mainScreen.java is:
package foo;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JOptionPane;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.JTextField;

import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.*;

import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author SGrunza
 */
public class mainScreen extends javax.swing.JFrame
{

   static SerialPort portNINA;
   static String portNINAstr;

   public void msSleep(int msToSleep)
   {
      try
         {
         Thread.currentThread().sleep(msToSleep);
         }
      catch (InterruptedException ex)
         {
         System.out.println(ex);
         }
   }

   public String pickPort(JFrame topFrame)
   {

      String retVal;

      SerialPort[] ports = SerialPort.getCommPorts();

      // Create array of descriptive port names
      ArrayList<String> names = new ArrayList<>();

      for (int i = 0; i < ports.length; i++)
         {
         names.add(ports[i].getDescriptivePortName());
         }

      // Turn ArrayList into String array
      String nameString[] = new String[names.size()];
      for (int i = 0; i < names.size(); i++)
         {
         nameString[i] = names.get(i);
         }

      // Choose the port
      retVal = ListDialog.showDialog(
              topFrame,
              topFrame,
              "Choose the serial port used by the NINA module",
              "Configure Serial Port",
              nameString,
              null,
              null);

      //System.out.println( retVal );
      portNINAstr = retVal;
      portNINA = null;

      for (int i = 0; i < names.size(); i++)
         {
         if (nameString[i].equals(portNINAstr))
            {
            // Found it
            portNINA = ports[i];
            }
         }

      return retVal;
   }

   public void openNINAport()
   {
      portNINA.openPort();

      portNINA.addDataListener(new SerialPortDataListener()
      {
         @Override
         public int getListeningEvents()
         {
            return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
         }

         @Override
         public void serialEvent(SerialPortEvent event
         )
         {
            if (event.getEventType() == SerialPort.LISTENING_EVENT_DATA_AVAILABLE)
               {
               while (portNINA.bytesAvailable() > 0)
                  {
                  byte[] newData = new byte[portNINA.bytesAvailable()];
                  int numRead = portNINA.readBytes(newData, newData.length);
                  setFromLog(newData, numRead);
                  }
               }
         }

      });

   }

   public void setFromLog(byte[] data, int len)
   {
      String text = new String(data);

      fromNINAlog.append(text + "\r\n");
      fromNINAlog.update(fromNINAlog.getGraphics());
   }

   public void setToLog(byte[] data, int len)
   {
      String text = new String(data);

      toNINAlog.append(text + "\r\n");
      toNINAlog.update(toNINAlog.getGraphics());
   }

   public void setFromLog(String text)
   {
      fromNINAlog.append(text + "\r\n");
      fromNINAlog.update(fromNINAlog.getGraphics());
   }

   public void setToLog(String text)
   {
      toNINAlog.append(text + "\r\n");
      toNINAlog.update(toNINAlog.getGraphics());
   }

   public void healthCheck()
   {
      Calendar now = Calendar.getInstance();
      int hour = now.get(Calendar.HOUR_OF_DAY);
      int minute = now.get(Calendar.MINUTE);
      int second = now.get(Calendar.SECOND);

      String timeString = new String();

      timeString = timeString.format("%02d:%02d:%02d", hour, minute, second);
      clockField.setText(timeString);
      //System.out.println( timeString );

      if (portNINA != null)
         {
         if (portNINA.isOpen())
            {
            commStatusTextField.setText(portNINA.getSystemPortName() + " open");

            if (portNINA.bytesAvailable() > 0)
               {
               System.out.println("Data available on com port");
               }

            }
         else
            {
            commStatusTextField.setText(portNINA.getSystemPortName() + " not open");
            }
         }
      else
         {
         commStatusTextField.setText("Not open");
         }

   } // end of healthCheck()

   /**
    * Creates new form mainScreen
    */
   public mainScreen()
   {
      Timer healthTimer = new Timer();

      initComponents();

      fromNINAlog.setLineWrap(true);
      fromNINAlog.setWrapStyleWord(true);
      toNINAlog.setLineWrap(true);
      toNINAlog.setWrapStyleWord(true);

      healthTimer.scheduleAtFixedRate(new TimerTask()
      {
         @Override
         public void run()
         {
            //System.out.println( "healthTask " + new Date() +
            //        "Thread name: " + Thread.currentThread().getName() );
            healthCheck();
         }
      },
              0, // delay until first run
              1000); // delay for each subsequent run

      clockField.setToolTipText("If the clock is updating, the code is running");
      clockField.setHorizontalAlignment(JTextField.CENTER);

      // Picking COM port each time is annoying
      String retVal;

      SerialPort[] ports = SerialPort.getCommPorts();

      // Create array of descriptive port names
      ArrayList<String> names = new ArrayList<>();

      for (int i = 0; i < ports.length; i++)
         {
         names.add(ports[i].getDescriptivePortName());
         }

      // Turn ArrayList into String array
      String nameString[] = new String[names.size()];
      for (int i = 0; i < names.size(); i++)
         {
         nameString[i] = names.get(i);
         }

      // Should be from a config file
      portNINAstr = "USB Serial Port (COM19)";
      portNINA = null;

      for (int i = 0; i < names.size(); i++)
         {
         if (nameString[i].equals(portNINAstr))
            {
            // Found it
            portNINA = ports[i];
            }
         }

      // Handle case where default didn't work
      if (portNINA == null)
         {
         portNINAstr = null;
         }
   }

   /**
    * This method is called from within the constructor to initialize
    * the form. WARNING: Do NOT modify this code. The content of this
    * method is always regenerated by the Form Editor.
    */
   @SuppressWarnings("unchecked")
   // <editor-fold defaultstate="collapsed" desc="Generated Code">
   private void initComponents()
   {

      helpAboutDialog = new javax.swing.JOptionPane();
      jPanel1 = new javax.swing.JPanel();
      resetButton = new javax.swing.JButton();
      factoryResetButton = new javax.swing.JButton();
      connectButton = new javax.swing.JButton();
      clockField = new javax.swing.JTextField();
      disconnectButton = new javax.swing.JButton();
      jLabel1 = new javax.swing.JLabel();
      commStatusTextField = new javax.swing.JTextField();
      configureNINAbutton = new javax.swing.JButton();
      jPanel2 = new javax.swing.JPanel();
      jScrollPane1 = new javax.swing.JScrollPane();
      toNINAlog = new javax.swing.JTextArea();
      jPanel3 = new javax.swing.JPanel();
      jScrollPane2 = new javax.swing.JScrollPane();
      fromNINAlog = new javax.swing.JTextArea();
      jMenuBar1 = new javax.swing.JMenuBar();
      FileMenu = new javax.swing.JMenu();
      QuitMenuItem = new javax.swing.JMenuItem();
      EditMenu = new javax.swing.JMenu();
      ConfigMenu = new javax.swing.JMenu();
      configSerialPort = new javax.swing.JMenuItem();
      HelpMenu = new javax.swing.JMenu();
      AboutMenuItem = new javax.swing.JMenuItem();

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      setTitle("Bogie IQ Emulator");

      jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

      resetButton.setText("Reset");

      factoryResetButton.setText("Factory Reset");
      factoryResetButton.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            factoryResetButtonActionPerformed(evt);
         }
      });

      connectButton.setText("Connect");
      connectButton.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            connectButtonActionPerformed(evt);
         }
      });

      disconnectButton.setText("Disconnect");
      disconnectButton.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            disconnectButtonActionPerformed(evt);
         }
      });

      jLabel1.setText("Comm Status:");

      commStatusTextField.setToolTipText("Select Comm port in Config menu");

      configureNINAbutton.setText("Configure NINA");
      configureNINAbutton.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            configureNINAbuttonActionPerformed(evt);
         }
      });

      javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
      jPanel1.setLayout(jPanel1Layout);
      jPanel1Layout.setHorizontalGroup(
         jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
               .addGroup(jPanel1Layout.createSequentialGroup()
                  .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                     .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(resetButton)
                        .addGap(51, 51, 51)
                        .addComponent(configureNINAbutton))
                     .addComponent(disconnectButton))
                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                  .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                     .addComponent(factoryResetButton)
                     .addComponent(clockField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
               .addGroup(jPanel1Layout.createSequentialGroup()
                  .addComponent(connectButton)
                  .addGap(87, 87, 87)
                  .addComponent(jLabel1)
                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                  .addComponent(commStatusTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                  .addGap(0, 189, Short.MAX_VALUE)))
            .addContainerGap())
      );

      jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {clockField, connectButton, disconnectButton, factoryResetButton, resetButton});

      jPanel1Layout.setVerticalGroup(
         jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
               .addComponent(resetButton)
               .addComponent(clockField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
               .addComponent(configureNINAbutton))
            .addGap(18, 18, 18)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
               .addComponent(connectButton)
               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                  .addComponent(jLabel1)
                  .addComponent(commStatusTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addGap(18, 18, 18)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
               .addComponent(disconnectButton)
               .addComponent(factoryResetButton))
            .addContainerGap(26, Short.MAX_VALUE))
      );

      jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("To NINA"));

      toNINAlog.setColumns(20);
      toNINAlog.setRows(5);
      jScrollPane1.setViewportView(toNINAlog);

      javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
      jPanel2.setLayout(jPanel2Layout);
      jPanel2Layout.setHorizontalGroup(
         jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addComponent(jScrollPane1)
      );
      jPanel2Layout.setVerticalGroup(
         jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 165, Short.MAX_VALUE)
      );

      jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("From NINA"));

      fromNINAlog.setColumns(20);
      fromNINAlog.setRows(5);
      jScrollPane2.setViewportView(fromNINAlog);

      javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
      jPanel3.setLayout(jPanel3Layout);
      jPanel3Layout.setHorizontalGroup(
         jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addComponent(jScrollPane2)
      );
      jPanel3Layout.setVerticalGroup(
         jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE)
      );

      FileMenu.setText("File");

      QuitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
      QuitMenuItem.setText("Quit");
      QuitMenuItem.setToolTipText("No checks so be careful");
      QuitMenuItem.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            QuitMenuItemActionPerformed(evt);
         }
      });
      FileMenu.add(QuitMenuItem);

      jMenuBar1.add(FileMenu);

      EditMenu.setText("Edit");
      jMenuBar1.add(EditMenu);

      ConfigMenu.setText("Config");

      configSerialPort.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.ALT_MASK));
      configSerialPort.setText("Serial Port");
      configSerialPort.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            configSerialPortActionPerformed(evt);
         }
      });
      ConfigMenu.add(configSerialPort);

      jMenuBar1.add(ConfigMenu);

      HelpMenu.setText("Help");
      HelpMenu.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            HelpMenuActionPerformed(evt);
         }
      });

      AboutMenuItem.setText("About");
      AboutMenuItem.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            AboutMenuItemActionPerformed(evt);
         }
      });
      HelpMenu.add(AboutMenuItem);

      jMenuBar1.add(HelpMenu);

      setJMenuBar(jMenuBar1);

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
               .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
               .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
               .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addContainerGap())
      );
      layout.setVerticalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(37, 37, 37)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
      );

      pack();
   }// </editor-fold>

   private void QuitMenuItemActionPerformed(java.awt.event.ActionEvent evt)
   {
      // TODO add your handling code here:
      System.exit(0);
   }

   private void HelpMenuActionPerformed(java.awt.event.ActionEvent evt)
   {
      // TODO add your handling code here:
   }

   private void AboutMenuItemActionPerformed(java.awt.event.ActionEvent evt)
   {
      // TODO add your handling code here:
      // Trying to launch an About dialog
      String versionString;
      try
         {
         versionString = "Compiled on " + programBuildTime.getLastModifiedDate();
         }
      catch (IOException | URISyntaxException ex)
         {
         versionString = "Unknown";
         }

      System.out.println("Version Info is: " + versionString);

      helpAboutDialog.showMessageDialog(jPanel1,
              versionString, // Message info
              "Version Info",
              JOptionPane.INFORMATION_MESSAGE);
   }

   private void configSerialPortActionPerformed(java.awt.event.ActionEvent evt)
   {
      // TODO add your handling code here:
      JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);

      pickPort(topFrame);
   }

   private void factoryResetButtonActionPerformed(java.awt.event.ActionEvent evt)
   {
      // TODO add your handling code here:
   }

   private void connectButtonActionPerformed(java.awt.event.ActionEvent evt)
   {
      // TODO add your handling code here:
      if (portNINAstr != null)
         {
         // Try to open the serial port
         fromNINAlog.append("Connecting to " + portNINAstr + "\r\n");
         toNINAlog.append("Connecting to " + portNINAstr + "\r\n");

         portNINA.openPort();

         portNINA.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 2000, 2000);
         portNINA.setComPortParameters(115200, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
         portNINA.setFlowControl(SerialPort.FLOW_CONTROL_RTS_ENABLED | SerialPort.FLOW_CONTROL_CTS_ENABLED);
         //portNINA.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
         portNINA.setDTR();
         portNINA.setRTS();

         }
      else
         {
         javax.swing.JOptionPane errDialog = new javax.swing.JOptionPane();
         errDialog.showMessageDialog(errDialog,
                 "No serial port selected", // Message info
                 "Serial Port Error",
                 helpAboutDialog.ERROR_MESSAGE);
         }
   }

   private void disconnectButtonActionPerformed(java.awt.event.ActionEvent evt)
   {
      // TODO add your handling code here:
      if (portNINAstr != null)
         {
         if (portNINA.isOpen())
            {
            // Turn off the module
            portNINA.clearDTR();
            portNINA.closePort();
            }
         }
   }

   private void configureNINAbuttonActionPerformed(java.awt.event.ActionEvent evt)
   {
      // TODO add your handling code here:
      if (portNINAstr != null)
         {
         if (portNINA.isOpen())
            {
            String cfgString;
            byte[] cfg;

            // Make sure NINA is in control/AT mode
            portNINA.clearDTR();
            msSleep(500);
            portNINA.setDTR();

            // Configure device name.  Should be looked up from BIQ
            // serial number
            //cfgString = "AT+UBTLN=\"BIQ_emu-001930" + clockField.getText() + "\"";
            cfgString = "AT+UBTLN=\"BIQ_" + clockField.getText() + "\"";
            cfg = cfgString.getBytes();
            portNINA.writeBytes(cfg, cfg.length);
            setToLog(cfgString);
            msSleep(2000);

            // Set GAP connectable mode
            cfgString = "AT+UBTCM=2";
            cfg = cfgString.getBytes();
            portNINA.writeBytes(cfg, cfg.length);
            setToLog(cfgString);
            msSleep(2000);

            // Set GAP general discoverable mode
            cfgString = "AT+UBTDM=3";
            cfg = cfgString.getBytes();
            portNINA.writeBytes(cfg, cfg.length);
            setToLog(cfgString);
            msSleep(2000);

            // Set GAP pairing mode
            cfgString = "AT+UBTPM=2";
            cfg = cfgString.getBytes();
            portNINA.writeBytes(cfg, cfg.length);
            setToLog(cfgString);
            msSleep(2000);

            // Set Bluetooth low energy Peripheral
            cfgString = "AT+UBTLE=2";
            cfg = cfgString.getBytes();
            portNINA.writeBytes(cfg, cfg.length);
            setToLog(cfgString);
            msSleep(2000);

            // Switch to extended data mode
            cfgString = "ATO2";
            cfg = cfgString.getBytes();
            portNINA.writeBytes(cfg, cfg.length);
            setToLog(cfgString);
            msSleep(2000);

            }
         }
   }

   /**
    * @param args the command line arguments
    */
   public static void main(String[] args)
   {
      /* Set the Nimbus look and feel */
      //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
      /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
       */
      try
         {
         for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
            {
            if ("Nimbus".equals(info.getName()))
               {
               javax.swing.UIManager.setLookAndFeel(info.getClassName());
               break;
               }
            }
         }
      catch (ClassNotFoundException ex)
         {
         java.util.logging.Logger.getLogger(mainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
         }
      catch (InstantiationException ex)
         {
         java.util.logging.Logger.getLogger(mainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
         }
      catch (IllegalAccessException ex)
         {
         java.util.logging.Logger.getLogger(mainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
         }
      catch (javax.swing.UnsupportedLookAndFeelException ex)
         {
         java.util.logging.Logger.getLogger(mainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
         }
      //</editor-fold>

      /* Create and display the form */
      java.awt.EventQueue.invokeLater(new Runnable()
      {
         public void run()
         {
            new mainScreen().setVisible(true);

         }
      });
   }

   // Variables declaration - do not modify
   public javax.swing.JMenuItem AboutMenuItem;
   public javax.swing.JMenu ConfigMenu;
   public javax.swing.JMenu EditMenu;
   public javax.swing.JMenu FileMenu;
   public javax.swing.JMenu HelpMenu;
   public javax.swing.JMenuItem QuitMenuItem;
   public javax.swing.JTextField clockField;
   public javax.swing.JTextField commStatusTextField;
   public javax.swing.JMenuItem configSerialPort;
   public javax.swing.JButton configureNINAbutton;
   public javax.swing.JButton connectButton;
   public javax.swing.JButton disconnectButton;
   public javax.swing.JButton factoryResetButton;
   public javax.swing.JTextArea fromNINAlog;
   public javax.swing.JOptionPane helpAboutDialog;
   public javax.swing.JLabel jLabel1;
   public javax.swing.JMenuBar jMenuBar1;
   public javax.swing.JPanel jPanel1;
   public javax.swing.JPanel jPanel2;
   public javax.swing.JPanel jPanel3;
   public javax.swing.JScrollPane jScrollPane1;
   public javax.swing.JScrollPane jScrollPane2;
   public javax.swing.JButton resetButton;
   public javax.swing.JTextArea toNINAlog;
   // End of variables declaration
}

If you actual build and run this code, you'll need to select a serial port with a loop-back (RX to TX, CTS to RTS) to get it to work.  If you disable flow control then you only need the TX to RX connection.
Select the Config menu to pick a serial port, then select Connect to open the serial port.  Then select "Configure NINA" to send a bunch of text to the loop-back connection.  You should see the text going to the NINA module in the "To NINA" window and the same text in the "From NINA" module.
There is a healthCheck method that updates the clock in the upper right hand side of the screen.  If the jSerialComm bytesAvailble() method returns a non-zero value, then the library has seen that there is data to be read but the event to read it wasn't trigger.
There may be a lot wrong with this code.  I'm willing to learn how to fix it but the key problem is the lack of a LISTENING_EVENT_DATA_AVAILABLE event.
My environment is NetBeans 8.2 with Java 8 on Win10 64-bit.


text:
Q: How to target a file path for windows/mac with actionscript3? I am developing an app, and when i am using it in my computer its okay, because i need to execute an .exe script and i know where the path for that file is. But the question is, how can i change it for an automatically way? i mean, i just pass the .exe name and then something find this path for me...
I am using nativeProcess... and i have this:
f = new File();
 f.nativePath = "C:/projects/SDK/Adobe Gaming SDK 1.0.1/Utilities/ATFTools/Windows/png2atf.exe";
thats works perfectly...
I just want to make it more automatically..
Any ideas?

A: using a File.applicationDirectory. this is automatically find your project root directory.
as follows:
new File(File.applicationDirectory.nativePath);
and if you want target a file path Win/Mac. try this:
//Mac
if (Capabilities.os.search("Mac") >= 0)
{

}
//Windows
else if (Capabilities.os.search("Windows")>=0)
{

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java more elegant way to write if statements with images Is there a more elegant/shorter/organized way of writing this bit of code?
for (int i = 0; i < SCREENSIZE; i++) {
        for (int j = 0; j < SCREENSIZE; j++) {
            if (map[y + i][x + j] == '@')
                g.drawImage(item, j * TILESIZE,i * TILESIZE, null);
            else if (map[y + i][x + j] == ' ')
                g.drawImage(ground, j * TILESIZE,i * TILESIZE, null);
            else if (map[y + i][x + j] == 'i')
                g.drawImage(bush, j * TILESIZE, i * TILESIZE, null);
            else if (map[y + i][x + j] == '~')
                g.drawImage(ocean, j * TILESIZE, i * TILESIZE, null);
            else if (map[y + i][x + j] == '=')
                g.drawImage(fence, j * TILESIZE, i * TILESIZE, null);
            else if (map[y + i][x + j] == '#')
                g.drawImage(grass, j * TILESIZE, i * TILESIZE, null);
            else if (map[y + i][x + j] == 'Y')
                g.drawImage(townsPerson, j * TILESIZE, i * TILESIZE, null);
            else if (map[y + i][x + j] == '/')
                g.drawImage(house01, j * TILESIZE, i * TILESIZE, null);
            else if (map[y + i][x + j] == '¯')
                g.drawImage(house02, j * TILESIZE, i * TILESIZE, null);
            else if (map[y + i][x + j] == '\\')
                g.drawImage(house03, j * TILESIZE, i * TILESIZE, null);
            else if (map[y + i][x + j] == '[')
                g.drawImage(house04, j * TILESIZE, i * TILESIZE, null);
            else if (map[y + i][x + j] == 'n')
                g.drawImage(house05, j * TILESIZE, i * TILESIZE, null);
            else if (map[y + i][x + j] == '_')
                g.drawImage(house06, j * TILESIZE, i * TILESIZE, null);
            else if (map[y + i][x + j] == ']')
                g.drawImage(house07, j * TILESIZE, i * TILESIZE, null);
            else if (map[y + i][x + j] == '`')
                g.drawImage(cground, j * TILESIZE, i * TILESIZE, null);
            else if (map[y + i][x + j] == 'O')
                g.drawImage(boulder, j * TILESIZE, i * TILESIZE, null);
            else if (map[y + i][x + j] == 'Ÿ')
                g.drawImage(alien, j * TILESIZE, i * TILESIZE, null);
            else if (map[y + i][x + j] == '.')
                g.drawImage(tree01, j * TILESIZE, i * TILESIZE, null);
            else if (map[y + i][x + j] == 'T')
                g.drawImage(tree02, j * TILESIZE, i * TILESIZE, null);
        }
    }

A: The first improvement could be to use a switch/case structure, but in your case, a simple map (Map<Char,Image>) will be even better.
Going even further, you could use an enum instead of characters to identify the objects, which will help you avoid typos, but at the very least you should be using character constants, like
public static final char MAP_ITEM = '@';
public static final char MAP_GROUND = ' ';

and so on.

A: Somewhere (in the constructor?), save a Map as a member variable:
images = new HashMap<Character, Image>();
images.put('@', item);
images.put(' ', ground);

Then, your drawing will look like:
for (int i = 0; i < SCREENSIZE; i++) {
    for (int j = 0; j < SCREENSIZE; j++) {
        g.drawImage(images.get(map[y+i][x+j]), j * TILESIZE, i * TILESIZE, null)
    }
}

A: Since you're basing off a character, you can use a switch statement.
The other thing you can do is, since you're using g.drawImage(SOMETHING, j * TILESIZE, i * TILESIZE, null) in every case, you can extract everything that's the same to after the switch and just assign some variable and use that for what changes
EX:
Object graphic;
switch (map[y + i][x + j]) {
case '@':
    graphic = item;
    break;
case '#':
    graphic = grass;
    break;
// etc....
}
g.drawImage(graphic, j * TILESIZE, i * TILESIZE, null);

A: use a switch/case (not a map) because the compiler would have more room to optimize since it knows the exact set of char values you are switching on:
...
switch(map[y+i][x+j]) {
    case: '@': image = item; break;
    case: ' ': image = ground; break;
    ...
}
g.drawImage(image, j * TILESIZE, i * TILESIZE, null);
...

A: You can use a switch with a char value so that might be clearer. Also the 2nd, 3rd and forth parameters are always the same so maybe set a var in the switch and call the method outside. A little pseudo code:
for() {
  for() {
     Image obj;
     switch (map[y+i][x +j]) {
       case '@':
         Obj = item;
         break;
     // other cases
       default:
       //default or error handling
   }
   g.drawImage(obj, j * TILESIZE, i * TILESIZE, null);
 }
}


text:
Q: Reloading to homepage after hitting an empty anchor Please have a look at http://iglica.dbox.pl/modx/ (clients graphical project)
Check "KURSY" on the menu - on the homepage everything is okay, the menu slides, I can pick something from the sub-menu, etc. Somehow, when I click on "KURSY" from every other place, MODX redirects me to the homepage.
The code responsible for the menu is in menu.min.js (I`ve bought it specially for this website - I'm not a jQuery familiar).
P.S.
I've tried this http://rtfm.modx.com/display/revolution20/Named+Anchor with no luck
P.S.
jQuery -
$(function () {
    $('#mainNav ul li.slide a').click(function () {
        var content = ($(this).parent().find("div").html());
        $('#navWrapper #subNav #subNavContainer').fadeOut(100, function () {
            $('#navWrapper #subNav #subNavContainer').html(content);
            $('#navWrapper #subNav #subNavContainer').fadeIn(100);
            $('#navWrapper').stop(false, false).animate({
                'left': 0
            }, 300)
        })
    });
    $('#navWrapper').mouseleave(function () {
        $('#navWrapper').stop(false, false).animate({
            'left': -200
        }, 300)
    })
});

A: Try to replace the a tags which you don't want to do anything with span tags and see if your js code still works fine. Maybe you have to look at your css styles afterwards.

Kursy

Dla dzieci

Dla młodzieży

Dla dorosłych

Ok, when slide functions are triggered by anchor may try a js workaround:
HTML

Kursy

Dla dzieci

Dla młodzieży

Dla dorosłych

JS
(function ($) {
    $(window).ready(function () {
        $('.preventdefault').on("click", function (e) {
            //Uncomment if the anchor is required on the url
            //document.location.hash = $(this).attr('href');

            return false;
        });
    });
}(jQuery));

Your code extended + adding html class:
$(function () {
    $('#mainNav ul li.slide a').click(function (e) {
        var content = ($(this).parent().find("div").html());
        $('#navWrapper #subNav #subNavContainer').fadeOut(100, function () {
            $('#navWrapper #subNav #subNavContainer').html(content);
            $('#navWrapper #subNav #subNavContainer').fadeIn(100);
            $('#navWrapper').stop(false, false).animate({
                'left': 0
            }, 300)
        })

        if ($(this).hasClass('preventdefault')) {
            //Uncomment if the anchor is required on the url
            //document.location.hash = $(this).attr('href');

            e.preventDefault();
            e.stopPropagation();
        }

    });
    $('#navWrapper').mouseleave(function () {
        $('#navWrapper').stop(false, false).animate({
            'left': -200
        }, 300)
    })
});


text:
Q: Why is Reference to Base Class ambiguous with :: -operator through derived class? So I was wondering why the following code snippet of the diamond problem is not able to be compiled.
I am aware that this problem is usually solved by virtual inheritance, i didn't use this on purpose. The code is just to showcase my question on why the compiler calls this ambiguous:
So i have two member variables declared in struct Base, because the two subclasses (in this case structs) do not inherit virtually, i would have a reference to the Base members in each derived struct. Now I have another struct AllDer which would run in the problem of knowing id_ and name_ two times.
However when i explicitly target id_ and name_ from Base, i don't understand why this would be ambiguous since the direct target variable is specified through the ::-operator.
cout << Der1::Base::id_ << Der1::Base::name_ << '\n';

Can somebody tell me, why the compiler runs into a problem here? (Please forgive possibly wrong technical terms)
Compiler error message says: "ambiguous conversion from derived class 'AllDer' to base class". Using MinGW 7.3.0 64-bit for C++ in QT Creator.
EDIT: Since this problem seems to get handled differently by compilers, please check the linked question.
#include <string>
#include <iostream>
using std::string; using std::cout;

struct Base
{
    int id_;
    string name_; //target members for readAllDer() in AllDer

    void read()
    {
        cout << id_ << ' ' << name_ << '\n';
    }
};

struct Der1 : public  Base
{
    //Der1 has own reference to id_, name_
    void readDer1()
    {
        cout << id_ << name_ << '\n';
    }
};

struct Der2 : public  Base
{
    //Der2 has own reference to id_, name_
    void readDer2()
    {
        cout << id_ << name_ << '\n';
    }
};

//
struct AllDer : public Der1, public Der2
{

    void readAllDer()
    {
        cout << Der1::Base::id_ << Der1::Base::name_ << '\n'; // Why is this ambiguous?
    }
};

A: Der1::Base and Der2::Base are the same class and AllDer derives from it twice. Your method compiles when you pick the members not from Base but from Der1:
struct AllDer : public Der1, public Der2
{

    void readAllDer()
    {
        cout << Der1::id_ << Der1::name_ << '\n';
    }
};

A: Its a classic diamond problem, even if you are saying you are specifying the direct target variable through scope(::)
Here 'Der1' already has copy of 'id_,name_' and you are still trying to access base's copy which is ambiguous for 'AllDer' as its coming by two ways Der1 and Der2.
instead of this:
Der1::Base::id_

try this:
Der1::id_ and Der1::name_

hope this helps

A: you need to inherit Der1 and Der2 virtually from base class like this
struct Der1 : virtual public  Base

struct Der2 : virtual public  Base

in this LINK said:
Virtual inheritance is a C++ technique that ensures only one copy of a base class's member variables are inherited by grandchild


text:
Q: Automatically join lines by snap After I smoothed a layer of lines I lost the connection with some vertices.

Is there an automatic way to connect the various lines to avoid doing it manually?

I think the best thing is to use v.clean but I am not sure of the right parameters that should be set.

A: You can try "Snap geometries to layer" from Processing Toolbox. You can select the same layer as input and reference.
In your case I would try the "Behavior" (Move end points only), as well as a suiting "Tolerance".


text:
Q: Identifying Aggregates and Aggregate roots for an application I have been reading about DDD, Event Sourcing (ES) and CQRS. I realized that if we consider ES and CQRS, aggregates have been at the central of the design.
Please correct me if I am wrong but I learned that:

*

*Each command will correspond to one aggregate, this could help us in defining the commands

*Each event streams corresponds to one aggregate, making it easy for us to define the events structure.

Now I was just thinking that if possible is there any tool or method that can help us in identifying the aggregates in the already existing application from some inputs?
I believe that "Historical transaction logs" and "Database Schema" as inputs can be really be helpful for getting some knowledge about some structure of the aggregates. I may be wrong here again, but has anyone tried something on the similar line to make the process of finding aggregates easy for the software engineers?

A: If you're talking about getting historical transaction logs and DB schemas from some existing system (presumably the one which you're looking to replace with a system designed following Domain Driven Design), I would strongly caution against that approach.
For the existing implementation, the transaction logs and schemas are at best an encoding of the domain and likely have discarded some context and contorted the domain in some way to fit the constraints of the DB.  If those are your main basis for discovering the domain, your likely best case is that you end up with a clone of the existing system that's inferior in some way.
The easiest way to find the aggregates is to look at what operations are desired and tracing how those operations' sequencing affects each other (e.g. "how does this command succeeding affect whether this later command succeeds"; if the answer is "no effect" then those commands are almost certainly not to the same aggregate, since in CQRS-style DDD the purpose of the aggregate is to determine whether commands succeed or fail).  This is typically going to entail working with domain experts to explore the domain, e.g. via event storming (or some similar technique).


text:
Q: converting a series to string in pandas, quirk I am trying to convert a series to a string,
When I convert, for some reason the whole text in the cell is not replicated, it is being cut off by ....
how can i convert it to a string with it showing the full text?
`summ1 = list1.iloc[bglist,0] #my list
bg_summ = bg_summ1.to_string(header=False,index=False) #converting list into string`
the top is my series item, then i convert it into a string, the rest of the text gets cut off


text:
Q: Openstack Keystone 3.0 API I currently have an Openstack Havana cluster that is running the 2.0 API. I am having some issues integrating my Keystone with my corporate read only LDAP.
I have done the LDAP/SQL split (for identity and assignment) as recommended. When I run the 'keystone user-list' command multiple times, it prints both SQL and LDAP users (i.e. SQL users sometimes and LDAP users sometimes). I don't understand this, as I expect it to fetch user list only from LDAP and not from SQL. What exactly is user-list trying to do internally?
Could there be some other settings in addition to the ones in Keystone.conf [LDAP] that I would need to change?
I also tried doing 'keystone user-role-add' to try and map the LDAP user to a precreated tenant with a member role, but it failed saying the user could not be found, which again means it is trying to look for the user inside SQL instead of inside LDAP
Some people have been talking about using the keystone 3.0 API, but I am yet to find material that guides me on how to install and get this running. What is the procedure to install and configure this? Being new to Linux, I have no idea whatsoever. How will the 3.0 API help me address this issue?
Also, I read that read only LDAP is flaky in Havana. Would migrating to Icehouse help? Was this made more stable in Icehouse?

A: Can you try by setting only the ldap driver for identity as follows :
driver = keystone.identity.backends.ldap.Identity


text:
Q: where are the rasters that make up a layer? I used raster calculator to add up 12 rasters made up of 0's and 1's to make a fire frequency map. Then I saved the output as a layer (lyr).
However, I need the raster output.
Did I add it up wrong, save the files wrongly or are they saved some where?

A: Note that layer files (.lyr) do not save the underlying dataset. But what should matter is that you know where you sent the output raster--like in the bottom of the illustration seen here: http://pro.arcgis.com/en/pro-app/tool-reference/spatial-analyst/raster-calculator.htm Is this similar to the dialog box you're using? What path are you putting for your Output Raster? That should be the path of your data.


text:
Q: Which CodePlex/Google code project to study in order to learn SharePoint best practices I am new to sharepoint development but have about 10 years of expirence in C++, VB6 and C#. It is my experience that a great way to learn a new language or coding style is to spend some time "dissecting" one of the open source projects available at CodePlex or Google code.
In order to avoid picking up some bad habits without knowing it, I would like to hear which projects you can recommend.
TIA

A: I would also recommend the CKS but I would also add that I have found that coding isn't the biggest issue when learning SharePoint but determining the best solution to acheive your goal. Should you use a workflow or an event handler? Should you use custom code or the BDC? Should you build a web part or a layout page? Should you use a list, a custom form or an InfoPath form?
So, in addition to learning coding practices you should spend a large amount of time finding approaches to solving problems. SharePoint offers a lot of benefits but unfortunately an easy learning curve is not one of them. I also have 10 years of development and it took me 6 months to start to fully comprehend best approaches on solving business requirements most effectively.
I recommend:
patterns & practices SharePoint Guidance
Best Practices Resource Center for SharePoint Server 2007
Microsoft Office SharePoint Server 2007 Best Practices (Paperback)
SharePoint 2007 and WSS 3.0 Dispose Patterns by Example

A: Generally speaking, SharePoint "code" will come in the form of web parts and pages that are written for specific SharePoint installations. However, that doesn't mean that there aren't any SharePoint utilities and libraries out there.
In fact, I'm a big fan of SmartPart, which is hosted on Codeplex. This is a very useful SharePoint tool with a lot of downloads and some bugs that need to be fixed, so it's a great project to serve as your reference point and submit some code to!

A: You can take a look at http://www.codeplex.com/CKS which is a project start by Microsoft employees.


text:
Q: AutoResetEvent in Multi-threading I have a sample code below which creates multi-thread having a block of code inside lock in separate thread.
I abort child-thread if response is null or if autoReset.WaitOne(timeout) elapses the time-span so that allowing next waiting thread in queue
to enter the lock and carryout the operations. But the problem here is if say ThreadA takes 8 seconds to execute the complex code inside lock then the next
waiting thread say ThreadB is left with only 2secs (since the AutoResetEvent's  wait time for all the threads were started at same time).
How can i make each thread to get same timespan to execute the complex block of code. I'm trying to solve this from past 2 days now, Any inputs will be really helpful.
Class A
{
    static void Main(){
     for(int i=0; i < 2; i++)
      {
        var mainThread = new Thread(ParentThreadMethod);
        mainThread.Start();
      }
    }

    void ParentThreadMethod(){
      var autoReset = new AutoResetEvent(false);
      ClassB obj;
      var childThread = new Thread(() =>
        {
            obj = new ClassB();
            var result = obj.ChildThreadMethod();
            autoReset.Set();
        }
         childThread.Start();

         // wait for 10sec
         autoReset.WaitOne(10000);
    }
 }

 Class B
 {
    private static readonly object threadLock = new object();
    string ChildThreadMethod(){
     lock (threadLock)
            {
                // complex logic taking 8sec
            }
    }
 }

A: I think the problem is that both threads share access to
private static readonly object threadLock = new object();

This means that the 2nd thread will spend 8sec waiting for the first to exit the critical region. This makes it look like the timeout is hitting early. But the timeout is working correctly.
It looks like you want to start the timeout only when the lock is successfully entered. This means that the thread itself must start the timeout because only the child thread knows when it entered the lock.
It could look like this:
lock (threadLock) {
    var timeoutTask = Task.Delay(10000);
    var workTask = Task.Run(RunWork);
    var firstTask = Task.WhenAny(timeoutTask, workTask).Result;

    if (!workTask.IsCompleted) {
     AbortWork();
     workTask.Wait(); //Wait for cancellation to finish.
    }
}

Generally the newer TPL features are easier to use than threads and events etc. If this code is new code I'd start over with TPL classes.


text:
Q: Next js - Next Auth - Keep having error=OAuthCreateAccount (google provider) I have set up next-auth with the GoogleProvider.
Everything works fine locally, however in production, I am having aOAuthCreateAccount error: api/auth/signin?error=OAuthCreateAccount
stating "Try signing in with a different account."
I have provided the ID & Secret of the Provider, I have dropped my DB, tried to log with multiples accounts... I do not understand. Is there something that my production environment is not accessing?
Here's my nextauth.js:
`
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import CredentialsProvider from "next-auth/providers/credentials";
import { MongoDBAdapter } from "@next-auth/mongodb-adapter";
import clientPromise from "../../../lib/mongodb";

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),

    // ...add more providers here
  ],
  secret: process.env.NEXTAUTH_SECRET,
  // Can custom page & path
  pages: {
    signOut: "/auth/signout",
    error: "/auth/error", // Error code passed in query string as ?error=
    verifyRequest: "/auth/verify-request", // (used for check email message)
    // newUser: "/auth/new-user", // New users will be directed here on first sign in (leave the property out if not of interest)
    newUser: "/recruiter/2", // New users will be directed here on first sign in (leave the property out if not of interest)
  },
  adapter: MongoDBAdapter(clientPromise),
});

`
And my mongodb.js:
`
import { MongoClient } from "mongodb";

const uri = process.env.MONGODB_URI;
const options = {
  useUnifiedTopology: true,
  useNewUrlParser: true,
};

let client;
let clientPromise;

if (!process.env.MONGODB_URI) {
  throw new Error("Please add your Mongo URI to .env.local");
}

if (process.env.NODE_ENV === "development") {
  // In development mode, use a global variable so that the value
  // is preserved across module reloads caused by HMR (Hot Module Replacement).
  if (!global._mongoClientPromise) {
    client = new MongoClient(uri, options);
    global._mongoClientPromise = client.connect();
  }
  clientPromise = global._mongoClientPromise;
} else {
  // In production mode, it's best to not use a global variable.
  client = new MongoClient(uri, options);
  clientPromise = client.connect();
}

// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise;

`
Thank you!
Read the documentations.
Look on Stackoverflow and github thread, tried all the offered solutions, in vain.

A: I have managed to fix it reading this thorough article: https://medium.com/geekculture/why-and-how-to-get-started-with-next-auth-61740558b45b
I was missing the database variable in my deployment system (vercel) :)


text:
Q: How to install CA certificate on Nexus 3? I have installed Nexus Repository Manager OSS 3.0.2-02 on my CentOS Linux release 7.4.1708.
Also I have CA certificate:
Issued to: \*.mycompany.com
Issued by: Go Daddy Secure Certificate Authority - G2
Valid from 2016-11-12 to 2018-01-11

The RSA private key match with my CA certificate, which was checked with Certificate Key Matcher and reported:

The certificate and private key match!

In Nexus3 directory I made the following changes:
Added to the file org.sonatype.nexus.cfg the lines:
nexus-args=${karaf.etc}/jetty.xml,${karaf.etc}/jetty-http.xml,${karaf.etc}/jetty-requestlog.xml,${karaf.etc}/jetty-https.xml
application-port-ssl=8443

Added to jetty-https.xml file next lines:
KeyStorePath /ssl/test.jks
KeyStorePassword 123456
KeyManagerPassword 123456
TrustStorePath ssl/test.jks
TrustStorePassword 123456

Created SSL directory in $NEXUS_HOME/etc/ and created inside the SSL directory a Java keystore file test.jks with command:
openssl pkcs12 -export -in mycompany.com.pem -inkey key.pem -name xxx.mycompany.com -out test.pks
keytool -importkeystore -deststorepass 123456 -destkeystore test.jks -srckeystore test.pks -srcstoretype PKCS12
keytool -import -alias bundle -trustcacerts -file gd_bundle.crt -keystore test.jks

After Nexus restart I can't not reach it by URL //xxx.mycompany.com:8443. Firefox says:

The page you are trying to view cannot be shown because the
  authenticity of the received data could not be verified

Also trying to do: docker login xxx.mycompany.com:8443 and providing default admin:admin:123 credentials cause:

Error response from daemon: Get xxx.mycompany.com:8443/v1/users/:
  x509: certificate signed by unknown authority

I also try to chain certificates by various scenarions from Google, including How to add certificate chain to keystore?, but got error on Docker:

Error response from daemon: Get //xxx.mycompany.com:8443/v1/users/: EOF

on Firefox, the same as first time and on Chrome:

//xxx.mycompany.com unexpectedly closed the connection

Question: Where is my mistake, or how to correctly install CA certificate on Nexus3?

A: I've found the resolution. Just needed to set in jetty-https.xml next lines:
<Set name="NeedClientAuth"><Property name="jetty.ssl.needClientAuth" default="false"/></Set>
<Set name="WantClientAuth"><Property name="jetty.ssl.wantClientAuth" default="false"/></Set>


text:
Q: Can't figure out how to do this all in one function I am creating a zoo simulation game in Unity 5.4.0f3 using C#. I am trying to spawn a bear prefab clone, do some math, wait for a period of time, do some more math, then destroy the clone object all in one function. Here is what I have right now. The math that I am trying to do in WaitForBearLife() does not happen. Thanks in advance!
using UnityEngine;
using System.Collections;

public class BuyBearButton : MonoBehaviour
{
    [SerializeField] GameManager gameManager;
    [SerializeField] GameObject bearPrefab;
    [SerializeField] Visitor visitor;

    GameObject bearClone;

    float xMin = -15;
    float xMax = 15;
    float yMin = 5;
    float yMax = 6;

    public void BuyBear()
    {
        Vector2 pos = new Vector2 (Random.Range (xMin, xMax), Random.Range (yMin, yMax));

        if (gameManager.myMoney >= gameManager.bearCost)
        {
            gameManager.numberOfBears++;
            gameManager.myMoney = gameManager.myMoney - gameManager.bearCost;
            visitor.spawnTime = visitor.spawnTime / visitor.bearAttraction;
            bearClone = (GameObject) Instantiate (bearPrefab, pos, transform.rotation);
            StartCoroutine (WaitForBearLife ());
            Destroy (bearClone, gameManager.bearLife);
        }
    }

    IEnumerator WaitForBearLife()
    {
        yield return new WaitForSeconds (gameManager.bearLife);
        visitor.spawnTime = visitor.spawnTime * visitor.bearAttraction;
    }
}

A: you need to move Destroy function from BuyBear to WaitForBearLife
The problem is that now StartCouroutine call immediately returns and Destroy() gets called right away

A: I've just copied your code in an empty project, and made placeholder classes for GameManager and Visitor, just with random values in the variables we need in this script. It works just fine... really.So, I'll make you some questions (as I don't have the reputation yet to comment in your post...)
First, there's a script in the bear prefab of any sorts?
This is because it maybe have something that could interrupt the coroutine. It seems unlikely, but you can't know for sure until you try.
Next, how is the declaration of Visitor and GameManager?
The very beginning, when you define the class name and such. In fact, I would like to know more about the variables you used, like gameManager.bearLife and such.
Now, let's see the values.
I've tried with:
public int myMoney = 50000;
public int bearCost = 50;
public int numberOfBears = 0;
public float bearLife = 2.0f;

In GameManager. And:
public float spawnTime = 5;
public float bearAttraction = 2;

In Visitor. It does some weird math, and the logic of this script itself is clearly in development right now, I suppose. But the point is, it works, and with this:
IEnumerator WaitForBearLife()
{
    yield return new WaitForSeconds (gameManager.bearLife);
    print (visitor.spawnTime);
    visitor.spawnTime = visitor.spawnTime * visitor.bearAttraction;
    print (visitor.spawnTime);
}

I get 2.5 and 5 in the correspondant prints if I only click once. Some prints (As @Benjamin-lecomte stated) could help you to know if it's even executing that part.
For now, I can't help you without knowing much more. So I'll wait for your answer, then.


text:
Q: Android IABv3 getSkuDetails not returning Sku Details I am currently battling with Android Iab v3.
I have previously been using the IabHelper class from Google to display available products with success. However, today it is no longer returning me anything.
The content of the querySku field passed to the getSkuDetails function of the IInAppBillingService in the IabHelper class is:

Bundle[{ITEM_ID_LIST=[com.app.android.credits.10,
  com.app.android.credits.25, com.app.android.credits.50]}]

What I get back in the bundle it return is:

Bundle[{DETAILS_LIST=[], RESPONSE_CODE=0}]

Since the time it has worked and now I have not altered the IabHelper code at all along with the code that displays the products. The important bit of code being:
private void getItemsForSale()
{
    ArrayList<String> skuList = new ArrayList<String>();
    skuList.add(getResources().getString(R.string.ten_credits_product_id));
    skuList.add(getResources().getString(R.string.twenty_credits_product_id));
    skuList.add(getResources().getString(R.string.fifty_credits_product_id));

    mHelper.queryInventoryAsync(true, skuList, this);
}

@Override
public void onQueryInventoryFinished(IabResult result, Inventory inv)
{
    if(result.isFailure())
    {
         Log.d("DEBUG", "Error Inventory Query: " + result);
         AppMsg.makeText(BuyCreditsActivity.this, R.string.sorry_something_went_wrong, AppMsg.STYLE_ALERT).show();
    }
    else
    {
         // Code here queries the inv object returned which has a blank array
    }
}

This is why I am so confused.
Does anyone have any idea as to what external factor might have caused this to start not returning any product details?

A: I had this same problem. In my case the following worked:

*

*Make sure it's actually published in alpha, beta, or production.
If it appears, for example, as "Draft in Alpha" or beta then you
haven't published in. Publishing means that you also need to upload
the minimum required assets for Google Play, descriptions, content
ratings, etc (See the APK, Store Listing, and Content Rating tabs in
the developer console).

*At least for alpha and beta testing, there is a list of testers that
you must create and add each tester's email. Look for the "Manage
Testers" section in the Alpha Testing or Beta Testing tab.

*Each tester must also accept to be a tester. There is an opt-in URL
link which you must send to your testers, and they must click on the
link and accepts the conditions.

*After all that is done, you still have to wait about 1 hour before
the purchase details start to appear.

Hope this helps!

A: I'm getting the same empty bundle since yesterday. This question is not the same thing, but it was asked recently, and seems to be related: Android inventory.getSkuDetails() returning null
 (I have experienced this one too about 2 weeks ago)
First answer states:
"they say they have made changes which requires the apk to be published before adding in app purchases they recommend uploading the apk to alpha testing channel and published (not in draft mode)."
I will try this, perhaps it solves the problem.
Update: I published the app, but the developer console wrote that the modifications does not take effect immediately. After some hours the problem existed, but today it works well.


text:
Q: Where to put SwingUtilities.invokeLater in Spring backed java standalone application? I am using Spring framework for my java Swing application. I am initializing my MVC objects as spring bean in my application-context.xml in this way, with @Autowired for DI.
<bean id="model" class="com.Model"/>

<bean id="view" class="com.View"/>

<bean id="controller" class="com.Controller"/>

It runs successfully without any problem. However by reading at this question, I think I should put every Swing components inside SwingUtilities.invokerLater() for this reason.

Some Swing component methods are labelled "thread safe" in the API specification; these         can be safely invoked from any thread. All other Swing component methods must be invoked   from the event dispatch thread. Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.

So my question is, where/how to put my stuff to this Event Dispatch Thread? Currently my main method is just a one liner...
ApplicationContext context =
    new ClassPathXmlApplicationContext("application-context.xml");

UPDATE:
I wanna know if this is what I should do?
SwingUtilities.invokeLater(new Runnable() {
  public void run() {
     ApplicationContext context =
        new ClassPathXmlApplicationContext("application-context.xml");
  }
  context.xxxx
  blahblahblah...
});

A: To run code on the event-dispatch thread, you can do:
EventQueue.invokeLater(new Runnable() {
    public void run() {
       //your code here
    }
 });

...or equivalently:
SwingUtilities.invokeLater(new Runnable() {
    public void run() {
       //your code here
    }
 });

You can use either approach in any location where you have code that you need to run on the event-dispatch thread.  Just wrap the code inside the anonymous Runnable and you're good to go.
Note that if you have variables defined outside of the anonymous Runnable implementation that you want to access from within it, you'll need to declare them as final.  For more information, try the following:

*

*Java: Access local variables from anon inner class? (PriorityQueue)

*SwingUtilities.invokeLater() vs EventQueue.invokeLater()

*https://weblogs.java.net/blog/2007/06/11/single-thread-rule-swing

A: I had this same question last night, searched everywhere, but could not find and appropriate answer.  I racked my brain for a couple of hours, this is what I came up with, and it looks pretty solid.
This solution uses Spring's lookup method injection to lazily load the swing Gui on the EDT.
IOnDemandBeanGetter.java
This is the interface Spring will use for the method injection
public interface IOnDemandBeanGetter {
    public IOnDemandBean getBean();
}

IOnDemandBean.java
Marker interface returned by IOnDemandBeanGetter
public interface IOnDemandBean {}

GuiOnEdtUtility.java
This utility uses an injected IOnDemandBeanGetter to get the bean and load it on the EDT.
public class GuiOnEdtUtility {
    private final IOnDemandBeanGetter beanGetter;

    public GuiOnEdtUtility(IOnDemandBeanGetter beanGetter) {
        this.beanGetter = beanGetter;
    }

    public void createGuiOnEdt(){
        SwingUtilities.invokeLater(()->beanGetter.getBean());
    }
}

MainGui.java
This contains the swing components, will be returned by IOnDemandBeanGetter, and loaded on the EDT by GuiOnEdtUtility.  You can inject any components, which I did not do for simplicity, but they all must have lazy-init="true"
public class MainGui implements IOnDemandBean {
    private final JFrame frame = new JFrame();

    public MainGui() {
        System.out.println(SwingUtilities.isEventDispatchThread()
                           ? "Created On EDT"
                           : "Not created On EDT");
    }

    public void init() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

Beans.xml
<bean name="onDemandBeanGetter" class="IOnDemandBeanGetter">
    <lookup-method name="getBean" bean="mainGui"/>
</bean>

<bean name="guiOnEdtUtility" class="GuiOnEdtUtility" init-method="createGuiOnEdt">
    <constructor-arg ref="onDemandBeanGetter"></constructor-arg>
</bean>

<bean name="mainGui" class="MainGui" init-method="init" lazy-init="true"/>

Update...
This is how MainGui.java would look if it inherited from JFrame, and it works the same
public class MainGui extends JFrame implements IOnDemandBean {

    public MainGui() {
        System.out.println(SwingUtilities.isEventDispatchThread()
                           ? "Created On EDT"
                           : "Not created On EDT");
    }

    public void init() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(200, 200);
        setLocationRelativeTo(null);
        setVisible(true);
    }
}


text:
Q: Split Down Unescaped Character in Javascript I have a period and backslash escaped string. I would like to split the string using any unescaped periods, but am struggling to come up with a pattern to do so.
const escaped = "two slashes: \\\\.one period: \..line and a dot: \\\.";

// ["two slashes: \\", "one period: .", "line and a dot: \."]
console.log(escaped.split(/* ? */))

This (?<!\\)(?:(\\\\)*)[*] is close, but split() includes capturing groups in the ouput array, which is not what I would like. The solution should be match-only, like here:
(?<!\\)(?:\\\\)*\K\.

A: The positive lookbehind solution will work with any JavaScript environment compatible with ECMAScript 2018+ standard:
/(?<=(?<!\\)(?:\\\\)*)\./

See this regex demo.

The regex matches any . char that is immediately preceded with any amount of an even amount of backslashes (i.e. even if there are no backslashes before . at all).
With older JavaScript environment, you will need a workaround like text.match(/(?:\\[^]|[^\\.])+/g). See this regex demo. This matches any one or more sequences of a a \ and any single char or any single letter other than a backslash and a dot.


text:
Q: Spring MVC Controller model.addAttribute I am new to Java.
I created a project below with Java Dynamic Web - servlet and it works.
@WebServlet("/the_data/userdata/userData")
public class userData extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");

        //query
        String query = "select * from country";

        try {
            //Note -> ConLib is my connection class
            ResultSet rst = ConLib.connect().createStatement().executeQuery(query);

            response.getWriter().print("
");
            response.getWriter().print("
");
            while(rst.next()) {
                response.getWriter().print("
");
                response.getWriter().print("    src/"+rst.getString("id")+"	");
                response.getWriter().print("    "+rst.getString("countryName")+"	");
                response.getWriter().print("    "+rst.getString("countryName")+"	");
                response.getWriter().print("
");
            }
            response.getWriter().print("
");
            response.getWriter().print("
");

        }
        catch (SQLException e) {
            e.printStackTrace();
        }

    }
}

Writing an html page like above is really hard.
I decide to write new project (Spring MVC Project). I am converting above code into Spring MVC Framework.
I have no idea, the code doesn't work. I just want to write the array in country_view.jsp file.
@RequestMapping(value = "/country", method = RequestMethod.GET)
public String pasar(Model model) throws SQLException {

    String theSQL = "select * from country";

    //Note -> ConLib is my connection class
    ResultSet rst = ConLib.connect().createStatement().executeQuery(theSQL);

    model.addAttribute(rst);

    return "country_view";
}

This is country_view.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>

    <title>Country</title>

Country

    <% while(rst.next()) { %>
        <%= rst.getString("countryName") %>
    <% } %>

This is error page:
type Exception report

message Unable to compile class for JSP:

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: 10 in the jsp file: /WEB-INF/views/country_view.jsp
rst cannot be resolved
7:
8:
Country

9:
10:  <% while(rst.next()) { %>
11:     <%= rst.getString("countryName") %>
12:  <% } %>
13:

An error occurred at line: 11 in the jsp file: /WEB-INF/views/country_view.jsp
rst cannot be resolved
8:
Country

9:
10:  <% while(rst.next()) { %>
11:     <%= rst.getString("countryName") %>
12:  <% } %>
13:
14:

Stacktrace:
    org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
    org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:366)
    org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:468)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:378)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:646)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:262)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1180)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:950)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

Would you please help me? And how to write an array in 'spring jsp view'?
Thank You...

A: Add this to the JSP
 <% ResultSet rst = (ResultSet)request.getAttribute("resultSet");%>
 <%= rst.getString("resultSet") %>

Change your pasar method to
model.addAttribute("resultSet",rst);


text:
Q: What does "Solve $ax \equiv b \pmod{337}$ for $x$" mean? I have a general question about modular equations:
Let's say I have this simple equation:
$$ax\equiv b \pmod{337}$$
I need to solve the equation.
What does "solve the equation" mean? There are an infinite number of $x$'s that will be correct.
Does $x$ need to be integer?
Thanks very much in advance,
Yaron.

A: Write  $p = 337$. This is a prime number.
First of all, if $a \equiv 0 \pmod{p}$ then there is a solution if and only if $b \equiv 0 \pmod{p}$, and then all integers $x$ are a solution.
If $a \not\equiv 0 \pmod{p}$, then the (infinite number of integer) solutions will form a congruence class modulo $p$. These can be found using Euclid's algorithm to find an inverse of $a$ modulo $p$, very much as you would do over the real numbers, say.
That is, use Euclid to find $u, v \in \Bbb{Z}$ such that $a u + p v = 1$, and then note that $x_{0} = u b$ is a solution, as $a x_{0} = a u b = b - p v b \equiv b \pmod{p}$. (Here $u$ is the inverse of $a$ modulo $p$, as $a u \equiv 1 \pmod{p}$.)
Then note that if $x$ is any solution, then $a (x - x_{0}) \equiv 0 \pmod{p}$, which happens if and only if $p \mid x - x_{0}$, so that $x \equiv x_{0} \pmod{p}$. Thus the set of solutions is the congruence class of $x_{0}$.

A: Typically this question means to find all the integer $x$ in the interval $[0,336]$ satisfying the equation.


text:
Q: MySQL Indexes: What is Size field in Indexes? What is the Size field in Indexes and how it works?

A: When you create an index, you can specify that only a prefix of the value should be included in the index. This is the size of the index. It's optional for most datatypes, but required for TEXT and BLOB columns. It's also needed for any column if its length exceeds the limit on index size; for instance, InnoDB's index size limit is 767 bytes for some table formats; if you want to index a VARCHAR(1023) column, you'll need to specify a prefix size less than 768.
See Column Prefix Key Parts

A: This is how much of the value will be uniquely indexed. You can index the whole value on a one-to-one basis, or you can index just a prefix which might put multiple values into one bucket. This is a performance/space trade off.
Here is a simplified example.
If you were to create an index with a single character...
create table animals (
    name varchar(255),
    index(name(1))
);

That will only index the first character of each name.
index       name
----------------
A           Ape
A           Aardvark
A           Ant
A           Anteater
B           Baboon
C           Cat
D           Dog
D           Dingo

So when you query where name = 'Aardvark' it will use the A index to find a list of Ape, Aardvark, Ant, Anteater and search it. The index improves the performance of the query, but there's still some searching to do.
Let's say you had index(name(3)).
index       name
----------------
Ape         Ape
Aar         Aardvark
Ant         Ant
Ant         Anteater
Bab         Baboon
Cat         Cat
Dog         Dog
Din         Dingo

Now when you query where name = 'Aardvark' it will use the Aar index to find just Aardvark and will perform fast. But if you search for where name = 'Ant' it will use Ant to find Ant, Anteater and have to search that list.
You need to make the decision between index size and performance that fits your data and queries.

A practical example, say I'm storing SHA-1 checksums as text. Those are 40 characters long. But for all practical purposes the first 7 or 8 characters are very, very likely to be unique. So I store all 40 characters, but only index the first 8.
checksum char(40),
index(checksum(8))

Now where checksum = '97531bc4cb33c00f3e9ff10d65386b8e96cdae3d' will use the 97531bc4 index and likely produce a single value. This potentially saves a lot of space without any impact on performance.


text:
Q: Is $T_1$ condition necessary in the definition of completely normality? Engelking states a theorem(2.1.7) in the book General Topology as follows:

For every $T_1$ spaces the following are equivalent:
(1) Every subspace of $X$ is normal.
(2) Every open subspace of $X$ is normal.
(3) Two separated sets have disjoint open neighborhoods.

I was asked to show that (1) and (3) are equivalent, however, I don't know where the $T_1$ condition is used in the proof. My proof goes as follows:
If $X$ satisfies (3), then let $Y$ be a subspace and $A,B\subset Y$ disjoint closed sets in the subspace $Y$. Denote the closure operator in $X$ by $Cl$ and in $Y$ by $Cl^*$. We claim that $A, B$ are separated in $X$: $$Cl(A)\cap B= Cl(A)\cap Cl^*(B) = Cl(A)\cap Cl(B)\cap Y = Cl^*(A)\cap Cl^*(B)$$ But this is empty by the fact that $A, B$ are closed. Then we can take disjoint open neighborhood of $A,B$ in $X$, and intersect both by $Y$.
If $X$ satisfies (1), then take two separated sets $A, B$ in $X$. The open subspace $Y=X-(Cl(A)\cap Cl(B))$ contains each of $A $ and $B$ by the fact that they are separated. The closure of them in $Y$ is empty: $Cl^*(A)\cap Cl^*(B)= Cl(A)\cap Cl(B)\cap Y$ is empty because $Y$ does not contain $Cl(A)\cap Cl(B)$. Take disjoint open neighborhood of $Cl^*(A)$ and $Cl^*(B)$ in $Y$, then by the fact that $Y$ is open, we are done with the proof.
So where exactly did I use $T_1$ condition in my proof?

A: Be aware that Engelking has the tendency to assume extra separation axioms in some definitions: compact/paracompact includes Hausdorff, normal and regular includes $T_1$, perfectly normal includes normal (which includes $T_1$) etc.
So in order to have a space all of whose subspaces are normal, we can only consider $T_1$ spaces to begin with. It's the price of admission, as it were.


text:
Q: how do I get cursor:pointer on an embedded object? 1) I am trying to place a transparent image over an embedded object. I am missing positions, relative and absolute, somewhere. But where?
I am actually placing the transparent image because I cannot use cursor:pointer for the object embed. So my idea was to place a transparent image and use cursor:pointer.
2) Why doesn't onclick work in IE? It works fine in Firefox and Chrome.

           <object width="475px" height="75px" onclick="window.location='http://www.google.com'; return false;">
                 <embed src="merchant_images/The_Marquee_Dealn.swf" type="application/x-shockwave-flash" style="z-index: 0; cursor:pointer" wmode="transparent" width="475px" height="75px">
                 </embed>
            </object>

Thanks in advance!

A: With your given code, add the position values to position: relative on #divmarquee, and change position to position: absolute and add cursor: pointer on #imgtrans:
#divmarquee { position: relative; }
#imgtrans { position: absolute; cursor: pointer; }

See here: http://jsfiddle.net/blineberry/pJZ2t/

A: In your code above you added cursor: pointer to the embed-tag. Try moving it to the image tag instead.

A: Don't use an , use a
 and make sure it expands to the width and height of the object.

A: Apply the cursor: pointer style to divmarquee.

A: For your onclick problem try these:
first, try
onclick = function(){window.location='http://www.google.com';return false;}

then try to change it to this:
onclick = window.location.href='somesite'

you can also try:
onclick = document.location='somesite'

if that doesn't work try:
var el = document.getElementById("imgtrans").firstChild;
if (el.addEventListener){
  el.addEventListener(
      'click',
      function(){
               window.location='http://www.google.com';
               return false;},
      false); //Decent Browsers
       }
else if (el.attachEvent){
      el.attachEvent(
          'onclick',
          function(){
               window.location='http://www.google.com';
               return false;
          }
      );
}//IE

ONE OF THOSE WILL WORK

A:

<object width="475px" height="75px" onclick="window.location='http://www.google.com'; return false;">
<embed src="merchant_images/The_Marquee_Dealn.swf" type="application/x-shockwave-flash" wmode="transparent" width="475px" height="75px">
</embed>
</object>

A: cursor: pointer will work when you wrap the object in a html hyperlink.


text:
Q: QTextEdit and QPrintPreview works slowly with large HTML table I'm trying to create reports like MS Access, and thanks to QTextEdit example everything works very nicely. But when I open a large HTML table (about 5000 rows), it takes about 35 seconds to load the table - so it's very slow. How can I optimise the print-preview? Maybe load only one page and change the current page in the print-preview window? But I can't find how to access the print-preview buttons. Or maybe change something with my HTML table?
#!/usr/bin/env python
import sys
from PyQt4 import QtCore, QtGui

class TextEdit(QtGui.QMainWindow):
    def __init__(self, fileName=None, parent=None):
        super(TextEdit, self).__init__(parent)

        self.setupFileActions()
        self.textEdit = QtGui.QTextEdit(self)
        self.setCentralWidget(self.textEdit)

        if fileName is None:
            fileName = './test5000.htm'
            self.load(fileName)

    def load(self, f):
        if not QtCore.QFile.exists(f):
            return False

        fh = QtCore.QFile(f)
        if not fh.open(QtCore.QFile.ReadOnly):
            return False

        data = fh.readAll()
        codec = QtCore.QTextCodec.codecForHtml(data)
        unistr = codec.toUnicode(data)

        if QtCore.Qt.mightBeRichText(unistr):
            self.textEdit.setHtml(unistr)
        else:
            self.textEdit.setPlainText(unistr)
        return True

    def setupFileActions(self):
        menu = QtGui.QMenu("&File", self)
        self.menuBar().addMenu(menu)

        self.actionOpen = QtGui.QAction(
            QtGui.QIcon.fromTheme('document-open'),
            "&Open...", self, shortcut=QtGui.QKeySequence.Open,
            triggered=self.fileOpen)
        menu.addAction(self.actionOpen)
        menu.addSeparator()

        self.actionPrintPreview = QtGui.QAction(
            QtGui.QIcon.fromTheme('fileprint'),
            "Print Preview...", self,
            shortcut=QtCore.Qt.CTRL + QtCore.Qt.SHIFT + QtCore.Qt.Key_P,
            triggered=self.filePrintPreview)
        menu.addAction(self.actionPrintPreview)

    def fileOpen(self):
        fn = QtGui.QFileDialog.getOpenFileName(self, "Open File...", "C:",
                                           "HTML-Files (*.htm *.html);;All Files (*)")
        if fn:
            self.load(fn)

    def filePrintPreview(self):
        printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)

        printer.setOrientation(1)
        printer.setPageSize(8)
        printer.setPageMargins(20, 20, 20, 20, 0)
        printer.setResolution(300)

        preview = QtGui.QPrintPreviewDialog(printer, self)
        preview.paintRequested.connect(self.printPreview)
        preview.exec_()

    def printPreview(self, printer):
        self.textEdit.print_(printer)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    mainWindows = []
    for fn in sys.argv[1:] or [None]:
        textEdit = TextEdit(fn)
        textEdit.resize(1024, 768)
        textEdit.show()
        mainWindows.append(textEdit)

    sys.exit(app.exec_())

Sample HTML file with images is here.
When you run script it opens the HTML file (slowly), then menu File->Print preview runs the print-preview dialog.


text:
Q: putting floats into a 2d array I'm new to C so sorry in advance if this is so obvious.
Basically, I'm trying to take an input like below and put into a 2d array.
C 3.25 18. 0.01 .01 .02 .04 .08 .02 .02
A 0 7.5 .054 .031 .016 .008 .116 .124 .147
D -1.5 0.5 .012 .025 .05 .1 .1 .1 .025

I wrote a function in order to know the number of variables(so the number of rows) and I've taken the number of floating points.
count = numofvar(tokens);
scanf("%d %ld", &count_inter, &count_exper);
float data[count][count_inter + 3];

for(i=0; i<count; i++)
{
    for(j=0; j<count_inter+3; j++)
    {
        scanf("%f", &data[i][j]);
    }
}

printf("\n");

for(i=0; i<count; i++)
{
    for(j=0; j<count_inter+3; j++)
    {
        printf("%f ", data[i][j]);
    }
    printf("\n");
}

Besides the floats, I'm also trying to store the letters in the beginning in to the array. (To understand what these values correspond to).
However I get this weird output:
-3.817211 0.000000 0.000000 0.000000 -3.817268 0.000000 -3.817295
0.000000 0.000000 -3.817238 0.000000 -3.817232 0.000000 0.000000
-309364117239383605807310438400.000000 0.000000 20366038377015803904.000000 -65873193319006208.000000 0.000000 0.000000    -311890318855195825296505831424.000000
pc:~$ A 0 7.5 .054 .031 .016 .008 .116 .124 .147
A: command not found
pc:~$ D -1.5 0.5 .012 .025 .05 .1 .1 .1 .025

What should I do?

A: Your code to parse the input lines appears to have no relationship to the input format, so you have work to do there. I'd suggest putting the storage arrays to one side for a while, and just concentrating on writing a program that reads the input and writes it out with annotations, e.g.
Label: C
List length: 9
1: 3.25
2: 18.0
3: 0.01
... etc.

... just to prove to yourself that you can read the input format.
Then you need to find a way to store your values. You can't store a char in a float[] or a float in a char -- or at least, not without some dirty tricks like casting.
Avoid dirty tricks. The language's type system is there to help you. Don't fight it.
Better to store the labels in a separate array, so:
 char labels[count];
 float labels[count][count_inter];

This should be enough to get a working program going.
There are other approaches, using constructs such as struct and union. When you learn about these, you could perhaps come back to this program and experiment with those as ways to make the code more elegant.

A: Set the data type of float to char. Then you can store both alphabets and numbers.
Instead of:
float data[count][count_inter + 3];

Use this:
char data[count][count_inter + 3];


text:
Q: How to solve Excel count of saturday I have a list of dates in MS Excel in column A.
I am using Excel 2016.

I want to find out how many dates are Sunday and separately Saturday.
I dont know exactly how many rows in sheet so I need to use the whole column.
I am using the following formula:
Count of Saturdays:
=SUMPRODUCT(--(WEEKDAY(A:A)=7))

Count of Sundays:
=SUMPRODUCT(--(WEEKDAY(A:A)=1))

The same formula is used for Friday only for testing.
Count of Fridays:
=SUMPRODUCT(--(WEEKDAY(A:A)=6))

The Friday and Sunday works well as I see, but Saturday returns an icorrect value (it seems to me works on blank values)
Could be is that a WEEKDAY function bug?
Somebody has the same problem?
Any Idea to solve the problem?

A: Add an additional clause to exclude blanks. And don't use entire column references within SUMPRODUCT. Either reformat your column entries as a Table, after which your formula would be:
=SUMPRODUCT(--(WEEKDAY(Table1[Date])=7),--(Table1[Date]<>""))
else use a construction which determines the last-used cell within that column:
=SUMPRODUCT(--(WEEKDAY(A1:INDEX(A:A,LastRow))=7),--(A1:INDEX(A:A,LastRow)<>""))
where LastRow is defined within Name Manager as:
=MATCH(9^9,Sheet1!$A:$A)
(Obviously amend Sheet1 in this definition as required.)

A: Considering
Sunday=1
Saturday=6
=SUMPRODUCT(N(WEEKDAY(A:A)={1,6}))


text:
Q: DST calculation using R I want to calculate the daylight saving time beginning date for each year from 2003 through 2021 and keep only the days that are 60 days before and after the daylight saving time begin date each year.
i.e date will change each year (falls on a Sunday) and moved from happening in April 2003-2006 to happening in March during the years 2007-2021.
I need to Create a running variable "days" that measures the distance from the daylight saving time begin date for each year with days=0 on the first day of daylight saving time.
Here's dataset
year month day propertycrimes violentcrimes
2003 1 1 94 34
2004 1 1 60 46
2005 1 1 106 41
2006 1 1 87 40
2007 1 1 72 36
2008 1 1 43 50
2009 1 1 35 32
2010 1 1 32 50
2011 1 1 29 45
2012 1 1 32 45
Here's my code so far
library(readr)
dailycrimedataRD <- read_csv("dailycrimedataRD.csv")
View(dailycrimedataRD)
days <- .POSIXct(month, tz="GMT")

A: How about this:
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
library(readr)
dailycrimedataRD <- read_csv("~/Downloads/dailycrimedataRD.csv")
#> Rows: 6940 Columns: 5
#> ── Column specification ────────────────────────────────────────────────────────
#> Delimiter: ","
#> dbl (5): year, month, day, propertycrimes, violentcrimes
#>
#> ℹ Use `spec()` to retrieve the full column specification for this data.
#> ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

tmp <-  dailycrimedataRD  %>%
  mutate(date = lubridate::ymd(paste(year, month, day, sep="-"), tz='Canada/Eastern'),
         dst = lubridate::dst(date)) %>%
  arrange(date) %>%
  group_by(year) %>%
  mutate(dst_date = date[which(dst == TRUE & lag(dst) == FALSE)],
         diff = (as.Date(dst_date) - as.Date(date))) %>%
  filter(diff <= 60 & diff >= 0)

tmp
#> # A tibble: 1,159 × 9
#> # Groups:   year [19]
#>     year month   day propertycrimes violentcrimes date                dst
#>    <dbl> <dbl> <dbl>          <dbl>         <dbl> <dttm>              <lgl>
#>  1  2003     2     6             68             8 2003-02-06 00:00:00 FALSE
#>  2  2003     2     7             71             8 2003-02-07 00:00:00 FALSE
#>  3  2003     2     8             81            12 2003-02-08 00:00:00 FALSE
#>  4  2003     2     9             68             7 2003-02-09 00:00:00 FALSE
#>  5  2003     2    10             68             9 2003-02-10 00:00:00 FALSE
#>  6  2003     2    11             61             8 2003-02-11 00:00:00 FALSE
#>  7  2003     2    12             73            10 2003-02-12 00:00:00 FALSE
#>  8  2003     2    13             62            14 2003-02-13 00:00:00 FALSE
#>  9  2003     2    14             71            10 2003-02-14 00:00:00 FALSE
#> 10  2003     2    15             90            11 2003-02-15 00:00:00 FALSE
#> # … with 1,149 more rows, and 2 more variables: dst_date <dttm>, diff <drtn>

Created on 2022-04-14 by the reprex package (v2.0.1)


text:
Q: Disabling double click inside the IFRAME with remote source Folks,
We have one strange requirement where we want to disable double click inside the IFRAME.
The complication here is HTML response is coming from remote URL and we donot have any control over it. Is it possible to disable double click inside this IFRAME.
e.g.
Iframe src="http://removeserver/view.jsp" height="300px" width="300px">
Note : We already investigated and it seems because of cross side scripting we cannot do this.Basically we cannot access HTML elements of page remoteserver/view.jsp as it is coming from remote web site.
Any help will be highly appreciated.

A: Empty div above iframe will disable any mouse actions on iframe content
http://jsfiddle.net/uxUF8/63/

another version allows you to scroll inside http://jsfiddle.net/uxUF8/62/


text:
Q: links absent when reading html into R I am attempting to get a list of all links of satellite data for a year/month on the European Space Agency's Cryosat-2 website (https://science-pds.cryosat.esa.int/#Cry0Sat2_data%2FSIR_SAR_L2%2F2013%2F02). No matter what web scraping or html reading package I use, the links are never included. Below is an example of such an attempt with the url provided, but it is by no means my only attempt. I am looking for an explanation as to why the links that initiate the download of individual files aren't extracted, and what the solution is to obtaining them.
library(textreadr)
html_string<- 'https://science-pds.cryosat.esa.int/#Cry0Sat2_data%2FSIR_SAR_L2%2F2013%2F02'
html_read<- read_html(html_string)
html_read

 [1] "Layer 1"                                                                                "European Space Agency"
 [3] "CryoSat-2 Science Server"                                                                    "The access and use of CryoSat-2 products are regulated by the"
 [5] "ESA's Data Policy"                                                                           "and subject to the acceptance of the specific"
 [7] "Terms & Conditions"                                                                          "."
 [9] "Users accessing CryoSat-2 products are intrinsically acknowledging and accepting the above." "Name"
[11] "Modified"                                                                                "Size"
[13] "ESA European Space Agency"

A: Ok, here is a solution. In this kind of case where you can't get the info with regular scraping (rvest and so on), two solutions:

*

*or you get the info with RSelenium and it can be tedious

*or you inspect the page and monitor the XHR request (with the element inspector of firefox for example: network, and XHR).

You will find out that the data are loaded from urls looking like:
https://science-pds.cryosat.esa.int/?do=list&maxfiles=500&pos=5500&file=Cry0Sat2_data/SIR_SAR_L2/2021/02
These pages appear like html, but if you open them, they are not. They are JSON. The webpage just display dynamically the info requested as JSON.
So you can simply get the info as follow:
url <- 'https://science-pds.cryosat.esa.int/?do=list&maxfiles=500&pos=5500&file=Cry0Sat2_data/SIR_SAR_L2/2021/02'
library(jsonlite)
fromJSON(url)

$success
[1] TRUE

$is_writable
[1] FALSE

$results
         mtime    size                                                        name
1   1616543429   37713 CS_OFFL_SIR_SAR_2__20210223T041611_20210223T042157_D001.HDR
2   1616543428  845594  CS_OFFL_SIR_SAR_2__20210223T041611_20210223T042157_D001.nc
3   1616543364   37713 CS_OFFL_SIR_SAR_2__20210223T043539_20210223T043844_D001.HDR
4   1616543363  528578  CS_OFFL_SIR_SAR_2__20210223T043539_20210223T043844_D001.nc
5   1616543321   37713 CS_OFFL_SIR_SAR_2__20210223T044915_20210223T045113_D001.HDR
6   1616543322  387650  CS_OFFL_SIR_SAR_2__20210223T044915_20210223T045113_D001.nc
7   1616543360   37713 CS_OFFL_SIR_SAR_2__20210223T045156_20210223T045427_D001.HDR
8   1616543359  456414  CS_OFFL_SIR_SAR_2__20210223T045156_20210223T045427_D001.nc
9   1616543328   37713 CS_OFFL_SIR_SAR_2__20210223T045551_20210223T045749_D001.HDR
10  1616543327  385998  CS_OFFL_SIR_SAR_2__20210223T045551_20210223T045749_D001.nc

                                                                                path
1   Cry0Sat2_data/SIR_SAR_L2/2021/02/CS_OFFL_SIR_SAR_2__20210223T041611_20210223T042157_D001.HDR
2    Cry0Sat2_data/SIR_SAR_L2/2021/02/CS_OFFL_SIR_SAR_2__20210223T041611_20210223T042157_D001.nc
3   Cry0Sat2_data/SIR_SAR_L2/2021/02/CS_OFFL_SIR_SAR_2__20210223T043539_20210223T043844_D001.HDR
4    Cry0Sat2_data/SIR_SAR_L2/2021/02/CS_OFFL_SIR_SAR_2__20210223T043539_20210223T043844_D001.nc
5   Cry0Sat2_data/SIR_SAR_L2/2021/02/CS_OFFL_SIR_SAR_2__20210223T044915_20210223T045113_D001.HDR
6    Cry0Sat2_data/SIR_SAR_L2/2021/02/CS_OFFL_SIR_SAR_2__20210223T044915_20210223T045113_D001.nc
7   Cry0Sat2_data/SIR_SAR_L2/2021/02/CS_OFFL_SIR_SAR_2__20210223T045156_20210223T045427_D001.HDR
8    Cry0Sat2_data/SIR_SAR_L2/2021/02/CS_OFFL_SIR_SAR_2__20210223T045156_20210223T045427_D001.nc
9   Cry0Sat2_data/SIR_SAR_L2/2021/02/CS_OFFL_SIR_SAR_2__20210223T045551_20210223T045749_D001.HDR
10   Cry0Sat2_data/SIR_SAR_L2/2021/02/CS_OFFL_SIR_SAR_2__20210223T045551_20210223T045749_D001.nc

These should give you all the info you need. If you tweak a bit the url, you should be able to get all the info from the date you want.

A: The problem seems to be that the page is dynamic. It probably has some JS code and only loads the links after it runs. So when you get the HTML from the link, you're only getting the base page (before the JS runs).
I can think of two possible solutions:

*

*You can try to use selenium, which emulates an user in the browser so it will load the page completely, but the set-up might be a bit complicated. See for an intro https://www.r-bloggers.com/2014/12/scraping-with-selenium/

*The page probably sends an HTTP request to get the links from an API, you can try to figure out the exact request. The network tab on you browser is a good place to start.


text:
Q: Store Shapely STRtree to a file for reuse I have an incredible amount of shapely geometry polygons, saved in a shapefile. I load them into a shapely STRTree. It seems very inefficient to have to recalculate their envelope every time the program is ran. Is there a way (with pickle maybe?) to store the entire tree? Even storing them with Redis would be useful.
Thanks!

A: On second thought... pickling for this reason will not really help much, because essentially all pickling the strtree does is convert each individual geometry to wkb format and write them all to a single file (see comment here). Unpickling recreates these geometries from the wkb and then creates a new STRtree with them. So the boundaries will be calculated again either way.

Pickling appears to work, though I have not tested it on all geometry types.
import pickle

from shapely.geometry import Polygon
from shapely.strtree import STRtree

polys = [Polygon(((i, i), (i + 1, i), (i, i + 1))) for i in range(100)]
strtree = STRtree(polys)

with open('strtree.pickle', 'wb') as f:
    pickle.dump(strtree, f)

And then in another process
import pickle

from shapely.geometry import Point

with open('strtree.pickle', 'rb') as f:
    strtree = pickle.load(f)

print(strtree.nearest(Point(39.8, 39.8)).wkt)
# POLYGON ((40 40, 41 40, 40 41, 40 40))

There was an update in shapely==1.7.1 that avoided a segfault when unpickling some STRtree objects. So you may want to get on the latest version for this.


text:
Q: Disable incremental search in firefox (and everything else!) All I find from googling "disable incremental search" is a bunch of people telling me how great incremental search is. It isn't. Firefox has the worst version of it, jumping around and making me lose my place because of a search I haven't even finished typing yet. I don't want the window scrolling up and down without my say-so.
It would be nice if I could search with regular expressions, like text search has been done in every non-toy application since ed. But the jumpiness of the window is the overriding concern.
How can this evil be defeated?
UPDATE
I see now that I was unclear in specifying exactly which user interface element I was talking about. I'm talking about the simple text search that you can get to by typing Control-F or using "Find" in the Edit menu. I should have specified that originally. Sorry for the waste of time caused by the ambiguity.

A: FindBar Tweak 0.5.5
https://addons.mozilla.org/en-US/firefox/addon/findbar-tweak
Quote:

Delay the highlights if the search term is shorter than a defined
  number of characters (default is 3) to improve performance

Hopefully this will work for you.