text:
Q: How to transfer a value from one JLabel to another? I have this calculator working, but I can't figure out how to get the value in the resultpane to the first textbox when you click the "finish" button.
I'm new to Java.  I've tried doing it, but I kept getting an error.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.AbstractAction;
import static javax.swing.Action.NAME;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestCalculator {

public static void main(String[] args) {
    new TestCalculator();
}

public TestCalculator() {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            }

            ResultPane resultPane = new ResultPane();

            JFrame frame = new JFrame("Testing");
            frame.setGlassPane(resultPane);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());
            frame.add(new CalculatorPane(resultPane));
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
}

public class ResultPane extends JPanel {

    private JLabel result;
    private Timer timer;

    private int xDelta = (Math.random() > 0.5) ? 1 : -1;
    private int yDelta = (Math.random() > 0.5) ? 1 : -1;

    ;

    public ResultPane() {
        setOpaque(false);
        setLayout(null);
        result = new JLabel();
        Font font = result.getFont();
        font = font.deriveFont(Font.BOLD, 26f);
        result.setFont(font);
        add(result);
        timer = new Timer(40, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Point point = result.getLocation();
                point.x += xDelta;
                point.y += yDelta;
                if (point.x < 0) {
                    point.x = 0;
                    xDelta *= -1;
                } else if (point.x + result.getWidth() > getWidth()) {
                    point.x = getWidth() - result.getWidth();
                    xDelta *= -1;
                }
                if (point.y < 0) {
                    point.y = 0;
                    yDelta *= -1;
                } else if (point.y + result.getHeight() > getHeight()) {
                    point.y = getHeight() - result.getHeight();
                    yDelta *= -1;
                }
                result.setLocation(point);
                repaint();
            }

        });
        timer.start();
    }

    public void setResult(Number number) {
        result.setText("Result: " + NumberFormat.getNumberInstance().format(number));
        result.setSize(result.getPreferredSize());
        setVisible(true);
    }

}

public class CalculatorPane extends JPanel {

    private final ResultPane resultPane;

    private final JLabel firstNumberLabel = new JLabel("First Number:");
    private final JLabel secondNumberLabel = new JLabel("Second Number:");

    private final JTextField firstNumberField = new JTextField(5);
    private final JTextField secondNumberField = new JTextField(5);

    public CalculatorPane(ResultPane resultPane) {

        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;

        this.resultPane = resultPane;

        JPanel fields = new JPanel();
        fields.add(firstNumberLabel);
        fields.add(firstNumberField);
        fields.add(secondNumberLabel);
        fields.add(secondNumberField);

        add(fields, gbc);

        JPanel buttons = new JPanel();
        buttons.add(new JButton(new AddAction()));
        buttons.add(new JButton(new SubtractAction()));
        buttons.add(new JButton(new MultiplyAction()));
        buttons.add(new JButton(new DivideAction()));
        buttons.add(new JButton(new ToText1Action()));

        add(buttons, gbc);

    }

    public class AddAction extends AbstractAction {

        public AddAction() {
            putValue(NAME, "+");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                double num1 = Double.parseDouble(firstNumberField.getText());
                double num2 = Double.parseDouble(secondNumberField.getText());

                double result = num1 + num2;

                //num1.setResult(firstNumberField);
                resultPane.setResult(result);
            } catch (NumberFormatException exp) {
            }
        }

    }
    public class SubtractAction extends AbstractAction {

        public SubtractAction() {
            putValue(NAME, "-");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                double num1 = Double.parseDouble(firstNumberField.getText());
                double num2 = Double.parseDouble(secondNumberField.getText());

                double result = num1 - num2;
                resultPane.setResult(result);
            } catch (NumberFormatException exp) {
            }
        }

    }
    public class MultiplyAction extends AbstractAction {

        public MultiplyAction() {
            putValue(NAME, "x");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                double num1 = Double.parseDouble(firstNumberField.getText());
                double num2 = Double.parseDouble(secondNumberField.getText());

                double result = num1 * num2;
                resultPane.setResult(result);
            } catch (NumberFormatException exp) {
            }
        }

    }
    public class DivideAction extends AbstractAction {

        public DivideAction() {
            putValue(NAME, "/");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                double num1 = Double.parseDouble(firstNumberField.getText());
                double num2 = Double.parseDouble(secondNumberField.getText());

                double result = num1 / num2;
                resultPane.setResult(result);
            } catch (NumberFormatException exp) {
            }
        }

    }
    public class ToText1Action extends AbstractAction {
        public ToText1Action() {
            putValue(NAME, "Finish");
        }
        @Override
        public void actionPerformed(ActionEvent e) {
            try {

                //i would like to put it here

            } catch (NumberFormatException exp) {
            }
        }
    }
}
}

A: Give your ResultPane a new public method that allows you to extract the text from its JLabel, something like:
  public String getResultText() {
     return result.getText();
  }

And then call it when you want to get the text of that field:
  public class ToText1Action extends AbstractAction {
     public ToText1Action() {
        putValue(NAME, "Finish");
     }

     @Override
     public void actionPerformed(ActionEvent e) {
         String resultText = resultPane.getResultText();
         double number = // extract number from resultText
         firstNumberField.setText(number);
     }
  }

Better still, simply store the latest result value in a double variable that is an instance field of the class, say called lastResult and set the firstNumberField with that.
Note that you should not have empty catch blocks.

Edit
For example:
public class CalculatorPane extends JPanel {
  private final ResultPane resultPane;
  private final JLabel firstNumberLabel = new JLabel("First Number:");
  private final JLabel secondNumberLabel = new JLabel("Second Number:");
  private final JTextField firstNumberField = new JTextField(5);
  private final JTextField secondNumberField = new JTextField(5);

  private double result = 0.0;   // ****** declared here

  // ***** etc..... *****

  public class DivideAction extends AbstractAction {

     public DivideAction() {
        putValue(NAME, "/");
     }

     @Override
     public void actionPerformed(ActionEvent e) {
        try {
           double num1 = Double.parseDouble(firstNumberField.getText());
           double num2 = Double.parseDouble(secondNumberField.getText());

           result = num1 / num2; // ****** note variable not declared
           resultPane.setResult(result);
        } catch (NumberFormatException exp) {
           // show error message
           // set text fields to "0"
        }
     }

  }

  public class ToText1Action extends AbstractAction {
     public ToText1Action() {
        super("Finish");
        putValue(MNEMONIC_KEY, KeyEvent.VK_F);
     }

     @Override
     public void actionPerformed(ActionEvent e) {
        firstNumberField.setText(String.format("%.2f", result));
     }
  }

A: As another approach, you could establish some kind of model, which is shared between the actions and the components, this helps de-couple of the UI as it's main linking factor is the model, not other UI elements.
For the ToText1Action, you will also need to pass it the field you want updated, but since it's primarily a JTextField, it shouldn't be to bad...
So, the primary change is the inclusion of some kind of model, which provides means to set the result, get the result and provide event notification when the model changes, so those interested parties can update themselves as required, for example...
public interface ResultsModel {

    public void setResult(double value);
    public double getResult();

    public void addChangeListener(ChangeListener listener);
    public void removeChangeListener(ChangeListener listener);

}

public class DefaultResultsModel implements ResultsModel {

    private List<ChangeListener> changeListeners;
    private double result;

    public DefaultResultsModel() {
        changeListeners = new ArrayList<>(25);
    }

    public double getResult() {
        return result;
    }

    public void setResult(double value) {
        if (value != result) {
            this.result = value;
            fireStateChanged();
        }
    }

    protected void fireStateChanged() {
        if (!changeListeners.isEmpty()) {
            ChangeEvent evt = new ChangeEvent(this);
            for (ChangeListener listener : changeListeners) {
                listener.stateChanged(evt);
            }
        }
    }

    @Override
    public void addChangeListener(ChangeListener listener) {
        changeListeners.add(listener);
    }

    @Override
    public void removeChangeListener(ChangeListener listener) {
        changeListeners.remove(listener);
    }

}

The ResultsPane and each action will need to be changed so that they can work with the model instead of directly with each.  This means that the ResultsPane will now listen to changes in the model instead of been updated directly
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import static javax.swing.Action.NAME;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class TestCalculator {

    public static void main(String[] args) {
        new TestCalculator();
    }

    public TestCalculator() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                ResultsModel model = new DefaultResultsModel();
                ResultPane resultPane = new ResultPane();
                resultPane.setModel(model);

                JFrame frame = new JFrame("Testing");
                frame.setGlassPane(resultPane);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new CalculatorPane(model));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public interface ResultsModel {

        public void setResult(double value);
        public double getResult();

        public void addChangeListener(ChangeListener listener);
        public void removeChangeListener(ChangeListener listener);

    }

    public class DefaultResultsModel implements ResultsModel {

        private List<ChangeListener> changeListeners;
        private double result;

        public DefaultResultsModel() {
            changeListeners = new ArrayList<>(25);
        }

        @Override
        public double getResult() {
            return result;
        }

        @Override
        public void setResult(double value) {
            if (value != result) {
                this.result = value;
                fireStateChanged();
            }
        }

        protected void fireStateChanged() {
            if (!changeListeners.isEmpty()) {
                ChangeEvent evt = new ChangeEvent(this);
                for (ChangeListener listener : changeListeners) {
                    listener.stateChanged(evt);
                }
            }
        }

        @Override
        public void addChangeListener(ChangeListener listener) {
            changeListeners.add(listener);
        }

        @Override
        public void removeChangeListener(ChangeListener listener) {
            changeListeners.remove(listener);
        }

    }

    public class ResultPane extends JPanel implements ChangeListener {

        private ResultsModel model;

        private JLabel result;
        private Timer timer;

        private int xDelta = (Math.random() > 0.5) ? 1 : -1;
        private int yDelta = (Math.random() > 0.5) ? 1 : -1;

