text:
Q: Find a student with select grades I have just made an Access 2010 database for analyzing students' grades in an exam. I was able to get grades for all students right. There are six subjects. What I want to do now is find who got A grade in any five out of six. That is, who missed full A grade by just one subject.
Right now I have the students' grades in a tabular format. The students' names, followed by their grades in all six subjects in the next six columns. Like this:
               ENG    LANGUAGE      PHY     CHE     BIO      MATH
ANN            A+      A+           C       A+      A+       A+

JOHN           B+       C           A       A+      B        C+

To find those who got A+ in all subjects I added A+ as the criteria in the query. But how do we find those who got A+ in ANY five subjects?
Can we add an expression to the query, or can we use a vba code? Could you please help me with it?I just couldn't find a way to do it. Any help is greatly appreciated.

A: Your database schema is poorly designed.  With a properly normalized schema you will get the results with a simple query.  This really probably should probably have 4 separate tables, but let me show you how to do this with two and a simple sql query.
One table will hold scores, and one table will hold our values.
ScoreValues
-----------
ID | Value
A+ | 4.3
A | 4.0
B | 3.0
C+ | 2.3
C | 2.0
D | 1.0

Scores
------
StudentID | Subject | Score
ANN | ENG | A+
ANN | LANGUAGE | A+
ANN | PHY | C
ANN | CHE | A+
ANN | BIO | A+
ANN | MATH | A+
JOHN | ENG | B+
JOHN | LANGUAGE | C
JOHN | PHY | A
JOHN | CHE | A+
JOHN | BIO | B
JOHN | MATH | C+

select Count(Subject) as AplusGradeCount, Student
from Scores,ScoreValues
where Scores.Score=ScoreValues.Value and
      ScoreValues.Value > 4.0
Group By Student

QueryResults
------------
AplusGradeCount | Student
5 | ANN
1 | JOHN

Anyway, I strongly suggest you spend time learning about database normalization.  A properly normalized database will making querying the data far easier.


text:
Q: How to use fireTableDataChanged in this case? (Or what other method should I use?) I am making a small program that retrieves data from a sqlite database and populates the JTable. User can also populate the database by the  proper form. Mu question is, how to update the JTable so it shows content added by user? For now, it only shows it after rerunning the whole application.
Here's the code for the table:
package kpkw;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import static javax.swing.WindowConstants.EXIT_ON_CLOSE;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;

public class MainTable {

//protected List<List<Object>> allMembers = new ArrayList<>();
//protected List<Object> member = new ArrayList<>();
protected MainTable(){

}

private  void PassFromDBtoTable(List<List<Object>> allMembers){

        Connection c = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
          c = DriverManager.getConnection("jdbc:sqlite:HistoriaPrzeplywow.s3db");
          c.setAutoCommit(false);
          stmt = c.createStatement();
          rs = stmt.executeQuery( "SELECT * FROM HistoriaPrzeplywow;" );
          while ( rs.next() ) {
              List<Object> member = new ArrayList();

             int idSQL = rs.getInt("ID");
             String id2SQL = rs.getString("ID2");
             int id3SQL = rs.getInt("ID3");
             String typSQL = rs.getString("Typ");
             String imieSQL = rs.getString("Imie");
             String nazwiskoSQL = rs.getString("Nazwisko");
             int naleznoscSQL = rs.getInt("Naleznosc");
             String tytulemSQL = rs.getString("Tytulem");
             String dataSQL = rs.getString("Data");

             member.add(idSQL);
             member.add(id2SQL);
             member.add(id3SQL);
             member.add(typSQL);
             member.add(imieSQL);
             member.add(nazwiskoSQL);
             member.add(ManageCurrency(naleznoscSQL));
             member.add(tytulemSQL);
             member.add(dataSQL);

             allMembers.add(member);

          }

        }
          catch ( SQLException e ) {
          System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          System.exit(0);
        }

        finally{
          if(rs!=null&& stmt!=null && c!=null){
            try{
                rs.close();
                stmt.close();
                c.close();
            }
            catch(SQLException e){
                e.printStackTrace();
            }
          }
        }
}

private String ManageCurrency(int naleznoscSQL){
    String currency = Integer.toString(naleznoscSQL);
    currency = new StringBuilder(currency).insert(currency.length()-2, ".").toString();

    return currency;

}

private void ResizeColumnWidth(JTable table){
    final TableColumnModel columnModel = table.getColumnModel();
    for(int col = 0; col < table.getColumnCount(); col++){
        int width = 70;
        for(int row = 0; row < table.getRowCount(); row++){
            TableCellRenderer renderer = table.getCellRenderer(row, col);
            Component component = table.prepareRenderer(renderer, row, col);
            int componentSize = component.getPreferredSize().width;
            width = Math.max(componentSize ,width);
        }
        columnModel.getColumn(col).setPreferredWidth(width);
    }
}  // method doesn't work so far

private void initUI(){

    JFrame mainFrame = new JFrame();

    JPanel mainPanel = new JPanel();

    JMenuBar menuBar = new JMenuBar();

    JMenu plikMenu = new JMenu("Plik");

    List<List<Object>> allMembers = new ArrayList<>();
    List<Object> member = new ArrayList<>();
    PassFromDBtoTable(allMembers);
    for(int i = 0; i< member.size(); i++){
        System.out.println(member.get(i));
    }
    MyTableModel mtb = new MyTableModel(allMembers);
    JTable rekordy = new JTable(mtb);
    JScrollPane scrollPane = new JScrollPane(rekordy);
    ResizeColumnWidth(rekordy);
    rekordy.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
    rekordy.setAutoCreateRowSorter(true);

    JMenuItem noweKPMenuItem = new JMenuItem("Nowe KP...");
    JMenuItem noweKWMenuItem = new JMenuItem("Nowe KW...");
    JMenuItem zakonczMenuItem = new JMenuItem("Zakończ");

    mainFrame.setLayout(new BorderLayout());
    mainFrame.setTitle("Historia Przepływów");
    mainFrame.setLocationRelativeTo(null);
    mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    mainFrame.setSize(660, 200);
    mainFrame.setJMenuBar(menuBar);

    //JButton test = new JButton("test");

    //mainFrame.add(mainPanel);

    mainPanel.setLayout(new BorderLayout());

    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

    mainPanel.add(scrollPane, BorderLayout.CENTER);
    //mainPanel.add(test);
    menuBar.add(plikMenu);
    plikMenu.add(noweKPMenuItem);
    plikMenu.add(noweKWMenuItem);
    plikMenu.add(zakonczMenuItem);
    mainFrame.add(scrollPane, BorderLayout.CENTER);
    mainFrame.setVisible(true);

       noweKPMenuItem.addActionListener(new ActionListener() {
       @Override
       public void actionPerformed(ActionEvent event) {
           //KP run = new KP();
           KP.run();
      }
   });

}

public class MyTableModel extends AbstractTableModel{

    protected List<List<Object>> allMembers = new ArrayList<>();

     public MyTableModel (List<List<Object>> allMembers) {
    this.allMembers = allMembers;
}

     protected MyTableModel(){

     }

    String[] columnNames = {"ID", "ID2", "ID3", "Typ", "Imię", "Nazwisko","Należność", "Tytułem", "Data"};

    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

    @Override
    public int getRowCount() {
        return allMembers.size();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        //List<Object> row = allMembers.get(rowIndex);
        return allMembers.get(rowIndex).get(columnIndex);

    }

    @Override
    public boolean isCellEditable(int row, int column)
    {
      return false;
    }

    protected  void addRecord(int ID, String ID2, int ID3, String typ, String imie, String nazwisko, int naleznosc, String tytulem, String data){
    Connection c = null;
    PreparedStatement pstmt = null;
    try {
        Class.forName("org.sqlite.JDBC");
        c = DriverManager.getConnection("jdbc:sqlite:HistoriaPrzeplywow.s3db");
        c.setAutoCommit(false);
        System.out.println("Opened database successfully");

        //pstmt = c.createStatement();
        String sqlCommand = ("INSERT INTO HistoriaPrzeplywow (ID,ID2,ID3,Typ,Imie,Nazwisko,Naleznosc,Tytulem,Data) VALUES (?,?,?,?,?,?,?,?,?);");
        pstmt = c.prepareStatement(sqlCommand);
        pstmt.setInt(1, ID);
        pstmt.setString(2, ID2);
        pstmt.setInt(3, ID3);
        pstmt.setString(4, typ);
        pstmt.setString(5, imie);
        pstmt.setString(6, nazwisko);
        pstmt.setInt(7, naleznosc);
        pstmt.setString(8, tytulem);
        pstmt.setString(9, data);

        pstmt.executeUpdate();
        c.commit();

        List<Object> rowData = new ArrayList<>();
        rowData.add(ID);
        rowData.add(ID2);
        rowData.add(ID3);
        rowData.add(typ);
        rowData.add(imie);
        rowData.add(nazwisko);
        rowData.add(tytulem);
        rowData.add(data);

        allMembers.add(rowData);
        fireTableDataChanged();

    }
    catch(SQLException| ClassNotFoundException e){
        e.printStackTrace();
    }
    finally{
        if(c!=null){
            try{
                c.close();
               // pstmt.close();
            }
            catch(SQLException e){
                e.printStackTrace();
            }
        }
    }
}

}

 /*MainTable(){

    initUI();

}*/

public static void main(String args[]) {

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            //System.out.println(new File(".").getAbsoluteFile());

            MainTable guiMainTable = new MainTable();
            guiMainTable.initUI();

                        }
    });
}
}

