text:
Q: Custom Border on NSTextField I want to customise the border of NSTextFields. I have searched around and am fairly sure this needs to be done within the NSTextFieldCell in drawInterior(withFrame:in:), but am not sure how.
Specifically I want a bottom border only, slightly thicker than normal.

A: You should probably read the documentation for the NSCell. It says that you must draw the border in the draw(withFrame:in) function and you must invoke drawInterior(withFrame:in:) if you override draw(withFrame:in). Additionally you must override cellSize and return the appropriate size that takes your new border into account. I updated the example to the full solution. Created a sample project on Github
/**
 Creates an custom border, that is just a line underneath the NSTextField.
 */
class CustomBorderTextFieldCell: NSTextFieldCell {
    // How thick should the border be
    let borderThickness: CGFloat = 3

    // Add extra height, to accomodate the underlined border, as the minimum required size for the NSTextField
    override var cellSize: NSSize {
        let originalSize = super.cellSize
        return NSSize(width: originalSize.width, height: originalSize.height + borderThickness)
    }

    // Render the custom border for the NSTextField
    override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
        // Area that covers the NSTextField itself. That is the total height minus our custom border size.
        let interiorFrame = NSRect(x: 0, y: 0, width: cellFrame.width, height: cellFrame.height - borderThickness)

        let path = NSBezierPath()
        path.lineWidth = borderThickness
        // Line width is at the center of the line.
        path.move(to: NSPoint(x: 0, y: cellFrame.height - (borderThickness / 2)))
        path.line(to: NSPoint(x: cellFrame.width, y: cellFrame.height - (borderThickness / 2)))
        NSColor.black.setStroke()
        path.stroke()

        // Pass in area minus the border thickness in the height
        drawInterior(withFrame: interiorFrame, in: controlView)
    }
}

This is the result

A: You can add your text field a background image and set your border style none.

A: Add to NSTableHeaderCell this code
override func draw(withFrame cellFrame: NSRect,
                     in controlView: NSView) {
    let path = NSBezierPath()
    path.lineWidth = borderWidth
    // Line width is at the center of the line.
    path.move(to: NSPoint(x: cellFrame.minX, y: cellFrame.minY))
    path.line(to: NSPoint(x: cellFrame.maxX, y: cellFrame.minY))
    NSColor.black.setStroke()
    path.stroke()

    self.drawInterior(withFrame: cellFrame, in: controlView)
  }


text:
Q: SQLITE_ERROR SQL error or missing database (near "Statements": syntax error) I am trying to apply injection attack prevention by using prepared statements. The way my code is set up is that I have a DBManager classe which acts as the catalyst between Java and sqlite by storing the java methods responsible for executing sqlite statements. Then I have table classes which store the sqlite statements themselves. Basically, I want to store a prepared statement which executes an INSERT statement and have a connection to it when  I call an open() method. Here are excerpts from the two classes in question where I am trying to create a prepared stament for a constant stored in the IncomeStatementTable class:
package com.anniemals.database;

//the database package is meant to be the API package which
// takes all queried values from a database and sets them to values
// in each respective class

