text:
Q: Writing a code for the game to be restarted using a JoptionPane in java While I was writing the code for the quiz game, I used a JOptionPane setting it to click a yes and allowing the game to restart. With the below code, I was able to get a new window showing the result and giving options to wether cohoe between to reset the game or to exit.  This is the code down below and by adding 'frame.setVisible(isEnabled));', I were able to get rid of the new window by clicking the reset button but the game window only showed me the very last page of the quiz, not allowing me to do the quiz again. I want the game to be started at its very first page , what should I do in this case?
  for (int i = 0; i < question.getAnswers().length; i++) {
        answersButtons[i] = new JButton(String.valueOf((char) ('A' + i))); // This will set the buttons text to A, B, C, D
        answersButtons[i].addActionListener(e -> { //ActionListener using Java 8 lambdas
            if (e.getActionCommand().charAt(0) - 'A' == question.getCorrectAnswer() - 1) { //Here we check if the button clicked was the one with the correct answer, converting the text from A-D to 0-3 and compare it to the index - 1 from the question model
                correctAnswers++; //Increase the correctAnswer + 1
                answerLabels[e.getActionCommand().charAt(0) - 'A'].setBackground(Color.GREEN); //Set the background color to green if it was correct
            } else {
                answerLabels[e.getActionCommand().charAt(0) - 'A'].setBackground(Color.RED); //Or red otherwise
            }
            if (currentQuestion == totalQuestions - 1) { //If we reach the end of questions, show the results screen
                int input = JOptionPane.showConfirmDialog(pane, new ResultsPane(correctAnswers, totalQuestions), "Results", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null);

                if (input == JOptionPane.YES_OPTION) {

                    frame.setVisible(isEnabled());
                    frame.setVisible(true);
                    //Reset everything and show your GUI again
                } else {
                    frame.dispose(); //If user says they don't want to retry, dispose the frame.
                }
            } else {
                timer.start(); //Start the timer that will display the results for half a second.
            }
        });
    }

Full code below :
     import java.awt.BorderLayout;
     Import java.awt.CardLayout;
     import java.awt.Color;
     import java.awt.Dimension;
     import java.awt.FlowLayout;
      import java.awt.Font;
      import java.awt.Window;
     import java.awt.event.ActionEvent;
       import java.awt.event.ActionListener;
   import java.text.SimpleDateFormat;
   import java.util.ArrayList;
   import java.util.List;

 import javax.swing.BoxLayout;
 import javax.swing.JButton;
 import javax.swing.JComponent;
 import javax.swing.JFrame;
 import javax.swing.JLabel;
 import javax.swing.JOptionPane;
 import javax.swing.JPanel;
 import javax.swing.RootPaneContainer;
 import javax.swing.SwingConstants;
 import javax.swing.SwingUtilities;
 import javax.swing.Timer;
 import javax.swing.UIManager;

  // main class, contains the CardLayout
  public class MainGamw {

    int c = 15;
    private JFrame frame;

    private QuestionPane[] cards;
    private JPanel pane;
    private CardLayout cl;

    private JLabel timerLabel;
    private JLabel timeNumber;

    private List<QuizQuestion> questions;
    private Timer temporaryTimer;

    public static void main(String[] args) {
        // place the program on the EDT using Java 8 lambdas
        SwingUtilities.invokeLater(new MainGamw()::createAndShowGUI);
    }

private void createAndShowGUI() {
    frame = new JFrame(getClass().getSimpleName()); //the class name and set it as the frame's title
    frame.getContentPane().setBackground(new Color(204,229,255));
    frame.setPreferredSize(new Dimension(600,350));
    frame.pack();

    cl = new CardLayout(); //Create a new CardLayout

    pane = new JPanel(cl); //Set the CardLayout to this JPanel
    pane.setBackground(new Color(204,229,255));
    pane.setVisible(true);

    temporaryTimer = new Timer(500, event -> { //The timer to show the result of the answer for half second before switching to the new one.
        c--;
        timeNumber.setText(String.valueOf(c));
        cl.next(pane); //This moves the CardLayout to the next one

        temporaryTimer.stop(); //We stop this timer when we switch to the next card.
    });

    generateQuestionsAndAnswers(); //We populate the model of questions with their answers here.

    cards = new QuestionPane[questions.size()];
    for (int i = 0; i < cards.length; i++) {
        cards[i] = new QuestionPane(questions.get(i), i, pane, cl, cards.length, frame, temporaryTimer); //We create a new QuestionPane and send some information as parameters

        pane.add(cards[i], "question" + i); //We add the card to the CardLayout pane
    }

    timerLabel = new JLabel("  Time: ");
    timerLabel.setFont(new Font("PT Serif",Font.PLAIN,16));

    timeNumber = new JLabel();
    timeNumber.setFont(new Font("PT Serif",Font.PLAIN,16));
    timeNumber.setText(String.valueOf(c));

    UIManager.put("OptionPane.okButtonText", "Start Quiz"); //We change the "OK" from the JOptionPane button to "Start Quiz"
    int option = JOptionPane.showConfirmDialog(frame, new JLabel("Click button to start quiz"),
                                            "Welcome", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null);
    if (option == JOptionPane.OK_OPTION) {

        //Start your timer for the first question
    }

    frame.add(pane); //We add the CardLayout pane to our JFrame's CENTER position
    frame.add(timerLabel, BorderLayout.SOUTH); //And the timerLabel at the bottom
    frame.add(timeNumber, BorderLayout.WEST);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true); //
}

private Object size(int i, int j) {
    // TODO Auto-generated method stub
    return null;
}

  //We create an ArrayList of QuizQuestion that each has their own    question, the possible answers and the correct answer (index + 1)
private void generateQuestionsAndAnswers() {
    questions = new ArrayList<>();
    questions.add(new QuizQuestion("Select the official name of the coronavirus.", new String[] {"COVID-19","Sars-CoV-2","Zaire ebolavirus","Influenza"}, 1));
    questions.add(new QuizQuestion("When did the corona virus first ecountered?", new String[] {"2018","2020","2017","2019"}, 4));
    questions.add(new QuizQuestion("What is the percentage of people recovering from the coronavirus?", new String[] {"63%","71%","80%","76%"}, 3));

    questions.add(new QuizQuestion("Which below is NOT the symptom of coronavirus?", new String[] {"Fever","Blurred vision","Dry Cough","Nasal Congestion"}, 2));
    questions.add(new QuizQuestion("Which part of the human body does the coronavirus attach itself to?", new String[] {"Red Blood Cells", "Antigens", "White Blood Cells", "Ace-2 recpetors in the airways"}, 4));
    questions.add(new QuizQuestion("How many hour can the coronavirus survive on plastic and stainless steel surfaces?", new String[] {"4-8 hours", "72 hours and more", "45-60 hours", "90 hours and more" }, 2));

    questions.add(new QuizQuestion("Which human organs in the body does the coronavirus attack?", new String[] {"Liver", "Lungs", "Heart", "Kidney" }, 2));
    questions.add(new QuizQuestion("How large is the coronavirus?", new String[] {"8000 billionths of metre in diameter", "800 billionths of metre in diameter","80 billionths of metre in diameter","8 billionths of metre in diameter" }, 3));
    questions.add(new QuizQuestion("Which is a safe distance to stay apart from people? ", new String[] {"3 feet(1 meter)", "2 feet(60 cm)", "1 foot (30cm)", "4.2 feet(1.3 meter)"}, 1));

    questions.add(new QuizQuestion("Who has the highest risk of getting infected by coronvirus?", new String[] {"Children", "Pregnant Women", "People over 60 years of age", "30-40 years agr of men"}, 3));
    questions.add(new QuizQuestion("When should face masks be worn?", new String[] {"Public Transport", "Confined or Crowed spaces", "Small restaurants or shops", "All of the above"}, 4));
    questions.add(new QuizQuestion( "Which is more effective for removing the coronavirus from your hands?", new String[] {"Soap and water", "Alcohol-based hand sanitiser","Detergent", "Face cleanser"}, 1));

    questions.add(new QuizQuestion("Which industry includes workers with increased exposure-risk?", new String[] {"Health care", "Airline operations", "Waste management", "All of the above"}, 4));
    questions.add(new QuizQuestion("What is the period of quartine?", new String[] {"21 days","7 days", "14 days", "6 days"}, 3));
    questions.add(new QuizQuestion("What is the name of the city where coronavirus was first detected?", new String[] {"Wuhan", "Hubei", "Hunan","Shanghai"}, 1));
}
 }

  @SuppressWarnings("serial")
   class ResultsPane extends JPanel { //This is a class that will   create a simple JPanel with vertical alignment to add the number of correct answers, accuracy and a text for the user if they want to retry
public ResultsPane(int correctAnswers, int totalQuestions) {
    setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    float percentage = ((float) (correctAnswers) / (float) (totalQuestions)) * 100;

    add(new JLabel("Correct Answers: " + correctAnswers + " / " +   totalQuestions));
    add(new JLabel("Accuracy: " + percentage + "%"));
    add(new JLabel("Want to Retry?"));
   }
 }

@SuppressWarnings("serial")
class QuestionPane extends JPanel { //This is the pane in which each   card will be displayed
private JButton[] answersButtons; //Array of buttons for the answers instead of 4 individual buttons

private JLabel questionLabel;
private JLabel questionNumber;
private JLabel[] answerLabels; //Same for the labels

private static int correctAnswers = 0; //This is static to count all the correct answers in all the instances

 public QuestionPane(QuizQuestion question, int currentQuestion, JPanel pane, CardLayout cl, int totalQuestions, JFrame frame, Timer timer) { //Probably this isn't the most elegant solution to send multiple objects as parameters here, as it makes the program tightly coupled.
    setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));

    questionNumber = new JLabel("Question " + (currentQuestion + 1), SwingConstants.LEFT);
    questionNumber.setFont(new Font("PT Serif",Font.BOLD,16));
    questionNumber.setHorizontalAlignment(JLabel.LEFT);

    //We set the question number on top and center the text

    questionLabel = new JLabel(question.getQuestion());
    questionLabel.setFont(new Font("PT Serif",Font.BOLD,15));
    questionLabel.setAlignmentX(LEFT_ALIGNMENT);

    // We set the question text to this label
    answerLabels = new JLabel[question.getAnswers().length];

    //We create our array of 4 labels and 4 buttons below

    answersButtons = new JButton[question.getAnswers().length];

    for (int i = 0; i < question.getAnswers().length; i++) {
        answersButtons[i] = new JButton(String.valueOf((char) ('A' + i))); // This will set the buttons text to A, B, C, D
        answersButtons[i].addActionListener(e -> { //ActionListener using Java 8 lambdas
            if (e.getActionCommand().charAt(0) - 'A' == question.getCorrectAnswer() - 1) { //Here we check if the button clicked was the one with the correct answer, converting the text from A-D to 0-3 and compare it to the index - 1 from the question model
                correctAnswers++; //Increase the correctAnswer + 1
                answerLabels[e.getActionCommand().charAt(0) - 'A'].setBackground(Color.GREEN); //Set the background color to green if it was correct
            } else {
                answerLabels[e.getActionCommand().charAt(0) - 'A'].setBackground(Color.RED); //Or red otherwise
            }
            if (currentQuestion == totalQuestions - 1) { //If we reach the end of questions, show the results screen
                int input = JOptionPane.showConfirmDialog(pane, new ResultsPane(correctAnswers, totalQuestions), "Results", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null);

                if (input == JOptionPane.YES_OPTION) {

                    frame.setVisible(isEnabled());
                    frame.setVisible(true);
                    //Reset everything and show your GUI again
                } else {
                    frame.dispose(); //If user says they don't want to retry, dispose the frame.
                }
            } else {
                timer.start(); //Start the timer that will display the results for half a second.
            }
        });
    }

    add(questionNumber, BorderLayout.EAST); //Add the question number
    add(questionLabel, BorderLayout.EAST); //The question text

    for (int i = 0; i < question.getAnswers().length; i++) {
        JPanel answerPane = new JPanel(new FlowLayout(FlowLayout.LEFT)); //Create a new JPanel for each label and button and make them left aligned

        answerPane.add(answersButtons[i]); //Add every button
        answerLabels[i] = new JLabel(question.getAnswers()[i]);     //Create a new label with each answer's text
        answerLabels[i].setOpaque(true); //Make them opaque (for the background colors later)
        answerPane.add(answerLabels[i]); //And add them to the pane

        add(answerPane); //Then add the pane to the wrapping pane
    }
}
}

 //A simple model for your questions.
 class QuizQuestion {
private String question;
private String[] answers;
private int correctAnswer;

public QuizQuestion(String question, String[] answers, int correctAnswer) {
    super();
    this.question = question;
    this.answers = answers;
    this.correctAnswer = correctAnswer;
}

public String getQuestion() {
    return question;
}

public void setQuestion(String question) {
    this.question = question;
}

public String[] getAnswers() {
    return answers;
}

public void setAnswers(String[] answers) {
    this.answers = answers;
}

public int getCorrectAnswer() {
    return correctAnswer;
}

public void setCorrectAnswer(int correctAnswer) {
    this.correctAnswer = correctAnswer;
}
}