And here's the form's code:
package kpkw;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class KP extends JFrame {
private ArrayList<JPanel> naleznosciArrayList   = new ArrayList<>();
private ArrayList<JTextField> zaCoArrayList   = new ArrayList<>();
private ArrayList<JTextField> zloteArrayList   = new ArrayList<>();
private ArrayList<JTextField> grArrayList   = new ArrayList<>();
private static int liczbaWierszy = -1;

public KP() {

    initUI();
}

private void usunPole(JPanel nal){
    nal.remove(naleznosciArrayList.get(liczbaWierszy));
    naleznosciArrayList.remove(liczbaWierszy);
    liczbaWierszy--;
}

private void initUI(){

   setTitle("KP");
   setSize(500, 300);
   setLocationRelativeTo(null);
   setDefaultCloseOperation(DISPOSE_ON_CLOSE);
   JMenuBar menubar = new JMenuBar();
   this.setJMenuBar(menubar);
   JMenu plik = new JMenu("Plik");
   menubar.add(plik);

   JPanel container = new JPanel();
   container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
   this.add(container);

   JPanel title = new JPanel();
   JLabel kpTytul = new JLabel("Generator KP");
   kpTytul.setFont(new Font("Serif",Font.BOLD, 14));

   container.add(title);
   title.add(kpTytul);

   JPanel pola1 = new JPanel();
   pola1.setLayout(new GridLayout(2,2));
   container.add(pola1);

   JLabel lData = new JLabel("  Data");
   JTextField tData = new JTextField(1);
   tData.setEditable(false);
   DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
   Date date = new Date();
   tData.setText((dateFormat.format(date)));
   JLabel lNumer = new JLabel("  KP");

   JPanel numery = new JPanel();
   numery.setLayout(new BoxLayout(numery, BoxLayout.X_AXIS));
   JTextField tNumerRef = new JTextField(1);
   tNumerRef.setEditable(false);
   Connection c = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
      c = DriverManager.getConnection("jdbc:sqlite:HistoriaPrzeplywow.s3db");
      c.setAutoCommit(false);
      stmt = c.createStatement();
      rs = stmt.executeQuery( "SELECT Count(*) FROM HistoriaPrzeplywow;" );
      rs.next();
      int numberOfRows = rs.getInt(1)+1;
      tNumerRef.setText(Integer.toString(numberOfRows));
    }
    catch(SQLException e){
        e.printStackTrace();
    }
    finally{
        if(c!=null&&rs!=null){
            try{
                c.close();
                //stmt.close();
                rs.close();
            }
            catch(SQLException e){
                e.printStackTrace();
            }
        }
    }
   JTextField tNumerReg = new JTextField(1);
   JTextField tNumerRok = new JTextField(1);
   DateFormat rokFormat = new SimpleDateFormat("yyyy");
   Date dataRok = new Date();
   tNumerRok.setText((rokFormat.format(dataRok)));
   tNumerRok.setEditable(false);

   numery.add(tNumerRef);
   numery.add(tNumerReg);
   numery.add(tNumerRok);

   pola1.add(lData);
   pola1.add(tData);
   pola1.add(lNumer);
   pola1.add(numery);

   JPanel pola2 = new JPanel();
   pola2.setLayout(new GridLayout(3,2));
   container.add(pola2);

   JLabel lImie = new JLabel("  Imię");
   JTextField tImie = new JTextField(1);
   JLabel lNazwisko = new JLabel("  Nazwisko");
   JTextField tNazwisko = new JTextField(1);
   //JLabel lZaCo = new JLabel("Za co");
   //JTextField tZaCo = new JTextField(1);

   pola2.add(lImie);
   pola2.add(tImie);
   pola2.add(lNazwisko);
   pola2.add(tNazwisko);

   JPanel naleznosci = new JPanel();
    naleznosci.setLayout(new BoxLayout(naleznosci, BoxLayout.X_AXIS));

    JLabel lZaCo = new JLabel("Tytułem:");
    JTextField tZaCo = new JTextField(1);
    zaCoArrayList.add(tZaCo);
    JLabel gap = new JLabel("       ");
    JLabel lKasa = new JLabel("Wartość:");
    JTextField tZlote = new JTextField(1);
    zloteArrayList.add(tZlote);
    JLabel lZl = new JLabel("zł");
    JTextField tGr = new JTextField(1);
    grArrayList.add(tGr);
    JLabel lGr = new JLabel("gr");
    JLabel gap2 = new JLabel("   ");
    JLabel gap3 = new JLabel("   ");
    //JLabel lWinien = new JLabel("Winien");
    //JTextField tWinien = new JTextField(1);

    naleznosci.add(lZaCo);
    naleznosci.add(tZaCo);
    naleznosci.add(gap);
    naleznosci.add(lKasa);
    naleznosci.add(gap3);
    naleznosci.add(tZlote);
    naleznosci.add(lZl);
    naleznosci.add(tGr);
    naleznosci.add(lGr);

    container.add(naleznosci);

   JPanel separator = new JPanel();
   container.add(separator);
   separator.add(new JSeparator(SwingConstants.HORIZONTAL));

   JButton generuj = new JButton("Generuj");
   container.add(generuj);
   generuj.setAlignmentX(Component.LEFT_ALIGNMENT);

   generuj.addActionListener(new ActionListener() {
       @Override
       public void actionPerformed(ActionEvent event) {

           if(tImie.getText().equals("") || tNazwisko.getText().equals("") || tNumerReg.getText().equals("") || tZaCo.getText().equals("") || tZlote.getText().equals("") || tGr.getText().equals("")){
               //System.out.println("Nie wypełniono wszystkich pól");
               ErrorWindow.setMessage("Nie wypełniono wszystkich pól");
               ErrorWindow.main();
           }
           else {

               try{
                   int ID = Integer.parseInt(tNumerRef.getText());
                   int ID3 = Integer.parseInt(tNumerRok.getText());
                   String typ = "KP";
                   String naleznosc = tZlote.getText() + tGr.getText();
                   int naleznoscInt = Integer.parseInt(naleznosc);
                   MainTable mt = new MainTable();
                   mt.new MyTableModel().addRecord(ID, tNumerReg.getText(), ID3, typ, tImie.getText(), tNazwisko.getText(), naleznoscInt, tZaCo.getText(), tData.getText());

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

           }
      }
   });

}

public static void run() {

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            KP gui = new KP();
            gui.setVisible(true);
        }
    });
}

}

Any help will be appreciated.

A: MainTable mt = new MainTable();
mt.new MyTableModel().addRecord(...);

Don't create a new JTable. You need to access the existing TableModel of the JTable that is displayed in the frame. Then you invoke the addRecord(...) method on that table model.
Also in your custom TableModel you are using:
fireTableDataChanged();