    public ResultPane() {
            setOpaque(false);
            setLayout(null);
            result = new JLabel();
            Font font = result.getFont();
            font = font.deriveFont(Font.BOLD, 26f);
            result.setFont(font);
            add(result);
            timer = new Timer(40, new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    Point point = result.getLocation();
                    point.x += xDelta;
                    point.y += yDelta;
                    if (point.x < 0) {
                        point.x = 0;
                        xDelta *= -1;
                    } else if (point.x + result.getWidth() > getWidth()) {
                        point.x = getWidth() - result.getWidth();
                        xDelta *= -1;
                    }
                    if (point.y < 0) {
                        point.y = 0;
                        yDelta *= -1;
                    } else if (point.y + result.getHeight() > getHeight()) {
                        point.y = getHeight() - result.getHeight();
                        yDelta *= -1;
                    }
                    result.setLocation(point);
                    repaint();
                }

            });
            timer.start();
        }

        public void setModel(ResultsModel value) {
            if (value != model) {
                if (model != null) {
                    model.removeChangeListener(this);
                }
                model = value;
                if (model != null) {
                    model.addChangeListener(this);
                }
            }
        }

        public ResultsModel getModel() {
            return model;
        }

        @Override
        public void stateChanged(ChangeEvent e) {
            double number = getModel().getResult();
            result.setText("Result: " + NumberFormat.getNumberInstance().format(number));
            result.setSize(result.getPreferredSize());
            setVisible(true);
        }

    }

    public class CalculatorPane extends JPanel {

        private final JLabel firstNumberLabel = new JLabel("First Number:");
        private final JLabel secondNumberLabel = new JLabel("Second Number:");

        private final JTextField firstNumberField = new JTextField(5);
        private final JTextField secondNumberField = new JTextField(5);

        public CalculatorPane(ResultsModel model) {

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            JPanel fields = new JPanel();
            fields.add(firstNumberLabel);
            fields.add(firstNumberField);
            fields.add(secondNumberLabel);
            fields.add(secondNumberField);

            add(fields, gbc);

            JPanel buttons = new JPanel();
            buttons.add(new JButton(new AddAction(model)));
            buttons.add(new JButton(new SubtractAction(model)));
            buttons.add(new JButton(new MultiplyAction(model)));
            buttons.add(new JButton(new DivideAction(model)));
            buttons.add(new JButton(new ToText1Action(firstNumberField, model)));

            add(buttons, gbc);

        }

        public abstract class AbstractResultsAction extends AbstractAction {

            private ResultsModel model;

            public AbstractResultsAction(ResultsModel model) {
                this.model = model;
            }

            public ResultsModel getModel() {
                return model;
            }

        }

        public class AddAction extends AbstractResultsAction {

            public AddAction(ResultsModel model) {
                super(model);
                putValue(NAME, "+");
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    double num1 = Double.parseDouble(firstNumberField.getText());
                    double num2 = Double.parseDouble(secondNumberField.getText());

                    double result = num1 + num2;

                    //num1.setResult(firstNumberField);
                    getModel().setResult(result);
                } catch (NumberFormatException exp) {
                }
            }

        }

        public class SubtractAction extends AbstractResultsAction {

            public SubtractAction(ResultsModel model) {
                super(model);
                putValue(NAME, "-");
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    double num1 = Double.parseDouble(firstNumberField.getText());
                    double num2 = Double.parseDouble(secondNumberField.getText());

                    double result = num1 - num2;
                    getModel().setResult(result);
                } catch (NumberFormatException exp) {
                }
            }

        }

        public class MultiplyAction extends AbstractResultsAction {

            public MultiplyAction(ResultsModel model) {
                super(model);
                putValue(NAME, "x");
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    double num1 = Double.parseDouble(firstNumberField.getText());
                    double num2 = Double.parseDouble(secondNumberField.getText());

                    double result = num1 * num2;
                    getModel().setResult(result);
                } catch (NumberFormatException exp) {
                }
            }

        }

        public class DivideAction extends AbstractResultsAction {

            public DivideAction(ResultsModel model) {
                super(model);
                putValue(NAME, "/");
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    double num1 = Double.parseDouble(firstNumberField.getText());
                    double num2 = Double.parseDouble(secondNumberField.getText());

                    double result = num1 / num2;
                    getModel().setResult(result);
                } catch (NumberFormatException exp) {
                }
            }

        }

        public class ToText1Action extends AbstractResultsAction {

            private JTextField field;

            public ToText1Action(JTextField field, ResultsModel model) {
                super(model);
                putValue(NAME, "Finish");
                this.field = field;
            }

            public JTextField getField() {
                return field;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    double result = getModel().getResult();
                    getField().setText(NumberFormat.getNumberInstance().format(result));
                    //i would like to put it here
                } catch (NumberFormatException exp) {
                }
            }
        }
    }
}

This is an example of the observer pattern


text:
Q: 3D-PDF Error when adding 3Dviews to media I am facing problems when I want to add 3Dviews to my media. I cannot compile the following code, getting an error 'undefined control sequence'. But without the line 3Dviews=test.vws, it works.
The strange thing is that this code had been working fine before I installed the newest MikTex distribution and also updated all packages... I would be thankful for any hints, can you help me please?
\documentclass[landscape]{article}
\usepackage[a4paper, left=1cm, right=1cm, top=2cm, bottom=2cm]{geometry}
\usepackage{graphicx}
\usepackage[dvipdfmx]{media9}
\usepackage[pdftex]{hyperref}

\begin{document}
\pagestyle{empty}
\centering
\includemedia[
label=converter3degreelines,
width=\textwidth,
height=\textheight,
activate=pagevisible,
deactivate=pageinvisible,
3Dviews=test.vws,
3Dmenu
]{
\includegraphics[width=0.45\textwidth]{test.png}
}{test.u3d}
\end{document}

The test.vws file contains the following:
VIEW=Default
    COO=4.675      -4.675       4.675
    C2C=0            0      80.9734
    ROO=6.1057
    ROLL=0
    ORTHO=0.081891

    PART=Mesh1
        RENDERMODE=Wireframe
    END
END

The error message from the Log is the following:
! Undefined control sequence.
<argument> \LaTeX3 error:
                           Missing number before '*'.
l.20 }{test.u3d}

The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

The file list from the .log is:
*File List*
article.cls 2007/10/19 v1.4h Standard LaTeX document class
size10.clo 2007/10/19 v1.4h Standard LaTeX file (size option)
geometry.sty 2010/09/12 v5.6 Page Geometry
keyval.sty 1999/03/16 v1.13 key=value parser (DPC)
ifpdf.sty 2011/01/30 v2.3 Provides the ifpdf switch (HO)
ifvtex.sty 2010/03/01 v1.5 Detect VTeX and its facilities (HO)
ifxetex.sty 2010/09/12 v0.6 Provides ifxetex conditional
graphicx.sty 1999/02/16 v1.0f Enhanced LaTeX Graphics (DPC,SPQR)
graphics.sty 2009/02/05 v1.0o Standard LaTeX Graphics (DPC,SPQR)
trig.sty 1999/03/16 v1.09 sin cos tan (DPC)
graphics.cfg 2010/04/23 v1.9 graphics configuration of TeX Live
pdftex.def 2011/05/27 v0.06d Graphics/color for pdfTeX
infwarerr.sty 2010/04/08 v1.3 Providing info/warning/error messages (HO)
ltxcmds.sty 2011/11/09 v1.22 LaTeX kernel commands for general use (HO)
media9.sty 2013/08/16 v0.30 acrobat-9/X compatible media
expl3.sty 2013/07/28 v4582 L3 Experimental code bundle wrapper
l3names.sty 2012/12/07 v4346 L3 Namespace for primitives
l3bootstrap.sty 2013/07/28 v4581 L3 Experimental bootstrap code
etex.sty 1998/03/26 v2.0 eTeX basic definition package (PEB)
l3basics.sty 2013/07/28 v4581 L3 Basic definitions
l3expan.sty 2013/07/24 v4565 L3 Argument expansion
l3tl.sty 2013/07/28 v4581 L3 Token lists
l3seq.sty 2013/07/28 v4581 L3 Sequences and stacks
l3int.sty 2013/07/28 v4581 L3 Integers
l3quark.sty 2013/07/21 v4564 L3 Quarks
l3prg.sty 2013/07/28 v4581 L3 Control structures
l3clist.sty 2013/07/28 v4581 L3 Comma separated lists
l3token.sty 2013/07/28 v4581 L3 Experimental token manipulation
l3prop.sty 2013/07/28 v4581 L3 Property lists
l3msg.sty 2013/07/28 v4581 L3 Messages
l3file.sty 2013/07/28 v4581 L3 File and I/O operations
l3skip.sty 2013/07/28 v4581 L3 Dimensions and skips
l3keys.sty 2013/07/28 v4581 L3 Experimental key-value interfaces
l3fp.sty 2013/07/09 v4521 L3 Floating points
l3box.sty 2013/07/28 v4581 L3 Experimental boxes
l3coffins.sty 2012/09/09 v4212 L3 Coffin code layer
l3color.sty 2012/08/29 v4156 L3 Experimental color support
l3luatex.sty 2013/07/28 v4581 L3 Experimental LuaTeX-specific functions
l3candidates.sty 2013/07/24 v4576 L3 Experimental additions to l3kernel
l3regex.sty 2013/07/24 v4576 L3 Experimental regular expressions
l3tl-build.sty 2011/12/08 v3039 L3 Experimental token list construction
l3tl-analysis.sty 2011/12/08 v3039 L3 Experimental token lists analysis
l3str.sty 2013/07/24 v4576 L3 Experimental strings
l3flag.sty 2011/12/08 v3039 L3 Experimental flags
l3str-convert.sty 2013/01/08 v4339 L3 Experimental string encoding conversio
ns
l3keys2e.sty 2013/07/28 v4582 LaTeX2e option processing using LaTeX3 keys
xparse.sty 2013/07/28 v4582 L3 Experimental document command parser
atbegshi.sty 2011/10/05 v1.16 At begin shipout hook (HO)
hyperref.sty 2012/11/06 v6.83m Hypertext links for LaTeX
hobsub-hyperref.sty 2012/05/28 v1.13 Bundle oberdiek, subset hyperref (HO)
hobsub-generic.sty 2012/05/28 v1.13 Bundle oberdiek, subset generic (HO)
hobsub.sty 2012/05/28 v1.13 Construct package bundles (HO)
ifluatex.sty 2010/03/01 v1.3 Provides the ifluatex switch (HO)
intcalc.sty 2007/09/27 v1.1 Expandable calculations with integers (HO)
etexcmds.sty 2011/02/16 v1.5 Avoid name clashes with e-TeX commands (HO)
kvsetkeys.sty 2012/04/25 v1.16 Key value parser (HO)
kvdefinekeys.sty 2011/04/07 v1.3 Define keys (HO)
pdftexcmds.sty 2011/11/29 v0.20 Utility functions of pdfTeX for LuaTeX (HO)
pdfescape.sty 2011/11/25 v1.13 Implements pdfTeX's escape features (HO)
bigintcalc.sty 2012/04/08 v1.3 Expandable calculations on big integers (HO)
bitset.sty 2011/01/30 v1.1 Handle bit-vector datatype (HO)
uniquecounter.sty 2011/01/30 v1.2 Provide unlimited unique counter (HO)
letltxmacro.sty 2010/09/02 v1.4 Let assignment for LaTeX macros (HO)
hopatch.sty 2012/05/28 v1.2 Wrapper for package hooks (HO)
xcolor-patch.sty 2011/01/30 xcolor patch
atveryend.sty 2011/06/30 v1.8 Hooks at the very end of document (HO)
refcount.sty 2011/10/16 v3.4 Data extraction from label references (HO)
hycolor.sty 2011/01/30 v1.7 Color options for hyperref/bookmark (HO)
auxhook.sty 2011/03/04 v1.3 Hooks for auxiliary files (HO)
kvoptions.sty 2011/06/30 v3.11 Key value format for package options (HO)
pd1enc.def 2012/11/06 v6.83m Hyperref: PDFDocEncoding definition (HO)
hyperref.cfg 2002/06/06 v1.2 hyperref configuration of TeXLive
url.sty 2006/04/12 ver 3.3 Verb mode for urls, etc.
hpdftex.def 2012/11/06 v6.83m Hyperref driver for pdfTeX
rerunfilecheck.sty 2011/04/15 v1.7 Rerun checks for auxiliary files (HO)
supp-pdf.mkii
epstopdf-base.sty 2010/02/09 v2.5 Base part for package epstopdf
grfext.sty 2010/08/19 v1.1 Manage graphics extensions (HO)
epstopdf-sys.cfg 2010/07/13 v1.3 Configuration of (r)epstopdf for TeX Live
nameref.sty 2012/10/27 v2.43 Cross-referencing by name of section
gettitlestring.sty 2010/12/03 v1.4 Cleanup title references (HO)
mediatest.out
mediatest.out
test.png Graphic file (type png)
***********