A: If you want to restart the game with a new JFrame instance, following code will help:
if (input == JOptionPane.YES_OPTION) {
    frame.dispose();

    MainGamw mainGame = new MainGamw();
    mainGame.createAndShowGUI(); // Make sure you change method access to public

} else {
    frame.dispose(); //If user says they don't want to retry, dispose the frame.
}

If you want to restart your game, with the existing JFrame instance, you need to modify your code slightly:

*

*Create the JFrame separately (you may keep it as it is)

*Separate the creation of child components of the JFrame (Cards, Panels etc) in a different method. Pass the JFrame instance as parameter.

*Write following code, at result Confirm Dialog:
if (input == JOptionPane.YES_OPTION) {
    frame.getContentPane().removeAll();
    // Call the method as described #2

} else {
    frame.dispose(); //If user says they don't want to retry, dispose the frame.
}


text:
Q: How to get more detailed error messages from net.ssh.authentication Ruby I am trying to view detailed error messages from an SSH server
what I have:

require 'rubygems'
require 'net/ssh'
require 'sshkey'
k = SSHKey.generate(
  type:       "RSA",
  bits:       2048
)
begin
Net::SSH.start("x.x.x.x","username", :keys=>[k.public_key], :verbose => Logger::DEBUG, :auth_methods => ['publickey']) do |ssh|
   end
  rescue SocketError
    puts "Host name cannot be resolved."
    strBypass = true
  rescue Net::SSH::AuthenticationFailed
    puts "  Authentication failure"
  end
I am particularly looking for a 'SSH2_MSG_USERAUTH_FAILURE' response from the ssh server.
Please help

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apposition at the end of sentence I think in the following sentence I used apposition at the end of sentence, I would like to know is it a correct way to introduce an apposition?

If  this rule be applied on the elements of the page, all such elements will be removed, regardless of their locations in the page, even if they be inside the main content.


text:
Q: django-admin-tools markup problems I try to install admin-tools for django.
I've got strange css and it's evident that something is wrong. But what? Google and css analyzing didn't help.
Screenshot
Thanks!
Update and solution:
I did the homework and solved the problem. What I got:
When I add admin-tools.theming, base.css is missing. The reason is wrong path. Instead of /static/admin/css/base.css it is /admin-media/css/base.css. "admin-media" was my admin media prefix. I left it when I tried to set up my apache server and then I changed static path.
So, it was necessary only to define right admin media prefix as "/static/admin/"

A: Firebug is your friend. Install it in Firefox (or use Firebug Lite in Chrome). Go to your page, hit F12, click the Element Selection Tool (a blue box with an arrow pointing into it in the upper right of the Firebug pane), then click on the offending item. On the left you will see all sorts of good style info including file and line number, and (if you scroll down) all of the style rules that were overridden by one file or another.
Enlightenment soon follows.
If you still have problems, update your question with a link to the live page with the problem so that we can go look at it (screenshots are dead pixels).

A: I too had the same issue, but digging deep into those issues i found out that the 'django-admin-tools' version which i used is not compatible with the django version (1.4).  That means the django-admin-tools have undergone many changes to accommodate modifications made in Django.  Since there is no package created for the latest source code of django-admin-tools, usage of 'easy_install' and 'pip' will always fetch the older version.
So the solution is to download the latest source code from here
https://bitbucket.org/izi/django-admin-tools/downloads
https://bitbucket.org/izi/django-admin-tools/get/tip.zip
and installing them by using 'setup.py install' command.


text:
Q: How can I insert background image in my java desktop application? I wanted to add set Background in my attached application, but it's not working out correctly for me. I've attached the whole source code + a screenshot of how I wanted the background to be in my application. Can anyone help me with this?
Screenshot:

Source Code (Specifically GUI Menu)

A: I'm not going to go through all your source - but it sounds like you want to set a background image on a panel.
You do that by overriding the panels paint code.
@Override
protected void paintComponent(Graphics grphcs) {
    grphcs.drawImage(background, 0, 0, getWidth(), getHeight(), null);
}

Where background is:
private final Image background;

and in your constructor:
    background = ImageIO.read(getClass().getResourceAsStream("FILENAME.jpg"));


text:
Q: "He had had his nap" or "he had his nap"? I am reading Jonathan Franzen's The Corrections, and I came across this sentence:

He'd had his nap and there would be no local news until five o'clock.

Why did Franzen choose to write the sentence using the past perfect instead of the simple past? My understanding of past perfect is that it is only used to denote an event in the past that occurred before another event. Should I consider the "local news until five o'clock" as that latter event?
I know that the past perfect subjunctive of "have" is "had had," but I do not believe that he is conveying that mood.

A: You need the larger context:

Three in the afternoon was a time of danger in these gerontocratic suburbs of St. Jude. Alfred had awakened in the great blue chair in which he'd been sleeping since lunch. He'd had his nap and there would be no local news until five o'clock. Two empty hours were a sinus in which infections bred.

Reference Time for this past perfect is introduced at the beginning of the paragraph: three in the afternoon. At some time before that Alfred had awakened; he had had his nap, so now he had no mindless activity left to occupy the two empty hours between Reference Time, three o'clock, and the next mindless activity, the local news, at five o'clock.

A: I personally do not think it makes sense without the wider context.  The narrative is in the past, but the nap was at earlier time than the wider context so the 'had had' shows that at that time in the past the nap had already happened and finished.


text:
Q: simple async function in javascript I'm playing with async/await and with the code below, shouldn't response be empty or null until the setTimeout in the response const has finished after 5 seconds? and shouldn't response return xyz instead of 1?

async function test() {
  try {
    const response = await setTimeout(
      function() {
        const obj = {};
        obj.text = "xyz";
        console.log('should console log after 5 seconds')
        return obj;
      },
    5000)

    if (response) {
      console.log(`response is ${response}`)
      console.log(`response.text is ${response.text}`)
    }
  }
  catch(err) {
    console.log(err)
  }
}

test();

A: You have to put a Promise to await the setTimeout().

async function test() {
try {
    const response = await new Promise((resolve) => {
        setTimeout(
            function() {
                const obj = {};
                obj.text = "xyz";
                console.log('should console log after 5 seconds')
                return resolve(obj);
            },
            5000)
    });

    if (response) {
        console.log(`response is ${response}`)
        console.log(`response.text is ${response.text}`)
    }
}
catch(err) {
    console.log(err)
}
}

test();

A: For your code to work as per the expectations, you need to wrap the set timeout in a promise. Check the snippet. Without wrapping it in promise, setTimeout returns value immediately which is the ID value of the timer.

async function test() {
  try {
    const response = await new Promise(function(resolve, reject) {
      setTimeout(
        function() {
          const obj = {};
          obj.text = "xyz";
          console.log('should console log after 5 seconds')
          resolve(obj);
        },
        5000)
    })

    if (response) {
      console.log(`response is ${response}`)
      console.log(`response.text is ${response.text}`)
    }
  } catch (err) {
    console.log(err)
  }
}

test();


text:
Q: How to fit intensity peaks from a image? I have an image that I can convert to a text file / table of intensities. In this image, several regions show higher intensity, i.e., a peak. A peak may be stored in a 10x10 matrix with rows and columns corresponding to the x1, x2 coordinates in the image. Basically my data looks like the two-dimensional normal distribution in the first plot of this pdf. I want to know the center of the peak and the full width half maximum for each of those matrices.
What should be the approach assuming that I can approximate this matrices to a multidimensional Gaussian? I have z, x1 and x2, but I would like to get the regression parameters.

A: What you need to do is fit a nonlinear regression model where the intensity is the response as a function of the x1, x2 coordinates.  The functional form will be the PDF of a multivariate normal.  In R, you can use ?nls to do this.  You can write the function yourself, but for convenience you may prefer to use ?dmvnorm from the mvtnorm package.  Here is a simplified example:
library(mvtnorm)  # for dmvnorm
set.seed(7124)    # this will make the code exactly reproducible
d = expand.grid(x1=1:10, x2=1:10)
i = dmvnorm(as.matrix(d), mean=c(2.5, 3), sigma=rbind(c( 1.0, -0.6),
                                                      c(-0.6,  1.0) ) )
e = rnorm(100, mean=0, sd=0.1)
y = 5 + 40*i + e;  d$y = y

round(matrix(i, nrow=10, ncol=10, byrow=F), 2)  # output omitted
round(matrix(y, nrow=10, ncol=10, byrow=F), 2)  # output omitted

mvn = function(m1, m2, v1, v2, cv12){  # you need this function for nls()
  y = dmvnorm(as.matrix(d[,1:2]), mean=c(m1, m2), sigma=rbind(c(v1,  cv12),
                                                              c(cv12,  v2) ))
  return(y)
}
mod = nls(y~b0+b1*mvn(m1, m2, v1, v2, cv12), d, algorithm="port",
          start=list(b0=mean(y), b1=diff(range(y)),
                     m1=d[which.max(d$y),1], m2=d[which.max(d$y),2],
                     v1=10, v2=10, cv12=0))
summary(mod)
#
# Parameters:
#      Estimate Std. Error t value Pr(>|t|)
# b0    4.99398    0.01112  449.02   <2e-16 ***
# b1   39.27467    0.50379   77.96   <2e-16 ***
# m1    2.49315    0.01129  220.87   <2e-16 ***
# m2    3.00054    0.01143  262.58   <2e-16 ***
# v1    0.96444    0.02354   40.97   <2e-16 ***
# v2    0.99235    0.02332   42.55   <2e-16 ***
# cv12 -0.58553    0.01913  -30.60   <2e-16 ***
# ---
# Residual standard error: 0.1012 on 93 degrees of freedom