That is the wrong method since you did not change all the data. All you did was add a single row of data, so you should be using:
fireTableRowsInserted(...);

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the difference between Node.SelectNodes(/*) and Node.childNodes?         string XML1 = "<Root><InsertHere></InsertHere></Root>";
        string XML2 = "<Root><child1><childnodes>data</childnodes><childnodes>data1</childnodes></child1><child2><childnodes>data</childnodes><childnodes>data1</childnodes></child2></Root>";

Among below mentioned two code samples.. usage of childNodes doesn't copy all the child nodes from XML2. only <child1> is being copied.
        string strXpath = "/Root/InsertHere";

        XmlDocument xdxmlChildDoc = new XmlDocument();
        XmlDocument ParentDoc = new XmlDocument();
        ParentDoc.LoadXml(XML1);
        xdxmlChildDoc.LoadXml(XML2);

        XmlNode xnNewNode = ParentDoc.ImportNode(xdxmlChildDoc.DocumentElement.SelectSingleNode("/Root"), true);

        if (xnNewNode != null)
        {
            XmlNodeList xnChildNodes = xnNewNode.SelectNodes("/*");
            if (xnChildNodes != null)
            {
                foreach (XmlNode xnNode in xnChildNodes)
                {
                    if (xnNode != null)
                    {
                        ParentDoc.DocumentElement.SelectSingleNode(strXpath).AppendChild(xnNode);
                    }
                }
            }
        }

code2:
    if (xnNewNode != null)
    {
        XmlNodeList xnChildNodes = xnNewNode.ChildNodes;
        if (xnChildNodes != null)
        {
            foreach (XmlNode xnNode in xnChildNodes)
            {
                if (xnNode != null)
                {
                    ParentDoc.DocumentElement.SelectSingleNode(strXpath).AppendChild(xnNode);
                }
            }
        }
    }

ParentDoc.OuterXML after executing first sample of code:
<Root>
    <InsertHere>
        <child1>
            <childnodes>data</childnodes>
            <childnodes>data1</childnodes>
        </child1>
        <child2>
            <childnodes>data</childnodes>
            <childnodes>data1</childnodes>
        </child2>
    </InsertHere>
</Root>

ParentDoc.OuterXML after executing second sample of Code
<Root>
    <InsertHere>
        <child1>
            <childnodes>data</childnodes>
            <childnodes>data1</childnodes>
        </child1>
    </InsertHere>
</Root>

A: I have done some debugging of the code, and it shows that xnNewNode.ChildNodes initially also returns 2 child nodes. After one iteration in the loop, the first child is however removed from ChildNodes, and therefore the loop ends prematurely.
If you want to use the ChildNodes property, one workaround is to "transfer" the child node references to an array or list, like this:
var xnChildNodes = xnNewNode.ChildNodes.Cast<XmlNode>().ToArray();

UPDATE
As Tomer W pointed out in his answer, when using XmlNode.AppendChild the inserted node is also removed from its original location. As stated in the MSDN documentation:
If the newChild is already in the tree, it is removed from
its original position and added to its target position.

With SelectNodes you have already created a new node collection, but with ChildNodes you are accessing the original collection.

A: this is a clearing of what Anders G posted, with more through explanation.
I am surprised the foreach  does not fail (Throw Exception) in this situation, but hell.
In code1.
1. Create a NEW COLLECTION of nodes
2. Select nodes to it
3. append to other node => removing from original collection, but not the newly created one.
4 you are removing the node you are adding from the newly collection.
in Code2
1. Reference the ORIGINAL node collection
{child1, child2}
2. append 1st Node away to another collection => removing it from the original collection
{child2}
3. now when the foreach at index 1,  it see that it passed the end of the collection. and exit.
this happens a lot when changing a collection that is subject to iteration.
but most the time, the IEnumerator is throwing an Exception when such happens.
hope i made it all clear

A: I had the same problem and observed, that whitespace nodes seem to have a value attached to the node, which is not the case with other nodes (at least in my application).This method removes the whitespace nodes from the node.ChildNodes list:
private List<XmlNode> findChildnodes(XmlNode node)
    {
        List<XmlNode> result = new List<XmlNode>();
        foreach (XmlNode childnode in node.ChildNodes)
        {
            if(childnode.Value == null)
            {
                result.Add(childnode);
            }
        }
        return result;
    }

A: In answer to your question, Node.childNodes is All of the child nodes, whereas Node.SelectNodes(/*) is all of the child nodes that match /*. Only XML elements will match /*, so any attributes, CDATA nodes, text nodes, etc will be excluded.
Nevertheless, the problem occurs because you are changing the collection of nodes while while iterating over them. You cannot do that. The select nodes method returns a list of references to nodes. This is why is works.


text:
Q: Find the minimal polynomial of rotation Find the minimal polynomial of rotation $A$ in angle of $\frac {\pi}{4} $ of $\mathbb R^3$ around the vector $v=(1,2,1)$
I know the rotation matrix in $\mathbb R^3$ is $$\begin{bmatrix} \cos (t) & - \sin (t) & 0 \\ \sin (t) & \cos (t) & 0 \\ 0 & 0 & 1 \end{bmatrix},$$ yet I'm not sure how to rotate around $v$... Thanks in in advance for any help!

A: We can see geometricaly that $A^4=I_3$ so the polynomial $P(x)=x^4-1$ annihilates $A$ and then the eigenvalues of $A$ are in the set of the roots of $P$ but clearly $- 1$ isn't eigenvalue of $A$ otherwise we can find an eigenvector $x$ such that
$$Ax=-x$$
which's geometricaly impossible, hence the polynomial $(x-1)(x^2+1)$ annihilates $A$ and since $A\ne  I_3$ then $\mu_A=(x-1)(x^2+1)$ is the minimal polynomial. Notice that $A$ is only diagonalizable over the complex field.


text:
Q: Why is Premiere Pro playback slower then Windows Media Player? I have installed Premiere Pro CS6 on my home workstation (RENDER-PC). When I log in using RDP from my laptop (DAVID-LAPTOP), the audio and video stutter (oddly, they are in sync, they just stutter).
When I export the video (720p, 5 Minutes, 29.97 FPS, encoded as an AVI, NTSC DV Preset), it renders perfectly in under 2 minutes.
If I play it back in Windows Media Player, it plays back fine.
What is the reason for this? Its the same video, just in different programs.
EDIT: This also happens if you play a video in Chrome. It stutters, but downloading the same video plays back fine in Media Player.
EDIT2: Here are the Export settings in Premiere

A: Not entirely sure about the details, but Windows Media Player is likely using the video streaming option of recent RDP protocol versions – it reads the compressed video file and tells the OS to stream it over RDP directly, having the client decompress and render it.
Meanwhile, other programs (unaware of RDP) render it server-side, causing each individual frame to be transmitted over RDP, decompressed. This obviously requires far more bandwidth (that's why the original video was compressed in the first place), causing some frames to be dropped.

(RDP does have some compression, but it uses different algorithms. It's optimized for program interfaces which have quite different requirements; loss-less since you wouldn't want a program to appear blurry; transferring frames in 256x256 tiles instead of whole frame; and so on. It doesn't work well for video.)


text:
Q: Accessing a global variable inside of a function which is a parameter for another function I'm trying to access a global variable inside of the success function of a $.ajax() call. Basically I have something like this:
function someFunc(email) {
var ret;
$.ajax({
    url: '/checkuseremail.php?email='+email,
    cache: false,
    success: function(data) {
        if ( data != '1' ) {
            alert(email+'\n'+data);
            ret = false;
        } else {
            alert(email+'\n'+data);
            ret = true;
        }
    }
});

alert(ret); // outputs "undefined"
return ret;
}

I'm aware that the alert() at the bottom is being called before the ajax response has been given, but I'm not sure what else to do. I would just put the return statement inside of the success function, but that would only return that function, not the parent one.
Any ideas how to do this?

A: Either take a look at $.Deferred() or pass in a callback function into someFunc as second parameter. Then call that callback function on success.

A: Given your last comment "... function is called as part of a form validation when form is submitted" I think that your requirement translates into a synchronous handling of the request.
In those cases, you can force synchronous behaviour on the ajax call.
Try adding:
async: false,

to your Ajax options.

A: Don't think of success like a function that returns a value.  It's a setting of $.ajax() that determines what action to take on the success (event), like a controller.
There are a couple of issues.

*

*You said it in your original post.  You are calling the alert before control is back in the hands of the client.

*The error message was telling you this.  Undefined When you are returning a value from a function, you have to assign it to something.  ret is global to our function but it's never assigned a value.

*You also need to parse the data object returned for your value.  I'm assuming the data != '1' is just some sample code?  You are getting a JSON object back most likely, possibly XML but either way it's not properly parsed.

*You should use $.get() instead of $.ajax().  $.get calls $.ajax and is the preferred method.
function someFunc(email) {
// assign the value returned to ret
var ret = $.get({ // 2 assign value, 4 use $.get
    url: '/checkuseremail.php?email='+email,
    cache: false,
    success: function(data) {
        if ( data ) {
            anotherFunc(data); // 3 parse data in function
            return false;//1 alert removed
        } else {
            return true;
        }
    }
});

alert(ret);
return ret;
};

`


text:
Q: OpenMP with new ecores/pcores Is there any discussion on how OpenMP could work with new 12th gen Intel ecores and pcores ?
Is this going to be a nightmare for !$omp parallel do, where all threads are expected to have a similar workload ?
I utilise !$OMP BARRIER to synchronise threads to assist in improving cache uiliisation, but if ecores are going to be slower (question?) this approach would fail.
At present, using OpenMP with gfortran on windows does not allow any core locking management.
I am wondering what this new pcore/ecore approach could mean.

A: The OpenMP API does not have a specific feature to deal with this situation.  If you know from your system that the P-cores are are cores 0-7 and the E-cores are 8-15, then you can do the following to restrict your OpenMP threads to run only on the P-cores:
In the shell (bash-like):
export OMP_PLACES=0-7
export OMP_PROC_BIND=true

Then, in your code do something like this (actually no change :-)):
!$omp parallel do
do ...
   ...
end do
!$omp end parallel do

Or in C/C++ syntax:
#pragma omp parallel for
for(...) {...}

If you want to span all P and E cores at the same code, you will have to accept some sort of load imbalance, but you could still make good use of them.
In the shell (bash-like):
export OMP_PLACES=cores
export OMP_PROC_BIND=true

Then, in your Fortran code:
!$omp parallel do schedule(nonmonotonic:dynamic,chunkz)
do ...
   ...
end do
!$omp end parallel do

Or in C/C++ syntax:
#pragma omp parallel for schedule(nonmonotonic:dynamic,chunksz)
for(...) {...}

In that case, I would anticipate that a dynamic schedule with a chunk size of chunksz would a good solution so that the (faster) P-cores get some more work compared to E-cores.
If you use OpenMP tasks, then you might still want to pin the OpenMP threads to cores, but since OpenMP tasks are dynamically scheduled to idling OpenMP threads, you get automatic load balancing.  As a rough rule of thumb you should make sure that you create 10x more tasks than you have OpenMP threads.


text: Q: ARM template for synapse auditing successfully ran but not reflecting the auditing configurations on the azure portal I am using ARM templates to enable auditing of the synapse pool, but though the template runs successfully in CI/CD release pipeline, the changes made aren't reflected on the portal. What could be the possible issue? I already have the required permissions and checked the parameters' values too.


text:
Q: Grails 2.4.2: Strange cascading save behaviour in nested transactions I have some strange behaviour with incorrect cascading of the save in my object graph. Maybe it has something to do with nested transaction, but maybe not.
Here are my 3 domain classes:
Station.groovy
class Station {

  /** Dependency injected {@link de.hutapp.tapandknow.system.SettingsService}.*/
  def settingsService

  static hasMany = [localizedStations: LocalizedStation,
    stationIdentifiers: AbstractStationIdentifier]

}

LocalizedStation.groovy
class LocalizedStation {

  /** Delete-cascade from the {@link Station} parent. */
  static belongsTo = [station : Station]

  /** An image that represents the LocalizedStation. */
  MediaFile headerImage

  /** The articles inside this LocalizedStation .*/
  List<Article> articles

  static hasMany = [articles: Article]

  static mapping = {
      headerImage cascade: 'all'
      articles cascade: 'all-delete-orphan'
  }
}

MediaFile.groovy
class MediaFile {

  /* some basic properties here*/

  static constraints = {
      name blank: false
      originalFilename blank: false
      description blank: false
  }

  def beforeDelete() {
      // delete the associated file
      new File(getFileLocation()).delete()
  }
}

So the object graph is Station->LocalizedStation->MediaFile
I save/update the objects with the following service methods:
StationService.groovy
@Transactional
class StationService {

def mediaFileService

/**
 * Creates a new {@link Station} and saves it.
 * @return The newly created {@link Station} instance.
 */
Station createStation(LocalizedStation localizedStationInstance, InputStream headerImage, String originalFilename) {

    localizedStationInstance = updateLocalizedStation(localizedStationInstance, headerImage, originalFilename)

    Station stationInstance = new Station()
    stationInstance.addToLocalizedStations(localizedStationInstance)
    stationInstance.save()
    stationInstance.localizedStations[0].headerImage.save() // TODO: check why this is necessary

    return stationInstance
}

LocalizedStation updateLocalizedStation(LocalizedStation localizedStationInstance, InputStream headerSource, String originalFilename) {

    if (headerSource) {
        MediaFile headerFile = mediaFileService.createMediaFile(headerSource, originalFilename, "foobar") // TODO: add description
        localizedStationInstance.headerImage = headerFile
    }

    localizedStationInstance.save()
    return localizedStationInstance

}
}

MediaFileService.groovy
@Transactional
class MediaFileService {

MediaFile createMediaFile(InputStream input, String originalFilename, String description) {

    MediaFile mediaFileInstance = new MediaFile(
            name: originalFilename,
            description: description)

    mediaFileInstance.save(flush: true) // flush for id
    mediaFileInstance.storeMediaFile(input, originalFilename)
    mediaFileInstance.save()

    return mediaFileInstance
}
}

As you can see, if I call stationService.createStation(), I have to manually save the MediaFile, that hangs on the LocalizedStation. This only happens if I call createStation(), which itself calls updateLocalizedStation().
Then the MediaFile won't be persisted unless I save it explicitly in createStation().
If I call updateLocalizedStation() directly, everything works as expected.
Any ideas or suggestions?

UPDATE:
This problems dissappears, if I add @Transactional(propagation=Propagation.REQUIRES_NEW) to the createMediaFile() method.
As far as I understand the documentation, this creates a new transaction. But this is not really what I want, I want a transaction, that spans all methods.


text:
Q: Linux/C: Redirecting Pipes to STDIN/STDOUT I was having trouble with simulating the shell script "env | grep HOME" with a C program. I found that commenting out line 29 solved this problem, but I'm not really sure why! I read on another question that it was because dup2() was closing the fd in the child, but the man page doesn't indicate that. Can anyone give me a definitive reason and help me understand this behavior? Thank you!
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void){
 pid_t childpid;
 int fd[2];
 if(pipe(fd) == -1){ /*setup a pipe*/
  perror("Failed to setup pipeline");
  return 1;
 }
 if((childpid = fork()) == -1){ /*fork a child*/
  perror("Failed to fork a child");
  return 1;
 }
 if(childpid == 0){ /*env is the child*/
  if(dup2(fd[1],STDOUT_FILENO)==-1)
   perror("Failed to redirect stdout of env");
  else if(close(fd[0] == -1)) /*close unused file descriptor*/
   perror("Failed to close extra pipe descriptors on env");
  else{
   execl("/usr/bin/env", "env", NULL); /*execute env*/
   perror("Failed to exec env");
  }
  return 1;
 }
 if(dup2(fd[0],STDIN_FILENO)==-1) /*grep is the parent*/
  perror("Failed to redirect stdin of grep");
 //else if(close(fd[1]==-1))
  //perror("Failed to close extra pipe file descriptors on grep");
 else{
  execl("/bin/grep", "grep", "HOME", NULL); /*execute "grep HOME"*/
  perror("Failed to exec grep");
 }
 return 1;
}

A: I found your bug. Here's what exits properly for me. It's a common mistake:
...
        else if (close(fd[0]) == -1) /*close unused file descriptor*/
            ...
    else if(close(fd[1]) == -1)
    ...