//MAKE SURE TO ADD METHODS TO ACCESS DB METADATA, FUNCTIONS, AND VIEWS LATER!
import com.anniemals.clients.ClientInfoIncomeStatement;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DBManager {

    public static final String DB_NAME = "clients.db";
    public static final String DB_PATH = "jdbc:sqlite:C:/Users/Steven/Documents/ProjectAnnieMalsRemote/Databases/" + DB_NAME;

    //SortOrders for queries
    public static final int ORDER_BY_NONE = 1;
    public static final int ORDER_BY_ASC = 2;
    public static final int ORDER_BY_DESC = 3;

    //Sets a connection to access and utilize sqlite expressions, which are assigned to the PreparedStatement variables for later use
    private Connection conn;

//Inserts
    private PreparedStatement insertIntoIncomeStatementPStatement;
//Composition has-a relationships for Table Classes
    private ClientInfoTable clientInfoTable;
    private IncomeStatementTable incomeStatementTable;

    public DBManager() {
        //Composition has-a relationships for Table Classes
        this.clientInfoTable = new ClientInfoTable();
        this.incomeStatementTable = new IncomeStatementTable();
    }

    public static DBManager getInstance() {
        return instance;
    }

    //Open and Close DB methods

    public boolean open(){
        try{
            conn = DriverManager.getConnection(DB_PATH);
//STATEMENT WHICH CAUSED THE ERROR!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            insertIntoIncomeStatementPStatement = conn.prepareStatement(incomeStatementTable.getInsertIncomeStatement());
            System.out.println("Database Opened");
            return true;
        } catch (SQLException e){
            System.out.println("Couldn't connect to database: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    public void close(){
        try {
            if (insertIntoIncomeStatementPStatement != null){
                insertIntoIncomeStatementPStatement.close();
            }
            if(insertIntoClientInfoPStatement != null){
                insertIntoClientInfoPStatement.close();
            }
            if (conn != null){
                conn.close();
                System.out.println("Database closed");
            }
        } catch (SQLException e){
            System.out.println("Couldn't close connection: " + e.getMessage());
        }
    }

public class IncomeStatementTable {

    //Column Labels
    public static final String TABLE_INCOME = "Income Statements";
    public static final String COLUMN_INCOME_ID = "_id";
    public static final String COLUMN_CLIENT_ID = "Client ID";
    public static final String COLUMN_INCOME_DATE = "Date";
    public static final String COLUMN_INCOME_TOTAL_OPER_EXPENSES = "Total Operating Expenses";
    public static final String COLUMN_INCOME_GROSS_PROFIT = "Gross Profit";
    public static final String COLUMN_INCOME_AMORTIZATION = "Amortization";
    public static final String COLUMN_INCOME_EBITDA = "E.B.I.T.D.A.";
    public static final String COLUMN_INCOME_PROFIT_BEFORE_TAX = "Profit Before Tax";
    public static final String COLUMN_INCOME_TAX = "Tax";
    public static final String COLUMN_INCOME_NET_PROFIT = "Net Profit";
    public static final String COLUMN_INCOME_EARN_PER_SHARE = "Earnings Per Share";

    //Column Indexes
    public static final int INDEX_INCOME_ID = 1;
    public static final int INDEX_INCOME_CLIENT_ID = 2;
    public static final int INDEX_INCOME_DATE = 3;
    public static final int INDEX_INCOME_TOTAL_OPER_EXPENSES = 4;
    public static final int INDEX_INCOME_GROSS_PROFIT = 5;
    public static final int INDEX_INCOME_AMORTIZATION = 6;
    public static final int INDEX_INCOME_EBITDA = 7;
    public static final int INDEX_INCOME_PROFIT_BEFORE_TAX = 8;
    public static final int INDEX_INCOME_TAX = 9;
    public static final int INDEX_INCOME_NET_PROFIT = 10;
    public static final int INDEX_INCOME_EARN_PER_SHARE = 11;

public static final String INSERT_INCOME_STATEMENT = "INSERT INTO " + TABLE_INCOME + "(" + COLUMN_INCOME_ID +
            ", " + COLUMN_CLIENT_ID +  ", " + COLUMN_INCOME_DATE  + ", " + COLUMN_INCOME_TOTAL_OPER_EXPENSES
            + ", " + COLUMN_INCOME_GROSS_PROFIT  + ", " + COLUMN_INCOME_AMORTIZATION  + ", " + COLUMN_INCOME_EBITDA
            + ", " + COLUMN_INCOME_PROFIT_BEFORE_TAX  + ", " + COLUMN_INCOME_TAX  + ", " + COLUMN_INCOME_NET_PROFIT
            + ", " + COLUMN_INCOME_EARN_PER_SHARE + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    public static String getInsertIncomeStatement() {
        return INSERT_INCOME_STATEMENT;
    }

I know that it has something to do with the variable assignment statement in the open() method because when I comment it out, the program works just fine and I can connect to the database. I've tried looking at answers from other questions that were similar to mine on here, but any changes I've made to the syntax of the sqlite statement itself still leave me with the same error. I've tried tracing the thread stack to see what "Statement" refers to in the error, but I'm still not sure. Could someone help me pinpoint further where the problem might be?
Here is the trace stack:
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (near "Statements": syntax error)
    at sqlite.jdbc@3.23.1/org.sqlite.core.DB.newSQLException(DB.java:909)
    at sqlite.jdbc@3.23.1/org.sqlite.core.DB.newSQLException(DB.java:921)
    at sqlite.jdbc@3.23.1/org.sqlite.core.DB.throwex(DB.java:886)
    at sqlite.jdbc@3.23.1/org.sqlite.core.NativeDB.prepare_utf8(Native Method)
    at sqlite.jdbc@3.23.1/org.sqlite.core.NativeDB.prepare(NativeDB.java:127)
    at sqlite.jdbc@3.23.1/org.sqlite.core.DB.prepare(DB.java:227)
    at sqlite.jdbc@3.23.1/org.sqlite.core.CorePreparedStatement.<init>(CorePreparedStatement.java:45)
    at sqlite.jdbc@3.23.1/org.sqlite.jdbc3.JDBC3PreparedStatement.<init>(JDBC3PreparedStatement.java:30)
    at sqlite.jdbc@3.23.1/org.sqlite.jdbc4.JDBC4PreparedStatement.<init>(JDBC4PreparedStatement.java:19)
    at sqlite.jdbc@3.23.1/org.sqlite.jdbc4.JDBC4Connection.prepareStatement(JDBC4Connection.java:48)
    at sqlite.jdbc@3.23.1/org.sqlite.jdbc3.JDBC3Connection.prepareStatement(JDBC3Connection.java:263)
    at sqlite.jdbc@3.23.1/org.sqlite.jdbc3.JDBC3Connection.prepareStatement(JDBC3Connection.java:235)
    at sqlite.jdbc@3.23.1/org.sqlite.jdbc3.JDBC3Connection.prepareStatement(JDBC3Connection.java:242)
    at AccountingFinancialModellingAndValuationApplication/com.anniemals.database.DBManager.open(DBManager.java:60)
    at AccountingFinancialModellingAndValuationApplication/com.anniemals.Main.main(Main.java:26)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)

Thanks in advance to those who can help.

A: The table name defined by this line:
public static final String TABLE_INCOME = "Income Statements"

contains a space and this is not allowed.
Change to this:
public static final String TABLE_INCOME = "[Income Statements]"

When a table or column name contains spaces must be enclosed in square brackets or backticks (ASCII code 096).
You must do the same for column names containing spaces or dots:
public static final String TABLE_INCOME = "[Income Statements]";
public static final String COLUMN_INCOME_ID = "_id";
public static final String COLUMN_CLIENT_ID = "[Client ID]";
public static final String COLUMN_INCOME_DATE = "Date";
public static final String COLUMN_INCOME_TOTAL_OPER_EXPENSES = "[Total Operating Expenses]";
public static final String COLUMN_INCOME_GROSS_PROFIT = "[Gross Profit]";
public static final String COLUMN_INCOME_AMORTIZATION = "Amortization";
public static final String COLUMN_INCOME_EBITDA = "[E.B.I.T.D.A.]";
public static final String COLUMN_INCOME_PROFIT_BEFORE_TAX = "[Profit Before Tax]";
public static final String COLUMN_INCOME_TAX = "Tax";
public static final String COLUMN_INCOME_NET_PROFIT = "[Net Profit]";
public static final String COLUMN_INCOME_EARN_PER_SHARE = "[Earnings Per Share]";

What seems strange is that since you are trying to insert rows to the table this means that you already created the table.
But how?
What names did you use for the table and the columns in the CREATE statement?

A: I found a solution to my problem. It is not the prettiest solution, but it works. Basically, I added a create method to the DBManager class as suggested by forpas:
 public boolean checkCreateIncomeStatementTable(){
    String sql = "CREATE TABLE IF NOT EXISTS Income_Statements(\n" +
            " _id INTEGER PRIMARY KEY,\n" +
            " Client_ID INTEGER NOT NULL,\n" +
            " Date NUMERAL,\n" +
            " Total_Operating_Expenses DOUBLE NOT NULL,\n" +
            " Gross_Profit DOUBLE NOT NULL,\n" +
            " Amortization DOUBLE NOT NULL,\n" +
            " EBITDA DOUBLE NOT NULL,\n" +
            " Profit_Before_Tax DOUBLE NOT NULL,\n" +
            " Tax DOUBLE NOT NULL,\n" +
            " Net_Profit DOUBLE NOT NULL,\n" +
            " Earnings_Per_Share DOUBLE NOT NULL\n" +
            ");";
    try{
        conn = DriverManager.getConnection(DB_PATH);
        Statement statement = conn.createStatement();
        System.out.println("Database Opened");
        statement.executeQuery(sql);
        System.out.println("Checked creation of Income Statement Table");
        return true;
    } catch (SQLException e){
        System.out.println("Couldn't connect to database: " + e.getMessage());
        e.printStackTrace();
        return false;
    }
}

Then, for each column label with spaces in it, I used underscores since the Main class did not want to read brackets for some reason;
public static final String TABLE_INCOME = "Income_Statements";
public static final String COLUMN_INCOME_ID = "_id";
public static final String COLUMN_CLIENT_ID = "Client_ID";
public static final String COLUMN_INCOME_DATE = "Date";
public static final String COLUMN_INCOME_TOTAL_OPER_EXPENSES = "Total_Operating_Expenses";
public static final String COLUMN_INCOME_GROSS_PROFIT = "Gross_Profit";
public static final String COLUMN_INCOME_AMORTIZATION = "Amortization";
public static final String COLUMN_INCOME_EBITDA = "EBITDA";
public static final String COLUMN_INCOME_PROFIT_BEFORE_TAX = "Profit_Before_Tax";
public static final String COLUMN_INCOME_TAX = "Tax";
public static final String COLUMN_INCOME_NET_PROFIT = "Net_Profit";
public static final String COLUMN_INCOME_EARN_PER_SHARE = "Earnings_Per_Share";

Everything seems to be working now

redpajama_set_name: RedPajamaStackExchange


text:
Q: calibration of the posterior probabilities currently i work on calibration of probability. i use the calibration approach, called rescaling algorithm - the source http://lem.cnrs.fr/Portals/2/actus/DP_201106.pdf (page 7).
the algorithm i wrote is:
rescaling_fun = function(x, y, z) {

    P_korg  = z # yhat_test_prob$BAD

    P_k_C1  = sum(as.numeric(y) - 1)/length(y) # testset$BAD
    P_kt_C1 = sum(as.numeric(x) - 1)/length(x) # trainset$BAD
    P_k_C0  = sum(abs(as.numeric(y) - 2))/length(y)
    P_kt_C0 = sum(abs(as.numeric(x) - 2))/length(x)

    P_new <- ((P_k_C1/P_kt_C1) * P_korg)/((P_k_C0/P_k_C0) * (1 - P_korg) + (P_k_C0/P_k_C1) * (P_korg))

  return(P_new)
}

the input values are:
1. x - train_set$BAD (actuals of `train set`)
2. y - test_set$BAD (actuals of `test set`)
3. z - yhat_test_prob$BAD (prediction on `test set`)

the problem - the result values are not within range of 0 and 1. Could you please help to solve the problem?

A: Your formulas to obtain probs (P_k_C1 ...) need to be modified. For example, according to the paper, y is a binary variable (0, 1) and the formula is sum(y - 1)/length(y) which is most likely to be negative - it converts y values to be -1 or 0, followed by adding them. I consider it should be (sum(y)-1)/length(y). Below is an example.
set.seed(1237)
y <- sample(0:1, 10, replace = T)
y
[1] 0 1 0 0 0 1 1 0 1 1
# it must be negative as it is sum(y - 1) - y is 0 or 1
sum(as.numeric(y) - 1)/length(y)
[1] -0.5
# modification
(sum(as.numeric(y)) - 1)/length(y)
[1] 0.4


text:
Q: Displaying the values of an Arraylist with a JTable I created a class named EmployeeGUI that is able to create any amount of user Employee objects and add them to an arraylist. The problem i have is that i have a JTable at the bottom of my GUI that i want to display all the objects that i've created but in my case the GUI Creates a new Table Object each time it goes through a for loop with the details of an object but as the for loop goes on the new details overwrites the old details rather than being added to the bottom of a jtable. Can anyone help me debug my errors?
Here is my Code
import java.awt.event.*;

public class EmployeeGUI extends JFrame implements ActionListener{

/**
 * @param args
 */
JFrame frame;
JButton button1, button2, button3, button4;
JTextField box1, box2, box3;
JLabel label1, label2, label3;
JTable table1;
int length = 0;
ArrayList<Employee> empArray = new ArrayList<Employee>();

public static void main(String[] args) {
    // TODO Auto-generated method stub
    EmployeeGUI empG = new EmployeeGUI();
    empG.frame.setVisible(true);
}

public EmployeeGUI()
{
    initialize();
}

public void initialize() {
    // TODO Auto-generated method stub
    frame = new JFrame("A Sample Window");
    frame.setBounds(50,50,680,400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    label1 = new JLabel("F-Name:");
    label1.setBounds(30,33,54,25);
    frame.getContentPane().add(label1);

    box1 = new JTextField();
    box1.setBounds(94, 35, 128,20);
    frame.getContentPane().add(box1);

    label2 = new JLabel("S-Name:");
    label2.setBounds(250,33,54,25);
    frame.getContentPane().add(label2);

    box2 = new JTextField();
    box2.setBounds(305, 35, 128,20);
    frame.getContentPane().add(box2);

    label3 = new JLabel("Phone:");
    label3.setBounds(461,33,54,25);
    frame.getContentPane().add(label3);

    box3 = new JTextField();
    box3.setBounds(500, 35, 128,20);
    frame.getContentPane().add(box3);

    button1 = new JButton("Add Employee");
    button1.addActionListener(this);
    button1.setBounds(71,131,113,39);
    frame.getContentPane().add(button1);

    button2 = new JButton("Remove Employee");
    button2.addActionListener(this);
    button2.setBounds(194,131,128,39);
    frame.getContentPane().add(button2);

    button3 = new JButton("Display Employee");
    button3.addActionListener(this);
    button3.setBounds(332,131,128,39);
    frame.getContentPane().add(button3);

    button4 = new JButton("Quit Program");
    button4.addActionListener(this);
    button4.setBounds(475,131,113,39);
    frame.getContentPane().add(button4);

    table1 = new JTable();
    table1.setBounds(0,184,664,178);
    frame.getContentPane().add(table1);
}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    String action = ((JButton) e.getSource()).getActionCommand();
    if(action.equals("Add Employee"))
    {
        String fName = box1.getText();
        String lName = box2.getText();
        String pNo = box3.getText();

        int mobile = Integer.parseInt(pNo);

        Employee ee = new Employee(fName,lName,mobile);
        empArray.add(ee);
        length++;
        JOptionPane.showMessageDialog(null, "Employee Added");
    }
    if(action.equals("Remove Employee"))
    {
        String fName = box1.getText(), lName = box2.getText();
        int mobile = Integer.parseInt(box3.getText());
        Employee ee = new Employee(fName,lName,mobile);
        if(length>0)
        {
            for(int i=0; i<empArray.size(); i++)
            {
                if(empArray.get(i).getLName() == ee.getLName())
                {
                    empArray.remove(i);
                    JOptionPane.showMessageDialog(null, "Employee Removed");
                }
            }
        }
        else{
            throw new ListEmptyException("List is Empty");
        }
    }
    if(action.equals("Display Employee"))
    {
        for(int i = 0; i <empArray.size(); i++)
        {
            table1.setModel(new DefaultTableModel(
                    new Object[][] {
                            {empArray.get(i).getFName(),empArray.get(i).getLName(),empArray.get(i).getMobile()}
                    },
                    new String[] {
                        "First Name", "Surname", "Phone Number"
                    }
                ));
        }
    }
    if(action.equals("Quit Program"))
    {
        System.exit(0);
    }
}
}

and the Employee Class
public class Employee {
private String fName,lName;
private int mobile;

public Employee(String fName, String lName, int mobile)
{
    setFName(fName);
    setLName(lName);
    setMobile(mobile);
}

private void setMobile(int mobile) {
    // TODO Auto-generated method stub
    this.mobile = mobile;
}

public void setLName(String lName) {
    // TODO Auto-generated method stub
    this.lName = lName;
}

public void setFName(String fName) {
    // TODO Auto-generated method stub
    this.fName = fName;
}

public String getFName()
{
    return fName;
}

public String getLName()
{
    return lName;
}

public int getMobile()
{
    return mobile;
}

public String toString()
{
    return getFName()+" "+getLName()+" "+getMobile();
}

public void print()
{
    System.out.println(toString());
}
}

A: only comment, longer

*

*see number of table1.setModel(new DefaultTableModel( created in loop for(int i = 0; i <empArray.size(); i++)

*new Object[][] {{empArray.get(i).getFName(), empArray.get(i).getLName(),empArray.get(i).getMobile()}}, is converted to DataVector, you lost, haven't access to this array

*(if is there reason to hold two the same arrays in your program then) use array based on util.List in AbstractTableModel

A:
the new details overwrites the old details rather than being added to the bottom of a jtable.

First add all the record in a List then set the model just once otherwise it will override the last one in loop.
sample code:
if (action.equals("Display Employee")) {
    List<Object[]> list = new ArrayList<Object[]>();
    for (int i = 0; i < empArray.size(); i++) {
        list.add(new Object[] {
                                  empArray.get(i).getFName(),
                                  empArray.get(i).getLName(),
                                  empArray.get(i).getMobile()
                              });

    }
    table1.setModel(new DefaultTableModel(list.toArray(new Object[][] {}),
                        new String[] {"First Name", "Surname", "Phone Number"}));
}

A: You can use the addRow() method of the DefaultTableModel, like this:
((DefaultTableModel)table1.getModel()).addRow(new Object[] {
     empArray.get(i).getFName(),
     empArray.get(i).getLName(),
     empArray.get(i).getMobile()
});


text:
Q: isIdleTimerDisabled = true works but setting back to false won't dim the screen again This is an iOS 13+ only app.
I want to let the user decide if the main view controller of my app prevents screen dimming or not. That view controller has in viewDidAppear:
UIApplication.shared.isIdleTimerDisabled = GlobalSettings.keepScreenOn // my setting variable

In viewDidDisappear it has:
UIApplication.shared.isIdleTimerDisabled = false

The intention is that whenever this VC is not on screen, screen dimming should work normally. While testing the feature, I see that once I turned the setting on, the screen won't dim again whether I let it sit in another VC, and whether I turn the setting off again.
Any ideas??


text:
Q: Variation of determinant of the metric tensor I have the metric tensor $g_{\mu\nu}$. I want to make the variation of $\sqrt{-g}$ where $g=detg_{\mu\nu}$.
How can I make this work? My attempt is the following:
$$\sqrt{-g}=\sqrt{-e^{Tr(log(g_{\mu\nu}))}}=\sqrt{-e^{-Tr(log(g^{\mu\nu}))}}$$
$$\rightarrow\delta\sqrt{-g}=\delta(\sqrt{-e^{-Tr(log(g^{\mu\nu}))})}=\delta(-e^{-\frac{1}{2}Tr(log(g^{\mu\nu}))})$$
$$=e^{-\frac{1}{2}Tr(log(g^{\mu\nu}))}\delta(-\frac{1}{2}Tr(log(g^{\mu\nu})))=-\frac{1}{2}\sqrt{-g}\delta g^{-1}Tr((log(g^{\mu\nu})))=$$
$$=-\frac{1}{2}\sqrt{-g}Tr(g_{\mu\nu}\delta g^{\mu\nu})=-\frac{1}{2}\sqrt{-g}\ g_{\mu\nu}\delta g^{\mu\nu}$$
But, there seems to be a problem of notation; I write $Tr(g_{\mu\nu}\delta g^{\mu\nu})$.

A: I am assuming the final equality $-\sqrt{-g}g_{\mu\nu}\delta g^{\mu\nu}/2$ is a known result you are trying to check against your calculation of $-\sqrt{g}\ \text{tr}(g_{\mu\nu}\delta g^{\mu\nu})/2$.  If so, you have essentially arrived at the same result, but notice that the expression $g_{\mu\nu}\delta g^{\mu\nu}$ in your final equality is already a scalar, since there is an implied sum over repeated indices. Taking the trace of such a quantity is trivial since there is only one element. Actually, what you have in the last equality is already the trace that you probably intended since for a matrix product $g_{\mu\nu}\delta g^{\nu\rho}$ the trace is given by summing over the remaining free indices $\mu$ and $\rho$:
$$
\text{tr} \left(g_{\mu\nu}\delta g^{\nu\rho}\right) =  g_{\mu\nu}\delta g^{\nu\mu}=g_{\mu\nu}\delta g^{\mu\nu}
$$

I'll also add that there is an easier way to do the calculation in your question. Namely, you could use Jacobi's formula for invertible matrices, which gives that for an invertible matrix $A$:
$$
d \det A = \det A \ \text{tr}\left(A^{-1} dA\right) \ .
$$
In terms of the variation of the metric tensor this means you can quickly find that $\delta g = g \left(g^{\mu\nu}\delta g_{\mu\nu}\right)$, which lets you compute
$$
\delta\sqrt{-g} = -\frac{1}{2\sqrt{-g}}\delta g= \frac{1}{2}\frac{-g}{\sqrt{-g}}\left(g^{\mu\nu}\delta g_{\mu\nu}\right) = -\frac{1}{2}\sqrt{-g}\left(g_{\mu\nu}\delta g^{\mu\nu}\right)
$$


text:
Q: query an indexed jsonb column I want to query a jsonb column with the @> operator.
This query gives results:
select * from json_table1
where p_attribute @> '{"age":"37"}'

This query doesn't fail but also doesn't give results:
select * from json_table1
where p_attribute -> 'age' @> '37'::jsonb

The table used in the example:
create table json_table1 (
    p_id int primary key,
    first_name varchar(20),
    last_name varchar(20),
    p_attribute jsonb,
    quote_content text
)

The index on p_attribute:
create index gin_idx on json_table1 using gin(p_attribute jsonb_path_ops)

A: Since "37" is a string, not a number, your second query would have to use a jsonb string:
... WHERE p_attribute -> 'age' @> '"37"'::jsonb

Note the double quotes around 37.
Also note that this query wouldn't be able to use the index, while the first query can.


text:
Q: Typescript type RequireSome removing undefined AND null from properties RequireSome type from another, very simialar question. This question is similar but it should not be a duplicate since here we want to also remove null as well as undefined from properties.
Maybe the name shouldn't be Require but something like NonNullable or of this kind. The goal of this type is to specify which fields from a type should not be undefined or null, and return their types without undefined and null.
type Question = {
    id: string;
    answer?: string | null;
    thirdProp?: number | null;
    fourthProp?: number | null;
}

// usage NonNullable<Question, 'answer' | 'thirdProp'> expect to equal
/*

type Question = {
    id: string; // no changes
    answer: string; // changed
    thirdProp: number; // changed
    fourthProp?: number | null; // no changes
}

*/

A: The simplified approach that just intersects with T with Required<Pick<T, K>> with the required part basically overriding the optional properties in T will not work here. (Incidentally this works because { foo?: X } & { foo: X } is essentially { foo: X })
To also remove nullability, we have to first create a type that removed null and undefined from a given type T (analogous to Required). Then we need to intersect the properties we want to make required and not null with the rest of the keys in T using the Omit type.
type Omit<T, K> = Pick<T, Exclude<keyof T, K>> // not needed in ts 3.5

type RequiredAndNotNull<T> = {
    [P in keyof T]-?: Exclude<T[P], null | undefined>
}

type RequireAndNotNullSome<T, K extends keyof T> =
    RequiredAndNotNull<Pick<T, K>> & Omit<T, K>

type Question = {
    id: string;
    answer?: string | null;
    thirdProp?: number | null;
    fourthProp?: number | null;
}

type T0 = RequireAndNotNullSome<Question, 'answer' | 'thirdProp'>


text:
Q: Call to open on MSXML2.ServerXMLHTTP.6.0 object fails Need to do a GET from VBScript to a web page to verify it is accessible.  This code used to work fine:
With CreateObject("Microsoft.XMLHTTP")
  .Open "GET", "https://www.google.com", False
  .Send
  content = .ResponseText
End With

Now, the code above fails with permission denied on the CreateObject line. Obviously a OS security configuration change.
I tried using MSXML2.ServerXMLHTTP.6.0 object instead as suggested by other posts (see code snippet below):
With CreateObject("MSXML2.ServerXMLHTTP.6.0")
  .Open "GET", "https://www.google.com", False
  .Send
  content = .ResponseText
End With

This code fails with the error message "the specified procedure could not be found" Code: 8007007F Source: msxml6.dll.
What on earth? It's implying a syntax error with the .Open.  The CreateObject call works fine so that gets it past the permission error, but it's saying the "Open" sub is not available for the MSXML2.ServerXMLHTTP.6.0 object?
Other Info:
Windows 10 Enterprise
Build: 10.0.19042

A: Looks like McAfee Endpoint Security is causing this.  The runtime error dialog from wscript.exe made it seem as if there was a syntax error in the VBscript code, but I guess McAfee has intercepted the event and really confused wscript.exe. Here's the message I found in Event Viewer if it helps anyone.  I guess if I want this changed, I'll need to contact the McAfee Endpoint Security manager and have them put in an exception if they are willing.

EventID=18060
domain\user ran C:\Windows\System32\wscript.exe, which attempted to access >the process winhttp.dll, violating the rule "ASR : File Download attempt by >Scripts", and was blocked. For information about how to respond to this >event, see KB85494.


text:
Q: \begin{align*} ... \end{align*} is not working I am getting an error in the following code on my LaTeX template. But the same code is running on MathJax.
\begin{align*}
    1. {\log_{a}a} = 1\  \mbox{log of a number to the same base is 1}

\end{align*}

Please help.

A: The error is due to the blank line, but also do not use align or align* for 1-line equations with no alignment, the vertical spacing will be wrong. If the 1. is not mathematics but part of an enumerated list then perhaps
\begin{enumerate}
\item $\log_{a}a = 1$ log of a number to the same base is $1$
\end{enumerate}


text:
Q: Preprocessing of spectroscopy data for PLSR: do I need to normalize the data for every wavelength? I want to apply a partially least square regression on spectroscopy data to model a chemical content of my probe. So, every wavelength of the spectrum serves as one variable in the model. Doing some research, I found several scenarios how to preprocess the data: Most just use the spectrums as they are and do no preprocessing at all. Others mention that it is important to do a column normalization (e.g. mean centering for every wavelength across the observations) before modeling. I also read that even the target variable should be normalized.
Since normalization is important for dimension reduction, (what is one part of PLSR) it kind of makes sense for me to normalize the data. However, most examples I found people are not doing any normalizations.
What would be the best procedure?
Thanks for any help!


text:
Q: Trying to install i386 package libc6:i386 on Raspberry Pi 3 B+ fails The end goal is to get my Raspberry Pi to work as a print server providing AirPrint for a Brother DCP-195C printer they already have.
I'm trying to follow this answer on how to achive that.
So I already got to the point of where I installed the printer driver, but since that is only provided in compiled form for 32bit x86. So I tried to install Qemu to be able to use those.
I'm getting stuck on
$ sudo apt install libc6:i386
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 libc6:i386 : Depends: libgcc1:i386 but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

A bit more information:
$ sudo aptitude install libc6:i386
The following NEW packages will be installed:
  gcc-6-base:i386{ab} libc6:i386 libgcc1:i386{ab}
0 packages upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 2,698 kB of archives. After unpacking 10.2 MB will be used.
The following packages have unmet dependencies:
 gcc-6-base : Breaks: gcc-6-base:i386 (!= 6.3.0-18+rpi1+deb9u1) but 6.3.0-18+deb9u1 is to be installed
 gcc-6-base:i386 : Breaks: gcc-6-base (!= 6.3.0-18+deb9u1) but 6.3.0-18+rpi1+deb9u1 is installed
 libgcc1 : Breaks: libgcc1:i386 (!= 1:6.3.0-18+rpi1+deb9u1) but 1:6.3.0-18+deb9u1 is to be installed
 libgcc1:i386 : Breaks: libgcc1 (!= 1:6.3.0-18+deb9u1) but 1:6.3.0-18+rpi1+deb9u1 is installed
The following actions will resolve these dependencies:

     Keep the following packages at their current version:
1)     gcc-6-base:i386 [Not Installed]
2)     libc6:i386 [Not Installed]
3)     libgcc1:i386 [Not Installed]

Accept this solution? [Y/n/q/?] n

*** No more solutions available ***

The following actions will resolve these dependencies:

     Keep the following packages at their current version:
1)     gcc-6-base:i386 [Not Installed]
2)     libc6:i386 [Not Installed]
3)     libgcc1:i386 [Not Installed]