text:
Q: SQL Sum total for same value I'm using SQL Server 2008.
This is my data:
column1   columnAmount
-----------------------
  ab           3
  ac           2
  ab           4

So in my query I want to sum the values which are the same in the colum1.
My desired output would be:
column1    columnAmount
----------------------
  ab           7
  ac           2

How can I do this?

A: This is a basic SUM ... GROUP BY
SELECT column1,
       Sum(columnAmount) AS columnAmount
FROM   YourTable
GROUP  BY column1

As the syntax suggests it divides the input into groups (one for each distinct value of column1) and calculates the sum for each group.


text:
Q: query ipaddresses by subnet I have a MS SQLServer 2005 table which includes an ipaddress column, and I would like to count entries by subnet.
Unfortunately the ipaddress column is a varchar with sample data like:
192.168.10.20
10.1.2.3
I think the best approach would be to convert the ipaddress to an integer, and then I could apply the appropriate bitmask.
Are there any suggestions on how to get a string of 4 octets into an integer?

A: To convert a 4 octtet dotted notation to a BIGINT we can do the following.
DECLARE @IP CHAR(15) SET @IP='192.168.123.123'
select (CONVERT(BIGINT, PARSENAME(@IP,1)) +
     CONVERT(BIGINT, PARSENAME(@IP,2)) * 256 +
     CONVERT(BIGINT, PARSENAME(@IP,3)) * 65536 +
     CONVERT(BIGINT, PARSENAME(@IP,4)) * 16777216)
from there it's a pretty simple thing to AND that with 4294967040 (255.255.255.0) to get /24 subnet
Thanks to Less Than Dot for the code.

A: you could also do this by using PARSENAME function as it is show here.


text:
Q: Page numbers in MS word 2007 am trying to insert the page numbers in the word document. The document contains table of content and the document contents. I wanna insert roman numerals to the page numbers before the first chapter n then normal numbers there after, how can I achieve this?

A: What you're looking for is called a section break.
In short... here's what you do.
Before on the page that starts your new numbering, you want to insert a section break.  (Under Page Layout ribon click on Breaks drop-down menu & click on Next Page)
Once the break is inserted... you can then go to your header or footer & add your page numbering.  While in the header/footer Design menu, you will have an option under "Page Number" to "Format Page Numbers..."  From there you can pick a different "style" (roman vs latin... and many others) as well as providing a new "Start at" number.  so the first three pages can be roman number i, ii, iii... and the next section can use latin-numbering starting at 1... and continuing on.
Because it's a section break... you can also add additional stuff before the break and the numbering will auto-adjust down-the-line.


text:
Q: Managing python versions on conda environments I've recently created a new environment following conda's instructions.
I currently installed anaconda3 with python3 as the default in my pc, but now I need to run python2 code so I created the virtual env as:
conda create -n py27 python=2.7 anaconda

But even inside py27, when I run python it uses python3 and not python2.
Is there a way I can change de behavior of the python command so it defults to python2 but only in my py27 virtual environment?
Thanks


text:
Q: Texfield on diffrerent page triggers StreamBuilder I have this StreamBuilder on Page1:
Widget _myFirebaseUser(BuildContext context) {
    return StreamBuilder<FirebaseUser>(
      stream: FirebaseAuth.instance.onAuthStateChanged,
      builder: (context, snapshot) {
        if (snapshot.hasData &&
            snapshot.connectionState == ConnectionState.active) {
          print('-loading user2-');
          FirebaseUser user = snapshot.data;
          if (user == null) {
            return Text('not logged in');
          }
          return ListTile(
            leading: CircleAvatar(
              backgroundImage: NetworkImage(
                user.photoUrl,
              ),
            ),
            title: Text(user.displayName),
            subtitle: Text(user.email),
            trailing: new IconButton(
                icon: new Icon(Icons.exit_to_app),
                highlightColor: Colors.pink,
                onPressed: () {
                   Navigator.of(context).pushNamed('/my-set');
                }),
          );
        }
        return Text("loading");
      },
    );
  }

On Page2 I have this:
TextField(
 controller: inputNewElement,
 decoration: InputDecoration(labelText: "Add Elements"),
 onSubmitted: (elem) {
  print("Changed textfield");
 },
),

When I move to Page2 and edit my TextField I can see the logs from previous page. I have tried StreamBuilder and FutureBuilder with same result.
How can avoid this behaviour?


text:
Q: Is there a JS design pattern to combine N objects into 1 façade object and have code editors know which methods it has? for example suppose I have:
var obj_a = {
  foo: function() {}
}

var obj_b = {
  bar: function() {}
}

How should I declare obj_c to have both methods so that typing obj_c. would popup foo and bar as valid autocomplete options?

A: I understand that you are looking for an IntelliSense equivalent, but if you need to create an obj_c which contains the properties of obj_a and obj_b, you can do so programmatically by using Object.assign:
const obj_c = Object.assign(obj_a, obj_b);

Working Example:

const obj_a = {
  foo: function() {}
}

const obj_b = {
  bar: function() {}
}

const obj_c = Object.assign({}, obj_a, obj_b)

console.log(obj_c);


text:
Q: ORACLE - Get the last record for each hour i have a datetime field, which sometimes it's retrieving me duplicate data, I need one record per hour, for that if the same objectid has 3 records at the same hour example 11 PM I need to take the last record from that hour
example
record 1 11:05 pm
record 2 11:35 pm
record 3 11:55 pm
pick only the record from 11:55 pm, the last record of each hour, could be that objectid has more records in different hours but I need just one record per hour picking the last one with more minutes. anY IDEA?
if i use max value would get just one record per objectid, i need one per hour the last one.
select *
from   prod.WX_RAW
where  trunc(datetimeutc,'DD') = to_date('01-01-2021')
and    objectid=10000355399
and    TEMP_CODE NOT IN ('7','2','3','R','U')
and    OBS_TYPEID IN ('7', '4', '6')
and    REPORTTYPE = 'FM-15'
ORDER BY DATETIMEUTc;

example data:
object id.  datetimeutc                     obstype country code.   wind direction
10000355399 1/1/2021 11:15:00.000000000 PM  7       KCLK    V020    340  N
10000355399 1/1/2021 11:35:00.000000000 PM  7       KCLK    V020    350  N
10000355399 1/1/2021 11:55:00.000000000 PM  7       KCLK    V020    360  N

A: You can use:
SELECT *
FROM   (
  select w.*,
         ROW_NUMBER() OVER (
           PARTITION BY objectid, TRUNC(datetimeutc, 'HH')
           ORDER BY datetimeutc DESC
         ) AS rn
  from   prod.WX_RAW w
  where  trunc(datetimeutc,'DD') = DATE '2021-01-01'
  and    objectid=10000355399
  and    TEMP_CODE NOT IN ('7','2','3','R','U')
  and    OBS_TYPEID IN ('7', '4', '6')
  and    REPORTTYPE = 'FM-15'
)
WHERE rn = 1
ORDER BY DATETIMEUTc;

db<>fiddle here


text:
Q: Why won't springboot talk to Docker MongoDB instance? I had an instance of MongoDB running in Docker which my spring boot application was talking to.
It seems to have inexplicitly stopped working, I'm really at a loss as to what's changed but now my Spring data repositories fail with an authentication error coming back from Mongo.
I am running my SpringBoot application from a launch config in IntelliJ Idea.
Can you spot any obvious issue in this config.... ?
I am able to connect to Mongo express, but no sign of "datastore".
Only thing I can think of is inadvertently changed a version of some dependency (I don't recall doing so), I like to try and stay up to date.
docker-compose
version: "3.8"
services:
  mongodb:
    image: mongo
    container_name: mongodb
    environment:
      MONGO_INITDB_ROOT_USERNAME: mongoroot
      MONGO_INITDB_ROOT_PASSWORD: pass12345
      MONGO_INITDB_DATABASE: datastore
    ports:
      - "27017:27017"
    expose:
      - 27017
    restart: unless-stopped

  mongo-express:
    image: mongo-express
    container_name: mongo-express
    environment:
      - ME_CONFIG_MONGODB_SERVER=mongodb
      - ME_CONFIG_MONGODB_PORT=27017
      - ME_CONFIG_MONGODB_ENABLE_ADMIN=true
      - ME_CONFIG_MONGODB_ADMINUSERNAME=mongoroot
      - ME_CONFIG_MONGODB_ADMINPASSWORD=pass12345
      - ME_CONFIG_BASICAUTH_USERNAME=admin
      - ME_CONFIG_BASICAUTH_PASSWORD=admin123
    depends_on:
      - mongodb
    ports:
      - "8081:8081"
    restart: unless-stopped

spring boot application.properties
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=datastore
spring.data.mongodb.username=mongoroot
spring.data.mongodb.password=pass12345

Error in SpringBoot log:
Invocation of init method failed; nested exception is org.springframework.data.mongodb.UncategorizedMongoDbException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='mongoroot', source='datastore', password=<hidden>, mechanismProperties=<hidden>}; nested exception is com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='mongoroot', source='datastore', password=<hidden>, mechanismProperties=<hidden>}


text:
Q: libreoffice calc not responding Libre Office Calc, 7.3.6.2, is not responding properly. In Ubuntu 22.04.01 LTS it keeps asking me to wait while telling me Libre Office is not responding.
All updates have been done. Besides waiting there is nothing to be done.
Is there a bug?
Ton


text:
Q: How do I make so I can attach an image with a !announce command on discord.js I know my title seems confusing, but simply, I want to make it so when I run an !announce command for discord.js, I want to add an image onto it, and it gets sent with the embed. here's an example.
When I run:
!announce (channel id) (message) THEN i attach an image, it gets sent to the channel with the message and image.
I've already got my code, I've made it so the !announce (Channel id) (message) already works, I need to know how to attach an image on the end, i dont mind the image being a link or an attachment.
Fyi, I have tried to find out how to do this, asking for help and using the discord.js documentation, but so far i've got nothing.
here's my code:
btw, i'm still on discord v12.2
const {MessageEmbed} = require('discord.js');

module.exports = {
    name: 'announce',
    description: "Does announcements in an embed",
    usage: "<channel id> <msg>",
    execute(message, args){
    if(!message.member.permissions.has(["MANAGE_MESSAGES"])) return message.reply("You don't have the required permissions to run this command.")

    let userArray = message.content.split(" ");
       let userArgs = userArray.slice(1);
       let member = message.mentions.members.first() || message.guild.members.cache.get(userArgs[0]) || message.guild.members.cache.find(x => x.user.username.toLowerCase() === userArgs.slice(0).join(" ") || x.user.username === userArgs[0]) || message.member;

       let rChannel = message.guild.channels.cache.get(args [0])
       if(!rChannel)return message.channel.send('Please specify the channel ID. Usage is: ;announce <channelID> <message>')
       let MSG = message.content.split(`;announce ${rChannel.id} `).join("")
       if(!MSG)return message.reply('Please specify a message. Usage is: ;announce <channelID> <message>')
       const embed = new MessageEmbed()
       .setTitle('Announcement')
       .setDescription(`${MSG}`)
       .setImage(message.attachments.first())
       .setFooter(message.author.tag, message.author.displayAvatarURL())
       .setTimestamp(Date.now())
       .setColor(0xA20B31)
       rChannel.send(embed);

    }
}

A: You'll have to check if message.attachments has any attachments by using first() and add the MessageAttachment url to the MessageEmbed.

message.attachments.first() ? embed.setImage(message.attachments.first().url) : "";