What you were doing originally was setting the file descriptor to be closed to the boolean value of fd[x] == -1, and what you wanted to do was check for -1 in the return value of close().


text:
Q: Vector space and Dual space I'm struggling with this problem:
Let $V$ be a vector space over a field $F$ and let there be $l_1,l_2 \in V^*$.
I need to show that if $l_1(x)l_2(x)=0$ for every $x \in V$ then at least one of $l_1,l_2$ is 0.

A: Suppose that $l_1(v)\neq 0$ and $l_2(w)\neq 0$.  Then think about $l_1(v+w)l_2(v+w)$.

A: This is my attempt after taking your note:
Let us take $v,w \in W$ such that:
$l_1(v) \neq 0$ and $l_2(w) \neq 0$
Note that since $l_1(v)$ and $l_2(v)$ are elements of a field, and since $l_1(v)l_2(v) = 0$ we get that $l_2(v) = 0$, similarly $l_1(w) = 0$.
Now $l_1(v+w)l_2(v+w) = (l_1(v)+l_1(w))(l_2(v)+l_2(w)) = l_1(v)l_2(v) + l_1(v)l_2(w) + l_1(w)l_2(v) + l_1(w)l_2(w)$.
But:
$l_1(w)l_2(v) = l_1(w)l_2(w) = l_1(v)l_1(w) = 0$
So finally we get $l_1(v)l_2(w) = 0$, but this is a contradiction. So either $l_1$ or $l_2$ are $0$.
I would like to know if this solution is correct.
Thanks!


text:
Q: Android SQLite 3, JOINS or multiple queries? I'm writing on a small Android App with SQLite 3 support. ATM I'm implementing some DB-Functions and asking myself if it is better have one big joined query or if it is OK to use multiple queries in respect to App performance.
Let's say I have a 3 Tables "drivers", "driven_runs", "race_disciplines". Every driven_run has a driver and a race_discipline. Let's assume I want to get all race disciplines by a certain driver in a certain discipline.
Solution 1
I already coded a function getDriver(driverID) with a Driver-Object in return and a function getRaceDiscipline(disciplineID) with a Race Discipline in return. So I would just create a function
public ArrayList<DrivenRun> getDrivenRunsOnDiscipline(short driverID, short disciplineID) {
    ArrayList<DrivenRun> drivenRuns = new ArrayList<DrivenRun>();
    String sql = "SELECT * FROM " + DBHelper.TABLE_DRIVEN_RUNS + " WHERE "
            + DBHelper.DRIVEN_RUNS_COLUMN_DRIVER_ID + "=" + driverID + " AND "
            + DBHelper.DRIVEN_RUNS_COLUMN_RACE_DISCIPLINE_ID + "=" + disciplineID + ";";
    Cursor result = rawQuery(sql);
    if (result.moveToFirst()) {
        do {
            Driver driver = getDriver(driverID);
            RaceDiscipline discipline = getRaceDiscipline(disciplineID);
            DrivenRun run = new DrivenRun();
            run.setDriver(driver);
            run.setDiscipline(discipline);
            run.setResult("WHATEVER");
            drivenRuns.add(run);
        } while(result.moveToNext());
    }
    return drivenRuns;
}

in this case there would be 3 queries executed on after another but the coding is much more simple.
Solution 2
I would create one big joined query like
String sql = "SELECT * FROM driven_runs CROSS JOIN drivers CROSS_JOIN race_disciplines WHERE driven_runs.driver_id=drivers.id AND driven_runs.race_discipline_id=race_disciplines.id"
Cursor result = rawQuery(sql);

and would manually create the Driver and DrivenRun Object.
This solution needs much more writing but only one query is executed (or does the DB executes 3 queries as well when joining 3 tables?)
Long story short, is it OK to go with solution 1 because in regards to performance there isn't much of a difference?

A: In general, go for the simpler code until there's a good performance reason not to. Given that this is SQLite anyway, I don't think there's likely to be much performance difference, since the overhead for queries is pretty low.
Premature optimization is the root of all evil.

A: You should use proper join syntax, then your query won't look so cumbersome:
SELECT THECOLUMNSYOUREALLYNEED
FROM driven_runs JOIN
     drivers
     on  driven_runs.driver_id=drivers.id join
     race_disciplines
     on driven_runs.race_discipline_id=race_disciplines.id
where driver.id = YOURDRIVEIDHERE and race_discipline = YOURDISCIPLINEIDHERE

Also, only return the columns that you need.  Second, insert the appropriate ids in the where clause.  Your version is returning everything, which is totally unnecessary.
This is a pretty simple query and it does what SQL databases do best -- joining large tables together.  Even with SQLite, you are probably better off letting the database do the work.  It is, at the very least, going to save some round trip communication from the database layer back to the application layer.
In a more sophisticated environment, the database will take advantage of multiple processors, multiple disks, and intelligently cache results to further optimize query response.


text:
Q: A vector of Mat images is changed after being transferred to a class I have a strange problem that causes missing variables after a communication between a class in a dll and the main app. The main app is loading 8 Mat images into a vector then calling a library dll to process it.
Here is the main app codes:
int ReturnCode = 0;

HINSTANCE DLLCALL = LoadLibrary(L"IMAGEPROC.dll");

Interface_factory factoryFunc = reinterpret_cast<Interface_factory>(::GetProcAddress(DLLCALL, "CreateCOGInterfaceObject"));

if (!factoryFunc) {
    ReturnCode = ERROR_UNABLETOLOADLIBRARY;

    ::FreeLibrary(DLLCALL);

    return ReturnCode;
}

COGInterface* cog = factoryFunc();

ReturnCode = Commitment(argc, argv, cog);

FreeLibrary(DLLCALL);

return ReturnCode;

In the Commitment:
vector<Mat>vectorImages;
for (int i = 0; i < NumFiles; i++) {
        string FileTemp = "";
        FileTemp.append(LastFileStatus);
        FileTemp.append(to_string(i));
        FileTemp.append(FileExtension);

        bool FileCheck = FileExistenceCheck(FileTemp.data());

        if (!FileCheck)
            return ERROR_IMAGEFILENOTEXIST;

        vectorImages.push_back(imread(FileTemp));

}

cog->VariableTransfer(vectorImages);

And here is the interface class in the DLL:
class COGInterface
{
public:
    virtual ~COGInterface() {};

public:
    virtual int ImageLoader(Mat &image) = NULL;
    virtual int VariableTransfer(vector<cv::Mat> vimage) = NULL;
};

   // And this is the hidden class in the same DLL:

class COGDLL : public COGInterface {

 public:
    COGDLL() {}
    ~COGDLL() {}

    void destroy() {delete this;}

        public:
            vector<string> strReport;
            vector<cv::Mat> vectorImages;

            Mat OriginalImage;
            Mat GrayImage;
            Mat RoIImage;
            Mat tPatternImage;
            Mat bPatternImage;

            int NumberofFiles;

            int ImageLoader(Mat &image);
            int MainProcess(Mat &image);
            int Preprocess(Mat &image);

            int VariableTransfer(vector<cv::Mat> vimage);
        };

        int COGDLL::ImageLoader(Mat &image)
        {

            imshow("test", image);
            waitKey(0);

            return 0;
        }

        int COGDLL::VariableTransfer(vector<Mat> loasters)
        {
            vectorImages.swap(loasters);

            imshow("Testers", vectorImages[0]);

            waitKey(0);

            return 0;
        }

        extern "C" __declspec(dllexport) COGInterface* __cdecl CreateCOGInterfaceObject()
        {
            return new COGDLL;
        }

Before I begin the transfer the vector, I checked the images are all OK in the vector but after that, it is completely changed and the vector looks like it doesn't have the same images at all.
Left: Before, right: after the transfer.

How can I make the class receive the same vector from the main app?
Thanks!


text:
Q: mysqli inner join: data not exist in other table I have 3 tables and I am using inner join to get the data from table.
 select b.pic,b.fname,b.lname, a.job_id, a.uid, a.job_title, a.description, a.city, a.position,
        a.salary, a.looking_for,a.website,a.date
   from job_posting a
  inner join users b
  inner join job_applied c on a.uid = b.uid and b.uid = c.uid
  where c.job_id IS NULL and c.uid IS NULL and a.looking_for = 'student'

Above query is not returning any data. It's empty.
Let me explain the table.

job_posting - Contain job information.
  users - contain user information who posted the job.
  job_applied - contain user has applied for the jobs.

So, I want to get the jobs those are not applied. In Job_paplied table I have job_id and uid.

A: Instead of inner join try LEFT JOIN like:
select b.pic,b.fname,b.lname, a.job_id, a.uid, a.job_title,a.description,a.city, a.position,
a.salary, a.looking_for,a.website,a.date from job_posting a
LEFT JOIN users b  on a.uid = b.uid
LEFT JOIN job_applied c  on b.uid = c.uid
where c.job_id IS NULL  and a.looking_for = 'student'

and try again.


text:
Q: IOC Container locking during integration tests When doing a check in, I run integration tests, but every once in a while it seems that my container is locking up.

*

*It happens on different integration tests

*It doesn't always happen

The error is :

The container can't be changed after the first call to GetInstance,
  GetAllInstances, Verify, and some calls of GetRegistration. Please see
  https://simpleinjector.org/locked to understand why the container is
  locked.

The one it locked on just now is this implementation:
 public SnsTests()
        {
            var container = new Container();
            IocBootstrapper.RegisterComponents(container);
            _container = IocBootstrapper.GetConfiguredContainer();
        }

Each one of my test classes registers an IOC container like above (I think that might be a large part of my problem)... However, how do I fix it?
Bootstrapper class:
public static class IocBootstrapper
    {
        private static Container _container = new Container();
        public static void RegisterComponents(Container container)
        {
            _container = container;
            IocConfig.RegisterTypes(container);
        }

        public static Container GetConfiguredContainer()
        {
            return _container;
        }
    }

A: Although state integration tests, it appears tests are using a shared resource that is leading to race conditions.
Tests, whether unit or integration, should should be isolated from each other to avoid such situations.
Suggest performing what happens in the bootstrapper individually in the tests
public SnsTests() {
    var container = new Container();
    IocConfig.RegisterTypes(container);
    _container = container;
}


text:
Q: Run Update Statement in Xamarin Studio I am using C# with xamarin studio. I can't find a working example to do an update statement against my db. I am trying to update a value of a record from 50 to 100.
This class represents one record in db:
    [Table("record")]
    public class Record
    {
        [PrimaryKey, AutoIncrementAttribute, Column("id")]
        public int ID {get; set;}
        [Column("value")]
        public string Value {get; set;}
    }

I can retrieve my records fine using:
    string pathToDatabase = "mydb.db";
    var db = new SqliteConnection (pathToDatabase);
    myRecords = db.Query<Record>("SELECT * FROM records;");

The update should be as simple as doing Get and then Update.
    var recToUpdate = db.Get<Record>(1); // record with primary key of 1.
    recToUpdate.Value = "100"; // instead of 50
    db.Update(recToUpdate);