Accept this solution? [Y/n/q/?] y
No packages will be installed, upgraded, or removed.
0 packages upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B of archives. After unpacking 0 B will be used.
How can I either make this work or is there another way to get the printer working?

A: I managed to make the DCP-197C to work:
I don't know if I miss something, because I tried it so many times, but I want to write somewhere what I did today, when it finally worked:
Install all the necessary stuff
apt-get install qemu binfmt-support qemu-user-static cups a2ps

Add architecture
dpkg --add-architecture i386

Download libc6 for i386 (I found it here)
wget old.kali.org/kali-security/pool/main/e/eglibc/libc6_2.13-38+deb7u8_i386.deb

If you try to install this, you will mess around with apt, so we will extract the deb and copy these files manually
dpkg -x libc6_2.13-38+deb7u8_i386.deb data

sudo cp -r data/lib/* /lib
sudo cp -r data/usr/* /usr
sudo cp -r data/etc/* /etc

Run this and add it to bashrc to run in every reboot
EXTRA_OPTS="-L /lib/i386-linux-gnu"

Download and install your drivers - for me e.g.:
wget https://download.brother.com/welcome/dlf005405/dcp197ccupswrapper-1.1.3-1.i386.deb
wget https://download.brother.com/welcome/dlf005403/dcp197clpr-1.1.3-1.i386.deb

sudo dpkg -i dcp197ccupswrapper-1.1.3-1.i386.deb
sudo dpkg -i dcp197clpr-1.1.3-1.i386.deb

A: I'm having the very same issue. From what I can tell there is not really a way to fix it at the moment. libc6:armhf can be installed alongside the i386 version if they are the exact same version. Because however, all raspbian packages have "rpi#" (# will be your version of the pi, so e.g. 1 for rpi 1/zero, 2 for 2 etc.) added into their version number, the versions will never line up correctly. This basically means that i386 can't be installed on raspbian (I have literally no idea how the guy from the post you referenced got it working).
I have found this post on a German forum saying that multiarch is working properly on Ubuntu Mate (which, unfortunately for me isn't available for RPi 1 and Zero) so it might be worth a shot to try this whole thing through Ubuntu.


text:
Q: Yii framework, after submiting the form text fields are not updated in database I am pretty new with MVC and Yii framework, therefore there is a good chance that my question is pretty stupid. If so, accept my appologies in advance.
I want to have a form in my admin section of the website, where, user can post some content. I followed the tutorial for sample blog however it seems that the content added to the fields that are defined as text in the database (textarea in my form) don't get updated after submitting the form (everything else works fine). here is the sql statement for my table:
CREATE TABLE `tbl_show` (
   `id` bigint(20) NOT NULL AUTO_INCREMENT,
   `presentation` text,
    PRIMARY KEY (`id`),
    KEY `fk_tbl_show_tbl_season1` (`tbl_season_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

I used Gii to make my Model and CRUD, I only add here the parts that might be related:
On my controller:
    public function actionCreate()
{
    $model=new Show;

    if(isset($_POST['Show']))
    {
        $model->attributes=$_POST['Show'];
        if($model->save())
                    {
                        $this->redirect(array('view','id'=>$model->id));
                    }
    }
    $this->render('create',array(
        'model'=>$model,
    ));

and my _form.php:

 <?php $form=$this->beginWidget('CActiveForm', array(
 'id'=>'show-form',
 'enableAjaxValidation'=>false,
  )); ?>

<?php echo $form->errorSummary($model); ?>

    <?php echo $form->labelEx($model,'presentation'); ?>
    <?php echo $form->textArea($model,'presentation',array('rows'=>6, 'cols'=>50)); ?>
    <?php echo $form->error($model,'presentation'); ?>

    <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

    <?php $this->endWidget(); ?>

Model Rules:
return array(
    array('id, presentation', 'safe', 'on'=>'search'),
);

I don't get why only the text content don't get updated, they appear as null in the database.
Thank you in advance,
Cheers,
Mahsa

A: You have to make the attribute safe . Add this to your Show models validation rules
array('presentation','safe')

A: I found the problem for the form not submitting correctly, I add it here in case anybody has the same problem:
I'd overwritten the beforeSave, but I wanted to complete it later so it wasn't returing anything:
protected function beforeSave() {
        if(parent::beforeSave())
        {
            if($this->isNewRecord)
            {
               //things that should be added by the system
            }
        }

    }

After commenting this everything works fine. Also as you guys recommended I added the fields that didn't have validation to the safe rule.

A: try this ..
public function actionCreate()
{
    $model=new Show;

    if(isset($_POST['Show']))
    {
        $model->attributes=$_POST['Show'];

        $save = $model->save(false);      // write like this...
        if($save)
                    {
                        $this->redirect(array('view','id'=>$model->id));
                    }
    }
    $this->render('create',array(
        'model'=>$model,
    ));

hope it will work for you..


text:
Q: Which is the best way to develop this UI? I'm trying to develop a particular UI, but I have some problems.
In my UI there are two main blocks of ImageViewsand EditTextsand under each block there is an ExpandableListView:

The main problem it's with the ExpandableListView, because i want that when those lists expands and the layout became bigger than the screen , the screen became scrollable. But if I put a scrollview, only the list that goes out of the screen became scrollable.
I've tryed different solutions but nothing worked...
So what's the best way to do this? witch layout it's better?


text:
Q: Group array of hashes on key and append nested array on another hash key I need to reduce an array of hashes into a single hash if that hash key matches.
my_array is an array of hashes, each of which has two keys: one an active record object, the other an array of different active record objects, similar to:
my_array = [
  {
    first_hash_key: {id: 1, title: "my title"},
    second_hash_key: ["stuff", "more stuff", "more stuff"]
  },
  {
    first_hash_key: {id: 1, title: "my title"},
    second_hash_key: ["stuff 3", "uniq stuff 2"]
  },
  {
    first_hash_key: {id: 2, title: "my other title"},
    second_hash_key: ["interesting stuff", "uniq stuff"]
  }
]

I want to combine hashes by first_hash_key[:id], add each item in hash_key_two to an array, not overwrite them to get:
my_array = [
  {
    first_hash_key: {id: 1, title: "my title"},
    second_hash_key: [
      ["stuff", "more stuff", "more stuff"],
      ["stuff 3", "uniq stuff 2"]
    ]
  },
  {
    first_hash_key: {id: 2, title: "my other title"},
    second_hash_key: ["interesting stuff", "uniq stuff"]
  }
]

I can reduce the top level array and hash, and use merge, but I'm losing the individual arrays inside the hash.
I've also tried grouping by the id of the first_hash_key, and then injecting like this:
my_array.group_by{|h| h[:first_hash_key]}.map{|k,v| v.inject(:merge)}

Again, I'm losing the arrays in the second_hash_key. I only get the last array listed. Without map, I get an array of each hash in the group, but the top level isn't combined.
[
  {
    :first_hash_key=>{:id=>1, :title=>"my title"},
    :second_hash_key=>["stuff 3", "uniq stuff 2"]
  },
  {
    :first_hash_key=>{:id=>2, :title=>"my other title"},
    :second_hash_key=>["interesting stuff", "uniq stuff"]
  }
]

Update
As noted by sawa and cary, there is no sense in guessing for the second_hash_key if the data is an array or array or arrays, better to always have an array of arrays.  The desired output is:
 [{:first_hash_key=>{:id=>1, :title=>"my title"},
   :second_hash_key=>[["stuff", "more stuff", "more stuff"],
                      ["stuff 3", "uniq stuff 2"]]
 },
 {:first_hash_key=>{:id=>2, :title=>"my other title"},
 :second_hash_key=>[["interesting stuff", "uniq stuff"]]
 }]

A: well it ain't pretty but here you go:
my_array.
  group_by { |elem| elem[:first_hash_key] }.
  transform_values { |vals| vals.map { |val| val[:second_hash_key] } }.
  reduce([]) do |memo, (key, vals)|
    memo + [{first_hash_key: key, second_hash_key: vals}]
  end

returns:
[
  {
    :first_hash_key=>{:id=>1, :title=>"my title"},
    :second_hash_key=>[
      ["stuff", "more stuff", "more stuff"],
      ["stuff 3", "uniq stuff 2"]
    ]
  }, {
    :first_hash_key=>{:id=>2, :title=>"my other title"},
    :second_hash_key=>[
      ["interesting stuff", "uniq stuff"]
    ]
  }
]

If you're not clear how this works you should inspect the result of each line, but to summarize

*

*group by first_hash_key

*call transform_values to get the values at second_hash_key corresponding to each of these first_hash_key values

*At this point you have a hash mapping first_hash_key value to all of the corresponding values of second_hash_key. Now just have to reduce it to get the final data structure.
This pattern of group_by => transform_values => reduce is something I use all the time and is very useful. transform_values is available in rails as well as ruby 2.5 I believe.

A: my_array.each_with_object({}) do |g,h|
  h.update(g[:first_hash_key][:id]=>g) { |_,o,n|
    o.merge(second_hash_key: [[*o[:second_hash_key]], n[:second_hash_key]]) }
end.values
  #=> [{:first_hash_key=>{:id=>1, :title=>"my title"},
  #     :second_hash_key=>[["stuff", "more stuff", "more stuff"],
  #                        ["stuff 3", "uniq stuff 2"]]},
  #    {:first_hash_key=>{:id=>2, :title=>"my other title"},
  #     :second_hash_key=>["interesting stuff", "uniq stuff"]}]

The receiver of Hash#values is the hash:
{1=>{:first_hash_key=>{:id=>1, :title=>"my title"},
     :second_hash_key=>[["stuff", "more stuff", "more stuff"],
                        ["stuff 3", "uniq stuff 2"]]},
 2=>{:first_hash_key=>{:id=>2, :title=>"my other title"},
     :second_hash_key=>["interesting stuff", "uniq stuff"]}}

This uses the form of Hash#update (aka merge!) that employs a block to determine the values of keys that are present in both hashes being merged, here the keys being 1 and 2. That block has three block variables: _ equals the common key1; o ("old") is value of the key _ in the hash being constructed and n ("new") is the value of the key _ in the hash being merged into the hash being constructed.
The expression [*o[:second_hash_key]] converts o[:second_hash_key] to an array of itself if o[:second_hash_key] is not an array and leaves o[:second_hash_key] unchanged if it is already an array. For example, [*1] #=> [1], whereas [*[1,2]] #=> [1,2].
The return value is problematic in that the value of :second_hash_key is in one case an array of arrays and in another it is simply an array. In subsequent calculations it therefore will be necessary to determine if each value is an array of arrays or just an array, and then take action accordingly. That could be done, of course, but it's messy and ugly; better to make all the values arrays of arrays. We could do that as follows.
my_array.each_with_object({}) do |g,h|
  h.update(g[:first_hash_key][:id]=>
    g.merge(second_hash_key: [g[:second_hash_key]])) { |_,o,n|
      o.merge(second_hash_key: o[:second_hash_key] + n[:second_hash_key]) }
end.values
  #=> [{:first_hash_key=>{:id=>1, :title=>"my title"},
  #     :second_hash_key=>[["stuff", "more stuff", "more stuff"],
  #                        ["stuff 3", "uniq stuff 2"]]},
  #    {:first_hash_key=>{:id=>2, :title=>"my other title"},
  #     :second_hash_key=>[["interesting stuff", "uniq stuff"]]}]

1 The use of the underscore--a valid local variable--for the common key is to inform the reader that it is not used in the block calculation.


text:
Q: Integration AutobahnJS with Vue.js I'm looking for an easy way to integrate Vue.js with AutobahnJS.
I've already checked this repo for guidance/template, but my main problem is that Autobahn has two layers of "wait":

*

*First you create a Connection/Session instance

*You wait for it to connect (maybe even retry N times)

*Only after this can you access the session methods (subscribe/call/etc..)

With my limited JS knowledge (i'm a backend dev), i have two ideas:

*

*Create a global variable which will be assigned to the autobahn session after connection. This will surely cause cases where the var is not yet set, so I'd have to check it's existence every time I want to subscribe from a vue instance.

*Place the Vue init code into the Session connected callback, but then that would delay the whole application, which is obviously bad too.

I'm looking for a simple and efficient solution, not necessarily a full-fledged plugin (which I haven't found anywhere).
Any help/advice is appreciated!

A: I've been looking for a plugin like this: https://github.com/lajosbencz/vue-wamp
Plugin calls are deferred until autobahn Session is ready, unsubscribe and unregister are automatically called component-wise.


text:
Q: Вывод информации из SQLite Здравствуйте. Есть код, он выводит всю информацию из БД в лист.
       final SQLiteDatabase sqLiteDatabase = dataBase.getReadableDatabase();
      Cursor cursor = sqLiteDatabase.query("Messeg",null,null,null,null,null,null);
      if(cursor.moveToFirst()){
         // while (cursor.moveToNext()){
          do {

              UpList.add(0, new DialogSaveData(
                     cursor.getString(cursor.getColumnIndex("fr")),
                    cursor.getString(cursor.getColumnIndex("fr")),
                     cursor.getString(cursor.getColumnIndex("data"))
             ));

   CastomDialog adapter = new CastomDialog(MainActivity.this, R.layout.castom_dialog_list, UpList);
              //присваиваем адаптер списку
              listChat.setAdapter(adapter);

          }while (cursor.moveToNext());
       }else {
          dataMess.setText("no table");
       }

   }

как вывести только те строки где data = "123"?

A: Cursor cursor = sqLiteDatabase.query("Messeg",
                                     null,
                                     "data = ?",
                                     new String[] { "123" },
                                     null, null, null);


text:
Q: ASP.NET Core 2.0 Preview 2 on IIS error 502.5 I use asp.net core 2 Preview 2.
I opened stdoutLogEnabled = "true" in web.config but the system does not write logs.
Deploying on windows server 2012 r2 gives :
Error

HTTP Error 502.5 - Process Failure.

Web.config
<aspNetCore processPath="dotnet" arguments=".\App.WebHost.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false" />

Logs

Please help me.

A: Try to install .NET Core SDK on the server:
https://www.microsoft.com/net/download/core
It solved the same problem for me.

A: You need add this to your project :
<PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>

Please view attached picture.

A: Try using exact location of dotnet.exe in web.config
processPath="dotnet",
i.e. In my case C:\Program Files(x86)\dotnet\dotnet.exe

A: Brand new .net core 2.1  app trying to deploy to new Azure app service with new app service plan.  Same issues, namely 502.5 error ( HTTP Error 502.5 - Process Failure ).
I implemented the above steps and still ran into errors.  I opted to use the  chose the self-contained deployment mode (compared to framework dependent (win-x64)).
This resolved my issue.
This answer was also submitted to [question]: .net-core-2.0 azure app service 502.5 error
Perhaps these questions should be linked.

A: I had this same problem, even after installing the hosting bundle. The solution was in the documentation -

Restart the system or execute net stop was /y followed by net start w3svc from a command prompt to pick up a change to the system PATH.

This is done after installing the .NET Core Windows server hosting bundle.

A: I had the same problem
You must install "Windows Hosting Bundle"
This is the newest version 2.1.0 and supports the old version
https://www.microsoft.com/net/download/thank-you/dotnet-runtime-2.1.0-windows-hosting-bundle-installer

A: I was having the same problem
I installed .NET Core 2.0 Preview 2 (the button in point 1) on the server
https://www.microsoft.com/net/core/preview#windowscmd
and it's running now

A: The same issue occurred then got resolved to follow below steps.
1: First delete .bin and.obj folder......mean Clean your application.
2: Definitely this is version mismatching issue to see this >> go to "ASP.Net Core WebServer" in the Output window to see action error.
In VS 2017, My case .
 2.1.4 at [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
AdminLTE> It was not possible to find any compatible framework version
AdminLTE> The specified framework 'Microsoft.AspNetCore.App', version '2.1.5' was not found.
3: Install Microsoft.AspNetCore.App 2.1.5 (for mine) through package manager console.
4: Rebuild again then issue got fixed.
Please reply if still getting the same issue.

A: First you have to check the required dot net version, Confirm the same version applied in both server and developed local machine.
Using Command prompt :
>dotnet --info

Solution 2:
Execute the dll file using command prompt with dotnet interpreter
YOUR_DLL_PATH> dotnet yourdllpath.dll

By this you can find the actual error.
Good luck


text:
Q: Python: Slicing a dataframe by a list returns a longer list than expected I have a list of 517 tuples. When I use that list to slice my dataframe using .loc, somehow there are 518 rows. If it's important, these are 517 tuples of a multi-index. Visual examination of the result appears to have no obvious header or null rows.
print(submatrix2.shape)
x = list(get_list_of_university_towns().itertuples(index=False, name=None))
print(len(x))
univ_matrix = submatrix2.loc[x,]
print(univ_matrix.shape)

Outputs:
(10730, 1)
517
(518,1)

What could be causing this mismatch?

A: You probably have a duplicate index, which allows your final shape to be greater than your passed list.
Reproducible example:
df = pd.DataFrame({'vals':["a", "b", "c", "d"],
                   'n':[0,1,1,2]})

df = df.set_index('n')

    vals
n
0   a
1   b
1   c
2   d

Now
>>> x=[0,1,2];len(x)
3
>>> df.loc[x,:].shape
(4, 1)


text:
Q: What is std::vector initialised to? std::vector<int> foo(5);  // creates 5-element int vector

what is the value (or that is the values) of foo?
I understand that it creates a 5-element character vector, but what is the value of each, is it zero or undefined?

A: When you use this particular constructor of std::vector, the elements of the vector are value initialized.
See http://en.cppreference.com/w/cpp/container/vector/vector for more details on vector::vector.
See http://en.cppreference.com/w/cpp/language/value_initialization for more on value initialization.
For your case, the elements are of type int. That implies each of the elements the vector is initialized to zero.


text:
Q: photoswipe opening wrong image after filter is applied After I apply a filter (setting some images to display none depending on class names). Photoswipe is opening according to the index number each image originally had. The array that photoswipe is pulling from is updated to only include filtered images. However, the index value that each image points to does not update.
If an image was item 5 in un-filtered gallery and number 1 in the filtered gallery, after applying filter, clicking on this image will open image number 5 in the filtered gallery.
This is my code that sets the array:
getFigures = function() {
var filteredFigures = [];
$pic.find('figure:visible > a').map(function() {
var $href = $(this).attr('href'),
$size = $(this).data('size').toString().split('x'),
$width = $size[0],
$height = $size[1];

                var figures = {
                    src : $href,
                    w   : $width,
                    h   : $height
                };
                filteredFigures.push(figures);
            });
            return filteredFigures;
        };

This is my code that is selecting index and opening photoswipe:
    $pic.on('click', 'figure', function(event) {
    event.preventDefault();

         filteredFigures = getFigures();
            $.map(filteredFigures, function(index, value) {
            image[index]     = new Image();
            image[index].src = value['src'];
        });
            var $index = $(this).index();
            var options = {
                index: $index,
                bgOpacity: 0.8,
                showHideOpacity: true
            }

            var lightBox = new PhotoSwipe($pswp, PhotoSwipeUI_Default, filteredFigures, options);
            lightBox.init();

Thanks in advance for any help!

A: One solution is to not open the picture using its index number because that is where the mismatch is happening. Use something else: The object has a key "src" who's value matches the href of the image you are clicking on. So use that to open the pictures
code to open photoswipe reading as follows works:
        $pic.on('click', 'a', function(event) {
        event.preventDefault();
        filteredFigures = getFigures();

    var clickedAHref = ($(this).attr('href'));
    console.log(clickedAHref);
    var matchedIndex = filteredFigures.map(function (obj) { return obj.src; }).indexOf(clickedAHref);

        var $index = $(this).index();
        var options = {
            index: matchedIndex,
            bgOpacity: 0.8,
            showHideOpacity: true
        }

        var lightBox = new PhotoSwipe($pswp, PhotoSwipeUI_Default, filteredFigures, options);
        lightBox.init();
    });


text:
Q: Applying Groupby function to multiple column in python and calculation I am trying to use groupby in python to divide the INPUT_DF based on two columns ID and DATE(MM/DD/YY) and then perform mathematical operation  on the grouped rows.
The Math function for the grouped Rows is: EXPOSURE * VALUE. For the grouped ID and DATE there might be multiple exposures in that case it should be SUM(EXPOSURE * VALUE)
INPUT_DF:
ID  PRODUCT EXPOSURE    DATE(MM/DD/YY)  VALUE
STA A   0.5 1/31/03 3
STA A   0.5 8/29/03 4
MP  B   0.6 8/29/03 5
MP  B   0.5 5/31/05 6
ZT  B   0.3 5/31/05 7
ZT  B   0.5 5/31/05 8
STA A   0.6 1/31/03 1
STA A   0.7 8/29/03 2
MP  B   0.8 8/29/03 3
MP  B   0.2 5/31/05 4
ZT  B   0.5 5/31/05 5
ZT  B   0.2 6/31/05 6

OUTPUT_DF:
ID  DATE    FINAL_VALUE
STA 1/31/03 2.1
STA 8/29/03 3.4
MP  8/29/03 5.4
MP  5/31/05 3.8
ZT  5/31/05 8.6
ZT  6/31/05 1.2

CODE:
I did try to do the following
OUTPUT_DF  = INPUT_DF[['ID','DATE(MM/DD/YY)']].groupby('ID', 'DATE(MM/DD/YY)')['EXPOSURE']*['VALUE'].sum()

But it is giving me an error. Can anyone help me in solving this.

A: Here is one way:
OUTPUT_DF = (INPUT_DF.groupby(['ID', 'DATE(MM/DD/YY)'])
             .apply(lambda x: sum(x.EXPOSURE * x.VALUE)))

ID   DATE(MM/DD/YY)
MP   5/31/05           3.8
     8/29/03           5.4
STA  1/31/03           2.1
     8/29/03           3.4
ZT   5/31/05           8.6
     6/31/05           1.2

To get it as a dataframe in the format you have posted, just add to_frame and reset_index:
OUTPUT_DF = (INPUT_DF.groupby(['ID', 'DATE(MM/DD/YY)'])
             .apply(lambda x: sum(x.EXPOSURE * x.VALUE))
             .to_frame('FINAL_VALUE')
             .reset_index())

>>> OUTPUT_DF
    ID DATE(MM/DD/YY)  FINAL_VALUE
0   MP        5/31/05          3.8
1   MP        8/29/03          5.4
2  STA        1/31/03          2.1
3  STA        8/29/03          3.4
4   ZT        5/31/05          8.6
5   ZT        6/31/05          1.2

A: Calculate your sumproduct column before you apply your groupby, and then simply sum:
input_df['FINAL_VALUE'] = input_df['VALUE'] * input_df['EXPOSURE']

output_df = input_df.groupby(['ID', 'DATE(MM/DD/YY)'])['FINAL_VALUE'].sum()

print(output_df)

This prints:
ID   DATE(MM/DD/YY)
MP   5/31/05           3.8
     8/29/03           5.4
STA  1/31/03           2.1
     8/29/03           3.4
ZT   5/31/05           8.6
     6/31/05           1.2


text:
Q: Como hago una peticion con mi token en un API? - JS? Este es mi código actual=

const myHeader = new Headers({
    'Authorization': 'Bearer  eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJkM2NIVUVibVJoc1EzeXhNbzV2VnliSTFzaDZCSDJZRCIsImlhdCI6MTU4NTkzMjYzNDU0OH0.tMSht_M3ryQl5IqCirhYR1gb8j3FQ26vILT4Qpx4XrdFz-zUmqbgFYiKTaZHPpB85etRIMhxVoZf6tOrHy0fnA'
    });

const myInit = {
    method: 'GET',
    headers: myHeader,
    mode: 'cors',
    cache: 'default'
};

const myrequest = new Request('https://eshop-deve.herokuapp.com/api/v2/orders/2117155815564',myInit);

fetch(myrequest)
.then(response => response.json())
.then(data => {console.log(data);})
.catch(err=> console.log(`Hubo error ${err}`))

me aparece el error:

Object { statusCode: 404, error: "Not Found" }

//Es mi token ---->
eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJkM2NIVUVibVJoc1EzeXhNbzV2VnliSTFzaDZCSDJZRCIsImlhdCI6MTU4NTkzMjYzNDU0OH0.tMSht_M3ryQl5IqCirhYR1gb8j3FQ26vILT4Qpx4XrdFz-zUmqbgFYiKTaZHPpB85etRIMhxVoZf6tOrHy0fnA


text:
Q: React .env.environment file's variable not working I connected my react app with Contentful's database. When I give the access key directly, it works fine. But when I give an access key in .env.environment file, the variable does not work.
contentful.js file:
import {createClient} from 'contentful';

export default createClient({
  space: process.env.REACT_APP_API_SPACE,
  accessToken: process.env.REACT_APP_ACCESS_TOKEN
});

.env.enviroment file:
 REACT_APP_API_SPACE= my access key
 REACT_APP_ACCESS_TOKEN= my access token

Console error:
Uncaught TypeError: Expected parameter accessToken
at createClient (contentful.node.js:7563)
at Object.<anonymous> (Contentful.js:3)
at __webpack_require__ (bootstrap fafcbb2b670a4f50dfbb:555)
at fn (bootstrap fafcbb2b670a4f50dfbb:86)
at Object.<anonymous> (context.js:5)
at __webpack_require__ (bootstrap fafcbb2b670a4f50dfbb:555)
at fn (bootstrap fafcbb2b670a4f50dfbb:86)
at Object.<anonymous> (FeaturedRooms.js:2)
at __webpack_require__ (bootstrap fafcbb2b670a4f50dfbb:555)
at fn (bootstrap fafcbb2b670a4f50dfbb:86)

But it works fine when I give the access key directly in my contentful.js file like this:
import {createClient} from 'contentful';

export default createClient({
  space: my access key,
  accessToken: my access token
});

As I am uploading to Git, I don't want to give the key directly.

A: #if using create-react-app
I don't think you can name your .env file like that, as of create-react-app.dev

*

*.env: Default.

*.env.local: Local overrides. This file is loaded for all environments except test.

*.env.development, .env.test, .env.production: Environment-specific settings.

*.env.development.local, .env.test.local, .env.production.local: Local overrides of environment-specific settings.

So, your .env.environment env file by default shouldn't work. Unless you modified somehow.
Restarting your Server
If so, Dont forget to restart your server as this note,

Note: You need to restart the development server after changing .env files.


text:
Q: How do I populate a select box depending on what was selected on the other select box? I want to populate my 2nd select box with the appropriate values depending on what was selected on the 1st select box.
This is what I have done so far but it's not working.
HTML:
    <form id = "step1">

                    Creator:
                    <select name="creator" id = "creator">
                        <option></option>
                        <option name = "hello" value = "hello">Hello</option>
                        <option name = "abc"> oiasfn</option>
                    </select>

                    Trip Title:
                    <select name="title" id = "title">
                        <option></option>
                    </select>

</form>

Javascript/Jquery:
$(document).ready(function(){
    updateform();

});

function updateform(){
    document.getElementById("creator").onchange = populatetitle;
}

function populatetitle(){
    var select = document.getElementById("creator");
    if(select.options[select.selectedIndex].value = "hello"){
        select.options.add(new Option('Byebye', 'Bye'));
    }
}

A: Your code has a few problems:
On line 11, you should use == or === for equality comparison, but you are mistakenly using =:
if(select.options[select.selectedIndex].value = "hello"){

Again on line 13, you are mistakenly adding the 'Bye' option to the same select, but I assume you want to add it to the #title select:
document.getElementById("title").options.add(new Option('Byebye', 'Bye'));

Also, your code is not idiomatic jQuery. You are using a mixture of jQuery and native DOM APIs which makes your code confusing. Also, IMHO, you can use better names for your functions and variables:
$(document).ready(function(){
    observeCreator();
});

function observeCreator() {
  $("#creator").change(onCreatorChanged);
}

function onCreatorChanged() {
  var creatorSelect = $(this);
  var titleSelect = $("#title");
  var options;

  if (creatorSelect.val() == "hello") {
     options = $("<option></option><option value='bye'>Bye</option>");
    titleSelect.html(options);
    titleSelect.val("bye");
  } else {
    options = $("<option></option>");
    titleSelect.html(options);
    titleSelect.val("");
  }
}

Finally, make sure you do not add the Bye option multiple times to the #title select if that is not your intention.

A: The problem with your code is that you add the value to the 1st select box. You need to change select.options.add(new Option('Byebye', 'Bye')); to select2.options.add(new Option('Byebye', 'Bye'));
Where
var select2 = document.getElementById("title");

Another solution is some code that I crafted up. Which does exactly the same thing, but makes it more dynamic.
Here is the JSFIDDLE
Code:
$(document).ready(function () {
    $('#creator').change(function () {
        populatetitle();
    });
});

//Set the values for the select boxes
var values = {"hello":
                 {
                     "ByeBye":"Bye",
                     "text":"value",
                     "value":"Bye2",
                 },
              "abc":
                 {
                     "ABC":"text",
                     "text":"value"
                 },
              "selectBox1value":
                  {
                      "SelectBox2Text":"SelectBox2Value"
                  },
              "": //Default case
                  {
                      "text":"value"
                  }
              };

function populatetitle() {
    var firstSelect = $("#creator");
    var secondSelect = $("#title");
    var valuesForSecondSelect = values[firstSelect.val()]; //get values based on 1st selection box
    secondSelect.empty(); // remove old options
    $.each(valuesForSecondSelect, function(key, value) {
        //loop through all values for 2nd box and add them
        secondSelect.append($("<option></option>")
                   .attr("value", value).text(key));
    });
}

A: The  problem likely stems from the fact that you're not adding it to the second select, but the first.  However, I haven't checked this because since you're already using jquery, you should use it for the change event handler as well.  It will make it much easier.
$(document).ready(function(){
    $('#creator').on('change', function() {
        var $title = $('#title').empty();
        if ($(this).val() == 'hello') {
            $title.append('<option value="Bye">Bye bye</option>');
        }
    });
});

A: Here's the FIDDLE
$(document).ready(function () {
    $('#creator').change(function () {
        populatetitle();
    });
});

function populatetitle() {
    var firstSelect = document.getElementById("creator");
    var secondSelect = document.getElementById("title");
    if (firstSelect.options[firstSelect.selectedIndex].value === "hello") {
        var option = document.createElement("option");
        option.text = "Byebye";
        option.value = "Bye";
        secondSelect.add(option, null);
    }
}


text:
Q: Match thickness and placement of lines in vmatrix and bmatrix environments I would like to fix this error:
$$\begin{matrix}
\left\lceil \begin{matrix} 1 \\ 0 \\ 1 \end{matrix} \right\rceil
\begin{vmatrix} 1 \\ 0 \\ 1 \end{vmatrix}
\left\lfloor \begin{matrix} 1 \\ 0 \\ 1 \end{matrix} \right\rfloor
\end{matrix}$$

Using something like this:
$$\begin{matrix}
\left\lceil \begin{matrix} 1 \\ 0 \\ 1 \end{matrix} \right\rceil
\begin{bmatrix} 1 \\ 0 \\ 1 \end{bmatrix}
\left\lfloor \begin{matrix} 1 \\ 0 \\ 1 \end{matrix} \right\rfloor
\end{matrix},$$

but without the heads on the brackets.  I think it would come down to using a different line type for the vmatrix environment.
Here is an image to supplement the dilemma:

Here is the MWE to generate this image:
\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\begin{document}
\begin{gather}
\frac{(-1)^\beta}{x_\beta}
\begin{bmatrix}
I_{\alpha-1} & & \left\lceil\begin{matrix} -x_1/x_\beta \\ \vdots \\ -x_{\alpha-1}/x_\beta \end{matrix}\right\rceil & \\
& \begin{bmatrix} 0 & \cdots & 0 \\ \\ & I_{\beta - \alpha} & \\ & & \end{bmatrix} &  \begin{matrix} -1/x_\beta \\ -x_\alpha/x_\beta \\ \vdots \\ -x_{\beta-1}/x_\beta \end{matrix} & \\
& & \left\lfloor\begin{matrix} -x_{\beta + 1}/x_\beta \\ \vdots \\ -x_n/x_\beta \end{matrix}\right\rfloor & I_{n - \beta}
\end{bmatrix}.
\end{gather}
\end{document}

And this is a better description of what I would like:

A: You can use a rule:
\documentclass[12pt,a4paper]{article}
\usepackage{amsmath}

\begin{document}

\[
\frac{(-1)^\beta}{x_\beta}
\begin{bmatrix}
I_{\alpha-1} & &
   \left\lceil\begin{matrix}
   -x_1/x_\beta \\ \vdots \\ -x_{\alpha-1}/x_\beta
   \end{matrix}\right\rceil
\\
& \begin{bmatrix}
  0 & \cdots & 0 \\ \\ & I_{\beta - \alpha} & \\ & &
  \end{bmatrix} &
  \vrule width 3pt \kern 2.3pt \begin{matrix}
  -1/x_\beta \\ -x_\alpha/x_\beta \\ \vdots \\ -x_{\beta-1}/x_\beta
  \end{matrix} \kern 2.3pt \vrule width 3pt \\
& &
  \left\lfloor\begin{matrix}
  -x_{\beta + 1}/x_\beta \\ \vdots \\ -x_n/x_\beta
  \end{matrix}\right\rfloor & I_{n - \beta}
\end{bmatrix}.
\]

\end{document}

A different hack (don't ask about \valign, please):
\documentclass[12pt,a4paper]{article}
\usepackage{amsmath}

\begin{document}

\[
\frac{(-1)^\beta}{x_\beta}
\begin{bmatrix}
\vcenter{\hbox{\valign{#\cr
  \vskip1em
  \hbox{$I_{\alpha-1}$\hskip\arraycolsep}
  \vfill\cr
  \vfill
  \hbox{\hskip\arraycolsep$
    \begin{bmatrix}
    0 & \cdots & 0 \\ \\ & I_{\beta - \alpha} & \\ & &
    \end{bmatrix}
  $\hskip\arraycolsep}
  \vfill\cr
  \hbox{\hskip\arraycolsep$
    \begin{bmatrix}
    -x_1/x_\beta \\ \vdots \\ -x_{\alpha-1}/x_\beta \\
    -1/x_\beta \\ -x_\alpha/x_\beta \\ \vdots \\ -x_{\beta-1}/x_\beta \\
    -x_{\beta + 1}/x_\beta \\ \vdots \\ -x_n/x_\beta
    \end{bmatrix}
  $\hskip\arraycolsep}\cr
  \vfill
  \hbox{\hskip\arraycolsep$I_{n - \beta}$}
  \vskip1em\cr
}}}
\end{bmatrix}
\]

\end{document}

A less fun solution:
\documentclass[12pt,a4paper]{article}
\usepackage{amsmath}
\usepackage{blkarray}

\begin{document}

\[
\frac{(-1)^\beta}{x_\beta}
\begin{blockarray}{[cc[c]c]}
& & -x_1/x_\beta & \\
I_{\alpha-1} & & \vdots & \\
& & -x_{\alpha-1}/x_\beta & \\
&
  \begin{bmatrix}
  0 & \cdots & 0 \\ \\ & I_{\beta - \alpha} & \\ & &
  \end{bmatrix}
&
  \begin{matrix}
  -1/x_\beta \\ -x_\alpha/x_\beta \\ \vdots \\ -x_{\beta-1}/x_\beta \\
  \end{matrix}
& \\
& & -x_{\beta + 1}/x_\beta & \\
& & \vdots & I_{n - \beta} \\
& & -x_n/x_\beta &
\end{blockarray}
\]

\end{document}


text:
Q: request.session in different views using curl I have a backend built with Django.
Problem:-
I am sending phone number via POST and storing in session via request.session['phone_number'] in one view and trying to get the same in another view but facing Key Error
What could be the issue?
Also via Postman its working fine but via curl or axios I'm getting this error.


text:
Q: What is blocking my main thread in this Discord Bot? Description
First and foremost, I'm fairly new to async/await development, especially with Python. At this moment, I've been developing a Discord bot where players can execute slots <bet>. An embed is displayed with emojis that are edited.

When you first invoke the command, the embed showcases a rotating emoji gif that is then 'edited' to be the real emoji after a few seconds (to give the impression that the slots are 'spinning'):

After it's complete, the player can select the "retry" functionality to repeat the process over again. So, all in all, the flow is this:

*

*Player invokes 'slot' command slots <bet>

*3 "Rotating" emojis appear and after 0.5 seconds, 1 after the other are switched to the 'static' verison

*The player can click the "retry" button and the process repeats.

Code
utilities.py
import asyncio
from functools import wraps, partial

def sync_to_async(func):
    @wraps(func)
    async def run(*args, loop=None, executor=None, **kwargs):
        if loop is None:
            loop = asyncio.get_event_loop()
        pfunc = partial(func, *args, **kwargs)
        return await loop.run_in_executor(executor, pfunc)

    return run

slotmachine.py
import asyncio
import random
from enum import Enum
from typing import Union

from discord import Color, Embed, Message, Reaction, User
from discord.ext.commands import Bot, Context

from utilities import sync_to_async

import arrow

class SlotMachine:
    class Reel(Enum):
        BANANA = ""
        CHERRY = ""
        GRAPE = ""
        DOLLAR = ""
        MONEY = ""

    symbols = list(Reel)
    animated_emoji = "<a:slots:765434893781041183>"
    row_of_three_payout = {
        Reel.BANANA: 2,
        Reel.CHERRY: 4,
        Reel.GRAPE: 8,
        Reel.DOLLAR: 15,
        Reel.MONEY: 20,
    }
    row_of_two_payout = {
        Reel.BANANA: 1,
        Reel.CHERRY: 2,
        Reel.GRAPE: 4,
        Reel.DOLLAR: 0,
        Reel.MONEY: 0,
    }

    def __init__(self, ctx, bot, user, coins, bet):
        self.ctx = ctx
        self.bot = bot
        self.user = user
        self.bet = bet
        self.profit = 0
        self.initial_coins = coins
        self.coins = coins
        self.message = None

    @sync_to_async
    def has_row_of_three(self, slots: list) -> bool:
        if all(i == slots[0] for i in slots):
            return SlotMachine.row_of_three_payout[slots[0]]

    @sync_to_async
    def has_row_of_two(self, slots: list) -> bool:
        if slots[0] == slots[1]:
            return True
        elif slots[1] == slots[2]:
            return True
        else:
            return False

    async def calculate_payout_multiplier(self, slots: list):
        has_three, has_two = await asyncio.gather(
            self.has_row_of_three(slots), self.has_row_of_two(slots)
        )
        if has_three:
            return SlotMachine.row_of_three_payout[slots[0]]
        elif has_two:
            return SlotMachine.row_of_two_payout[slots[1]]
        else:
            return 0

    @sync_to_async
    def generate_embed(self, embed_color, multiplier, slots):
        embed = Embed(title=f"Slots ", color=embed_color)
        embed.add_field(
            name="Spin",
            value=f"{' | '.join(slots)}",
            inline=False,
        )
        multiplier = f"{multiplier}x" if multiplier > 0 else "None"
        embed.add_field(name="Multiplier", value=multiplier)
        embed.add_field(name="Profit", value=self.profit)
        embed.add_field(name="Coins", value=self.coins)
        embed.add_field(name="Again?", value="React with  to play again.")
        embed.set_footer(text=self.user, icon_url=self.user.avatar_url)
        return embed

    async def play(self):
        slots = [random.choice(SlotMachine.symbols) for _ in range(3)]
        payout_multiplier = await self.calculate_payout_multiplier(slots)
        return (self.bet * payout_multiplier, payout_multiplier, slots)

    @sync_to_async
    def generate_spin_embed(self, display) -> Embed:
        embed = Embed(title=f"Slots ", color=Color.from_rgb(0, 0, 0))
        embed.add_field(
            name="Spin",
            value=" | ".join(display),
            inline=False,
        )
        embed.set_footer(text=self.user, icon_url=self.user.avatar_url)
        return embed

    async def spin_animation(self, slots) -> None:
        display = [SlotMachine.animated_emoji] * 3
        embed = await self.generate_spin_embed(display)
        await self.message.edit(embed=embed)
        for i in range(len(slots)):
            await asyncio.sleep(0.5)
            display[i] = slots[i].value
            embed = await self.generate_spin_embed(display)
            await self.message.edit(embed=embed)

    def is_valid_reaction(self, reaction: Reaction, user: User):
        return (
            user == self.user
            and str(reaction.emoji) in ("")
            and reaction.message.id == self.message.id
        )

    async def game_loop(self):
        has_busted = False
        is_first = True
        self.message = await self.ctx.send(embed=Embed(title="⌛ Loading..."))
        try:
            while not has_busted:
                money_out, multiplier, slots = await self.play()
                self.profit = money_out - self.bet
                self.coins += self.profit
                await self.spin_animation(slots)

                if self.coins <= 0:
                    self.coins = 0
                    has_busted = True
                    await self.message.edit(
                        embed=await self.generate_embed(
                            Color.red(), multiplier, [s.value for s in slots]
                        )
                    )
                else:
                    if self.profit == 0:
                        embed_color = Color.from_rgb(0, 0, 0)
                    elif self.profit > 0:
                        embed_color = Color.green()
                    else:
                        embed_color = Color.red()

                    embed = await self.generate_embed(
                        embed_color, multiplier, [s.value for s in slots]
                    )
                    await asyncio.sleep(0.5)
                    await self.message.edit(embed=embed)

                    if is_first:
                        await self.message.add_reaction("")
                        is_first = False
                    else:
                        await self.message.remove_reaction("", self.user)

                    if self.bet > self.coins:
                        has_busted = True
                    else:
                        await self.bot.wait_for(
                            "reaction_add", timeout=30, check=self.is_valid_reaction
                        )

            # They busted at this point
            amount = self.bet if self.bet > self.coins else self.initial_coins
            await self.bot.api.modify_gambling_profit(
                user_id=self.user.id, game="slots", amount=-1 * amount
            )
        except asyncio.TimeoutError:
            if self.initial_coins > self.coins:
                amount = -1 * (self.initial_coins - self.coins)
            else:
                amount = self.coins - self.initial_coins
            await self.bot.api.modify_gambling_profit(
                user_id=self.user.id, game="slots", amount=amount
            )

commands.py
    @commands.command(name="slots", aliases=["slot"])
    @commands.cooldown(1, 5, commands.BucketType.user)
    async def slots_command(self, ctx: Context, bet: int) -> None:
        user_id = ctx.author.id
        if await self.currently_playing.get(f"gambling.{user_id}"):
            await ctx.send("❌ Already in another game.")
            return
        else:
            await self.currently_playing.set(f"gambling.{user_id}", 1)

        if not await self.is_valid_bet(bet):
            await ctx.send("❌ Bet must be a positive whole number.")
            return

        stats = await self.bot.api.get_economy_user(user_id=user_id)
        coins = stats["coins"]

        if await self.has_enough_coins(user_id, coins, bet):
            await SlotMachine(ctx, self.bot, ctx.author, coins, bet).game_loop()
        else:
            await ctx.send("❌ Not enough coins")

        await self.currently_playing.delete(f"gambling.{user_id}")

Problem
When I was testing with 1 person, it works fantastic; however, when multiple people are running the same 'slots' command everyone receives a huge lag. It's almost as if one slot 'run' is waiting on the other.
Questions

*

*Does anyone see what is noticeably wrong with the code? Is there something that is blocking the main the thread? I suppose so?

*What methods can I use to debug / investigate this issue? I'm currently running debug on asyncio, but it doesn't yield any warnings about the slots command?

At this point, I've become so frustrated that I'm about to switch over to a more 'async' friendly language such as go or javascript. That's a bit of an over-exaggerative / novice thought though ;)


text:
Q: Leaving a cell blank in excel, or display a different cell I've tried to read the other posts and follow but I just can't wrap my head around this formula.

I would like F9 to:

*

*be blank if no data is entered in D9

*if data is entered in E9, then D9*E9

*if no data entered in E9, then D9
Any guidance is appreciated.

A: Try this:
=IF(D9<>"",IF(E9<>"",E9,1)*D9,"")

A: Fairly simple formula here:
=IF(ISBLANK(E9), D9, IF(ISBLANK(D9), "", D9*E9))
This does however, leave F9 with a 0 in it if neither field has any data.
To fix that you can add an AND check at the front, to check if either cell has data.
=IF(AND(D9="", E9=""),"",IF(ISBLANK(E9), D9, IF(ISBLANK(D9), "", D9*E9)))

A: My version:
=IF(NOT(ISBLANK(D9)), IF(NOT(ISBLANK(E9)), D9 * E9, D9), "")

This aligns with your written rules and (imho) is easier to follow than Scott's answer - specifically the 1*D9 bit if there is no value in E9 - and removes the unnecessary AND(D9="", E9=""), clause from Michael's answer.


text:
Q: Column Name Ambiguous Despite Referencing to Table Despite not having this problem in a very similar function, I seem to have it in this one and cannot find any advice on the issue in this specific context (that I can comprehend lol). If anyone can give any advice or references that would be greatly appreciated.
ERROR: "column reference "customerid" is ambiguous"
CREATE OR REPLACE FUNCTION update_FlightBooking(INTEGER, INTEGER, INTEGER, INTEGER, CHAR(1), TIMESTAMP, DECIMAL)
RETURNS TABLE
(
  BookingID INTEGER,
  CustomerID INTEGER,
  FlightID INTEGER,
  NumSeats INTEGER,
  Status CHAR(1),
  BookingTime TIMESTAMP,
  TotalCost DECIMAL
) AS $$

BEGIN
  IF NOT EXISTS (SELECT CustomerID FROM FlightBooking WHERE FlightBooking.CustomerID = $2) THEN
    INSERT INTO FlightBooking VAlUES($1, $2, $3, $4, $5, $6, $7);

  ELSE
    UPDATE FlightBooking AS fb
    SET NumSeats = NumSeats + $4, TotalCost = TotalCost + $7
    WHERE fb.CustomerID = $2;
  END IF;

  IF NOT EXISTS (SELECT CustomerID FROM LeadCustomer WHERE LeadCustomer.CustomerID = $2) THEN
    ROLLBACK;
  END IF;

  IF (check_Seats($3) < 0) THEN
    ROLLBACK;
  END IF;

  RETURN QUERY
    SELECT fb.BookingID, fb.CustomerID, fb.FlightID, fb.NumSeats, fb.Status, fb.BookingTime, fb.TotalCost
    FROM FlightBooking AS fb WHERE fb.CustomerID = $1;
END;
$$
LANGUAGE plpgsql;

A: https://www.postgresql.org/docs/9.5/plpgsql-implementation.html says

By default, PL/pgSQL will report an error if a name in a SQL statement
  could refer to either a variable or a table column. You can fix such a
  problem by renaming the variable or column, or by qualifying the
  ambiguous reference, or by telling PL/pgSQL which interpretation to
  prefer.

This applies to customerId in IF NOT EXISTS (SELECT CustomerID ...


text:
Q: Swift 3 - Check if a string exist inside an array and sort it I have this special array var myArray : [Array<String>] = [["a"],["b"],["c"]]
I want to detect if "a" is already inside myArray
and after i would like to sort my array alphabetically but i havn't found any function to do all these things for my array

A: To find if your [[String]] contains "a", you can use contains twice:
var myArray : [Array<String>] = [["a"],["b"],["c"]]

if myArray.contains(where: { $0.contains("a") }) {
    print("a found")
}

To sort the inner arrays, apply map to the outer array and sort each element:
var myArray : [Array<String>] = [["c", "a"], ["e", "b"], ["d"]]

let sorted = myArray.map { $0.sorted() }

print(sorted)

[["a", "c"], ["b", "e"], ["d"]]


text:
Q: How to create a loop for changing data frame names I have several data frames and for all of them, I want to carry out the same procedure. As an example, for one data frame (df1), the code looks the following:
def create_url():
    df_id = (str(str((df1['id'].tolist()))[1:-1])).replace(" ", "")
    ids1 = "ids=" + df_id1
    url1 = "https://api.twitter.com/2/tweets?{}&{}".format(ids1, tweet_fields)
    return url1

However, for all df which I have I want to loop this code in order to get one url per df (which are names then url1, url2, etc.). To get the whole list of names of df, I used the following code:
for j in dfs:
    print(j)

Hope somebody can help!
Thank you a lot in advance!

A: If i understand correctly
Try this:
def create_url(dfx):
    df_id = (str(str((dfx['id'].tolist()))[1:-1])).replace(" ", "")
    ids = "ids=" + df_id
    url = "https://api.twitter.com/2/tweets?{}&{}".format(ids, tweet_fields)
    return url

for j in dfs:
    print(j)
    create_url(j)


text:
Q: Hiding multiple web services behind one? There is a system with a rather big amount of different small services.
The idea is to hide them behind one, which is going to be an entry point to the system.
Is that considered a good practice?
Are there any common approaches/solutions for such case in asp.net core?

A: This is called an API Gateway pattern.

API gateway is the single entry point for all clients. The API gateway handles requests in one of two ways. Some requests are simply proxied/routed to the appropriate service. It handles other requests by fanning out to multiple services.

As the starting point, you may look into Proxy Middleware for ASP.NET Core.


text:
Q: Run Ubuntu on imac with busted graphics card I have an old imac (2012) with a busted graphics card (AMD 1GB). The computer has 16 GB of RAM and an i5 sandy bridge processor (3.1 GHZ). OSX runs without the graphics driver using onboard graphics but is extremely sluggish. If I install ubuntu, will it give me better performance using the onboard graphics?
I ask this as I believe that OSX restricts the RAM that OSX uses when its using integrated graphics. Would Ubuntu allow me to use more RAM and hence give me better performance?
Thanks for the help!


text:
Q: Как восстановить EFI раздел? После перезагрузки openSUSE Tumbleweed (ядро 6.0.0-1) меня встретил grub rescue:
grub-rescue > ls
(hd0) (hd0,msdos1) (hd1) (hd2)
grub-rescue > insmod gpt_part
error: no such partition

Отправляюсь в UEFI, и там катастрофа:
Select Boot Option:
/dev/sda
/dev/sdb
/dev/sdc
/dev/sdd # флешка с Ventoy
ventoy.efi

Пропали GRUB и Windows 11!
Гружу Kubuntu Live. Ну и ловлю Kernel Panic на blkid. Гружу Linux Lite: тут blkid уже прекрасно работает, и все разделы на месте. fsck.fat тоже особо не ругается. Через gparted проверяю - esp метка на EFI разделе на месте. Переназначаю метку - проблема не исчезает. Загружаю AdminPE - да все диски на месте:
/dev/sda1  Ventoy     C: exFAT
/dev/sdb1  EFI        D: FAT32
/dev/sdc1  linuxboot  E: ext2
/dev/sdb2  Windows 11 F: NTFS
/dev/sdd1  disk_d     G: ext2
/dev/loop0 AdminPE    H: iso9660

Захожу в диск и пробую bootrec:
Admin@AdminPE-cmd (D:\EFI\Microsoft\Boot) # bootrec /fixboot

Не помогает вернуть хотя бы Windows-овый загрузчик
Ну, пробую вернуть GRUB на место:
root@linuxlite6-live: ~ # mount -t ext4 /dev/sdc2 /mnt
root@linuxlite6-live: ~ # mount -t ext2 /dev/sdc1 /mnt/boot
root@linuxlite6-live: ~ # mount -t vfat /dev/sdb2 /mnt/boot/efi
root@linuxlite6-live: ~ # mount --bind /dev /mnt/dev
root@linuxlite6-live: ~ # mount --bind /dev/pts /mnt/dev/pts
root@linuxlite6-live: ~ # mount --bind /proc /mnt/proc
root@linuxlite6-live: ~ # mount --bind /sys /mnt/sys
root@linuxlite6-live: ~ # chroot /mnt
root@opensuse-tumbleweed: ~ # grub2-install
Installing for x86_64-efi.
Installation finished. No error occured.

А все равно GRUB лезет с grub-rescue. Ну и как вернуть хотя бы одну из ОС в рабочее состояние?
И да, SecureBoot не отрубается, он включён перманентно:
Secure Boot State: Enabled (immutable)
OS Type: Other OS

Версия UEFI - 8601, дата - 07/25/2002
Пробую пересоздать EFI раздел для Windows по гайду отсюда: http://woshub.com/how-to-repair-deleted-efi-partition-in-windows-7/. Не помогает, EFI раздел не виден и лезет GRUB...
efibootmgr не спасает:
root@linuxlite6-live: ~ # efibootmgr -c -L "Windows11" -d /dev/sdb -p 1 -l 'EFI\Microsoft\Boot\bootmgfw.efi'

A: Справился очень радикальным методом (можно было конечно обойтись badblocks, но я сделал так):
1.Бэкап Windows:
# dd if=/dev/sdc2 of=microsoft_reserved.img
# dd if=/dev/sdc3 of=win11_rootfs.img
# gparted
# пересоздал таблицу разделов и разделы на диске. При этом я сделал все В ТОЧНОСТИ как ранее, байт в байт.
# mount -t ntfs -o remove_hiberfile,ro win11_rootfs.img /mnt
# для сноса hiberfile.sys
# dd if=win11_rootfs.img of=/dev/sdc2

И затем переустановил EFI загрузчик.


text:
Q: Windows doesn't like resized FAT filesystem I resized a FAT filesystem.  Then the filesystem  stopped working as a Windows 10 Recovery Drive.  ("This may be due to a recent change in your hardware or software...").  And a running Windows is unable to open the filesystem, when it could before.
Resize tool: gparted-0.27.0-1.fc25.x86_64 (Fedora 25)
The resize was performed on a disk image file, copied from a USB drive as a backup.  gparted was run on a loop device created from the image file using losetup -f -P. (Or later, Gnome Disks and "Attach Disk Image" from the... whatever you call the app-specific menu, in the top bar of gnome shell).

A: There is some defect in this gparted.  Although Linux is able to mount the resulting filesystem (and the files compare identical to the original), file -s shows the following weirdness:
Before

/dev/loop0p1: DOS/MBR boot sector, code offset 0x58+2, OEM-ID "MSDOS5.0", sectors/cluster 8, reserved sectors 3310, Media descriptor 0xf8, sectors/track 63, heads 255, hidden sectors 2048, sectors 15114240 (volumes > 32 MB) , FAT (32 bit), sectors/FAT 14729, serial number 0x9a856b85, unlabeled

After

/dev/loop1p1: DOS/MBR boot sector; partition 2 : ID=0xb2, start-CHS (0x2f0,0,0), end-CHS (0x0,0,0), startsector 2944401408, 51 sectors; partition 4 : ID=0x65, start-CHS (0x0,0,0), end-CHS (0x163,118,41), startsector 1626349669, 2144852992 sectors

Clearly some part of the Windows 10 Recovery boot path accepts the weirdness - I guess the part where the EFI filesystem driver is used.   Later code must use similar checks to a fully running Windows, and does not accept it.
In the case of a Windows 10 Recovery Drive for UEFI, this could be worked around simply by creating a smaller FAT filesystem and copying the files into it.  (Yes, really :).


text:
Q: The virtual path '/' maps to another application, which is not allowed. MVC and Hangfire I have tried other solutions posted to stackoverflow and have found none that work, here is my problem.
So I want to send an email using hangfire through my MVC application, this works on my local machine but when I upload it to a remote server I get the following error on hangfire:
The virtual path '/' maps to another application, which is not allowed

This is the code I use to send the email:
foreach (var EmailEntry in EmailEntries)
        {
            var email = new EmailTemplateModel
            {
                ViewName = "EmailTemplateModel",
                FromAddress = "donotreply@emailservice.com",
                EmailAddress = EmailEntry,
                Subject = "Task Report",
                Date = Dates,
                Task = DatesAndTasks,
            };
            email.Send();
        }

When I use the 'ViewName' method it returns '~/Views/Emails' on my local machine.
Inside of the Send() method:
// Summary:
        //     Convenience method that sends this email via a default EmailService.
        public void Send();

Application structure in IIS:
Server > Sites > Default > MyApplication
Issue raised by JodyL's solution below:
StructureMapDependencyScope.get_CurrentNestedContainer()

Solution:
Edited the following code in 'StructureMapDependencyScope' class:
Before:
public IContainer CurrentNestedContainer {
            get {
                return (IContainer)HttpContext.Items[NestedContainerKey];
            }
            set {
                HttpContext.Items[NestedContainerKey] = value;
            }
        }

After:
public IContainer CurrentNestedContainer {
            get {
                IContainer container = null;
                if (HttpContext != null)
                    container = (IContainer)HttpContext.Items[NestedContainerKey];
                return container;
            }
            set {
                HttpContext.Items[NestedContainerKey] = value;
            }
        }

Before:
private HttpContextBase HttpContext {
            get {
                var ctx = Container.TryGetInstance<HttpContextBase>();
                return ctx ?? new HttpContextWrapper(System.Web.HttpContext.Current);
            }
        }

After:
private HttpContextBase HttpContext {
            get {
                var ctx = Container.TryGetInstance<HttpContextBase>();
                if (ctx == null && System.Web.HttpContext.Current == null)
                    return null;

                return ctx ?? new HttpContextWrapper(System.Web.HttpContext.Current);
            }
        }

A: This problem is probably caused because HTTPContext is not available to Postal when using Hangfire. If HTTPContext.Current is null, Postal uses http://localhost as the URL, which doesn't map to your application location. In order to get around this problem, you can use FileSystemRazorViewEngine when sending the email and pass it the path of your email template.
See the answer to this question for details on how to achieve this.
Using Postal and Hangfire in Subsite

A: Most probably the problem is related to IIS rather than Hangfire, etc. So, could you please try to using with dot (.) as shown below:
Instead of using
'~/Views/Emails'

try this
'./Views/Emails'

Similarly you might also encounter some problems when displaying images and in such case you should make the following changes:
~/../Content/images/image.png

to
./../Content/images/image.png

A: Please try to use MapPath as follows:
var path = HostingEnvironment.MapPath(@"~/Views/Emails");


text:
Q: super+space stopped toggle language Up until a week ago or so, I could use super+space to toggle between English and Swedish. Then it stopped working for some reason. I have tried different key-combinations but no matter what I cannot toggle the input source.
Have anyone experienced something similar?
Here is something, but that did not help me. According to this, it has not worked at all for others, but for me super+space has worked up to recently and now no key-combination works.
Other short commands work fine.


text:
Q: CLion and Boost 1.60.0 For the past few days I have been struggling to get the Boost libraries included in my project. I have been reading and using suggestions made by numerous posters on Stack Overflow and for some reason that I don't understand I still cannot get CMake to find Boost, or if it does find Boost, I can't compile because it can't find the boost_system library that I apparently need to link with to remove the system config() not found error.
I am currently working on Windows 10 with the MinGW Implementation of the GNU C++ Compiler v4.9.3-1
Boost is currently extracted on my system here:
C:\boost_1_60_0

This is what my CMake file currently looks like:
cmake_minimum_required(VERSION 3.5)
project(Engine)

#SET(GCC_COVERAGE_LINK_FLAGS "-lboost_system")

message(STATUS "start running cmake...")

SET(BOOSTROOT "C:/boost_1_60_0/")
SET(BOOST_ROOT "C:/boost_1_60_0/")
SET(BOOST_LIBRARYDIR "C:/boost_1_60_0/libs/")

find_package(Boost 1.60.0 COMPONENTS system REQUIRED)

if(Boost_FOUND)

    message(STATUS "Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
    message(STATUS "Boost_LIBRARIES: ${Boost_LIBRARIES}")
    message(STATUS "Boost_VERSION: ${Boost_VERSION}")

    include_directories(${Boost_INCLUDE_DIRS})
    add_definitions("-DHAS_BOOST")

endif()

add_executable(Engine main.cpp)

if(Boost_FOUND)

    target_link_libraries(Engine ${Boost_LIBRARIES})

endif()

set(SOURCE_FILES main.cpp)

The Error that I am currently getting is:
Error:Unable to find the requested Boost libraries.
Boost version: 1.60.0
Boost include path: C:/boost_1_60_0
Could not find the following Boost libraries:
        boost_system
No Boost libraries were found.  You may need to set BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT to the location of Boost.

** UPDATE **
This is the output when running cmake with -DBoost_Debug=ON:
_boost_TEST_VERSIONS = 1.61.0;1.61;1.60.0;1.60
Boost_USE_MULTITHREADED = TRUE
Boost_USE_STATIC_LIBS =
Boost_USE_STATIC_RUNTIME =
Boost_ADDITIONAL_VERSIONS =
Boost_NO_SYSTEM_PATHS =
Declared as CMake or Environmental Variables:
 BOOST_ROOT = C:/boost_1_60_0/
 BOOST_INCLUDEDIR =
 BOOST_LIBRARYDIR = C:/boost_1_60_0/libs/
_boost_TEST_VERSIONS = 1.61.0;1.61;1.60.0;1.60
location of version.hpp: C:/boost_1_60_0/boost/version.hpp
version.hpp reveals boost 1.60.0
guessed _boost_COMPILER = -mgw49
_boost_MULTITHREADED = -mt
_boost_RELEASE_ABI_TAG = -
_boost_DEBUG_ABI_TAG = -d
_boost_LIBRARY_SEARCH_DIRS_RELEASE = C:/boost_1_60_0/libs/;C:/boost_1_60_0//lib;C:/boost_1_60_0//stage/lib;C:/boost_1_60_0/lib;C:/boost_1_60_0/../lib;C:/boost_1_60_0/stage/lib;PATHS;C:/boost/lib;C:/boost;/sw/local/lib_boost_LIBRARY_SEARCH_DIRS_DEBUG   = C:/boost_1_60_0/libs/;C:/boost_1_60_0//lib;C:/boost_1_60_0//stage/lib;C:/boost_1_60_0/lib;C:/boost_1_60_0/../lib;C:/boost_1_60_0/stage/lib;PATHS;C:/boost/lib;C:/boost;/sw/local/lib
Searching for SYSTEM_LIBRARY_RELEASE: boost_system-mgw49-mt-1_60;boost_system-mgw49-mt;boost_system-mt-1_60;boost_system-mt;boost_system
Searching for SYSTEM_LIBRARY_DEBUG: boost_system-mgw49-mt-d-1_60;boost_system-mgw49-mt-d;boost_system-mt-d-1_60;boost_system-mt-d;boost_system-mt;boost_system

Thanks in advance

A: There are some useful flags to help FindBoost to find libraries.
Try setting these variables (on or off - it depends on your boost installation) before calling find_package(Boost)
set(Boost_LIB_PREFIX            "lib"       CACHE STRING "")
set(Boost_USE_MULTITHREADED     ON          CACHE BOOL "") # '-mt' flag
set(Boost_USE_STATIC_LIBS       ON          CACHE BOOL "")
set(Boost_USE_STATIC_RUNTIME    ON          CACHE BOOL "") # '-s' tag
set(Boost_USE_DEBUG_RUNTIME     ON          CACHE BOOL "") # '-g' tag
set(Boost_COMPILER              "-mgw49"    CACHE STRING "")

Setting a flag with set(Boost_DETAILED_FAILURE_MSG TRUE) will greatly help you in diagnostics


text:
Q: Can I use the token info endpoint instead of the official Google Client SDK (in production)? I am currently implementing Google authentication on my client's website (back in Symfony), and would like to install the Google SDK on its API (https://developers.google.com/identity/sign-in/web/backend-auth). The situation is such that we can't install this SDK for the moment (deep dependency conflict).
Could we use (temporarily) tokeninfo api endpoint instead of the Google PHP SDK recommended by Google for production ?


text:
Q: Authentication with Private Key does not work I try to connect SFTP Server using Jsch Library. It works when i use username/password, but with private/public key does not work. i have been read all questions about this theme in Stackoverflow and in other Site webs, but i did not find what i search for.
To test my private key, i have used Terminal(also WinSCP), it works fine, but with Java Code i get this " Auth fail"
This is an Example:
 public static void main(String[] args) throws JSchException, SftpException, IOException {
        JSch jsch = new JSch();
        Properties config=new Properties();
        config.put("StrictHostKeyChecking", "no");
        jsch.addIdentity("path_to_private_key");
        Session session;
        session = jsch.getSession("user", "host", 22);

        session.setConfig(config);
//        session.setPassword("pass");
        session.connect();
        System.out.println("CONNECT !!! ");
        session.disconnect();
    }

.  I have generated keys using this command: ssh-keygen -C "" -m PEM id_rsa
.  past public key in /.ssh/authorized_keys
Any help please?