const { MessageEmbed } = require("discord.js");

module.exports = {
    name: "announce",
    description: "Does announcements in an embed",
    usage: "<channel id> <msg>",
    execute(message, args) {
        if (!message.member.permissions.has(["MANAGE_MESSAGES"])) return message.reply("You don't have the required permissions to run this command.");

        let userArray = message.content.split(" ");
        let userArgs = userArray.slice(1);
        let member =
            message.mentions.members.first() ||
            message.guild.members.cache.get(userArgs[0]) ||
            message.guild.members.cache.find((x) => x.user.username.toLowerCase() === userArgs.slice(0).join(" ") || x.user.username === userArgs[0]) ||
            message.member;

        let rChannel = message.guild.channels.cache.get(args[0]);
        if (!rChannel) return message.channel.send("Please specify the channel ID. Usage is: ;announce <channelID> <message>");
        let MSG = message.content.split(`;announce ${rChannel.id} `).join("");
        if (!MSG) return message.reply("Please specify a message. Usage is: ;announce <channelID> <message>");
        const embed = new MessageEmbed().setTitle("Announcement").setDescription(`${MSG}`).setImage(message.attachments.first()).setFooter(message.author.tag, message.author.displayAvatarURL()).setTimestamp(Date.now()).setColor(0xa20b31);
        message.attachments.first() ? embed.setImage(message.attachments.first().url) : "";

        rChannel.send(embed);
    },
};


text:
Q: The order of the kernel of the $p$th power map of an abelian and noncyclic group of order $p^3$ Let $p$ be an odd prime, and $G$ an abelian group of order $p^3$ which is not cyclic. The $p$th power map
$$\phi:G\to G,\qquad g\mapsto g^p$$
is a group homomorphism. Is it true that $\ker\phi$ has order $p^2$ or $p^3$ ?
This is equivalent to asking whether $\operatorname{im}\phi$ has order $1$ or $p$.
Since $G$ is not cyclic, every nonidentity element of $G$ has order $p$ or $p^2$, so every nonidentity element of $\operatorname{im}\phi$ has order $p$. But this does not imply that $\operatorname{im}\phi$ has order $p$, so I'm stuck.
Note: I can show this when $G$ is nonabelian.
Note: I would prefer a proof which does not use the fundamental theorem of finitely generated abelian groups.

A: Your group is $C_p\times C_{p^2}$ or $C_p\times C_p\times C_p$ by the Fundamental theorem about finitely generated abelian groups. In the first case the kernel is of size $p^2$, in the second case it is $p^3$.

A: By Cauchy's theorem, there is an element of order $p$ .Call it $x$ (this means the kernel can't be trivial)
if $x,...,x^{p-1}$ are the only elements of order $p$ in $G$, then, any other non-identity element in $G$ has to be of order $p^{2}$. But, if $y\in G$ and has order $p^{2}$, then, $|y^{p}|=p$ So, you can show that there can't be exactly one subgroup of order $p$ thus $|ker\phi|\neq p$
For the remaining cases, I guess you have to use the Fundamental theorem of finitely generated abelian groups show that the cases for $p^2$ and $p^3$ are valid.

A: This answer is inspired and guided by (and also copied from) everyone who helped me: Lubin, JCAA, and M.darwich.
By Cauchy's theorem (or, as Lubin mentioned, by the fact that $G$ is a $p$-group), $G$ has an element of order $p$, so $\ker\phi\neq1$.
Suppose that $|\ker\phi|=p$.
Then, as M.darwish noted, every element of $G\backslash\ker\phi$ has order $p^2$, so if $x\in G\backslash\ker\phi$, then $|x^p|=p$. It follows that $x^p\in\ker\phi$ for all $x\in G$, i.e., $\operatorname{Im}\phi\subseteq\ker\phi$.
Hence, $|\operatorname{Im}\phi|\leq|\ker\phi|$. Now,
$$|\operatorname{Im}\phi|=\frac{|G|}{|\ker\phi|}=\frac{p^3}{p}=p^2>p=|\ker\phi|,$$
a contradiction. Hence, $|\ker\phi|\neq p$.


text:
Q: What is the operator form of $1/P_x$? I know that the operator form of $1/P_x$ ($P_x$ is the $x$-component of momentum operator $\mathbf{P}$) should have an integral form like: $$\frac{i}{\hbar}\int\,dx,$$ but I'm not sure about the limits of integral. Any help would be appreciated.

A: The operator
$$\frac{1}{P_x}$$
produces a divergent result if it acts on a wave function with $P_x=0$ (the eigenstate with this eigenvalue looks like a constant function of $x$). The superpositions of a $P_x=0$ states with the eigenstates associated with nonzero values of $P_x$ are still singular.
That's why a well-defined result of $(1/P_x)|\psi\rangle$ is only obtained if $|\psi\rangle$ contains no $P_x=0$ admixture in the superposition. But that's equivalent to
$$ \int_{-\infty}^{+\infty} dx \,\psi(x) = 0$$
The left hand side is nothing else than the $P_x=0$ Fourier component. For that reason, the prescriptions
$$[\frac{1}{P_x} \psi] (x) \leftrightarrow \frac{i}{\hbar}\int_{-\infty}^x dx'\,\psi(x') $$
and
$$[\frac{1}{P_x}\psi](x) \leftrightarrow -\frac{i}{\hbar}\int_{x}^\infty dx'\,\psi(x') $$
produce the same result.
If you wanted to generalize the action of an operator $1/P_x$ on a wave function that does contain a $P_x=0$ piece, then you would have to decide whether you mean the "principal value" of $1/P_x$ or $1/(P_x+i\epsilon)$ or something else. This extra refinement could make the operator well-defined for a broader set of test functions $\psi(x)$.

A: One way to treat Quantum mechanics is that writing the operators in terms of matrices.
One can think of operators $\hat{X}$, $\hat{P_x}$ and $\hat{P_x}^{-1}$ in terms of matrix quantum mechanics. In the $|x \rangle$ basis (where $\hat{X} |x \rangle=x|x \rangle$), we can discretize the space up to some overall constant as a unit of spacing, and write the operators as
$$\hat{X}=a{\begin{pmatrix}
\ddots & 0 & 0 & 0 & 0 & 0&0\\
0 & -2 & 0 & 0 & 0 & 0&0\\
0 & 0 & -1 & 0 & 0 & 0&0\\
0 & 0 & 0 & 0 & 0 & 0&0\\
0 & 0 & 0 & 0 & 1 & 0&0 \\
0 & 0 & 0 & 0 & 0 & 2&0 \\
0 & 0 & 0 & 0 & 0 & 0& \ddots \\
\end{pmatrix}}$$
$$\hat{P_x}=-i \hbar \partial_X=i \hbar a^{-1}{\begin{pmatrix}
\ddots & 0 & 0 & 0 & 0 & 0&0\\
1 & 0 & -1 & 0 & 0 & 0&0\\
0 & 1 & 0 & -1 & 0 & 0&0\\
0 & 0 & 1& 0 & -1 & 0&0\\
0 & 0 & 0 & 1 & 0 & -1&0 \\
0 & 0 & 0 & 0 & 1 & 0&-1 \\
0 & 0 & 0 & 0 & 0 & 0& \ddots \\
\end{pmatrix}}$$
Easy to check $$[\hat{X},\hat{P_x}]=i\hbar$$
Thus,
$$\frac{1}{\hat{P_x}}=\hat{P_x}^{-1}$$
Thus, $\frac{1}{\hat{P_x}}=\hat{P_x}^{-1}$ is just the inverse matrix of $\hat{P_x}$. One may need to consider two cases: periodic boundary conditions on a 1D circle $S^1$ or an infinite size 1D system. Treated two cases separately.


text:
Q: Matplotlib Patches not matching supplied arguments. been struggling with python and the matplotlib module. I am trying to draw some circles that are not filled and outlined in black. I am putting the correct arguments in the artist circle but it seems to ignore it and put blue. any ideas? Also the figure shows up automatically without me stating draw or show. How can i block that and control when the graph pops up? Thanks in advance.
my code
    def draw_lattice(self,chart):

    patches = []
    for x in range(1,4):
        for y in range (1,4):
            circle = Circle((x,y), .25,color='k',fill=False)
     #       chart.add_patch(circle)
            patches.append(circle)

    p = PatchCollection(patches)
    chart.add_collection(p)

Thanks in advance.
* UPDATE *
if i add each circle individually to the axes it will be formatted properly. If i add the collection it does not work. I have many more shapes to add and i would like to go the collection route. Any reason why one way would work and another wouldn't? I read somewhere that you need to add the artist but i tried that and got an error.

A: This is a rather late answer but I just came across the same problem and here is how to solve it:
What you need to do is tell the PatchCollection to match the original patches. To do this simply add match_original=True, like so:
p = PatchCollection(my_patches, match_original=True)

A: You can set the color of the circles when you create the patch collection:
p = PatchCollection(patches,facecolors='w',edgecolor='k')

From the Collection documentation:
"If any of edgecolors, facecolors, linewidths, antialiaseds are None, they default to their matplotlib.rcParams patch setting, in sequence form."


text:
Q: How to redirect site's port only when changing site more **details in topic** So I want to be able to redirect site's port only since I'm running the website as 3 different types of IPS. So on WebServer hosting device I've edited the host file 127.0.0.1 to q. So on host device I can access my website as q:8080. On internal devices I can access it as 192.168.43.1:8080 and I've port forwarded version.I have DNS and changed the external port. So other people can access my site by entering http://ladasno.hopto.org:8080. So the reason I'm asking this because I pretty lack knowledge yet. So I want for each address to be redirected from 8080 to 9090 (For Internal ports) and from 80 to 90 for external ports. So what should I do.
So I've tried like looking for a way to read website's url user is accessing from (FAILED TO FIND). Then I've tried to like to make window.location.replace("urls") 4 times at once. Then I used .. since I thought it will autofind the part that has left of the url
So first I just tried:
function redirect() {
    window.location.replace("http://q:9090/Page/Index.html");
    window.location.replace("http://192.168.43.1:9090/Page/Index.html");
    window.location.replace("http://ladasno.hopto.org:9090/Page/Index.html");
   }

This has failed since redirects to last URL I've provided. Then I've tried:
function redirect() {
    window.location.replace("..:9090/Page/Index.html");
   }