It executes the update line fine, but the db still holds the older value of 50 instead of 100, when I run the app again.
Is my approach totally wrong?

A: try with
recToUpdate.Value = "100"; // instead of 50
int i =  db.Update(recToUpdate);
//check number of rows updated (i), db.Update() returns number of rows updated...
//or first try with recToUpdate.Value = 100; and see the number of rows affected + use try/catch if an error appears.

A: If you are including an existing db in your app bundle, you cannot write to it.  The app bundle is read only - this is an iOS security measure.  In order to write to your db, you will need to move it to a user writable folder.
// in your app startup
string rootPath = "/mydb.db";
string userPath = Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments), "mydb.db";

// if userdb does not exist, copy it from the app bundle
if (!File.Exists(userPath)) {
  File.Copy(rootPath, userPath);
}

When you want to actually access your db, you just use the db access code you already have, but be sure you are using the user writable path.
var db = new SqliteConnection (userPath);

Finally, if your db is read-only and will not be updated by the user, you can leave it in the app bundle and don't need to make a writable copy.


text:
Q: Difference between specifying JSTL  value via attribute and body I'm trying to figure out if there's any functional difference between these two uses of the JSTL <c:set> tag. Let's assume I have imported some string constants into my JSP page via something like:
<%@ page import="some.package.of.AppConstants"%>

So, given the above import directive, what's the difference between these two examples:

*

*Specifying the value in value attribute:
<c:set var="SOME_VAR" value="${AppConstants.SOME_CONSTANT}" />

*Specifying the value in tag body:
<c:set var="SOME_VAR">
    <%=AppConstants.SOME_CONSTANT%>
</c:set>

Is there any difference in what the value of ${SOME_VAR} will be in the second example versus the first example? Would the presence of any special characters in AppConstants.SOME_CONSTANT affect the value of ${SOME_VAR} in either of these cases?

A:
Difference between jstl c:set value in attribute and body of tag

There is a technical difference.
The value keeps the original value type. E.g., if you supplied Integer or whatever, it will stay Integer. The body, however, basically does a toString() on the value and thus essentially converts any type to String. This can be beneficial in some cases, e.g.:

*

*Convert integer value to string using JSTL/EL

*How to find length of an integer in JSP?

*How to check isNumeric/IsNumber in JSTL

*how to get the base url from jsp request object?

Coming back to the concrete functional requirement, the first example will only work if you're targeting a Servlet 3.1 / EL 3.0 container (Tomcat 8, etc) with a webapp whose web.xml matches Servlet 3.1.
<c:set var="SOME_VAR" value="${AppConstants.SOME_CONSTANT}" />

Namely, this is only supported since EL 3.0. This is definitely the preferred approach over the Scriptlet way. You should try to avoid Scriptlets at all cost. You only need to keep in mind that the code is not backwards compatible with older versioned target runtimes.
See also:

*

*How to reference constants in EL?

*How to avoid Java code in JSP files?

A: According to O'Reillys HeadsFirstServlets pg 457, why would you use the body version of c:set instead of the no-body version. It looks like they do the same thing.
Answer:

That's because they DO... do the
  same thing. The body version is just for
  convenience when you want more room for
  the value. It might be a long and complex
  expression, for example, and putting it in
  the body makes it easier to read.

Update
After some additional research it turns out the above reasoning pertains only to EL v2.2 and lower. See the answer by BalusC for 3.0 behavior.


text:
Q: GIMP using command line I want to do some operation on some images using GIMP through the command line on Ubuntu.
Operations that I want to do are:

*

*Open an image

*Convert an image to gray-scale

*Convert a PNG image to JPEG

How I can do them using the command line?

A: I don't know how to use Gimp for this task, but actually I think the tools from the package imagemagick are better choice for such CLI tasks. This package is widely used as conversion tool on the web server's applications as MediaWiki and WordPress, also it is a back end for some operations performed by graphical apps such PhotoShop. First you need to install the package:
sudo apt install imagemagick

Then use the following command to accomplish the task (reference):
convert input-file.png -set colorspace Gray -separate -average output-file.jpg

If you need to convert all PNG files in the current directory you can use a loop like this:
for f in *.png; do convert "$f" -set colorspace Gray -separate -average "${f%.*}.jpg"; done

A: *

*Open an image is really easy (image.png is the image that you want to open)
gimp image.png

*Convert RGB image to Grayscale :
Create a GIMP Script-Fu file (named here dmmConvertPNGtoGrayscale.scm and saved in $HOME/.gimp-2.8/scripts) :
; dmmPNGtoGrayscale - GIMP Script-Fu to convert a PNG image to Grayscale
;    This Script-Fu must be put in The GIMP's script directory
;    (e.g., $HOME/.gimp-1.2/scripts).
;    For command-line invocation, use the shell script rgbtogs.sh
;    For interactive invocation, run The GIMP and go to
;    Xtns -> Script-Fu -> dmm
;
(define (dmmPNGtoGrayscale infile outfile)
   (let* ((image (car (file-png-load 1 infile infile)))
             (drawable (car (gimp-image-active-drawable image)))
          )

         (gimp-convert-grayscale image)

         (file-png-save 1 image drawable outfile outfile
              1 0 0 0 0 0 0 )
            ; 1 Adam7 interlacing?
            ;   0 deflate compression factor (0-9)
            ;     0 Write bKGD chunk?
            ;       0 Write gAMMA chunk?
            ;         0 Write oFFs chunk?
            ;           0 Write tIME chunk?    ?? backwards in DB Browser
            ;             0 Write pHYS chunk?  ?? backwards in DB Browser
   )
)

(script-fu-register                                 ; I always forget these ...
   "dmmPNGtoGrayscale"                              ; script name to register
   "<Toolbox>/Xtns/Script-Fu/dmm/dmmPNGtoGrayscale" ; where it goes
   "dmm PNG (RGB or Indexed) to Grayscale"          ; script description
   "David M. MacMillan"                             ; author
   "Copyright 2004 by David M. MacMillan; GNU GPL"  ; copyright
   "2004-02-08"                                     ; date
   ""                                               ; type of image
   SF-FILENAME "Infile" "infile.png"                ; default parameters
   SF-FILENAME "Outfile" "outfile.png"
)

And launch it using this script (I named it rgbtogs.sh for example) :
# rgbtogs.sh
# Invoke The GIMP with Script-Fu dmmPNGtoGrayscale.scm
# No error checking.

if [ -e $1 ]
then
   echo "Usage: rgbtogs.sh degrees filebasename"
   echo "Error: Parameter (filename base) required"
   exit 1
fi

gimp -c -i -d -b "(dmmPNGtoGrayscale \"$1.png\" \"$1-gray.png\")" "(gimp-quit 0)"

Give execution to the script and start it :
chmod +x rgbtogs.sh
./rgbtogs.sh image

*Convert a PNG image to JPEG (or JPG) :
Create a GIMP Script-Fu file (named here dmmConvertPNGtoJPG.scm and saved in $HOME/.gimp-2.8/scripts) :
; dmmConvertPNGtoJPG.scm - GIMP Script-Fu to Convert PNG to JPG
;    This Script-Fu must be put in The GIMP's script directory
;    (e.g., $HOME/.gimp-1.2/scripts).
;    For command-line invocation, use the shell script pngtojpg.sh
;    For interactive invocation, run The GIMP and go to
;    Xtns -> Script-Fu -> dmm
;
(define (dmmConvertPNGtoJPG infile outfile)
   (let* ((image (car (file-png-load 1 infile infile)))
          (drawable (car (gimp-image-active-drawable image)))
         )

         (file-jpeg-save 1 image drawable outfile outfile
              0.75 0 1 1 "GIMP" 0 1 0 0 )
            ; 0.75 quality (float 0 <= x <= 1)
            ;      0 smoothing factor (0 <= x <= 1)
            ;        1 optimization of entropy encoding parameter (0/1)
            ;          1 enable progressive jpeg image loading (0/1)
            ;            "xxxx"  image comment
            ;                   0 subsampling option number
            ;                     1 force creation of a baseline JPEG
            ;                       0 frequency of restart markers
            ;                         in rows, 0 = no restart markers
            ;                         0 DCT algoritm to use
   )
)

(script-fu-register                                 ; I always forget these ...
   "dmmConvertPNGtoJPG"                             ; script name to register
   "<Toolbox>/Xtns/Script-Fu/dmm/dmmConvertPNGtoJPG" ; where it goes
   "dmm Convert PNG to JPG"                         ; script description
   "David M. MacMillan"                             ; author
   "Copyright 2004 by David M. MacMillan; GNU GPL"  ; copyright
   "2004-01-27"                                     ; date
   ""                                               ; type of image
   SF-FILENAME "Infile" "infile.png"                ; default parameters
   SF-FILENAME "Outfile" "outfile.png"
)

And launch it using this script (I named it pngtojpg.sh for example) :
# pngtojpg.sh
# Invoke The GIMP with Script-Fu dmmConvertPNGtoJPG.scm
# No error checking.

if [ -e $1 ]
then
   echo "Usage: pngtojpg.sh filebasename"
   echo "Error: Parameter 1 (filename base) required"
   exit 1
fi

gimp -c -i -d -b "(dmmConvertPNGtoJPG \"$1.png\" \"$1.jpg\")" "(gimp-quit 0)"

Give execution to the script and start it :
chmod +x pngtojpg.sh
./pngtojpg.sh image

Source : http://beefchunk.com/documentation/lang/gimp/GIMP-Scripts-Fu.html
NB : inside GIMP Script-Fu file, you can remove all lines which begins with ; character (or everything on the right on this character), these are just comments
NB: These .scm script-fu were made originally for GIMP 1.2, but I tested with GIMP 2.8 and there is no issue

A: You can run gimp -h to get the different options availabe for gimp
1.Open an image
gimp -n image_name.xxx
2.Convert an image to gray-scale
I have no idea if it's possible using Gimp navigate these links: https://www.gimp.org/tutorials/Basic_Batch/
https://superuser.com/questions/1334386/how-to-load-an-image-in-gimp-from-the-terminal-and-exiting-afterwards
3.convert png image to jpeg
I suggest using convert command line which is part of the ImageMagick
convert image1.xxx image2.yyy


text:
Q: Changing properties with property grid I am trying to make this mini paint with three buttons(line, circle and rectangle). on each button click , a related shape with random color and start point will be printed. I've made this combo box so that the user chooses a shape and see its properties in propertyGrid :
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    switch (comboBox1.SelectedItem.ToString())
    {
        case "circle":
            {
                propertyGrid1.SelectedObject = c;
            }
            break;
        case "line":
            {
               propertyGrid1.SelectedObject = l;
            }
            break;
        case "rectangle":
            {
                propertyGrid1.SelectedObject = r;
            }
            break;
        default:
            break;
    }
}