A: The problem are the tabs in the .vws file,
COO=0.2899417579174042 [TAB] 0 [TAB] -4.275146484375

causing the error message stated in the question, or
[TAB]PART=Mesh1

causing an error like
! LaTeX error: "kernel/key-unknown"
!
! The key 'media9/views/    PART' is unknown and is being ignored.

Replacing the [TAB] by whitespaces solves the problem.
Furthermore, the use of comments, like
%    PART=Mesh1

also causes an error:
! LaTeX error: "kernel/key-unknown"
!
! The key 'media9/views/%    PART' is unknown and is being ignored.

Removing all tabs and comment lines worked for me.

A: This is due to changes in the expl3 package loaded by media9. A package update should resolve this issue:
tlmgr update --all

The current version [2013/08/16 v. 0.30] of media9 is not yet available through MiKTeX package manager.
TeXLive is usually faster at package updates than MiKTeX.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to multithread a function in Flask? I have a function that gets the current price of any currency that i choose using the financial google, i want to multithread it so i can send any request separately .
Here is my code:
def currency_converter(amount, currency):
    url = 'https://finance.google.com/finance/converter?a={}&from=KGS&to={}&meta=ei%3DmSr0WeHCCYvBsAH8n6OIBA'.format(amount, currency)
    urlHandler = urllib2.urlopen(url)
    html = urlHandler.read()
    bsoup = BeautifulSoup(html, 'lxml')
    num = bsoup.find('span').text.split()[0]
    return float(num)

@main_route.app_template_filter('currency_converter')
def thread_me(amount, currency):
    t = threading.Thread(target=currency_converter, args=[amount, currency])
    t.start()
    t.join()
    return t

here is how i run the filter inside my template:
{{ product.price|float|currency_converter('RUB') }} руб
Here i am returning the t value , i want to return the data from the api , please how can i make that done ??
Another problem that i forgot to mention that, if i opened any product page the page delays for about 10 seconds !!

A: You should try multiprocessing instead:
from multiprocessing.pool import ThreadPool

#currency_converter code

@main_route.app_template_filter('currency_converter')
def thread_me(amount, currency):
    pool = ThreadPool(processes=1)

    result = pool.apply_async(currency_converter, (amount, currency))

    return result.get()


text:
Q: Filter in dplyr if condition is met across ANY variable within a row Take the following tiny dataframe.
df = tribble(
~col1,~col2,~col3,
1,2,3,
4,5,6,
7,8,9
)

I want to filter rows where ANY value is less than 5. The following doesn't work but was my initial thought:
df %>%
filter(across(
    .fns = ~.<5
))

The output for that, however, is
1 , 2 , 3

instead of the expected output of
1 , 2 , 3,
4 , 5 , 6

While there is a solution by not using across() and filtering using filter(col1 < 5 | col2 < 5 | col3 < 5), I would like to learn of a more generalizable approach for larger datasets that could be used with all_of() or everything().
How would one go about doing this?

A: 1) Use rowSums
df %>% filter(rowSums(. < 5) > 0)
## # A tibble: 2 x 3
##    col1  col2  col3
##   <dbl> <dbl> <dbl>
## 1     1     2     3
## 2     4     5     6

2) or Reduce
df %>% filter(Reduce(`|`, as.data.frame(. < 5)))
## # A tibble: 2 x 3
##    col1  col2  col3
##   <dbl> <dbl> <dbl>
## 1     1     2     3
## 2     4     5     6

Replace dot with select(., ...whatever...) or just use ordinary subscripting if you want to only consider certain columns.
3) or use c_across
df %>% rowwise %>% filter(any(c_across() < 5))
## # A tibble: 2 x 3
##    col1  col2  col3
##   <dbl> <dbl> <dbl>
## 1     1     2     3
## 2     4     5     6

A: Earlier we could use filter_all :
library(dplyr)
df %>% filter_all(any_vars(. < 5))

However, since filter_all is deprecated we can combine Reduce with across.
df %>% filter(Reduce(`|`, across(.fns = ~. < 5)))

#   col1  col2  col3
#  <dbl> <dbl> <dbl>
#1     1     2     3
#2     4     5     6


text:
Q: mouse_event / PostMessage key down messages - inconsistent with GetKeyState() I'm trying to do two things:

*

*Send "key down" events, both for keyboard keys, as well as mouse keys, to an external process' window

*Later on, query whether a given keyboard or mouse key is currently pressed in that window, which could happen if

*

*My tool had previously sent a "key down" (but obviously no key up) event to the window

*The user had any manual interaction with the window

One of the cases could for example be that I send a "key down" event for the left mouse button to the window. The user then clicks inside the window themselves manually. As a consequence after both of those interactions, the window recognizes the mouse key as "up" again.
So far, for the key presses, I've been using user32.dll API calls PostMessage (for keyboard events) and mouse_event (for mouse keys).
As for retrieving the current state, I've been trying to use "GetKeyState". However, its return values are inconcistent with actual behaviour. For example, when I post a key down through my tool, and there are no further interactions (neither by me, nor by the user), GetKeyState() still returns 0 (= key is NOT pressed).
I presume I'm using the wrong API for retrieving the state here (in particular as GetKeyState doesn't take in a window handle either?).
Is there any way to figure out the actual key state for the given window? Or am I going wrong elsewhere here?
Thanks