And this just shows error in console:
Uncaught DOMException: Failed to execute 'replace' on 'Location': '..:9090/Page/Index.html' is not a valid URL.
    at redirect (http://192.168.43.1:8080/:5:21)
    at HTMLButtonElement.onclick (http://192.168.43.1:8080/:10:31)

Please HELP ME!
So I have high expectations for stackoverflow community members. And I don't think I can describe actual results because I haven't seen any details.


text:
Q: pax-logging-log4j2 is not stopping in PaxExam+Karaf I am running test cases with paxexam+karaf, but after test execution when paxexam try to stop log42 bundle during containaer shutting it got stuck and stay on below line
I am using Paxexam 4.11
DEBUG | features-2-thread-1 | util                             | 14 - org.apache.aries.util - 1.1.3 | BundleEvent STOPPING - org.apache.aries.util
 DEBUG | features-2-thread-1 | util                             | 14 - org.apache.aries.util - 1.1.3 | BundleEvent STOPPED - org.apache.aries.util
 DEBUG | features-2-thread-1 | Deployer                         | 10 - org.apache.karaf.features.core - 4.2.0 | Usage for bundle org.apache.felix.fileinstall [9] is 1
 DEBUG | features-2-thread-1 | Deployer                         | 10 - org.apache.karaf.features.core - 4.2.0 | Currently selecting bundle org.apache.felix.fileinstall [9] for destroy (with reference [org.osgi.service.cm.ConfigurationListener, org.apache.felix.fileinstall.ArtifactListener, org.apache.felix.fileinstall.ArtifactInstaller])
 DEBUG | features-2-thread-1 | Deployer                         | 10 - org.apache.karaf.features.core - 4.2.0 | Selected bundle [org.apache.felix.fileinstall [9]] for destroy (lowest ranking service)
 INFO  | features-2-thread-1 | FeaturesServiceImpl              | 10 - org.apache.karaf.features.core - 4.2.0 |   org.apache.felix.fileinstall/3.6.4
 DEBUG | features-2-thread-1 | fileinstall                      | 9 - org.apache.felix.fileinstall - 3.6.4 | BundleEvent STOPPING - org.apache.felix.fileinstall
 DEBUG | features-2-thread-1 | fileinstall                      | 9 - org.apache.felix.fileinstall - 3.6.4 | ServiceEvent UNREGISTERING - [org.osgi.service.url.URLStreamHandlerService] - org.apache.felix.fileinstall
 DEBUG | features-2-thread-1 | fileinstall                      | 9 - org.apache.felix.fileinstall - 3.6.4 | ServiceEvent UNREGISTERING - [org.osgi.service.cm.ConfigurationListener, org.apache.felix.fileinstall.ArtifactListener, org.apache.felix.fileinstall.ArtifactInstaller] - org.apache.felix.fileinstall
 DEBUG | features-2-thread-1 | fileinstall                      | 9 - org.apache.felix.fileinstall - 3.6.4 | ServiceEvent UNREGISTERING - [org.osgi.service.cm.ManagedServiceFactory] - org.apache.felix.fileinstall
 DEBUG | features-2-thread-1 | fileinstall                      | 9 - org.apache.felix.fileinstall - 3.6.4 | BundleEvent STOPPED - org.apache.felix.fileinstall
 DEBUG | features-2-thread-1 | Deployer                         | 10 - org.apache.karaf.features.core - 4.2.0 | Usage for bundle org.ops4j.pax.logging.pax-logging-api [6] is 0
 DEBUG | features-2-thread-1 | Deployer                         | 10 - org.apache.karaf.features.core - 4.2.0 | Usage for bundle org.ops4j.pax.logging.pax-logging-log4j2 [7] is 1
 DEBUG | features-2-thread-1 | Deployer                         | 10 - org.apache.karaf.features.core - 4.2.0 | Selected bundles [org.ops4j.pax.logging.pax-logging-api [6]] for destroy (no services in use)
 INFO  | features-2-thread-1 | FeaturesServiceImpl              | 10 - org.apache.karaf.features.core - 4.2.0 |   org.ops4j.pax.logging.pax-logging-api/1.10.1
 DEBUG | features-2-thread-1 | pax-logging-api                  | 6 - org.ops4j.pax.logging.pax-logging-api - 1.10.1 | BundleEvent STOPPING - org.ops4j.pax.logging.pax-logging-api
 INFO  | features-2-thread-1 | Activator                        | 6 - org.ops4j.pax.logging.pax-logging-api - 1.10.1 | Disabling SLF4J API support.
 INFO  | features-2-thread-1 | Activator                        | 6 - org.ops4j.pax.logging.pax-logging-api - 1.10.1 | Disabling Jakarta Commons Logging API support.
 INFO  | features-2-thread-1 | Activator                        | 6 - org.ops4j.pax.logging.pax-logging-api - 1.10.1 | Disabling Log4J API support.
 INFO  | features-2-thread-1 | Activator                        | 6 - org.ops4j.pax.logging.pax-logging-api - 1.10.1 | Disabling Avalon Logger API support.
 INFO  | features-2-thread-1 | Activator                        | 6 - org.ops4j.pax.logging.pax-logging-api - 1.10.1 | Disabling JULI Logger API support.
 INFO  | features-2-thread-1 | Activator                        | 6 - org.ops4j.pax.logging.pax-logging-api - 1.10.1 | Disabling Log4J v2 API support.
 DEBUG | features-2-thread-1 | pax-logging-api                  | 6 - org.ops4j.pax.logging.pax-logging-api - 1.10.1 | BundleEvent STOPPED - org.ops4j.pax.logging.pax-logging-api
 DEBUG | features-2-thread-1 | pax-logging-log4j2               | 7 - org.ops4j.pax.logging.pax-logging-log4j2 - 1.10.1 | BundleEvent STOPPING - org.ops4j.pax.logging.pax-logging-log4j2

Regards,


text:
Q: Spring RestTemplate with HttpClient Client Certificate How can I include client certificate using latest HttpClient (httpclient5)?
I'm using hakky54 sslcontext with latest RestTemplate (rest framework 6.0.4) and HttpClient.  It throws exception when I create an in-mem keystore (same result with "PKCS12" and "JKS") with just my certificate

500 Internal Server Error: "{"ErrorCode":"APPAP330E","ErrorMsg":"Failed to verify application authentication data: Could not obtain client certificate details."}"

Syntax in Kotlin:
val x509 : X509Certificate = getCertificateFromStore(...)
val restTemplate = RestTemplate()
val request = HttpComponentsClientHttpRequestFactory()
val httpClient : HttpClientBuilder = HttpClients.custom()

val clientStore = KeyStore.getInstance(KeyStore.getDefaultType())
val clientManager = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
clientStore.load(null)
clientStore.setCertificateEntry("clientCert", x509 )
clientManager.init(clientStore, null)

val sslFactory = SSLFactory.builder()
        .withIdentityMaterial(clientManager)
        .build()
val connectionManager : HttpClientConnectionManager = PoolingHttpClientConnectionManagerBuilder.create()
        .setSSLSocketFactory(Apache5SslUtils.toSocketFactory(sslFactory))
        .build()
httpClient.setConnectionManager(connectionManager)

request.httpClient = httpClient.build()
restTemplate.requestFactory = request
...
val response : ResponseEntity<String> = restTemplate.getForEntity(...)

In Windows if I replace keystore init with val clientStore = KeyStore.getInstance("Windows-MY") with just one client cert in the store it works fine
I need the ability to pick a different cert that's in the store or use a cert that's not pre-installed
Am I not configuring the keystore correctly?  How can I inject a client cert into a resttemplate request in the latest Spring Framework.  It seems the latest Spring Framework and httpclient5 are not compatible with all the samples I have found online that rely on httpclient4


text:
Q: JOB TALEND TRIGGER I've a question about Talend, I want to insert data in csv in real time after each inserting in PostgreSql database. Have you ideas ?
Thank you !
My Job TALEND

A: Unfortunately you cannot trigger Talend's operation from database.
If your table is very intensively written - so all the exercise does not make any sense at all. If the inserts are relatively rare - i would recommend to create a postgreSQL trigger, to populate table with PK of a new record. Talend job will pick the newly inserted records, by probing that new table, let's say every second, and will delete that Pk.


text:
Q: Push notification received, but app closes I'm sending a push notification to an iOS device via Notification Hubs. The notification is received successfully. Once the user clicks the notification, the splash screen is displayed then the app closes. I've check the crash logs and there isn't any errors.
If we review the console logs, the last message was 'Received incoming message on top xx at priority 10'.
There's an warning earlier in the logs stating 'No data found at /var/mobile/Library/UserNotification/com.xxxx.xxx/PendingNotifications.plist.
If I send a notification directly from the Azure portal (same device and payload), the notification is received and the app opens as expected.
Thoughts?

A: When you open the app by clicking the notification, didFinishLaunchingWithOptions/ or DidReceiveRemoteNotificationis called. you should add some log prints to see where it gets stuck.
Please take a look at this thread for debugging push notification.
Note: If an application isn't running when a push notification arrives, the application will be launched but the DidReceiveRemoteNotification method won't process the notification. Instead, get the notification payload and respond appropriately from the WillFinishLaunching or FinishedLaunching overrides.
Further reference please visit:
https://learn.microsoft.com/en-us/xamarin/ios/platform/user-notifications/deprecated/remote-notifications-in-ios
Hope it helps.


text:
Q: Java - Stack Trace showing offending lines in code which isn't the same as original source code I recently encountered an issue where my NullPointerException produced a stack trace - the offending lines in which don't match the source code used to compile the classes.
I can confirm 100% that the code is the same since all other signatures have matched for our code. It seems that the lines are off for the top 2-3 files - Others are okay.
I am not sure if this is a file line formatting issue or some configuration. But I would assume that the configuration-related problem should corrupt all line numbers not just a file or two.
Has anyone encountered this before?
By the way - I have recompiled in 2/3 different machine - no difference. I cannot share the source code since it's proprietary.


text:
Q: I want to use bcrypt.compare together with mongoose/mongo enginee search Consider this code:
const hashPassword = function(plainText) {
  return crypto
    .createHmac(process.env.Secret_hash_Password, "secret key")
    .update(plainText)
    .digest("hex");
};

As you may have noticed, this is a simple hashing function using crypto.
Now consider this code excerpt:
bcrypt.compare(password, user.password, (err, isMatch) => {....}

As you may have noticed, this is a simple comparing hashing function using bcryptjs.
As I believe everyone will agree, the second is most secure.
Now consider the problem:
I have a key to store on mongo, and this key is a sensitive information, as so, I have decided to hash it as so no one can decrypt it. This key is used to make mongo searches, this an information that just the user has, a sort of password.
Solution: use the first code, as so nonetheless you cannot decrypt, you can get the same result of hashing if the input is the same.
Problem: my solution is using a tecnique that is well-known to be easily hacked, someone that somehow had access to the server just need to enter several inputs and once they get the same output, they got it! this is a well-known flaw of my solution.
Desired solution: use the second code with mongo.
Discussion: I could simply get all the database information with find({}), and apply say ForEach and bcrypt.compare, nonetheless, I know from my studies that mongo is optimized for search, e.g. they use indexes. It would be nice to be able to pass the bcrypt.compare as a customized function to mongo search enginee.
It was suggested "Increase the bcrypt salt rounds.": I cannot use salt since that would change the key and whenever I will need to compare, it will change. bcrypt.compareexists to overcome that, but mongo/mongoose queries does not have such internal enginee.

What  I have in my head, in pseudocode:
Model.findOne({bcrypt.compare (internalID, internalID')}) //return when true

Where: bcrypt.compare (internalID, internalID') would be a sort of callback function, on each search, mongo would use this function with internalID', the current internalID  under comparison, and return the document that produces true.
Any suggestion, comment, or anything?
PS. I am using mongoose.

A: From what i understand, you don't ever want anyone to know the patient ids (non -discover-able from real life patient-ids), even the database admin (and of course hackers).
I think you design is a bit messed up.
Firstly - indexes use B tree data structure for faster lookup so you have to provide exact string for lookup and by your condition of un-hash-able ids, indexes won't work. So you'll have to iterate over every patient id by that doctor and compare to get true result, which is pretty compute- extensive and frankly bad design.
There are multiple ways to approach to approaching this problem- depending upon your level of trust and paranoia.
I think using cryptojs is the correct solution. Now you have to add some randomness to the key/solution. Basically you hash the id with cryptojs, but instead of supplying the key yourself, you could take the secret key from doctor itself then hash every id with that key. Now you will have to unhash and hash every patient id everytime doctor changes secret key (using some sort of message queue).
You could also hash the secret key entered by doctor before saving and will have to unhash everytime (twice!) doctor wants to lookup by patientId.
Depending upon the number of users you expect your application to serve, if number is low enough- my solution would work. But too many users, you'd have to increase compute resources and probably invest in some security measures instead of my overkill solution. Why'd you be losing secret key to hackers anyway?
Good luck.


text:
Q: PHP typing and null values there is a functionality in Java that allows me to pass null values to methods in parameters and also to return null values:
class Test {
    public List<String> method (String string) {
        return null;
    }

    public void otherMethod () {
        this.method(null);
    }
}

However, in PHP, the following does not work:
<?php

class SomeClass {

}

class Test {
    public function method (): SomeClass
    {
        return null;
    }
}

$test = new Test();

$test->method();

I can't pass null values to typed methods either:
class Test {
    public function method (SomeClass $obj)
    {
        // I can't pass null to this function either
    }
}

I find this very annoying, is there something I am missing? Or is it just how it works in PHP and there is nothing I can do?

A: php7.1 allows nullable types by prefixing the type with a question mark ?. You can pass nullable parameters or define functions returning nullable types.
Documentation here.
Your example:
<?php
class SomeClass {
}
class Test {
    public function method (): ?SomeClass
    {
        return null;
    } }
$test = new Test();
$test->method();

or
class Test {
    public function method (?SomeClass $obj)
    {
        // pass null or a SomeClass object
    }
}


text:
Q: Is it possible to send a DOM reference to another browser thru a server? I want to be able to send some element that I selected with JQuery to another browser which opened the same page. Like if focus a textfield, the selection to happen on the second browser too. With a server, that's possible, but is there a way to serialize or somehow transfer the element reference (not id, cause not every element has an id)

A: Not so much transfering, but you can "reveal" your values to a specific browser.  Try setting up a conditional statement for browser feature detection, within a ajax request on success() or on done(), to then display your DOM reference for a specific browser.  Hope this helps.


text:
Q: Headless browser get data-URI of an image without losing the quality I am trying to save a captcha locally with a headless Chrome browser, don't wanna take a screenshot and without losing the quality of the captcha.
The way I came up with is to convert the image to data-URI and then write it to a file.
I try the following code, it did work and save an image for me. The problem is, the captcha I got is not as good as the one I just download or take a screenshot.
captcha_img_element = browser.find_element_by_xpath("//span[text()='some text']//img")

img_base64 = browser.execute_script("""
    var ele = arguments[0];
    var cnv = document.createElement('canvas');
    cnv.width = ele.width; cnv.height = ele.height;
    cnv.getContext('2d').drawImage(ele, 0, 0);
    return cnv.toDataURL('image/jpeg').substring(22);
    """, captcha_img_element)

with open("captcha_js.png", 'wb') as f:
    f.write(base64.b64decode(img_base64))

The one with high quality:

The one I got through js code:

they look the same, but when you zoom up them, the pixels are different.
So, how can I get the data-URI of the first one (with high quality), or is there any alternative way without using data-URI (under headless browser mode)

A: Use ele.intrinsicWidth and ele.intrinsicHeight. This gives the actual width and height of the image and not the width/height of the DOM element.


text:
Q: Desktop overlay program showing CPU, HDD, etc. stats In different screenshots of people's Linux desktops, I've seen different apps that overlay the desktop with information about their computer. Often this gadget/app shows CPU and HDD information. Sometimes it has network and temperature information as well. I've seen these a lot but they often have different looks and different information.
What program does this? Is it built-in to any Linux distribution?

A: I use conky to display date, battery, cpu, ram and swap information. You can find my conky file here or take a look at a thread about conky configs in the arch-linux forum. There you find many different configs and screenshots of conky in use.

A: I use the conky-colors theme/scripts for one of my desktops. It's a fairly user-friendly way to begin with conky.


text:
Q: php obtaining complex file extension like mysql-5.0.1.tar.gz I've run into a typical problem here. Till now i was doing
strstr($filename,".");

$filename is the file i got from $_FILE i.e uploaded file.It was running fine until i hit a filename of the type i mentioned.
Even doing
pathinfo($filename);

gives me
.gz

I need to see whether it is EXACTLY
.tar.gz

A: Technically, pathinfo is correct: the one and only extension for that file is .gz. The fact that it has .tar in the name is as coincidental as the fact that it has 5.0.1 in it.
That doesn't make your interest in checking for .tar.gz files invalid, but it does raise the question: what specifically do you want to find?
The most direct solution to your specific question is: first look for the extension (via pathinfo or the strpos function) and then if it happens to be .gz look for the "extension" in the remaining filename (via the same technique).
$parts = pathinfo($filename);
$extension = $parts['extension'];
if ($extension == '.gz') {
    $parts = pathinfo($parts['filename']);
    $extension = $parts['extension'] . $extension;
}

A: The most simple way would be to check for the last 7 characters of the filename - this ensures that every file ends with .tar.gz:
if (substr($filename, -7) == '.tar.gz') {
    // continue
}

A: And if you needed to parse 'this.is.a.very.long.file.name.with.lots.of.full.stops' then what part of that is the file extension? Relying on a particular part of a filename to convey semantic, machine readable information about the contents of the file is, at best dangerous.
It's not clear what the problem you are trying is - why do you need to know what the extension is?
C.

A: I just posted the following enhanced version of pathinfo() in comments over on PHP.net. This version groups all of the parts of the file extension in as the extension (e.g. "tar.gz" instead of just "gz"), leaving the rest as the filename:
<?php
  function pathinfo_enhanced($file_path) {
    $core_path_info = pathinfo($file_path);
    $filename = $core_path_info['filename'];

    if (isset($core_path_info['extension'])) {
      $extension = $core_path_info['extension'];
    } else {
      $extension = '';
    }

    $extension_parts = array();

    while (!empty($extension)) {
      array_unshift($extension_parts, $extension);

      $remaining_path_info = pathinfo($filename);
      $filename = $remaining_path_info['filename'];

      if (isset($remaining_path_info['extension'])) {
        $extension = $remaining_path_info['extension'];
      } else {
        $extension = '';
      }
    }

    $revised_path_info = array(
      'filename'  => $filename,
      'extension' => implode('.', $extension_parts),
    );

    return array_merge($core_path_info, $revised_path_info);
  }

Here are some examples you can run to show how it handles the different cases:

  // Directory; two extensions
  $path = '/www/htdocs/inc/file.tar.gz';
  $info = pathinfo_enhanced($path);

  echo "$path\n";
  print_r($info);
  echo "\n";

  // Directory; one extension
  $path = '/www/htdocs/inc/file.tgz';
  $info = pathinfo_enhanced($path);

  echo "$path\n";
  print_r($info);
  echo "\n";

  // Directory; no extension
  $path = '/www/htdocs/inc/lib';
  $info = pathinfo_enhanced($path);

  echo "$path\n";
  print_r($info);
  echo "\n";

  // No directory; one extension
  $path = 'test.php';
  $info = pathinfo_enhanced($path);

  echo "$path\n";
  print_r($info);
  echo "\n";

  // No directory; dot file
  $path = '.example';
  $info = pathinfo_enhanced($path);

  echo "$path\n";
  print_r($info);
  echo "\n";

  // Directory only
  $path = '/www/htdocs/inc/';
  $info = pathinfo_enhanced($path);

  echo "$path\n";
  print_r($info);
  echo "\n";

A: THIS is the answer:
strstr(pathinfo('asdasd/qweqwe/asdasd.tar.gz')['basename'], '.');

will return you '.tar.gz'


text:
Q: git tag -l is not showing any result in gitlab pipeline for few projects git tag -l is not showing any output, However for some projects it returns tags on gitlab pipeline
locally on my machine it works for all projects, only not working on gitlab


text:
Q: Difference in seconds between user input and current date I need difference between two dates in seconds. I input datetime in format "YYYY-MM-DD HH:MM" and then calculate difference in seconds, but the run_time is in UTC timezone and current_time is calculated from system timezone.
#!/bin/bash
run_time=$1
run_time=$(date -d "$run_time" +"%s")
current_time="$(date +"%s")"

echo $run_time
echo $current_time
echo "$(($run_time-$current_time))"

How to retrieve absolute value of seconds between current datetime and another one?
Edit: actually that script has worked after restart of computer. No clue why previously it showed up different results. I have not changed anything in settings, nor computer time.

A: Right @Jetchisel, based on your comment a sample script could look like:
#!/bin/bash
STARTTIME_UTC=$1
STARTTIME_UTC=$(date -u -d "${STARTTIME_UTC}" +"%s")

echo "CURRENT DATE: $(date)"
CURRENTTIME="$(date +"%s")"

echo
echo "STARTTIME_UTC: ${STARTTIME_UTC} sec since"
echo "CURRENTIME: ${CURRENTTIME} sec since"
echo

echo "RUNTIME: $((${CURRENTTIME}-${STARTTIME_UTC})) sec"

As per original question

I input datetime in format "YYYY-MM-DD HH:MM"

the value of input time seconds in ${STARTTIME_UTC} will be set to zero (:00) whereby the value of current time seconds in ${CURRENTIME} will be set to what the clock provides. I.e., if it is 18 seconds before the next minute and the runtime would be almost zero, the script will report a difference of 42 seconds.


text:
Q: How to create a releationship linking to PK column Plus another I am trying to create a relationship between two models where the child links to the PK id plus another Id column in the parent
Public Class AClass
{
    public int AClassId {get; set; }

    public int UserId { get; set; }
    public User User { get; set; }

    public ICollection<BClass> LinkedUsers { get; set; }

    public int SubUserId { get; set;}
    public User SubUser{ get; set; }

    public ICollection<BClass> LinkedSubUsers { get; set; }
}

Public Class BClass
{
    public int BClassId {get; set; }

    public int AClassId {get; set; }

    public int UserId { get; set; }

    public AClass AClass { get; set; }

    public ICollection<Rules> Rules { get; set; }
}

So BClass can only Exist if AClass has a set UserId or a SubUserId linked to it. Multiple AClass can have multiple instances of BClass for the same User
public Aclass a = new Aclass();
a.AClassId = 1;
a.UserId = 1;
a.SubUserId = 2;

//Ok
BClass b1 = new BClass();
b1.AClassId = 1;
b1.UserId = 1;

//Ok
BClass b2 = new BClass();
b2.AClassId = 1;
b2.UserId = 1;

//OK
BClass b3 = new BClass();
b3.AClassId = 1;
b3.UserId = 2;

//Not OK No AClass 1 with UserId 3
BClass b1 = new BClass();
b1.AClassId = 1;
b1.UserId = 3;

I'm creating the relationship using:
System.Data.Entity.ModelConfiguration.EntityTypeConfiguration
HasRequired(c => c.AClass).WithMany(i => i.LinkedUsers).HasForeignKey(t => new { t.AClassId, t.UserId } );

but I get the error:
"The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical."
I hope this is possible but can't work out how to create the correct mapping using EF.


text:
Q: Is anyone aware of the limitations in the gawk gsub function? I'm trying to mask sensitive values like keys, token, etc... in a command line before writing it into a log file.
For example:
MY_TOKEN='MaskThisPlease'
MY_CMD="my_command ${MY_TOKEN} SomeOtherString"
echo "${MY_CMD}" | gawk -v k="${MY_TOKEN}" -v m="XXXXXX" '{gsub(k,m);print}'

The result is:
my_command XXXXXX SomeOtherString

Now when MY_TOKEN contains specific characters, the masking will not work and/or will produce an error. Some of the special characters are: $ ^ * ( ) + [ ] | \ ?
The below works fine
MY_TOKEN='MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..zzzzzzzzzzzzzzzzzzzzzzzzz'
MY_CMD="my_command ${MY_TOKEN} SomeOtherString"
echo "${MY_CMD}" | awk -v k="${MY_TOKEN}" -v m="XXXXXX" '{gsub(k,m);print}'

I tried sed but there's the delimiter limitation, i.e. when the '+' is in MY_TOKEN
MY_TOKEN='MaskThisPlease_SomeABCs_Some123s_SomeOther+PlusSign+here'
MY_CMD="my_command ${MY_TOKEN} SomeOtherString"
echo "${MY_CMD}" | sed "s+${MY_TOKEN}+XXXXXX+g"

sed: -e expression #1, char 55: unknown option to `s'

So, my question is

Is there another way to perform a masking without hitting the above and without size limitations (MY_TOKEN maybe 700 characters)?

The below was added later in response of your comments and Answer 1:

I just join Stack Overflow and it's my first posting. I was unable to attach my test data as r.dat. Each line in r.dat is the value of my token (see answer 1 below for more details).
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..zzzzzzzzzzzzzzzzzzzzzzzzz
AlphaNumericCharacters1234567890
''MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..zzzzzzzzzzzzzzzzzzzzzzzzz''
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^(zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?*zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?**zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?*)zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?*.zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?.*zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?*(zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?\\zzzzzzzzzzzzzzzzzzzzzzzzz
MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?\zzzzzzzzzzzzzzzzzzzzzzzzz

Here's the 1st code snippet which shows some limitations in the r.awk and in bash build-in replace functions
clear
# Read one by one my test cases
I=0
cat ./r.dat | while IFS= read -r MY_TOKEN
do
    I=$((I+1))

    echo
    echo "#########################################################"
    echo "${I}) MyToken is ${MY_TOKEN}"
    echo "#########################################################"

    # Build my command including the value of my token
    MY_CMD="my_command ${MY_TOKEN} SomeOtherString"

    printf "Mask with gawk function: "
      echo "${MY_CMD}" | gawk -F'\n' -v k="${MY_TOKEN}" -v m="XXXXXX" -f ./r.awk 2>/dev/null

    printf "Mask with bash built-in: "
      echo "${MY_CMD/${MY_TOKEN}/XXXXXX}"
done

The test case 19 show that the r.awk does better than the bash build-in replace function
The test case 20 show that both fail
The test case 21 show that both fail
Here's the 2nd code snippet which shows how to fix the issues in both r.awk and bash build-in replace functions
clear
# Read one by one my test cases
I=0
cat ./r.dat | while IFS= read -r MY_TOKEN
do
    I=$((I+1))

    # Escape RegEx characters
    MY_TOKEN_ESCAPED=$(echo ${MY_TOKEN} | sed 's:[][\/.^$*]:\\&:g')

    echo
    echo "#########################################################"
    echo "${I}) MyToken is ${MY_TOKEN}"
    echo "${I}) Escaped is ${MY_TOKEN_ESCAPED}"
    echo "#########################################################"

    # Build my command including the value of my token
    MY_CMD="my_command ${MY_TOKEN} SomeOtherString"

    printf "Mask with gawk function: "
      echo "${MY_CMD}" | gawk -F'\n' -v k="${MY_TOKEN_ESCAPED}" -v m="XXXXXX" -f ./r.awk 2>/dev/null

    printf "Mask with bash built-in: "
      echo "${MY_CMD/${MY_TOKEN_ESCAPED}/XXXXXX}"
done

May be there's a better & simple way to handle it and that's 100% POSIX....

A: You can use index (its second argument is a string not a regular expression) and read a key from a file. Here is an example. Create four files:
r.awk
BEGIN {
    getline k < kfile; close(kfile)
    n = length(k)
}

function process(rst,   i, pre, ans) {
    while (i=index(rst, k)) {
        pre = substr(rst, 1,  i-1)
        rst = substr(rst, i + n)
        ans = ans pre m
    }
    return ans rst
}

{
    print process($0)
}

r.sh
awk -v kfile=r.key -v m=XXX  -f r.awk r.dat

r.dat
test\t\tMaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..zzzzzzzzzzzzzzzzzzzzzzzzztest

r.key
\t\tMaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..zzzzzzzzzzzzzzzzzzzzzzzzz

Run it with
sh r.sh
Expected output:
testXXXtest

A: It looks like this is what you're trying to do:
$ cat tst.sh
while IFS= read -r my_token
do
    old_my_cmd="my_command $my_token SomeOtherString"

    new_my_cmd=$(
        printf '%s\n' "$old_my_cmd" |
        awk -v m='XXXXXX' '
            BEGIN {
                my_token=ARGV[1]; ARGV[1]=""; ARGC--
                lgth = length(my_token)
            }
            {
                while ( start = index($0,my_token) ) {
                    printf "%s%s", substr($0,1,start-1), m
                    $0 = substr($0,start+lgth)
                }
                print
            }
        ' "$my_token"
    )

    printf 'old_my_cmd="%s"\n' "$old_my_cmd"
    printf 'new_my_cmd="%s"\n' "$new_my_cmd"
    printf "\n"

done < r.dat

.
$ ./tst.sh
old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command AlphaNumericCharacters1234567890 SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command ''MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..zzzzzzzzzzzzzzzzzzzzzzzzz'' SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^(zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?*zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?**zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?*)zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?*.zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?.*zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?*(zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?\\zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

old_my_cmd="my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?\zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString"
new_my_cmd="my_command XXXXXX SomeOtherString"

A: Here's the 3rd code snippet combines @EdMorton's approach into my original code
# Read one by one my test cases
I=0
cat ./r.dat | while IFS= read -r MY_TOKEN
do
    I=$((I+1))

    echo
    echo "#########################################################"
    printf '%s) MyToken is %s\n' "${I}" "${MY_TOKEN}"
    echo "#########################################################"

    # Build my command including the value of my token
    MY_CMD="my_command ${MY_TOKEN} SomeOtherString"

    MY_CMD_MASKED=$(
        printf '%s\n' "${MY_CMD}" |
        awk -v m='XXXXXX' '
            BEGIN {
                my_token=ARGV[1]; ARGV[1]=""; ARGC--
                lgth = length(my_token)
            }
            {
                while ( start = index($0,my_token) ) {
                    printf "%s%s", substr($0,1,start-1), m
                    $0 = substr($0,start+lgth)
                }
                print
            }
        ' "${MY_TOKEN}"
    )

    printf 'Mask with gawk function: %s\n' "${MY_CMD_MASKED}"
    printf 'Mask with bash built-in: %s\n' "${MY_CMD/${MY_TOKEN}/XXXXXX}"
done

Here are the results of test cases 19, 20 and 21 we discussed before:
#########################################################
19) MyToken is MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?*(zzzzzzzzzzzzzzzzzzzzzzzzz
#########################################################
Mask with gawk function: my_command XXXXXX SomeOtherString
Mask with bash built-in: my_command XXXXXX SomeOtherString

#########################################################
20) MyToken is MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?\\zzzzzzzzzzzzzzzzzzzzzzzzz
#########################################################
Mask with gawk function: my_command XXXXXX SomeOtherString
Mask with bash built-in: my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?\\zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString

#########################################################
21) MyToken is MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?\zzzzzzzzzzzzzzzzzzzzzzzzz
#########################################################
Mask with gawk function: my_command XXXXXX SomeOtherString
Mask with bash built-in: my_command MaskThisPlease_SomeABCs_Some123s_SomeOther//!!@@##%%_--==``~~{{}}::;;""<<>>,,..$^()+[]|?\zzzzzzzzzzzzzzzzzzzzzzzzz SomeOtherString

When removing the below line from the above script, it passes the "checkbashisms -fx" as well as the http://www.shellcheck.net/
printf 'Mask with bash built-in: %s\n' "${MY_CMD/${MY_TOKEN}/XXXXXX}"

The above line was there only to demonstrate the differences between the two approaches.
Thank you all for the quick feedback and helping me improving my communication in  this post.


text:
Q: session::push error htmlspecialchars() expects parameter 1 to be string, array given I insert a number of items in a session using session::push it works till refreshing page I get error:

htmlspecialchars() expects parameter 1 to be string

Here is the controller function:
 public function shopping(Request $request){
    if($request->has('cart')){

        $x=request('name');
        $y=request('quantity');
        Session::push('item',$x);

        return view('Crochet.shopping');

    } else {
        return redirect()->back();
    }
}

in view:
@foreach(session('item')as $y){{$y}} @endforeach

How can it be fixed?
Added from comments:
the $x is a string I request from the url in each page:
http://127.0.0.1:8000/Pearl%20Crochet/cart/shopping?name=Nubian&image=image1.jpg

$x is the name.

A: You can check if the session exists before the loop:
@if (session('item'))

   @foreach(session('item') as $y)
     {{ $y }}
   @endforeach

@endif


text:
Q: Take screenshot of a FMX form from another process, even if the form is not topmost / modal I am currently trying to take a screenshot of a 2D Firemonkey (FMX) form from another process.
The following is using a well-known method based of GDI, using a BitBlt() to produce a bitmap, and WIC to save it to a PNG file.
{...}
uses
  system.UITypes,
  system.SysUtils,
  system.Hash,
  {$IF Defined(MSWINDOWS)}
  winapi.Windows,
  Winapi.Direct3D9,
  WinApi.D3DX9,
  Winapi.Wincodec,
  WinApi.ActiveX,
  {$ENDIF}
  { some internal units }
  path.types,
  path.utils,
  os.utils;

{...}

Type
  TWindowSnapshot = record
     window_handle: THandle;    // handle to window
     process_id: Cardinal;      // PID of the process
     window_rect: TRect;        // position of the window
     title: string;             // title
     file_path: string;         // path to the window's image file
  end;

  TWindowSnapshots = Tarray<TWindowSnapshot>;

procedure HRCHECK(r: HRESULT); inline;
begin
  if r <> S_OK then abort;
end;

function pad(s,g:integer): integer; inline;
begin
 dec(g);
 result := (s + g) and not g;
end;

function WICSavePixelsToPng(r: TRect; stride: cardinal; pixels: PByte; filePath: string): HRESULT;
var
  factory: IWICImagingFactory;
  encoder: IWICBitmapEncoder;
  frame: IWICBitmapFrameEncode;
  encoderOptions: IPropertyBag2;
  stream: IWICStream;
  pf: TGUID;
  coInit : HResult;

begin
  result := E_INVALIDARG;
  if not assigned(pixels) then exit;
  if (filepath = '')  then exit;
  coInit := CoInitialize(nil);
  pf := GUID_WICPixelFormat32bppBGRA;
  result := CoCreateInstance(CLSID_WICImagingFactory, nil, CLSCTX_INPROC_SERVER, IWICImagingFactory, factory);
  if result <> S_OK then exit;
  result := factory.CreateStream(&stream);
  if result <> S_OK then exit;
  result := stream.InitializeFromFilename(PWideChar(filePath), GENERIC_WRITE);
  if result <> S_OK then exit;
  result := factory.CreateEncoder(GUID_ContainerFormatPng, TGUID.Empty, encoder);
  if result <> S_OK then exit;
  result := encoder.Initialize(stream, WICBitmapEncoderNoCache);
  if result <> S_OK then exit;
  result := encoder.CreateNewFrame(frame, encoderOptions);
  if result <> S_OK then exit;
  result := frame.Initialize(nil);
  if result <> S_OK then exit;
  result := frame.SetSize(r.width, r.height);
  if result <> S_OK then exit;
  result := frame.SetPixelFormat(pf);
  if result <> S_OK then exit;
  if pf <> GUID_WICPixelFormat32bppBGRA then
  begin
    assert(false,'ToDo');
  end;
  inc(pixels,(r.Left*4) + r.Top * stride);
  result := frame.WritePixels(r.height, stride, stride * r.height, pixels);
  if result <> S_OK then exit;
  result := frame.Commit();
  if result <> S_OK then exit;
  result := encoder.Commit();
  if (coInit <> 0) then
    CoUninitialize();
end;

function take_window_snapshot_GDI(win_handle: THandle; PID: Cardinal; out cs: TWindowSnapshot; const image_folder: string): boolean;
    var
      Wr: TRect;
      HdcSRC: HDC;
      hDCDest: HDC;
      hBmp: HBITMAP;
      hOld: HGDIOBJ;
      hFlags: Cardinal;
      l: integer;
      src_shot,dst_shot,lsrc,ldst: PByte;
      sr: PRGBTriple;
      dr: PRGBQuad;
      buff_size: cardinal;
      x,y, src_stride, dst_stride: integer;
      bi: tagBITMAPINFO;

    begin
      result := false;
      cs.window_handle := win_handle;
      cs.title := '';
      cs.window_rect := TRect.Empty;
      cs.process_id := 0;
      try
        hFlags := GetWindowLong(win_handle,GWL_STYLE);
        if (hFlags and (WS_DLGFRAME or WS_POPUP)) = 0 then exit;
        if (hFlags and WS_VISIBLE) = 0 then exit;
        GetWindowRect(win_handle,Wr);
        if (Wr.Width = 0) or (Wr.Height = 0) then exit;
        L := GetWindowTextLength(win_handle);
        if L > 0 then
        begin
          setlength(cs.title,L);
          GetWindowText(win_handle,pchar(cs.title),L+1);
        end;

        { reserve memory for bitmaps }
        src_stride := pad((wr.Width * 3),4);
        dst_stride := pad((wr.Width * 4),4);
        buff_size := src_stride * wr.Height;
        getmem(src_shot,buff_size);
        if not assigned(src_shot) then exit;
        getmem(dst_shot,dst_stride * wr.Height);
        if not assigned(src_shot) then
        begin
          freemem(src_shot);
          exit;
        end;
        try
          try
            HdcSRC := GetWindowDC(win_handle);
            HdcDest := CreateCompatibleDC(HdcSRC);
            SetStretchBltMode(HdcDest, COLORONCOLOR);
            HBmp := CreateCompatibleBitmap(HdcSRC,Wr.Width,wr.Height);
            hOld := SelectObject(hDCDest,hBmp);
            BitBlt(hDCDest,0,0,wr.width,wr.Height,HdcSRC,0,0,SRCCOPY);

            { target bitplane is 24 bits RGB }
            bi := default(tagBITMAPINFO);
            bi.bmiHeader.biSize := sizeof(TBitmapInfoHeader);
            bi.bmiHeader.biWidth := wr.Width;
            bi.bmiHeader.biHeight := wr.Height;
            bi.bmiHeader.biPlanes := 1;
            bi.bmiHeader.biBitCount := 24;
            bi.bmiHeader.biCompression := BI_RGB;
            GetDIBits(hDCDest,HBmp,0,wr.Height,src_shot,bi,DIB_RGB_COLORS);

            { now convert pixels to RGBA, in correct line order.
              On Windows, last line is first in bitmap }
            ldst := dst_shot;
            lsrc := src_shot + (src_stride * wr.Height);
            for y := 0 to wr.Height  - 1 do
            begin
              dec(lsrc,src_stride);
              sr := pointer(lsrc);
              dr := pointer(ldst);
              for x := 0 to wr.Width - 1 do
              begin
                dr.rgbBlue := sr.rgbtBlue;
                dr.rgbRed := sr.rgbtRed;
                dr.rgbGreen := sr.rgbtGreen;
                dr.rgbReserved := 255;
                inc(dr);
                inc(sr);
              end;
              inc(ldst,dst_stride);
            end;

            { save to PNG with WIC }
            var tmp_name := Tpath.GetTempFileName('png',false,image_folder);
            wr.Offset(-wr.Left,-wr.top);
            if WICSavePixelsToPng(wr,dst_stride,dst_shot,tmp_name) = S_OK then
            begin
              result := true;
              { rename temp file name to new name if it doesn't exist already }
              var new_name := Tpath.ExtractDirectory(tmp_name) + THashSHA1.GetHashStringFromFile(tmp_name) + '.png';
              if not TPath.FileExists(new_name) then
              begin
                if Tfile.Rename(tmp_name,new_name) then
                begin
                  cs.file_path := '';
                end else begin
                  cs.file_path := new_name;
                end;
              end else begin
                cs.file_path := new_name;
              end;
            end;
            Tfile.Delete(tmp_name);
            result := true;
          finally
            freemem(src_shot);
            freemem(dst_shot);
          end;
        finally
          SelectObject(hDCDest,hold);
          DeleteDC(hDCDest);
          ReleaseDC(win_handle,HdcSRC);
        end;
        except begin
          result := false;
        end;
      end;
    end;

This method is working for Delphi forms using VCL, however with forms using Firemonkey (FMX)  2D, it only produces bitmaps filled with BLACK (0) pixels.
I have tried an alternative using Direct3D9, that is working for Firemonkey form, however with a limitation I'll explain after the code snippet
function Take_window_snapshot_D3D(win_handle: THandle; PID: Cardinal; out cs: TWindowSnapshot; const image_folder: string): boolean;
var
  D3D: IDirect3D9;
  D3DDevice: IDirect3DDevice9;
  mode: D3DDISPLAYMODE;
  device: IDirect3DDevice9;
  surface: IDirect3DSurface9;
  parameters: D3DPRESENT_PARAMETERS;
  rc: D3DLOCKED_RECT;
  pitch: UINT;
  shot: PByte;
  shot_size: cardinal;
  adapter: cardinal;
  wr: TRect;
  hCurWnd: THandle;
  hCurThreadID: Cardinal;
  L: integer;
  hFlags: cardinal;
  hr: HRESULT;

begin
  result := false;
  cs := default(TWindowSnapshot);
  try
    { get the window type }
    hFlags := GetWindowLong(win_handle,GWL_STYLE);
    if (hFlags and (WS_DLGFRAME or WS_POPUP)) = 0 then exit;
    if (hFlags and WS_VISIBLE) = 0 then exit;
    { size }
    GetWindowRect(win_handle,Wr);
    if (Wr.Width = 0) or (Wr.Height = 0) then exit;
    { title }
    L := GetWindowTextLength(win_handle);
    if L > 0 then
    begin
      setlength(cs.title,L);
      GetWindowText(win_handle,pchar(cs.title),L+1);
    end;
    cs.window_handle := win_handle;
    cs.window_rect := wr;
    cs.process_id := PID;

    { Direct3D capture }
    adapter := D3DADAPTER_DEFAULT;
    D3D := Direct3DCreate9(D3D_SDK_VERSION);
    HRCHECK(D3D.GetAdapterDisplayMode(adapter,mode));
    parameters := default(D3DPRESENT_PARAMETERS);
    parameters.Windowed := TRUE;
    parameters.BackBufferCount := 1;
    parameters.BackBufferHeight := mode.Height;
    parameters.BackBufferWidth := mode.Width;
    parameters.SwapEffect := D3DSWAPEFFECT_DISCARD;
    parameters.hDeviceWindow := win_handle;

    { create device & capture surface }
    HRCHECK(d3d.CreateDevice(adapter, D3DDEVTYPE_HAL, win_handle, D3DCREATE_SOFTWARE_VERTEXPROCESSING, @parameters, device));
    { create surface }
    HRCHECK(device.CreateOffscreenPlainSurface(mode.Width, mode.Height, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &surface, nil));

    { bring our window to front }
    hCurWnd := GetForegroundWindow;
    hCurThreadID := GetCurrentThreadId;
    AttachThreadInput(PID,hCurThreadID,TRUE);
    SetWindowPos(win_handle,HWND_TOPMOST,0,0,0,0,SWP_NOSIZE or SWP_NOMOVE);
    SetWindowPos(win_handle,HWND_NOTOPMOST,0,0,0,0,SWP_SHOWWINDOW or SWP_NOSIZE or SWP_NOMOVE);
    SetForegroundWindow(win_handle);
    SetFocus(win_handle);
    SetActiveWindow(win_handle);
    AttachThreadInput(PID,hCurThreadID,false);

    { Obtain stride value to allocate buffer }
    HRCHECK(surface.LockRect(rc,nil,0));
    pitch := rc.Pitch;
    HRCHECK(surface.UnlockRect());
    shot_size := pitch*mode.Height;
    getmem(shot,shot_size);
    if not assigned(shot) then abort;

    try
      { get surface data }
      HRCHECK(device.GetFrontBufferData(0, surface));
      { copy surface data }
      HRCHECK(surface.LockRect(rc,nil,0));
      move(rc.pBits^,shot^,shot_size);
      HRCHECK(surface.UnlockRect());

      { save snapshot to file using WIC, using a temporary file name first }
      var tmp_name := Tpath.GetTempFileName('png',false,image_folder);
      if WICSavePixelsToPng(wr,pitch,shot,tmp_name) = S_OK then
      begin
        result := true;
        { rename temp file name to new name if it doesn't exist already }
        var new_name := Tpath.ExtractDirectory(tmp_name) + THashSHA1.GetHashStringFromFile(tmp_name) + '.png';
        if not TPath.FileExists(new_name) then
        begin
          if Tfile.Rename(tmp_name,new_name) then
          begin
            cs.file_path := '';
          end else begin
            cs.file_path := new_name;
          end;
        end else begin
          cs.file_path := new_name;
        end;
      end;
      Tfile.Delete(tmp_name);
    finally
      FreeMem(shot);
    end;
    except
      result := false;
  end;
end;

The limitation that I have with the D3D method is that in reality I don't take a snapshot of a specific window but I take a snapshot of the entire screen that I crop after to take only the window of my interest.
For that, I must bring first the target window to front, but in some case this may not be possible. For instance if the target form is behind a modal form, it might be partially or totally hidden, as one can see below

So, my question : Is it possible to take a snapshot / print a single Firemonkey 2D form from another process, even if the form is not modal / partially covered by another form.

A: (Sorry for an answer here rather than a comment, which I can't do.)
I know little about working with different processes, but do you realise that FMX has a snapshot ability built in?
TControl.MakeScreenshot returns a bitmap of the control (with child controls).  So if you can call that from the other process and return the result, that might solve your problem.
However, this won't meet your needs if you literally need the whole form including the non-client area, as a form doesn't have that method.  If the contents of the form are all you need, and you have a control (e.g. a TLayout) filling the form and containing all the child controls, you could use the .MakeScreenshot of that bottom control.
And yes, .MakeScreeshot works even if something else is covering the form.