c,l and r are new objects from circle , line or rectangle class. now I want to be able to override properties using propertyGrid, like changing a circles color or startpoint. some thing like :
private void propertyGrid1_Click(object sender, EventArgs e)
{
    circle.changeproperties=Griditem.value;
}

so how should I write this?

A: The trick is: You don't have to do anything. By binding your object instance the PropertyGrid by setting propertyGrid1.SelectedObject = XXX, you're already done.
The grid will automatically populate its editors to make it possible to edit that values. By changing them, the values will automatically be written back to the corresponding class instance.
Go try it and write a full blown property implementation in your classes like this
    public int Radius
    {
        get { return _radius; }
        set { _radius = value; }
    }

and put a breakpoint in the setter. You'll see that it will get called if you change the value in the UI.
Anyway - now you got the values back in your class instance. Fine. But now you have to trigger your application to do anything with it. Typically, a control should invalidate itself now to trigger its painting again to make that change visible in the UI. Depending on your application logic, you might implement INotifyPropertyChanged in your Circle, Rectangle and Line class and react on it. See here for more detail: Implementing INotifyPropertyChanged - does a better way exist?


text:
Q: How to remove database connection in hibernate configuration in netbeans? I have created an Oracle database connection while creating Hibernate application in NetBeans 8.0. But now I want to remove the connection that is appearing in the drop down list containing label Database connection.
How do I remove that connection from the list so that I can create the same connection as a new connection?
The reason to remove the connection is that I wanted to practice creating the connection to the database while using Hibernate framework. When I try to create the same connection that I had created, then I get an error stating Unable to add connection. Connection already exists.

A: First you need to disconnect from your database connection. Then

*

*Open Data Source Enterprise Explorer by go to window -> Show View -> Other -> Data Management (in Hibernate perspective) -> Data Source Explorer

*Expand the category for the connection profile you want to delete.

*Delete the connection that you want to delete.

A: Go to Netbeans' Services window and expand the databases option in the Services menu. You will find your database connection within the items listed. Right click on it and then:

*

*disconnect

*delete


text:
Q: google places api get details not returned for every place Hi
I am creating a page on my site which uses the google places api and the user's geo location(lat, lng) and finds nearby restaurants. As part of the code i also look up the distance of the restaurant from the user's location. The issue is while it gets every result and I have a function called getDistance that is called for each place. This is returning empty string for a lot of results and does return it for some. For the purpose of an example i am hardcoding the user's location in this plunker example. Can someone please point out why the distance is not being returned for every place and why its returning an empty string for some and the correct fix for this? I really appreciate your help.
Im calling the get distance function that calculates the distance in miles for each restaurant in the callback function for places service
 angular.forEach(results, function(result) {

        //using new function for getting distance from user's location
        var place = getDistance(result, service);

        $scope.places.push(place);
      });

Here is the getDistance function
function getDistance (place, service) {

    var request = {
      reference: place.reference
    };

    service.getDetails(request, function (details, status) {

        if(status == google.maps.places.PlacesServiceStatus.OK) {

          place.details = details;
          var distance = google.maps.geometry.spherical.computeDistanceBetween
          (new google.maps.LatLng(33.940496, -84.048816), new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng()));
          var distanceInMiles = getMiles(distance);
          place["distance"] = distanceInMiles;
        }
    });

    return place;
};

Plunker example

A: Your requests may be subject to blocking if all of your users are making requests at the same time when running client-side geocode requests at periodic intervals. To avoid this, consider one of the following Quota Considerations:

*

*Use a caching strategy.

*Introduce random intervals to your requests (jitter). Ensure requests
are random across your entire userbase.

*If developing for Android, use an inexact repeating alarm.

*If developing for Android, select an appropriate location strategy.

The Google Maps API allows you to cache geocodes which can be useful if you repeatedly look up the same address. However, there are two important things to keep in mind as stated in the documentation. One is that:

Geocoding changes often as our data gets more and more accurate. So even if you have cached data, you should refresh it periodically, to make sure you are getting the best geocodes for your locations.

In addition to providing a list of places within an area, the Places service can also return detailed information about a specific place. Place Details are requested with a call to the service's getDetails() method. This method takes a request containing the desired place's placeId and also takes a callback method which needs to handle the status code passed in the google.maps.places.PlacesServiceStatus response, as well as the google.maps.places.PlaceResult object.
Lastly, for the sync issue, wherein place is returned before getDetails() callback sets place, this related SO post - Can't wait until results come back from google API can help you.


text:
Q: Change the UPS battery while it's powered on? Is it dangerous or not advisable to change the UPS battery while it is plugged in? We have an APC Smart-UPS 1500 and we need to replace its battery. I have the new battery but the UPS powers a few machines that I would rather not turn off for the replacement procedure.
Would something bad happen if I just replace it while it's still plugged in and powered on?

A: I "Hot Swapped" 3 APC Smart UPS 1500 batteries at three different power plants here in southern California. These UPS systems are used to power the CAISO RIG (California Independent System Operator Remote Intelligent Gateway). It is a critical system for our electric power grid in the State of California.It took me less than ten minutes to perform this task! This is the first time I ever had to change a battery in a UPS system. The tools I used were just one Phillips screw driver

A: According to the manual:

Replacing the Battery Module

This UPS has an easy to replace,
    hot-swappable battery module. Replacement is a safe procedure,
    isolated from electrical hazards. You may leave the UPS and connected
    equipment on for this proce- dure.

A: The Smart-UPS 1500 battery is hot-swappable. You do not need to unplug or power down the UPS before changing the battery.
Of course, it is essential to refer to the product documentation and take all appropriate measures to protect yourself from the shock/electrocution hazards associated with live batteries and charging equipment. Under the right (wrong) circumstances, even a 12-volt lead acid battery can deliver a fatal shock.

A: Apparently most APC UPS's, not just "smart" ones, support battery hot swapping.
The manual for the Back-UPS ES 525 advises:

Do not replace the battery when the UPS is On Battery (amber indicator
  is lit).

-- but that dumb warning is obviously applicable to "smart" UPS's as well.
The manual proceeds telling:

NOTE: Small sparks may occur during battery connection. This is
  normal.

-- can't remember if sparks fly during an offline UPS battery connection.


text:
Q: Как реализовать ограничение по кол-ву добавления клиентов на сайте Всем привет. Впервые на форуме, не судите строго если напишу неверно вопрос.
Проблема такая. На сайте реализован рейтинг пользователей "Мини, Партнер, Спонсор и Ген. спонсор". Пользователи при регистрации могут добавлять консультантов. При добавлении консультантов, у пользователя с определенным рейтингом должны быть ограничения по кол-ву создаваемых консультантов. Например при ранге "Мини" можно создать 3 консультантов. При ранге "спонсор" можно создать 5 консультантов.
Само создание консультантов завязано сильно на mysql.
Как реализовать данное ограничение? В PHP ещё не особо силен по знаниям)
Вот код который сейчас реализован

                    <a style="float:left;margin: 10px; " href="/kons.php?action=new_form&rowformi=<?=$poisk?>" class="jsdelete_pers btn btn-warning btn-sm" >Добавить консультанта

 <?php $result444 = mysql_query ("SELECT count(`Долж_конс`) as count,`Долж_конс` FROM `medsoft` where `N`=".$poisk." and `Долж_конс` like 'medsoft%'", $db);
$rowcount = mysql_fetch_array($result444);