Example code:
    class NativeCalls
    {
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

        [DllImport("user32.dll")]
        public static extern short GetKeyState(int nVirtKey);

        [DllImport("user32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        static extern short GetAsyncKeyState(int vKey);

        public static void test()
        {
            var state_x1 = GetAsyncKeyState(0x41);

            var ok1 = SetForegroundWindow(Globals.Hwnd);
            var ok2 = PostMessage(Globals.Hwnd, 0x0100, 0x41, 0); // key down "A"
            Thread.Sleep(10);
            var state = GetKeyState(0x41); // check if key "A" Is down
            var state_x2 = GetAsyncKeyState(0x41);

            // state_x1, state, and state_x2 are all 0
        }
    }


text:
Q: Getting the argument type of a function with template argument I have a code that works, except the following line
std::is_same<first_argument<functorArgTemplated>::type,int>::value <<std::endl;  // this does not work

Does anybody know what kind of definitions of helper() I have to add?
The  compiler error is
1>d:\git\testprojekt\testprojekt\testprojekt.cpp(60): error C2065: 'functorArgTemplated': undeclared identifier
1>d:\git\testprojekt\testprojekt\testprojekt.cpp(60): error C2923: 'first_argument': 'functorArgTemplated' is not a valid template type argument for parameter 'F'
1>d:\git\testprojekt\testprojekt\testprojekt.cpp(60): error C2955: 'first_argument': use of class template requires template argument list
1>  d:\git\testprojekt\testprojekt\testprojekt.cpp(22): note: see declaration of 'first_argument'
1>d:\git\testprojekt\testprojekt\testprojekt.cpp(60): warning C4552: '<<': operator has no effect; expected operator with side-effect

complete code:
#include <iostream>

template<typename F, typename Ret>
void helper(Ret(F::*)());

template<typename F, typename Ret>
void helper(Ret(F::*)() const);

template<typename F, typename Ret, typename A, typename... Rest>
void helper(Ret(F::*)(A, Rest...));

template<typename F, typename Ret, typename A, typename... Rest>
void helper(Ret(F::*)(A, Rest...) const);

template<typename F, typename Ret, typename A, typename... Rest>
void helper(Ret(F::*)(A, Rest...) const);

template<typename F>
struct first_argument {
    typedef decltype(helper(&F::operator())) type;
};

template <typename Functor, typename Arg = typename first_argument<Functor>::type>
struct DoStuff;

template <typename Functor>
struct DoStuff<Functor, char>
{
    void print() { std::cout << "has arg" << std::endl; };
};

template <typename Functor>
struct DoStuff<Functor, void>
{
    void print() { std::cout << "does not have arg" << std::endl; };
};

struct functorNoArg {
    void operator() () {};
};

struct functorArg {
    void operator()(int a) { std::cout << a; };
};

struct functorArgTemplated {
    template <typename TArg>
    int operator()(TArg a) { std::cout << a; return a; };
};

int main()
{
    auto lambdaNoArg = []() {};
    auto lambdaArg = [](int a) {};

    std::cout << std::is_same<first_argument<functorArgTemplated>::type,int>::value <<std::endl;  // this does not work

    DoStuff<functorArg> doStuff;
    doStuff.print();

    DoStuff<functorNoArg> doStuff2;
    doStuff2.print();

    DoStuff<decltype(lambdaArg)> doStuff3;
    doStuff3.print();

    DoStuff<decltype(lambdaNoArg)> doStuff4;
    doStuff4.print();

    return 0;
}

A: In C++ you can answer the question "can I invoke this with an int" and get an answer (in the immediate context), but you cannot answer "what can I invoke this with".
In the general case answering the second question requires solving Halt, as what makes an acceptable argument to an object in C++ can be a Turing Complete computation.
You solved the problem for simple cases: the problem in general cannot be solved.  Solving it beyond the simplest of cases requires increasing amounts of hacks that get the answer wrong in various ways.
Usually trying to answer the question is a mixture of asking the wrong question or wanting to DRY when writing scripting/language interface code (often with languages with less ridiculous metaprogramming or type system, or an interface that narrows the type information that is transmitted).  People asking this question on SO tend to ask about their narrow issue without bothering to mention what led them down this dead end path: it is always a good idea to post a MCVE and a sketch of the motivating reason behind the problem.


text:
Q: why saving a file that I opened with fitz will change its size? I looked for what opening a file with fitz do to the file, but didn't find anything. The code is simple:
import fitz
doc = fitz.open('a.pdf')
doc.save('b.pdf')

What I don't understand is why this will change the pdf size. With the file I tried, its size went from 829kb to 854kb.
I am not confortable with this because I would like to change a characteristic of a large number of files and I can't do it before being sure this won't alter them in any sense but in the characteristic I want to change.
BTW, what I want is just set the inner title of a pdf to be equal to the shown name of its file.
import fitz
doc = fitz.open(r'a.pdf')
doc.metadata['title']=None
doc.setMetadata(doc.metadata)
doc.save(r'b.pdf')

Can I asume I won't lose some information in this second example? Why the change in size when I just open and save the file in the first example?

A: You should check the metadata of the document.
It may have information on modification date, saving date, etc., that could explain the increased size.


text:
Q: Change dates format in one column (replace, insert column, append), any way to update? ..it must be simple Need to change dates format in Excel column.
I can get into single cell but in case to update whole column with "proper_date" I am stuck
wb = load_workbook(...)
ws = wb['Lista']
daty_wystawienia = ws['G']

# This solution works but assigning values to first column under the chart

for daty in daty_wystawienia:
    date_string = daty.value
    if re.search('[0-9-]', str(date_string)):
        proper_date = datetime.datetime.strptime(date_string, '%d-%m-%Y').strftime('%y.%m.%d')
        for row in range(1):
            ws.append([proper_date])

#tried to make last line: daty_wystawienia.append([proper_date]) but got:
AttributeError: 'tuple' object has no attribute 'append'

wb.save(...)

# Also tried this, and only this seems to work. Meaning replacing values with other correctly formatted, but I need this applied to whole column at once:

wb = load_workbook(...)
ws = wb['Lista polis']
daty_wystawienia = ws['G']

ws['G6'] = "19.05.06"
ws['G7'] = "19.05.06"
ws['G8'] = "19.05.06"

ws['G10'] = "19.05.07"
ws['G11'] = "19.05.07"

# or replace

for i in ws['G']:
        ws['G9'] = ws['G9'].value.replace('06-05-2019', '10000000000')

wb.save(...)

Is there any way to replace, append, override existing values in excel using openpyxl. I am stuck on this.
Thanks in advance.

A: If you just want Excel to change the format of the Cell in order to display the date as you like, this is how I did it for a column:
from openpyxl import load_workbook

book = load_workbook('Example.xlsx')
ws = book['Sheet1']

for x in range (1, 500):
    _cell = ws.cell(x,1)
    _cell.number_format = '[$-en-GB]dd-mmm-yyyy'

book.save("Dates.xlsx")

A: Thanks for your effor. It looks beautiful but for some reason it does not work for me.
I went through it like this:
def date_of_issuance():
    for i in ws.iter_rows():
        for cell in i:
            d_w = 'Date of issuance'
            if cell.value == d_w:
                c = cell.column
                col = column_index_from_string(c)
                r = cell.row
                for daty in ws[c]:
                    date_string = daty.value
                    if re.search('[0-9]', str(date_string)):
                        proper_date = datetime.datetime.strptime(date_string, '%d-%m-%Y').strftime('%y-%m-%d')
                        date = datetime.datetime.strptime(proper_date, '%y-%m-%d').date()
                        for j in range(1):
                            ws.cell(row=r+1, column=col, value=date)
                            r += 1


text:
Q: How to determine $\lim_{h \to 0}\frac{g(h+1)-g(1)}{h}$ It is given that $g(x) = x^{20}$
Determine $$\lim_{h \to 0} \frac{g(h+1)-g(1)}{h}$$
Can someone give me a hint please? I worked it out to be so far as:
$$\lim_{h \to 0} \frac{(1+h)^{20}-1}{h}$$
The exponent of power $20$ is quite problematic. Any hints?
Note: I have to do it using first principles.

A: Hint: $x^n-1=(x-1)(1+x+x^2+\cdots +x^{n-1})$. Set $x=1+h$.

A: Hint $$(1  +h)^{20} - 1 = h\dot\, ((h+1)^{19} +  \ldots + 1)$$

A: $[(1+h)^{20}-1]\\=[1+\binom{20}{1}.h+\binom{20}{2}.h^2+\cdots+\binom{20}{19}.h^{19}+h^{20}]-1\\=\space \binom{20}{1}.h+\binom{20}{2}.h^2+\cdots+\binom{20}{19}.h^{19}+h^{20}\\=\space h[\binom{20}{1}+\binom{20}{2}.h^1+\cdots+\binom{20}{19}.h^{18}+h^{19}] $
So,
$\lim_{h \to 0 }{{(1+h)^{20}-1}\over h}\\=\lim_{h \to 0 }{{h[\binom{20}{1}+\binom{20}{2}.h^1+\cdots+\binom{20}{19}.h^{18}+h^{19}]}\over h}\\=\lim_{h\to0}[\binom{20}{1}+\binom{20}{2}.h^1+\cdots+\binom{20}{19}.h^{18}+h^{19}]\\=\binom{20}{1}\\=20.$

A: For $(x+h)^n$ you can use the binomial formula
$$(x+h)^n = \sum_{k=0}^n\dbinom{n}{k}h^kx^{n-k}$$
With that you alloways get
$$\frac{\partial}{\partial x}x^n =\lim_{h \to 0} \frac{(x+h)^n-x^n}{h}=\lim_{h \to 0} \sum_{k=1}^n\dbinom{n}{k}h^{k-1}x^{n-k} $$
Only the term with $k=1$ survives in the sum. All the others go to zero.
Thus:
$$\frac{\partial}{\partial x}x^n =\dbinom{n}{1}h^{1-1}x^{n-1}=nx^{n-1} $$


text:
Q: How can I retrieve a task's sessionid in an eBPF program? I want to retrieve the sessionid from a task struct in an eBPF program. I have the following code in my eBPF program:
struct task_struct *task;
u32 sessionid;

task = (struct task_struct *)bpf_get_current_task();
sessionid = task->sessionid;

This runs, but the sessionid always ends up being -1. I read in this answer that I can use task_session to retrieve it, but I get an error about invalid memory access. I believe I need to use bpf_probe_read to move the task_struct that task points to onto the stack, but I can't get it to work. Is there anything I'm missing?

A: After a bit more digging through the task_struct struct I realised you could do this:
struct task_struct *task;
struct pid_link pid_link;
struct pid pid;
unsigned int sessionid;

task = (struct task_struct *)bpf_get_current_task();

bpf_probe_read(&pid_link, sizeof(pid_link), (void *)&task->group_leader->pids[PIDTYPE_SID]);
bpf_probe_read(&pid, sizeof(pid), (void *)pid_link.pid);

sessionid = pid.numbers[0].nr;


text:
Q: FTP tranfer is kept on hold I've set up a PROFTP server on a CentOS 7 machine. And I am accessing it from other machines (with windows servers) to send files to it.
I've created some rules to only enable to stor files to a certain directory and the subdirectories will have different ownerships. At this point they are owned by user.
<Directory pathToDir>
    <Limit STOR CWD>
       AllowAll
    </Limit>
    <Limit READ RMD DELE MKD>
      DenyAll
    </Limit>
<Directory>

So here is what happens to me.
I log in with user from a windows server machine and access first sub-directory (own user grp user), mput several files and the files are copied.
I log in with user from a different windows server machine and access second sub-directory (own user grp user), put file and I get confirmation code (200 PORT command successful), but transfer doesn't start, however the file is created on the server and it is empty.
If I use my laptop, everything works.
Does anyone know how to fix this? Or what is wrong with my FTP server?
EDIT: FIXED. It was a windows firewall issue, couldn't get response from the ftp server. Since my server has a static ip I managed to add an exception to the windows firewall allowing only that ip to have full access to the ftp rather than opening a set of ports.

A: these would point to a firewall issue:

*

*If the connection times out (rather than fails instantly)

*If a directory listing from the client also fails

as a workaround you could try passive (PASV) FTP.


text:
Q: SocketChannel connect takes long time SocketChannel sockChannel = SocketChannel.open();
sockChannel.configureBlocking(false);
sockChannel.connect(new InetSocketAddress(remoteAddr, remotePort));

Connect is taking 30ms to 50ms sometimes more than 100ms on Android
version 2.3.4 and 3.2.1.
I have executed several tests on two hardwares and it is always that
slow. I was hoping that it takes less than 2-3 ms since it is non-
blocking.
Is this a known issue ?
I am using Selector to select over the 10s of SocketChannels for
SelectionKey.OP_CONNECT. Selector.select uses a timeout of 100ms in
this case but overall time taken is more than 1 second which is mostly
because of the SocketChannel.connect. Is there any alternative to
avoid the problem of SocketChannel.connect and still achieve to finish
the selector in 100ms.
Thanks
Alex

A: If remoteAddr is a String, a (blocking) attempt will be made to resolve that name into an InetAddress. See here.
30 to 100 ms sounds like a reasonable round trip time for a DNS query.
That means, the delay occurs before connect() is even called.


text:
Q: How to convert a single char into an int I have a string of digits, e.g. "123456789", and I need to extract each one of them to use them in a calculation. I can of course access each char by index, but how do I convert it into an int?
I've looked into atoi(), but it takes a string as argument. Hence I must convert each char into a string and then call atoi on it. Is there a better way?

A: Or you could use the "correct" method, similar to your original atoi approach, but with std::stringstream instead. That should work with chars as input as well as strings. (boost::lexical_cast is another option for a more convenient syntax)
(atoi is an old C function, and it's generally recommended to use the more flexible and typesafe C++ equivalents where possible. std::stringstream covers conversion to and from strings)

A: You can make use of atoi() function
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[]){
    int num ;
    num = atoi(argv[1]);
    printf("\n%d", num);
}

A: The answers provided are great as long as you only want to handle Arabic numerals, and are working in an encoding where those numerals are sequential, and in the same place as ASCII.
This is almost always the case.
If it isn't then you need a proper library to help you.
Let's start with ICU.

*

*First convert the byte-string to a unicode string. (Left as an exercise for the reader).

*Then use uchar.h to look at each character.

*if we the character is UBool   u_isdigit (UChar32 c)

*then the value is int32_t u_charDigitValue     (   UChar32      c       )
Or maybe ICU has some function to do it for you - I haven't looked at it in detail.

A: #define toDigit(c) (c-'0')

A: #include<iostream>
#include<stdlib>
using namespace std;

void main()
{
     char ch;
     int x;
     cin >> ch;
     x = char (ar[1]);
     cout << x;
}

A: You can utilize the fact that the character encodings for digits are all in order from 48 (for '0') to 57 (for '9'). This holds true for ASCII, UTF-x and practically all other encodings (see comments below for more on this).
Therefore the integer value for any digit is the digit minus '0' (or 48).
char c = '1';
int i = c - '0'; // i is now equal to 1, not '1'

is synonymous to
char c = '1';
int i = c - 48; // i is now equal to 1, not '1'

However I find the first c - '0' far more readable.

A: If you are worried about encoding, you can always use a switch statement.
Just be careful with the format you keep those large numbers in.  The maximum size for an integer in some systems is as low as 65,535 (32,767 signed).  Other systems, you've got 2,147,483,647 (or 4,294,967,295 unsigned)

A: Any problems with the following way of doing it?
int CharToInt(const char c)
{
    switch (c)
    {
    case '0':
        return 0;
    case '1':
        return 1;
    case '2':
        return 2;
    case '3':
        return 3;
    case '4':
        return 4;
    case '5':
        return 5;
    case '6':
        return 6;
    case '7':
        return 7;
    case '8':
        return 8;
    case '9':
        return 9;
    default:
        return 0;
    }
}

A: By this way You can convert char to int and int to char easily:
int charToInt(char c)
{
   int arr[]={0,1,2,3,4,5,6,7,8,9};
   return arr[c-'0'];
}

A: I agree with @jalf. Using the sstream library and stoi appears to be the recommended approach:
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {

  stringstream st;
  st << 1  << '2';

  cout << stoi(st.str()) + 1;

  return 0;
}

Output
13

I am a new student of C++ but a long-time LAMP stack developer. I was hoping the string class had more things to smoothly transition between chars and strings, but I've not yet found such a thing that is natively supported.

A: For me the following worked quite well:
QChar c = '5';
int x = c.digitValue();
// x is now 5

Documentation: int QChar::digitValue() const which says:

Returns the numeric value of the digit, or -1 if the character is not
  a digit.


text:
Q: good reference for the Hitchin fibration can you please recommend me a good reference to learn about the Hitchin fibration in the language of algebraic geometry?

A: At the moment I am not sure what to recommend if you want short introduction.
But if you something like a longer text giving various perspective is Okay for you I would suggest:
Ron Donagi, Eyal Markman
Spectral curves, algebraically completely integrable Hamiltonian systems, and moduli of bundles, http://arxiv.org/abs/alg-geom/9507017.
As a kind of remark, according to my experience looking from solely algebraic geometry
point of view is somehow not  quite good to get complete understanding.
I am not aware of any "natural" explanation why Hitchin's hamiltonians Poisson commute (i.e. fibration would be Lagragian) given in terms of algebraic geometry.
Original Hitchin's approach is via differential geometry and Beilinson-Drinfeld point of view is via representation theory.


text:
Q: Removing a property in JSON with Jackson? In a Java/Spring application, I have a POJO/bean. Let's call it CourseRequest. It is converted/serialized into a string and sent out in a PUT REST request. The conversion is done using org.codehaus.jackson.map.ObjectMapper. The sending is done using org.scribe.model.OAuthRequest. See simplified code:
OAuthRequest request = new OAuthRequest(...);
CourseRequest courseRequest = new CourseRequest(...);
ObjectMapper mapper = new ObjectMapper();
String courseJson = null;

try {
    // convert to json.
    courseJson = mapper.writeValueAsString(courseRequest);
    request.addPayload(courseJson);
    request.send();
} catch (JsonGenerationException e) {
    logger.error(e);
} catch (JsonMappingException e) {
    logger.error(e);
} catch (IOException e) {
    logger.error(e);
}

I have run into a problem where I need to remove a property instructorId from the JSON/payload before sending the request. Obviously, I can't just naively remove the property in CourseRequest because the POJO/bean is used in other places too.
So, what is the best way to do it?
I can't use @JsonIgnore or alike annotations, because

*

*I want to remove the property only on some conditions;

*There are other requests elsewhere in the application which may want to keep the property

For initial thoughts:

*

*As a "hack", I can do a regex replace on the courseJson to remove the property after mapper.writeValueAsString(courseRequest) but I think that's not a very clean way to do it.

*I can parse the courseJson back into some kind of map and then remove the property but that's just clumsy.

P.S. I am using Jackson v1.9.13


text:
Q: Can't start slurm database (slurmdbd) daemon Slurm 17.02.3 was installed on my cluster some time ago but recently I decided to use SlurmDBD for the accounting.
After installing several packages(slurm-devel, slurm-munge, slurm-perlapi, slurm-plugins, slurm-slurmdbd and slurm-sql) and MariaDB in CentOS 7, I created an SQL database:
mysql> grant all on slurm_acct_db.* TO 'slurm'@'localhost'
-> identified by 'some_pass' with grant option;
mysql> create database slurm_acct_db;

and configured the slurmdbd.conf file:
AuthType=auth/munge
DbdAddr=localhost
DbdHost=localhost
SlurmUser=slurm
DebugLevel=4
LogFile=/var/log/slurm/slurmdbd.log
PidFile=/var/run/slurmdbd.pid
StorageType=accounting_storage/mysql
StorageHost=localhost
StoragePass=some_pass
StorageUser=slurm
StorageLoc=slurm_acct_db

Then, I stopped the slurmctl daemon on the head node of my cluster and tried to start slurmdbd, but I got the following:
$ systemctl start slurmdbd
Job for slurmdbd.service failed because the control process exited with error code. See "systemctl status slurmdbd.service" and "journalctl -xe" for details.
$ systemctl status slurmdbd.service
● slurmdbd.service - Slurm DBD accounting daemon
   Loaded: loaded (/etc/systemd/system/slurmdbd.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since lun 2017-11-20 10:39:26 CET; 53s ago
  Process: 27592 ExecStart=/usr/sbin/slurmdbd $SLURMDBD_OPTIONS (code=exited, status=1/FAILURE)

nov 20 10:39:26 nodo00 systemd[1]: Starting Slurm DBD accounting daemon...
nov 20 10:39:26 nodo00 systemd[1]: slurmdbd.service: control process exited, code=exited status=1
nov 20 10:39:26 nodo00 systemd[1]: Failed to start Slurm DBD accounting daemon.
nov 20 10:39:26 nodo00 systemd[1]: Unit slurmdbd.service entered failed state.
nov 20 10:39:26 nodo00 systemd[1]: slurmdbd.service failed.
$ journalctl -xe
nov 20 10:39:26 nodo00 polkitd[1078]: Registered Authentication Agent for unix-process:27586:119889015 (system bus name :1.871 [/usr/bin/pkttyagent --notify-fd 5 --fallback], object path /or
nov 20 10:39:26 nodo00 systemd[1]: Starting Slurm DBD accounting daemon...
-- Subject: Unit slurmdbd.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit slurmdbd.service has begun starting up.
nov 20 10:39:26 nodo00 systemd[1]: slurmdbd.service: control process exited, code=exited status=1
nov 20 10:39:26 nodo00 systemd[1]: Failed to start Slurm DBD accounting daemon.
-- Subject: Unit slurmdbd.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit slurmdbd.service has failed.
--
-- The result is failed.
nov 20 10:39:26 nodo00 systemd[1]: Unit slurmdbd.service entered failed state.
nov 20 10:39:26 nodo00 systemd[1]: slurmdbd.service failed.
nov 20 10:39:26 nodo00 polkitd[1078]: Unregistered Authentication Agent for unix-process:27586:119889015 (system bus name :1.871, object path /org/freedesktop/PolicyKit1/AuthenticationAgent,
nov 20 10:40:06 nodo00 gmetad[1519]: data_thread() for [HPCSIE] failed to contact node 192.168.2.10
nov 20 10:40:06 nodo00 gmetad[1519]: data_thread() got no answer from any [HPCSIE] datasource
nov 20 10:40:13 nodo00 dhcpd[2320]: DHCPREQUEST for 192.168.2.19 from 00:1e:67:48:79:d0 via enp6s0f1
nov 20 10:40:13 nodo00 dhcpd[2320]: DHCPACK on 192.168.2.19 to 00:1e:67:48:79:d0 via enp6s0f1
nov 20 10:40:39 nodo00 dhcpd[2320]: DHCPREQUEST for 192.168.2.13 from 00:1e:67:48:74:e0 via enp6s0f1
nov 20 10:40:39 nodo00 dhcpd[2320]: DHCPACK on 192.168.2.13 to 00:1e:67:48:74:e0 via enp6s0f1

I've just found out the file /var/run/slurmdbd.pid does not even exist.
I'd appreciate any hint on this issue.
Thanks


text:
Q: Greatest common divisor of some binomial coefficients Note that this is now cross-posted on mathoverflow.
While making some computation, I stumbled upon a curious relation among some binomial coefficients.
Consider the sequence of binomial coefficients $a(k,n)$, $0 \le k \le n-1$, $n \ge 2$ defined as follows:
$$a(k,n) = \binom{\frac{n(n-1)}{2}+3+k}{\lfloor\frac{n-1}{2}\rfloor+1+k}$$
and the sequence ($n \ge 2$):
$$b_n=\gcd(a(0,n),a(1,n),\ldots,a(n-2,n),a(n-1,n))$$
I conjecture that:
$$b_n \gt 1 \space\space\space\space \forall n \ge 2$$
The first few values of $b_n$ starting from $b_2$ are $2,5,6,143,102,253,899,703$. I didn't check for $n \gt 9$.
Any hint for proving or disproving the conjecture?
Also, can we say something about the values of $b_n$?

A: I believe your conjecture is true. Here is an attempted proof that's pretty close to working but ends up relying on a famous number theory conjecture.
First note: If $p$ is prime, then $p | n!$ if and only if $n \ge p$.
Let $r(n,k) = \frac{n(n-1)}{2} + 3 + k$ and $s(n,k) = \lfloor \frac{n-1}{2} \rfloor + 1 + k$, so that $a(k,n) = \binom{r(n,k)}{s(n,k)}$. Among the coefficients being GCD'd to compute $b_n$, the smallest $r$ will be $r(n,0) = \frac{n(n-1)}{2} + 3$; the largest $s$ is $s(n,n-1) = \lfloor \frac{n-1}{2} \rfloor + n$; and $r-s$ will be the same across all of the binomial coefficients in question. This means the conjecture will be proved if we can show there's some prime $p$ satisfying
$$\begin{align}
\left\lfloor \frac{n-1}{2} \right\rfloor + n &< p \\
\frac{n(n-1)}{2} - \left\lfloor \frac{n-1}{2} \right\rfloor + 2 &< p \\
p &\le \frac{n(n-1)}{2} + 3 \\
\end{align}$$
We actually have $\left\lfloor \frac{n-1}{2} \right\rfloor + n \le \frac{n(n-1)}{2} - \left\lfloor \frac{n-1}{2} \right\rfloor + 2$ for all $n \ge 1$, so we can ignore the first inequality above.
Let $x(n) = \frac{n(n-1)}2$. Then $\left\lfloor \frac{n-1}{2} \right\rfloor \le \sqrt{x/2}$, and for my proof to work I need to find $p$ with $x-\sqrt{x/2}+2 < p \le x+3$.
This last statement is true for all the $n$ I could quickly check. Also, the statement being true for sufficiently large $x$ (i.e. sufficiently large $n$) is basically Legendre's conjecture but a little stronger due to the fixed constant. See also Wikipedia's sections on upper bounds for prime gaps and conjectures related to prime gaps for more reading material. Basically, people in the field think the conjecture is probably true, but cutting edge number theory methods have been sloooowly chipping away at the problem by proving slightly better bounds over time.
Even if the conjecture I need is true, that would only prove the statement for sufficiently large $n$. We'd still need to check some number of smallish cases by hand. I've already checked at least up through $n=10,000$ though, and it seems fine at least that far.
Good luck getting a full answer! I think it's totally possible that this question may be answerable by some much simpler means. This is just the first approach I thought about.


text:
Q: Change Mobile View to Desktop Version? I would like to be able to view my sharepoint site on my ipad. I'm using Safari. When I go to my site page it's not the same. It's a simplified mobile version. I know you can switch browsers, like I did on my cell phone, to desktop version instead of mobile version. Is there any way to do this for SharePoint 2013 online, or is there only the dumbed down mobile view? It's bothering me because there's a large list I've created with multiple different views and collapsed groupings, but the mobile view isn't displaying it in the same intricate way the desktop internet explorer is. It's only displaying the first column I chose to group by. When you click on the column it shows the rest of the information in the edit mode. In conclusion, can you make the mobile view the same as the normal desktop view?

A: Goto your site settings -> site features -> deactivate the "Mobile Browser View" feature.
type out the site url in your ipad or phone browser again, it should show the desktop version directly. No need to click on "..."

A: If you click on sites at the top, you will then notice three dots in the bottom right corner. If you click on them you can change the view to PC.

A: In Safari press and hold the refresh icon - it should pop up a panel at the bottom that says; "Request Desktop Site" - press on this choice.  This is a toggle - to toggle back to mobile view choose that same choice again.  In Google Chrome go under the ... (in vertical - not horizontal arrangement) and choose this same choice...
This is very handy in OWA as it allows you to choose "Open Another Mailbox" - which is not a choice in the mobile Outlook app or in OWA without switching to the Desktop view...


text:
Q: How do I import a Python package from the top level (from FastAPI docs) I am working through the "Bigger Applications - Multiple Files" section of the FastAPI docs. This describes a package structure with a top-level directory called app, a main.py and __init__.py in that directory, and then two subdirectories named routers and internal each with their own __init__.py and source files.
In main.py (again, from the top level, this is app/main.py), they describe adding the line: from app.routers import items
However, this does not work for me, even in the simplest example:
├── app
│   ├── __init__.py
│   ├── main.py
│   └── foo
│   │   ├── __init__.py
│   │   ├── bar.py

Both __init__.py files are empty. main.py is one line:
from app.foo import bar
foo/bar.py is:
def baz():
    print("hi")

That's it. As simple as it gets, while still following the model described in the FastAPI docs. However it fails:
Traceback (most recent call last):
  File "/path/to/my/src/app/main.py", line 1, in <module>
    from app.foo import bar

Similarly, they describe using relative imports like from .internal import admin. This too does not work.
What gives? I can find similar patterns in many projects and documents, but I can't figure out what I am missing in making this work. Yes, I could put main.py a level up and everything else in a subdirectory. But that's adding clutter, and based on the docs it seems like this is something that should work (I realize this is not a FastAPI-specific problem, it's just that their docs have a clear example). Similarly, I have found answers that talk about changing PYTHONPATH, but I have seen no evidence that other projects using this pattern do that. There must be something I am missing.
I am using Python 3.9.5, but I've tried it with 3.6.x also.


text:
Q: How to correctly bson.MarshalJSON(myStruct) with an ObjectID? When I take my grab a post form my db and try and render it to JSON I run into some problems:
type PostBSON struct {
  Id      bson.ObjectId `bson:"_id,omitempty"`
  Title   string        `bson:"title"`
}

// ...

postBSON := PostBSON{}
id := bson.ObjectIdHex(postJSON.Id)
err = c.Find(bson.M{"_id": id}).One(&postBSON)

// ...

response, err := bson.MarshalJSON(postBSON)

The MarshalJSON doesn't handle hexing Id (ObjectId) for me . Thus I get:
{"Id":{"$oid":"5a1f65646d4864a967028cce"}, "Title": "blah"}

What is the correct way to clean up the output?
{"Id":"5a1f65646d4864a967028cce", "Title": "blah"}

Edit: I wrote my own stringify as described here.
Is this a performant solution?
And is it idiotmatic go?
func (p PostBSON) String() string {
  return fmt.Sprintf(`
        {
          "_id": "%s",
          "title": "%s",
          "content": "%s",
          "created": "%s"
        }`,
    p.Id.Hex(),
    p.Title,
    p.Content,
    p.Id.Time(),
  )

A: You can implement a MarshalJSON to satisfy json.Marshaler interface, e.g.:
func (a PostBSON) MarshalJSON() ([]byte, error) {
    m := map[string]interface{}{
        "id": a.Id.Hex(),
        "title": a.Title,
    }
    return json.Marshal(m)
}


text:
Q: API - Isolating returned JSON keys and values within indexed objects Building a web app using a flight data API and, welp, the struggle is real.
My returned array and it's objects look something like this:
results:

0:{destination: "YTO",
departure_date: "2018-01-24",
return_date: "2018-01-25"
airline: "TS"}

1:{destination: "BOS",
departure_date: "2018-01-08",
return_date: "2018-01-11",
airline: "AC"}

2:{destination: "SJU",
departure_date: "2018-01-31",
return_date: "2018-02-01",
airline: "AA"}

Before I can dump the results into the DOM to display them to the visitor of the site, I need to run certain returned values through an additional API (long story) so I obviously need to isolate them somehow.
For this example, I'm using destination so my initial thought process is start by to logging out:
console.log(response.results[0].destination);

Which we know will print the FIRST destination in the FIRST object, since [0] is the index of that object (so in this case in this case we get back YTO).
Since every returned object has an index number, I think I need to loop through them (for each?) to pull the values I need but I'm trying variations of that with no luck.....or for all I know it's something else entirely.
(your two cents goes here)

A: forEach works for arrays.
try using for loop

for(let key in response.results){
  console.log(response.results[key].destination);
}

A: You can turn an Object's keys into an array with the Object.keys() method, this will allow you to use the Array.forEach() method to loop through an Object's enumerable properties, like so...
Object.keys(dataObj).forEach(function(k) {
    var dest = dataObj[k].destination;
    /* ... etc ... */
});

Hope that helps.

*

*More on Object.keys() @MDN


text:
Q: Postfix ++ Operator Not Behaving As Expected Inside While Condition I've written a simple solution for the Brian Kernighan's "The C Programming Language" Exercise 1-19, that which reverses a character string. The reverse(char[]) function is as below and everything is fine with it;
void reverse(char src[])
{
    int len = 0;
    while( src[len] != '\0')
        len++;

    for(int i = 0; i < len/2; i++)
    {
        char temp = src[i];
        src[i] = src[len - 1 - i];
        src[len - 1 - i] = temp;
    }
}

However, if I use the postfix increment (++) operator inside the while loop, the function fails;
void reverse(char src[])
{
    int len = 0;
    while( src[len++] != '\0')      // this fails
        ;

    for(int i = 0; i < len/2; i++)
    {
        char temp = src[i];
        src[i] = src[len - 1 - i];
        src[len - 1 - i] = temp;
    }
}

The only difference is, instead of incrementing the variable len inside the while loop, I used a postfix ++ operator that which the behaviour expectation should be as, "Use the old value for conditional check, after finished increment it".
Why it is not working as expected, where am I doing wrong? I'm compiling it under Windows 10 Mingw/gcc compiler. Here is the whole test code;
Test Code
#include <stdio.h>

#define STR_NUM     5
#define STR_SIZE    20

void reverse(char[]);   // declaration

int main()
{
    char str[STR_NUM][STR_SIZE] =
    {
        { "A"     },
        { "AB"    },
        { "ABC"   },
        { "ABCD"  },
        { "ABCDE" }
    };

    for(int i = 0; i < STR_NUM; i++)
        reverse(str[i]);

    for(int i = 0; i < STR_NUM; i++)
        printf("%s\n", str[i]);

    return 0;
}

// this is working
void reverse(char src[])
{
    int len = 0;
    while( src[len] != '\0')
        len++;

    for(int i = 0; i < len/2; i++)
    {
        char temp = src[i];
        src[i] = src[len - 1 - i];
        src[len - 1 - i] = temp;
    }
}

// this is failing
/*
void reverse(char src[])
{
    int len = 0;
    while( src[len++] != '\0')      // this fails
        ;

    for(int i = 0; i < len/2; i++)
    {
        char temp = src[i];
        src[i] = src[len - 1 - i];
        src[len - 1 - i] = temp;
    }
}
*/

A: The postfix increment operator returns the original value and increments by one.
while( src[len] != '\0')
    len++;

In the working version, the while loop will terminate when src[len] is a \0. When the while loop test condition fails the statement inside the loop does not execute. After the loop len contains a value such that src[len] == '\0'.
while (src[len++] != '\0');

In your modified version, when the final test is preformed len will be incremented one additional time. After the loop len contains a value such that src[len] is one past the end of the array.
However the for loop assumes that len is the string length, so you have an off-by-one error.


text:
Q: How to convert string with point to symbol I am trying to convert the string "country." to a symbol. I expect to receive :country. including the point ..
I tried the following, but they do not work as my symbols still have quotes.
"country.".to_sym; #=> :"country."
"country.".intern; #=> :"country."
"country.".parameterize.underscore.to_sym; #=> :country
"country\.".to_sym; #=> :"country."

A: perhaps it will help you:
:'country.'

A: It's working as expected.
A symbol most of the time looks like:
:symbol_name

However when the symbol contains special characters such as spaces or hyphens, or in your case a period, it needs to be enclosed in quotes:
:"symbol name with-many special characters."

Although it doesn't look 'correct', it will act as any other symbol.


text:
Q: Javascript object properties visible in console, but undefined? I'm having trouble figuring out how to access object properties in Javascript.  I have a function that returns an object, and I can see that object and all of its properties when it is logged to the console in Safari, but I can't get the property values for other functions.  For example trying to alert out one of the properties returns 'undefined'.
The function that generates a object

getProfile : function() {

  FB.api('/me', function(response) {
    facebook.profile.user_id = response.id;
    facebook.profile.name = response.name;
    facebook.profile.firstName = response.first_name;
    facebook.profile.lastName = response.last_name;
    facebook.profile.gender = response.gender;
  });

  FB.api('/me/photos', {limit: 8}, function(response) {
    facebook.profile.numPhotos = response.data.length;
    for (key in response.data) {
      var photoUrl = response.data[key].source;
      eval('facebook.profile.photo' + key + '= photoUrl');
    }
  });

  return facebook.profile;
}

Trying to use that function in another script

function loadProfile() {
  var profile = facebook.getProfile();
console.log(profile);
  alert(profile.name);
}

A: The function getProfile invokes FB API function FB.api which executes an asynchoronous HTTP request. In your loadProfile function call you call getProfile which immediately returns facebook.profile object which is not populated with data yet since the HTTP request is not finished yet.
Consider following change:
getProfile : function(fCallback) {
  var bInfo = false,
      bPhotos = false;

  FB.api('/me', function(response) {
    facebook.profile.user_id = response.id;
    facebook.profile.name = response.name;
    facebook.profile.firstName = response.first_name;
    facebook.profile.lastName = response.last_name;
    facebook.profile.gender = response.gender;

    bInfo = true;
    if (bPhotos)
       fCallback(facebook.profile);
  });

  FB.api('/me/photos', {limit: 8}, function(response) {
    facebook.profile.numPhotos = response.data.length;
    for (key in response.data) {
      var photoUrl = response.data[key].source;
      eval('facebook.profile.photo' + key + '= photoUrl');
    }

    bPhotos = true;
    if (bInfo)
       fCallback(facebook.profile);
  });
}

and call this function the following way now:
function loadProfile() {
  facebook.getProfile(function (profile) {
    alert(profile.name);
  });
}

The reason why ou could see fields in the console is because you introspected the object after the asynch call was successfully executed. The alert call however executed immediately in the same thread on a not yet populated object.

A: Though 'Sergey Ilinsky' might have considered a right ground, but there are more things, that can be taken into consideration. Usually comes by mistaken, and hard to debug.
Sometime its so happens, that your object-keys contains spaces, let say:
var myObj = new Object();

myObj['key1'] = 'val1';
myObj['key2'] = 'val2';
myObj['key3 '] = 'val3';  //the key contains spaces here
myObj['key4 '] = 'val4';  // the key contains spaces here

so, when you log it to console by console.log(myObj), you will get:
Object { key1="val1", key2="val2", key3 ="val3",  key4 ="val4"}

But when you access:
alert(myObj.key1); //Ok: val1
alert(myObj.key2); //Ok: val2

alert(myObj.key3); //undefined
alert(myObj.key4); //undefined

alert(myObj['key3']; //undefined
alert(myObj['key4']; //undefined

These are the common areas of mistakes, where one mistakenly puts the space, may be while doing copy-paste, and it so happens, that one says, console log is able to show it, but I cannot access it.


text:
Q: Tables with float attributes refuse to be in div, even though the table tags are literally inside of the div tags I made two tables side by side in one div that's colored grey. However, the tables are outside of the div even though they're literally within the div tags. This is because of the float attribute. Without it, it works fine

#table1 {
  position: relative;
  left: 100px;
  border: 1px solid black;
  float: left;
}

#table2 {
  position: relative;
  right: 100px;
  border: 1px solid black;
  float: right;
}

TABLE 1

TABLE 2

Test it, the tables refuse to go inside the div.

A: Parent elements are not to expand to contain floated elements. So your parent div collapses as it properly should.
To get the div to do what you want, add overflow:auto; or overflow:hidden; to its CSS.


text:
Q: How I remove the needle in string How can I remove the "-" in my string?
$text  = 'lorem ipsum - dolor sit amet!';
$lorem = strstr($text, '-');

echo $lorem;

return:
- dolor sit amet!
And I need this:
dolor sit amet!

A: This is simple enough to use explode(). Use list() with it to make it a one-liner and give the variable a clear name (i.e. not use array syntax like $parts[1]).
list(,$dolor) = explode(' - ', $text);
echo $dolor;

A: $str = 'lorem ipsum - dolor sit amet!';
$pos = strpos($str,'-');
echo substr($str ,$pos+1,strlen($str));


text:
Q: [Vue warn]: Property "$primevue" was accessed during render but is not defined on instance Case and problem
I´m working on a private project with Vue.js and have the following error, which occurs when I´m trying to use the FileUpload component of PrimeVue:
[Vue warn]: Property "$primevue" was accessed during render but is not defined on instance.

Trying to use FileUpload in my component:
<template>
  <FileUpload name="demo[]" url="" @upload="onUpload" :multiple="true" :maxFileSize="1000000">
    <template #empty>

Drag and drop files to here to upload.

    </template>
  </FileUpload>
</template>

The error only occurs, when I try to use FileUpload, if I remove it, the component works. FileUpload and PrimeVue are imported like they should, in the main.js:
import {createApp} from 'vue'
import router from "./router";
import store from "./store";
import PrimeVue from "primevue/config";
import PrimeIcons from "primevue/config";
import App from "./App";

const app = createApp(App);

app.use(
    router,
    PrimeVue,
    PrimeIcons,
    store
)

import 'primevue/resources/primevue.min.css'
import 'primeflex/primeflex.css'
import 'primeicons/primeicons.css'
import 'primevue/resources/themes/bootstrap4-dark-purple/theme.css'

import Card from "primevue/card";
import Menubar from "primevue/menubar";
import FileUpload from "primevue/fileupload";

app.component('Card', Card)
app.component('Menubar', Menubar)
app.component('FileUpload', FileUpload)

app.mount('#app')

What I tried so far
I searched this issue, but the only exact match for this error is an old closed issue on GitHub regarding the Calendar component: Issue #808. The error in this issue was caused because of the breaking change with the new PrimeVue API. This should not be my case, because it was introduced with V3.1 and I´m using V3.7.
In case the version is the problem I tested different versions of PrimeVue, like 3.1, 3.2, 3.3 but the error still shows. Thats why the actual dependencie is still the latest:
"primevue": "^3.7.0"

Maybe there is an already existing solution on SO or Google, but either my english is to bad to understand or I´m still to fresh at Vue.js to comprehend the problem.
Thanks in advance!

A: Your usage of app.use() is incorrect:
app.use(
    router,
    PrimeVue,
    PrimeIcons,
    store
)

app.use() takes only two arguments:

*

*first argument: the Vue plugin

*second argument: the plugin options

Also, PrimeIcons is not a plugin, so that should not be passed to app.use().
Solution
Pass each plugin individually to app.use():
app.use(router)
   .use(PrimeVue)
   //.use(PrimeIcons)   // not a plugin
   .use(store)


text:
Q: How can we use Martingales to identify an unknown particle? Suppose there is a particle in a box. We  are interested in identifying what type of particle it is, but are not allowed look inside the box. All we can do is observe the particles that are entering the box and how their behaviour changes as they exit.  For example if a proton enters the box and
leaves with it's trajectory bent towards the centre of the box we get some evidence that the unknown particle is negatively charged. Assume the order of incoming particles is deterministic but unknown in advance.
All exit behaviour is subject to random fluctuation. So it's a possible a proton will be bent away from the centre of the box by a negatively-charged particle. However we know the parameters of the random fluctuations for each type of entering particle. For example the means and subgaussian proxies of all possible interactions. So for example if a series of protons enters and is bent towards the centre, we can compute a confidence with which the unknown particle is negative.
Mathematically we can reduce this to a seres of random varaiables $X_1,X_2,\ldots, X_N$ with known proxies $\sigma_1^2,\sigma_2^2,\ldots, \sigma_N^2$ and mean $1$ in case the unknown particle is positive charge, and mean $0$ otherwise.
The optimal way to combine all the data after $N$ observations is using the  linear combination $Y_N = \sum_i \alpha_i X_i$ for $\alpha_i = \frac{1/\sigma_i^2 }{\sum_j 1/\sigma_j^2}$. This gives $Y_N$ with subgaussian proxy $\Sigma_N = \sum_i \sigma_i^2$. Then we can guess positive charge if   $Y_N > 1/2$ and negative if $Y_N \le 1/2$. The subgaussian proxy says the guess is correct with probability $O(e^{-K \Sigma_n})$ for some fixed $K >0$.
So far so good. But what if we are instead interested in tail bounds for the guesses. In other words we want to bound the probability all the guesses on turns $m,m+1,\ldots, N$ are correct?
This is easy if for example all $\sigma_i^2 = c$. In that case the linear combination is just $Y_n = \frac{X_1 + \ldots + X_n}{n}$ and the guess  has accuracy $O( e^{-K n})$ which we can integrate to get $O(\frac{e^{-K m}}{K})$ for the tail.
Following this approach we could try to sum up $e^{-K \Sigma_n}$ for $n= m,m+1,\ldots, N$. But this raises at least one silly problem. Namely if some $\sigma_n^2 = \infty$ say (or in other words particle $n$ provides no information) then it makes sense to assign zero coefficient to that random variable, and get  $Y_{n} = Y_{n-1}$, but no sense to include both terms $e^{-K \Sigma_{n-1}}$ and $e^{-K \Sigma_n}$ in the sum, since guesses $n-1$ and $n$ are the same.
This particular silly example can be remedied by just ignoring all bad particles, for example ignore all neutrino-type particles. The interesting case is when there are particles that provide a small yet nonzero amount of information, and we want to include them in our guesses in a way that improves the theoretical bounds rather than damages them.
Informally I would suspect that if sample $n$ provides very little information we will give it a very small coefficient and a good guess on turn $n-1$ increases the likelihood of a good guess on turn $n$. I wonder is there a way to make this formal?


text:
Q: Error reading data from MySQL table 1227 (42000): Access denied; you need (at least one of) the SYSTEM_USER privilege(s) for this operation I am connected to the MySQL database in Python using the (MySQL Connector) Python module in jupyter notebook. I can perform operations for example creating a table or reading data from a table. In the following code, I want to create a view but before creating a view first I want to make sure that the database doesn't have the view if it has I want to drop it.
import mysql.connector as con
try:
    connection = con.connect(host = 'localhost',
                             database='mydb',
                             user='***',      # my user name is also correct
                             password='****') # my password is correct

    create_view_query = """
    drop view if exists chicago_public;
    create view chicago_public as
    select NAME_OF_SCHOOL as school_name,Safety_Icon as afety_rating,
    Family_Involvement_Icon as family_rating,
    Environment_Icon as environment_rating,
    Instruction_Icon as instruction_rating,
    Leaders_Icon as leaders_rating,
    Teachers_Icon as teacher_rating
    from CHICAGO_PUBLIC_SCHOOLS;
     """

    cursor = connection.cursor()
    cursor.execute(create_view_query)
    print("View created succussfully.")

except con.Error as e:
    print("Error reading data from MySQL table",e)
finally:
    if connection.is_connected():
        connection.close()
        cursor.close()
        print("MySQL connection is closed")

But when I run this query from jupyter notebook I am getting the following error.

Error reading data from MySQL table 1227 (42000): Access denied; you
need (at least one of) the SYSTEM_USER privilege(s) for this operation

Please help me with this how to solve this problem.
Thank you in advance.

A: You have multiple queries so you need to use
cursor.execute(create_view_query,(), multi=True)

A: Use CREATE OR REPLACE to atomically replace the view.
create_view_query = """
create or replace view chicago_public as
...

So you don't need to enable multi=True for the query.


text:
Q: Associativity of function call operator in C I was going through the topic of associativity of C operators.
There I came across this fact that the function call operator () has a left to right associativity. But associativity only comes to play when multiple operators of the same precedence occur in an expression. But I couldn't find any example involving function call operator where associativity plays a crucial role.
For example in the statement a = f(x) + g(x);, the result depends on the evaluation order and not on the associativity of the two function calls.
Similarly the call f(g(x)) will evaluate function g() first and then the function f(). Here we have a nested function call and again associativity doesn't play any role.
The other C operators in this priority group are array subscript [], postfix ++ and postfix --. But I couldn't find any examples involving a combination of these operators with () where associativity plays a part in expression evaluation.
So my question is does the associativity of function call being defined as left to right affect any expression in C? Can anyone provide an example where the associativity of function call operator () does matter in expression evaluation?

A: Here is an example, where left-right associativity of function call operator matters:
#include <stdio.h>

void foo(void)
{
    puts("foo");
}

void (*bar(void))(void) // bar is a function that returns a pointer to a function
{
    puts("bar");
    return foo;
}

int main(void)
{
    bar()();

    return 0;
}

The function call:
bar()();

is equivalent to:
(bar())();

A: The statement that function application associates to the left is entirely redundant in the C language definition. This "associativity" is implied by the fact that a function argument list appears right of the function expression itself and must be enclosed in parentheses. This means that for a given function expression, there can never be any doubt about the extent of its argument list: it extends from the obligatory opening parenthesis after the function expression to the matching closing parenthesis.
The function expression (which often is just an identifier, but may be more complicated) might itself be a (bare) function call, as in f(n)(1,0). (Of course this requires the value returned by f(n) to be something that can then be called with argument list (1,0), for which C has some possibilities and C++ a lot more, but these are semantic considerations that only come to play after parsing, so they should be ignored for the associativity discussion.) This means the syntax rule for function calls is left-recursive (the function part can itself be a function call); this may be formulated by saying "function calls associate to the left", but the fact is obvious. By contrast the right part (argument list) cannot be a (bare) function call because of the required parentheses, so there cannot be right recursion.
For instance consider (a)(b)(c) (where I put in redundant parenthesis in order to suggest symmetry and possible ambiguity). Here in itself (b)(c) might be taken to be the call of b (redundantly parenthesised) with argument c; however such a call cannot be construed to be the argument of a, since that would require additional parentheses as in (a)((b)(c)). So without any mention of associativity, it is clear that (a)(b)(c) can only mean that a is called with argument b, and the resulting value is called with argument c.

A: In addition to @GrzegorzSzpetkowski's answer, you can also have the following:
void foo(void) { }

int main(void) {
    void (*p[1])(void);
    p[0] = foo;
    p[0]();
    return 0;
}

This creates an array of function pointers, so you can use the array subscript operator with the function call operator.


text:
Q: Regression with flexible functional form I am assuming a model of the form
$$Y_i=\alpha+\beta X_i+g(\mathbf{Z}_i)+\epsilon_i,$$
here $\mathbf{Z}_i$ is an $m$ dimensional vector and $\epsilon_i$ is i.i.d. white noise. I would like to establish whether $\beta$ is statistically significant based on my data without taking a strong stance of the form of $g$. What type methods are usually applied for this type of problem?

A: This sounds like a great job for GAMs via the mgcv package.  Use a penalized smoothing spline to estimate $g$ and add an additive effect of $X$.  The model would look like gam(y ~ x + s(z).
library(mgcv)
#> Loading required package: nlme
#> This is mgcv 1.8-31. For overview type 'help("mgcv-package")'.

z = rnorm(1000)
x = rnorm(1000)
y = 2 + 0.25*x + sin(pi*z) + rnorm(1000, 0, 0.3)
d = data.frame(x, y, z)

model = gam(y ~ x + s(z), data = d)

summary(model)
#>
#> Family: gaussian
#> Link function: identity
#>
#> Formula:
#> y ~ x + s(z)
#>
#> Parametric coefficients:
#>             Estimate Std. Error t value Pr(>|t|)
#> (Intercept) 1.968566   0.009514  206.91   <2e-16 ***
#> x           0.262245   0.009888   26.52   <2e-16 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Approximate significance of smooth terms:
#>        edf Ref.df     F p-value
#> s(z) 8.977      9 625.1  <2e-16 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> R-sq.(adj) =  0.865   Deviance explained = 86.6%
#> GCV = 0.091407  Scale est. = 0.090404  n = 1000

Created on 2020-10-20 by the reprex package (v0.3.0)

A: This model is a partially linear regression models, and in your case, $g(Z)$ is a nuisance parameter. See page 62 of this link for a primer on the subject. Of especial note in application is Robinson's Transformation (Section 7.7 on page 62 of the linked file).
Inference is particularly tricky in these settings, since it's hard to say anything about the asymptotics of $g(Z)$ in a general sense, so you typically need to assume it lies in some space. A recent very general approach to inference was proposed by Chernozhukov et al. (2017) if of interest.


text:
Q: Java boolean not being set to true My code takes a user inputted string and returns the number of words as well as the first word. When the user inputs an empty string I don't want "Your string has x words in it" or "The first word is x" to display so I created a boolean but the boolean is not being set within the method I tried to set it to true in. Any Help I can get on why or how to fix it would be great. Thanks!
public static void main(String[] args){
    boolean empty = false;
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a string: ");
    String str = in.nextLine();

    if (empty == false) {
        System.out.println("Your string has " + getWordCount(str)+" words in it.");
        System.out.println("The first word is: " + firstWord(str));
    }
}

public static String firstWord(String input) {

    for(int i = 0; i < input.length(); i++)
    {
        if(input.charAt(i) == ' ')
        {
            return input.substring(0, i);
        }
    }

    return input;
}

 public static int getWordCount(String str){
       int count = 0;

       if(str != null && str.length() == 0){
           System.out.println("ERROR - string must not be empty.");
           empty = true;
       }

       else if (!(" ".equals(str.substring(0, 1))) || !(" ".equals(str.substring(str.length() - 1)))){

            for (int i = 0; i < str.length(); i++){

                if (str.charAt(i) == ' '){
                    count++;
                }
            }
            count = count + 1;
        }
    return count;
    }
 }

A: You have to re-think your logic here (see below snippet):

*

*First off: you don't need the empty variable

*You can know if the "word" is empty by calling the getWordCount method and store the result in a variable (wordCount?). Then you can check if there is at least one word by doing wordCount > 0.

The snippet:
    public static void main(String[] args){
        // boolean empty = false;           // --> not needed
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = in.nextLine();
        final int wordCount = getWordCount(str);

        if (wordCount > 0) { // show message only if there is at least one word
            System.out.println("Your string has " + wordCount +" words in it.");
            System.out.println("The first word is: " + firstWord(str));
        }
    }

    public static String firstWord(String input) {
        // .. code omitted for brevity
    }

    public static int getWordCount(String str){
        int count = 0;

        if(str != null && str.length() == 0){
            System.out.println("ERROR - string must not be empty.");
            // empty = true; -->  not needed
        }

        // ... code omitted for brevity
        return count;
    }

A: you just need to change the place if for the sake of variable visibility.
public static void main(String[] args) {
        boolean empty = false;
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = in.nextLine();

        if (str != null && str.length() == 0) {
            System.out.println("ERROR - string must not be empty.");
            empty = true;
        }

        if (empty == false) {
            System.out.println("Your string has " + getWordCount(str) + " words in it.");
            System.out.println("The first word is: " + firstWord(str));
        }
    }

public static String firstWord(String input) {

        for (int i = 0; i < input.length(); i++) {
            if (input.charAt(i) == ' ') {
                return input.substring(0, i);
            }
        }

        return input;
    }

public static int getWordCount(String str) {
        int count = 0;

        if (!(" ".equals(str.substring(0, 1))) || !(" ".equals(str.substring(str.length() - 1)))) {

            for (int i = 0; i < str.length(); i++) {

                if (str.charAt(i) == ' ') {
                    count++;
                }
            }
            count = count + 1;
        }
        return count;
    }

A: If you would really want to use a boolean, try creating a boolean method using a string parameter, which returns true only if the string is not empty, then assign the boolean return type to an empty boolean variable.


text:
Q: How to consume a storage queue from data factory pipeline? I am working on a project where I need to consume the entries of the storage queue from a data factory pipeline.
Files will be uploaded to a blob storage which triggers a azure function. This azure function writes into a storage queue. Now I want to consume the entries of this storage queue. Due to the fact that the storage queue provide a rest api to consume data, I can use a web client in the azure data factory which can be scheduled every few minutes. But I would prefere a more direct way, so that when the storage queue has been filled, my pipeline should be starting.
I am quite new to the azure world, so now I am searching for solution. Is there a way to subscribe to the storage queue? I can see that there is the possibilty to create custom triggers in the data factory how can I connect to a storage queue there? Or is there another way?

A: Thank you @Scott Mildenberger for pointing out in the right direction. After taking the inputs and reproducing from my end, this was working when I used Queue Trigger called When a specified number of messages are in a given queue (V2) where we can specify the Threshold of the Queue to get the flow triggered. Below is the flow of my Logic App.

RESULTS:
In Logic App

In ADF


text:
Q: EntityFramework ConnectionString utf8 I want to add utf8 support to my Entity Framework database application (sql server 2008 r2)
I think I need to add the charset to the connectionString.
This is how my connectionString works (anonymized, of course)
<add name="MyContainer" connectionString="metadata=res://*/MyDatabase.csdl|res://*/MyDatabase.ssdl|res://*/MyDatabase.msl;provider=System.Data.SqlClient;provider connection string="Data Source=myserver\instancename;Initial Catalog=MyCatalog;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD;MultipleActiveResultSets=True;"" providerName="System.Data.EntityClient" />

I had a look at connectionstrings.com, but I found nothing regarding utf8.
I tried adding charset=utf8, but that doesn't do the trick.
 <add name="MyContainer" connectionString="metadata=res://*/MyDatabase.csdl|res://*/MyDatabase.ssdl|res://*/MyDatabase.msl;provider=System.Data.SqlClient;provider connection string="Data Source=myserver\instancename;Initial Catalog=MyCatalog;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD;MultipleActiveResultSets=True;charset=utf8;"" providerName="System.Data.EntityClient" />

Results in a System.Data.EntityException:
{"The underlying provider failed on ConnectionString."}
{"Keyword not supported: 'charset'."}
Question:
How do I set the charset to utf8 in the connectionString? Or is utf8 enabled by default?

A: Usage of unicode is defined by variable or column type. Char and varchar are non-unicode and nchar and nvarchar are unicode (UCS-2).
There are also collations which define code page for char and varchar columns and the way in which strings are compared and ordered. Each database has a default collation and each column or variable can have explicitly defined other collation.
Character set is not configured by connection.


text:
Q: Use of made up words in writing In writing, mainly seen in novel writing, how should we put a word that doesn't exist?
for example, "We're screwed beyond levels of screwedness."
Please don't tell me that's too unprofessional and I need to change the sentence with a substitute word that exists. I've seen made up words in some novels, but I can't remember how they're written if they're italic or have a hyphen to separate the part that makes the word nonexistent (screwed-ness).

A: This is a question of style, not grammar.  Grammar doesn't require you do anything to demarcate the word.  Look at all the words Lewis Carroll invented, for example:

'Twas brillig, and the slithy toves did gyre and gimble in the wabe;
  all mimsy were the borogoves, and the mome raths outgrabe.

You'll note Carroll didn't do anything special to introduce his nonce words but just let them stand in standard text like they were any other normal word.
That said, you could italicize it, like you said.  That's something people do sometimes.  You might also use scare quotes, because that's one of the things they are for – to signal you're using what is in quotes "in a non-standard, ironic, or otherwise special sense."