?>

                                Код	Готов	Фото	ФИО	Должность	E-mail	Телефон	WhatsApp	Telegram

                       <?php
                            $result_sys2 = mysql_query ("
                                 SELECT
                                 `Сч_Выст`,
                                 `N`,
                                 `Фото`,
                                 `Код_конс`,
                                 `Готов`,
                                 `ФИО_конс`,
                                 `Фам_конс`,
                                 `Имя_конс`,
                                 `Отч_конс`,
                                 `Долж_конс`,
                                 `Почт_конс`,
                                 `Фот_конс`,
                                 `Теле_конс`,
                                 `Вац_конс`,
                                 `Телег_конс`
                                 FROM `medsoft` where `N`=".$poisk."  ORDER BY `Код_конс` asc", $db);

                            while($row = mysql_fetch_array($result_sys2)) {

                                    //$row['Дата']= date("d.m.Y", strtotime(htmlspecialchars($row['Дата'])));
                                   // $row['Дата_обновл']= date("d.m.Y", strtotime(htmlspecialchars($row['Дата_обновл'])));
                                    echo "
";
                                    echo"
";
                                    echo"

".$row['Код_конс']."	".$row['Готов']."	".$row['Фото']."	".$row['ФИО_конс']."	".$row['Долж_конс']."	".$row['Почт_конс']."	".$row['Теле_конс']."	".$row['Вац_конс']."	".$row['Телег_конс']."	"; //onMouseOver='f_over(this);' onMouseOut='f_out(this);'

                                    echo"";
                                    echo"";

                                   echo"

";
                                echo"
";
a:
                                }

                                ?>

    ```

A: *

*Не надо тулить ВСЁ в одно место.

*база не должна быть источником логики, она только для выборки и вставки данных

Я бы решил примерно так:
<?php

declare(strict_types=1);

final class Consultant
{
    // param ...
    // param ...
    // param ...
    // param ...

    // code ....
    // code ....
    // code ....
    // code ....
    // code ....
}

<?php

declare(strict_types=1);

final class UserConsultants
{
    private $values;

    public function getAll(): array
    {
        return $this->values;
    }

    public function add(Consultant $consultant): void
    {
        if(!$this->has($consultant))
        {
            $this->values[] = $consultant;
        }
    }

    private function has(Consultant $consultant): bool
    {
        // какая-то логика по определению есть ли уже этот консультант или нет
    }

    public function count(): int
    {
        return count($this->values);
    }
}

<?php

declare(strict_types=1);

final class UserStatus extends \MyCLabs\Enum\Enum
{
    public const
        MINI = 'mini',
        PARTNER = 'partner',
        PARTNER2 = 'partner2',
        PARTNER3 = 'partner3',
        PARTNER4 = 'partner4',
        PARTNER5 = 'partner5';
}

<?php

declare(strict_types=1);

final class User
{
    private UserStatus $status;
    private UserConsultants $consultants;
    // private ....
    // private ....
    // private ....
    // private ....
    // private ....
    // private ....

    public function __construct(
        UserStatus      $status,
        UserConsultants $consultants
        // $param,
        // $param,
        // $param,
        // $param,
    )
    {
        $this->status = $status;
        $this->consultants = $consultants;
    }

    // code ...
    // code ...
    // code ...
    // code ...
    // code ...

    public function addConsultant(Consultant $consultant): void
    {
        switch ($this->status->getValue()) {
            case UserStatus::MINI:
                $max = 3;
                break;
            case UserStatus::PARTNER:
                $max = 5;
                break;
            // ......
        }

        if ($this->consultants->count() > $max) {
            throw new DomainException('Максимальное число консультантов УЖЕ установлено');
        }

        $this->consultants->add($consultant);
    }
}


text:
Q: Keras Tensorflow: Why this error on using Tensor Dataset returned by tf.data.experimental.make_csv_dataset() in call to model.fit? I have training data and validation data in two csv files, each containing a target column. I am trying to load these using a Data API Dataset, and feed to the model.fit() method. I am using Keras 2.8.0
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras import metrics

print(tf.__version__)

TRAINING_DATA_DATASET = 'train_data_Dataset1.csv'
VALIDATION_DATA_DATASET =  'validation_data_Dataset1.csv'

train_data_set=tf.data.experimental.make_csv_dataset(
       file_pattern = TRAINING_DATA_DATASET,
       batch_size=1024,
       label_name='target',
       ignore_errors=True)

validation_data_set=tf.data.experimental.make_csv_dataset(
       file_pattern = VALIDATION_DATA_DATASET,
       batch_size=1024,
       label_name='target',
       ignore_errors=True)

model = keras.Sequential([
    layers.Dense(128, activation="relu"),
    layers.Dropout(0.5),
    layers.Dense(32, activation="relu"),
    layers.Dropout(0.5),
    layers.Dense(1, activation="sigmoid")
])

model.compile(optimizer="rmsprop",
              loss="binary_crossentropy",
              metrics=[metrics.BinaryAccuracy(threshold = 0.5)])

model.fit(
       train_data_set,
       steps_per_epoch=TRAIN_DATA_SIZE // 1024,
       epochs= 3 ,
       validation_data=validation_data_set,
       validation_steps=VALIDATION_DATA_SIZE // BATCH_SIZE,
       verbose = 1)

On the call to mode.fit(), the following error is returned:
WARNING:tensorflow:Layers in a Sequential model should only have a single input tensor.

Received: inputs=OrderedDict([('NumberOfPeriods', <tf.Tensor 'IteratorGetNext:0' shape=(1024,) dtype=float32>),
    ('P_2:average', <tf.Tensor 'IteratorGetNext:1' shape=(1024,) dtype=float32>),
    ('P_2:average outlier1', <tf.Tensor 'IteratorGetNext:2' shape=(1024,) dtype=int32>),
    ('P_2:average outlier2', <tf.Tensor 'IteratorGetNext:3' shape=(1024,) dtype=int32>),
    ('P_2:average outlier3', <tf.Tensor 'IteratorGetNext:4' shape=(1024,) dtype=int32>),
    ('P_2:stddev', <tf.Tensor 'IteratorGetNext:5' shape=(1024,) dtype=float32>)]).
Consider rewriting this model with the Functional API.

Whilst it says WARNING, the entire call to model.fit() failed. Clearly the input it not the correct shape, but I thought since Keras v2, it was possible to pass Datasets directly to model.fit().    What must be done to the dataset before being passed to model.fit (and later model.predict)?    I have not yet tried rewriting to use the Functional API instead, as I cant see how that would change the input shape. Thanks for any help.

A: Well i don't know the reason behind this but i found a way to get it to fit in the model.The reason behind is that data type is in order dict form and you need to convert it tf tensors data type.
Coding sample i used to convert ordered dict to tensor form
In the above picture, i used tf.stack statement to convert tf ordered dict to tf tensor datatype and then fit it to the model and it worked!.Well i applied it on titanic dataset but you can apply it on your dataset.


text:
Q: Redirect Alternative Domain Names for a Web Site While Maintaining Request Integrity We bought some domain names that are similar to the primary domain name for our Web Site. All of these alternative domain names are associated with a single VirtualHost of which I can edit the single .htaccess file for.
What I want in the redirection implementation is integrity to the protocol of the initial request, and also any and all of the string after the initial request's TLD (like /images/smile.jpg). I also want the literal integrity of that path too. I believe this requires the 'NE' tag.
For the specific examples see: http://pastebin.com/raw.php?i=K99wxW7J

A: You would have to make a script on the site that is redirecting. DNS is not smart enough for what you want.
Hope this helps!


text:
Q: Problems with Graphics in MVC structure I testing to implement graphics into MVC structure but Im a bit stuck. Here is what I got so far. For now I just want to get the red ball to bounce back and forth. And use the button start to start the thread and button stop to stop the thread that runs the GameLoop in the controller.
But I think Im mixing this up a bit. Would very much appreciate some feedback!
Heres what I got so far:
GameModell
suppose to controll the bouncing. If the location of the ball is under 40 px or above 80 px - multiply the locationX with -1 to make the ball change direction
GameView
Here Im putting the labels on a JFrame. I also want to display the buttons start and stop to controll the thread but I guess they are hidden by the JPanel in TheGraphics class
GameController
Starts and stops the thread with ActionListeners. Contains the GameLoop
TheGraphics
Paints the ball and controll the direction
I guess I got a lot of thing that are all wrong but this is the best I can do at the moment. Would very much apreciate some help!
Thanks!
MAIN:
public class MVCgame {

    public static void main(String[] args) {
        GameModel gm = new GameModel();
        GameView gv = new GameView();
        GameController gc = new GameController(gm, gv);
    }
}

MODEL:
public class GameModel {
    private int multi = 1;

    public void setMulti(int locX) {
        if(locX < 40 || locX > 80) {
            multi = multi * -1;
        }
    }

    public int multi() {
        return multi;
    }
}

VIEW:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class GameView extends JFrame {

    private JPanel jp = new JPanel();
    private JButton start = new JButton("Start");
    private JButton stop = new JButton("Stop");
    TheGraphics gr = new TheGraphics();

    public GameView() {
        add(jp);
        add(gr);

        jp.add(start);
        jp.add(stop);
        setSize(250, 250);
        setVisible(true);
    }

    public void addListener(ActionListener theListener) {
        start.addActionListener(theListener);
        stop.addActionListener(theListener);
    }

    public JButton getStart() {

        return start;
    }

    public JButton getStop() {
        return stop;
    }

    // GUESS I SHOULD PUT THIS IN THE VIEW???
    public void paintEllipse(Graphics theG) {
        Graphics2D g2d = (Graphics2D) theG;
        g2d.setColor(new Color(255, 0, 0));
        g2d.fillOval(0, 0, 10, 10);
    }
}

CONTROLLER:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class GameController implements Runnable {

    GameView gv;
    GameModel gm;
    private Thread thread;
    private boolean running = false;

    public GameController(GameModel gm, GameView gv) {
        this.gv = gv;
        this.gm = gm;
        gv.addListener(theListener);
        start();
    }

    ActionListener theListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == gv.getStart()) {
                start();
                System.out.println("PLAY = ");
            } else if (e.getSource() == gv.getStop()) {
                stop();
                System.out.println("STOP = ");
            }
        }
    };

    public synchronized void start() {
        thread = new Thread(this);
        thread.start();
        running = true;
    }

    public synchronized void stop() {
        thread.interrupt();
        running = false;
    }

    // GameLoop
    public void run() {
        long lastTime = System.nanoTime();
        double amountOfTicks = 60.0;
        double ns = 1000000000 / amountOfTicks;
        double delta = 0;
        long timer = System.currentTimeMillis();
        int frames = 0;

        while (running) {
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            while (delta >= 10) {
            // tick();
                delta--;

                // repainting the graphics
                gv.gr.drawer();
                gm.setMulti(gv.gr.drawer());
                System.out.println("gv.gr.drawer() = " + gv.gr.drawer() + " gm.multi() " + gm.multi());
                // I want to use this value in the model to change the direction
            }
            if (running) {
            }
            frames++;
            if (System.currentTimeMillis() - timer > 1000) {
                timer += 1000;
                System.out.println("FPS: " + frames);
                frames = 0;
            }
        }
    }
}

THE GRAPHICS:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;

public class TheGraphics extends JPanel {

    private int locX = 40;

    public TheGraphics() {

    }

    public int drawer() {
        locX++;

        repaint();
        return locX;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(new Color(255, 0, 0));
        g2d.fillOval(locX, 30, 10, 10);
    }
}

A:
GameModell suppose to controll the bouncing. If the location of the ball is under 40 px or above 80 px - multiply the locationX with -1 to make the ball change direction

public void setMulti(int locX) {
    if(locX < 40 || locX > 80) {
        multi = multi * -1;
    }
}

Really bad idea. You should always check position and direction (sign(speed)). Otherwise, your object might get stuck out of bounds always changing direction without moving from place forever.
Apart from this, using the MVC concept is overkill in my eyes and shouldn't be used in such a small project nor in a game. In a game, you should more or less put all three together. Of course you can, but the advantages and disadvantages of the MVC concept don't fit the needs of a game in many ways (except for the GUI, perhaps).
Your main loop might look something like this (you kind of did this already, but why is the tick() commented out in your code?):
while (running) {
   update(); // Update all game objects
   paint(); // Paint them all
}

Each game object will have its own update() and paint() implementation. You absolutely need to separate the logic of update and paint, even if they are in the same class. So this one:
public int drawer() {
    locX++;

    repaint();
    return locX;
}

is an absolute no-go.
Edit: (Referring your update answer)
You are using the method location() for different purposes. According to the Java name convention, you should rename it getLocation() and setLocation() depending on the use to clarify the code.
(Even if this is not really MVC anymore, I'd let GameFrame implement ActionListener instead of specifying it as variable of GameController.)
One thing you should really change is this one:
private int locX = 0;

public void location(int loc) {
    this.locX = (int) loc;
}

Basically, you are duplicating the location value every frame and create unused redundant data. Another problem is, that this might work fine for only one variable, but what if you add more than the position to your model later on? Instead TheGraphics has to render on an instance of the data model, not its values. As long you are using one GameModel
private GameModel model; // set value once at initialisation

and rendering its values in paintComponent will work fine, but if you want to add more than one GameModel (handling GameModel more like a GameObjectModel), you will need to pass it as parameter in the paint method.
public void update() {
    repaint();
}

Remove it and try getting around without. A method called from one place forwarding to a different method is a bad idea most of the time, especially if it obfuscates the functionality with a different name.
            gv.gr.update();
            gv.gr.location(gm.location());

You are first repainting your image and then setting the location? Basically, your game runs one frame behind all the time. Swap that order.
            gv.gr.location(gm.location());
            gv.gr.repaint();

Will be fine (I already said about location()).


text:
Q: Django1.9: No model matches the given query I am following a tutorial to create a blog.
The code is correct according to the tutorial.
The only difference is that I use Django 1.9 instead of 1.8
Calling the Post model in the view without
publish__year=year,
publish__month=month,
publish__day=day)

doesn't return a 404 Error - No Post matches the given query.
This is view.py
def post_detail(request, year, month, day, post):
    post = get_object_or_404(Post, slug=post,
                                   status='published',)
                                   #publish__year=year,
                                   #publish__month=month,
                                   #publish__day=day)
    return render(request, 'blog/post/detail.html', {'post': post})

The model part looks like that models.py
class Post(models.Model):
    ...
    publish = models.DateTimeField(default = timezone.now)
    ...

Any ideas why the query is not found?
EDIT:
The URL looks like localhost/blog/2016/07/30/second-post-entry/
def get_absolute_url(self):
        return reverse('blog:post_detail', args=[self.publish.year,
                                                 self.publish.strftime('%m'),
                                                 self.publish.strftime('%d'),
                                                 self.slug])

It seems that those are the problem:
self.publish.strftime('%m'), # eg. == 07, but publish__month == 7
self.publish.strftime('%d')  # eg. == 30, publish__day == 30

A: As I got it, you can either change self.publish.strftime('%m') and                                                 self.publish.strftime('%d') to self.publish.month and self.publish.day,
either you can convert passed data into int publish__year=int(year), publish__month=int(month), publish__day=int(day). That should do the trick.


text:
Q: WordPress allows multiple users to have same email ID; and I've a problem with it! While looking at the source code of a popular membership plugin, I found out that they allow changing of email ID without 'verifying' it. In fact, even WP core allows two different users to have same email ID. I'm not sure if it's by design.
The problem, I have is that when two users have the same email ID, my get_user_by( 'email', 'xyz@pqr.com' ); function breaks. What WP does is simply look into the table and return the first user it finds in the table that has matching email ID.
Now, if I've just the email ID of the user and I want to log-them in programmatically, I'll have to write a custom function to check for all users in DB that share the email ID.
Has anyone else faced problem with email authentication? If yes, how do you uniquely identify a user with email?


text:
Q: Dolphin Platform Chart Objects not working? in my Dolphin Platform project, the XYChart.Series Object, which contains a series of XYChart.Data, does not seem to synchronize its datamodel.
My viewbinder binds the data of the BarChart with the PM and sets it to the BarChartObjekt
public class GesamtErgebnisViewBinder extends AbstractViewBinder<GesamtErgebnisModel> {
 @Override
    protected void init() {
       ....
        ObservableList<XYChart.Series<String, Integer>> data = FXWrapper.wrapList(getModel().getData())
        barChart.setData(data);
    }
}

The model consists of an observable list of BarChart Data
@DolphinBean
public class GesamtErgebnisModel {

   ....

    private ObservableList<XYChart.Series<String, Integer>> data;

    ....
}

On the serverside I am computing the BarChart data to pass it to my model object.
@DolphinController("GesamtErgebnisController")
public class GesamtErgebnisController {

@Inject
private BeanManager beanManager;

@DolphinModel
private GesamtErgebnisModel model;
...
        taskExecutor.execute(GesamtErgebnisController.class, e -> {
            final Series<String, Integer> series = beanManager.create(XYChart.Series.class);
            rawFilterData.entrySet().stream().map((mitgliedToFilterResultEntry) -> {
                final XYChart.Data<String, Integer> datas = beanManager.create(XYChart.Data.class);
                ....
            }).forEach((datas) -> {
            series.getData().add(datas);
        });
        model.getData().add(series);
});

But the bar chart just stays empty. Just the category is visible. Because I thought maybe my data that I put together is flawed, I altered an example from the Oracle website and tested the data manually. On server side, this doesn´t work either.. same output. If I put this code on clientside inside the init method of my viewbinder, the data shows correctly. So there should be nothing wrong with the data being passed. Observerable lists with String i.e work just fine. Maybe I am missing something else?

A: I think it's not a good idea to use the JavaFX classes on the server (or in the shared model). When using Dolphin Platform it should be best practice to create a client API independent (presentation) model. You can bind this model easily to the client model that uses the specific classes of the UI-Toolkit (like JavaFX). I created a sample for your concrete problem that uses a BarChart in a JavaFX client that is bound to a Dolphin Platform model. You can find it at Github.


text:
Q: routerLink is rendering %23, instead of # I am trying to send href="#", using routerLink, but it is rendering  %23 instead of #.
Not sure what is wrong.
item.linkname

item = {
  url: '#',
  linkname:'abcd'
}

A: Angular will always encode your URL with encodeURIComponent(). I do not understand what your intention is from a developer prespective but you can either:

*

*Create a custom serializer to stop angular from encoding your URL;

*

*If you only want to "add" an hashtag to your route you can simply use href instead of router link: {{ item.linkname }}.


text:
Q: Applications acts differently locally and on shiny server pro I have a set of codes. (sorry cannot produce it since it is huge). But this acts properly locally. But when deployed on shiny server pro, it is not working.
I checked all libraries that are loaded are of same version.
One question, even if libraries are not loaded and there version are different between local and shiny server. Will this effect the application?


text:
Q: EXTJS - Load Mask I want to present the source code, which is taken from inside a div with jQuery, inside an Ext.Window. I have managed to do that, but my problem is that sometimes the source code is huge, since it contains encoded images and the Ext.Window takes some time to appear in the screen after it is triggered via click event. I would like to present the Ext.Window but with a loading icon until the data is ready.
win = new Ext.Window ({
    title:'Source Code',
    width:800,
    height:300,
    items: [{
        xtype : 'textarea',
        readOnly: true,
        value: sourceCode
    }]
});
win.show();

A: Try with a undefined function and a setTimeout function. Do not forget the config layout: 'fit'.
Ext.application({
name : 'Fiddle',

launch : function() {
       var win =  Ext.create('Ext.window.Window', {
            title:'Source Code',
            width:800,
            height:300,
            layout: 'fit',
            items: [{
                xtype : 'textarea',
                readOnly: true,
                value: 'test'
            }]
        });

        win.show(undefined, function(){
            win.getEl().mask('Loading...');

            setTimeout(function() {
                win.getEl().unmask();
            }, 3000);

        });
    }

});

Or
Ext.application({
name : 'Fiddle',

launch : function() {
   Ext.create('Ext.window.Window', {
        title:'Source Code',
        width:800,
        height:300,
        layout: 'fit',
        items: [{
            xtype : 'textarea',
            readOnly: true,
            value: 'test'
        }]
    }).show(undefined, function(){
        win.getEl().mask('Loading...');

        setTimeout(function() {
            win.getEl().unmask();
        }, 3000);

     });
  }

});

TRY
    win.show(undefined, function(){
        win.getEl().mask('Loading...');
        win.suspendEvents();
        win.down('textarea').setValue(sourceCode);
        win.down('textarea').focus();
        win.resumeEvents();
        setTimeout(function() {
            win.getEl().unmask();
        }, 2000);
    });

A: What you can try is to set the value only after the window is already displayed:
win = new Ext.Window ({
    title:'Source Code',
    width:800,
    height:300,
    items: [{
        xtype : 'textarea',
        readOnly: true
    }],
    listeners: {
        afterrender: function(sourceWindow) {
            sourceWindow.down('textarea').setValue(sourceCode)
        }
    }
});
win.show();

Then you can add josei's mask/unmask approach on top of that, although I would recommend that you search some event that happens after the value has been set to remove the mask (you can try the change event on the textarea), because that way your wait wouldn't be a fixed amount of time, but related to the time it takes to render the textarea value.


text:
Q: Is there a connection between Affront, Effront, Effrontery? From the Oxford Dictionary

Affront
  An action or remark that causes outrage or offence.

Effront is not in any of the major modern dictionaries including the Oxford dictionary, however it is cited in wiktionary from the 1913 Webster's dictionary as

Effront
  To give assurance to.

Effrontery is listed in the modern day Oxford Dictionary as well as other dictionaries

Effrontery
  Insolent or impertinent behaviour.

I came across this word as a crossword answer for the clue Brass Neck which made me assume that Effrontery was the action of Effronting or performing an Effront. However it does not seem to be the case and the historic definition of Effront appears to be something else entirely. I would not have been surprised to have seen the definition of Affront appearing as the definition for Effront because they seem connected.
Are these words all related somehow? I could not find much about the etymology.
Edit:
Thanks for the link to etymonline I haven't come across that before. It explains that there was an Effront but it disappeared. It says to compare Effrontery with Affront but it offers no explanation of how it came to be. Looking up Affront on there shows Related: Affronted; affronting. but no Affrontery and the meaning is worded differently perhaps they are considered interchangable.
I would like to know how we ended up with some words beginning with A and some beginning with E and why there are certain variations that do not exist in each set. Seems strange.

A: According to the OED, the word effront is a backformation from effronted (which used to be an English word) and means:

*

*To free from bashfulness,

*To put to confusion.

In the 1911 Webster's dictionary on Google books, I find the second definition, as well as:

*To give assurance to.

The verb effront is incredibly rare; nearly all the hits in Google books are misspellings of affront. I suspect that it has mainly been used by people who guessed at its meaning by knowing the meaning of the adjective effronted, and not by people who learned its meaning from hearing or reading it.
The word effronted used to be a real English word, and according to the OED it means:

Shameless, barefaced, unblushingly insolent.

So what would effront mean, if it's a backformation from effronted? It's what you have to do to somebody to make them effronted. What would do this isn't clear at all.
So would all three definitions of effront above, if done to somebody, result in them being shameless, barefaced, unblushingly insolent?
I think so, although it's only clear for the first definition. For the second definition, somebody who is confused and scared might lash out and be unblushingly insolent. For the third definition, if you gave assurance to somebody that their actions would have no consequences to them, they might become shameless or unblushingly insolent.
The adjective effronted comes from the French adjective effronté, which also does not appear to have a corresponding verb. And effronté comes from the Latin word effrons, which also gave us effrontery.
Literally, the Latin word effrons means without a forehead. Why that should mean shameless is not entirely clear. Merriam-Webster gives two possible explanations. One of them is:

Some explain that "frons" can also refer to the capacity for blushing, so a person without "frons" would be "unblushing" ...

The word affront comes from the French verb affronter, meaning to confront, to face. This comes from Old French afronter, whose construction would literally mean "to slap on the forehead", but which le trésor de la langue français informatisé says also meant "to shame" and "to confront".
So effronted and affronted in common have the root front, meaning forehead in French. It's possible that the word front was a metonym for blush in the etymology of both of them—so the etymology of effronted would be unblushing, while affront would be to cause to blush (one of its early meanings was shame; the other to slap in the face.).

A: The connection is the term front: late 13c., "forehead," from Old French front "forehead, brow" (12c.), from Latin frontem (nominative frons) "forehead, brow, front; countenance, expression (especially as an indicator of truthfulness or shame).
(Etymonline)
Effrontery:

*

*To the Romans, the shameless were "without forehead," at least figuratively. Effrontery derives from Latin effrons, a word that combines the prefix ex- (meaning "out" or "without") and "frons" (meaning "forehead" or "brow") .

*The Romans never used "effrons" literally to mean "without forehead," and theorists aren't in full agreement about the connection between the modern meaning of "effrontery" and the literal senses of its roots.

*Some explain that "frons" can also refer to the capacity for blushing, so a person without "frons" would be "unblushing" or "shameless." Others theorize that since the Romans believed that the brow was the seat of a person's modesty, being without a brow meant being "immodest," or again, "shameless."

(M-W)