问:
PyQT/PySide - Button and lineEdit not working on Second Window
I successfully created a second window (ChiffrerWindow) but whenever I try to click a button in the second window nothing happens (The button don't execute the slots). They behave like blank widgets

I have 5 files ui_mainwindow.py and ui_chiffrerwindow.py (Which are generated from QtDesigner), chiffrerwindow.py and mainwindow.py (Are the corresponding files where I pass in the slots),
main.py (Executes the app).
This is my mainwindow.py (I didn't show the top file imports)

```<code>from ui_mainwindow import Ui_MainWindow
from ui_chiffrerwindow import Ui_ChiffrerWindow

class MainWindow(QMainWindow, Ui_MainWindow,Ui_ChiffrerWindow):
    def __init__(self,app):
        super().__init__()
        self.setupUi(self)

        self.actionChiffrer.triggered.connect(self.ouvrirChiffrer)

    def ouvrirChiffrer(self):
        self.window = QtWidgets.QMainWindow()
        self.ui = Ui_ChiffrerWindow()
        self.ui.setupUi(self.window)
        self.window.show()
</code>```

This is my chiffrerwindow.py

```<code>from ui_chiffrerwindow import Ui_ChiffrerWindow
class ChiffrerWindow(QMainWindow, Ui_ChiffrerWindow):
    def __init__(self,app):
        super().__init__()
        self.setupUi(self)
        self.ui = Ui_ChiffrerWindow()

        # self.getFileToEncrypt = self.findChild(QPushButton, "pushButtonFileDirCrypt")
        # self.getPubKeyToEncrypt = self.findChild(QPushButton, "pushButtonPubKeyCrypt")
        # self.line_edit_file_dir = self.findChild(QLineEdit, "lineEditFileDirCrypt")
        # self.ine_edit_pub_key = self.findChild(QLineEdit, "lineEditPubKeyCrypt")

        self.ui.pushButtonFileDirCrypt.clicked.connect(self.getFileToEncrypt)
        self.ui.pushButtonPubKeyCrypt.clicked.connect(self.getPubKeyToEncrypt)

    def getFileToEncrypt(self):
        fname = QFileDialog.getOpenFileName(self,"Open File","", "All Files (*);; Word Documents (*.docx)")

        # Output file name
        if fname:
            self.ui.lineEditFileDirCrypt.setText(fname[0])

    def getPubKeyToEncrypt(self):
        print("You want to get the keys to encrypt the file")
</code>```

This is what my app looks like. This is the main window
This is the main window

This is the second window
This is the second window. Whenever I click the buttons on the second window I would like to open a File Dialog to permit to the user to select a file.

I am a beginner and this is a project of implementing PGP cryptography in a desktop app.
Thank you very much for your concern and your help

Body:
I successfully created a second window (ChiffrerWindow) but whenever I try to click a button in the second window nothing happens (The button don't execute the slots). They behave like blank widgets

I have 5 files ui_mainwindow.py and ui_chiffrerwindow.py (Which are generated from QtDesigner), chiffrerwindow.py and mainwindow.py (Are the corresponding files where I pass in the slots),
main.py (Executes the app).
This is my mainwindow.py (I didn't show the top file imports)

from ui_mainwindow import Ui_MainWindow
from ui_chiffrerwindow import Ui_ChiffrerWindow

class MainWindow(QMainWindow, Ui_MainWindow,Ui_ChiffrerWindow):
    def __init__(self,app):
        super().__init__()
        self.setupUi(self)

        self.actionChiffrer.triggered.connect(self.ouvrirChiffrer)

    def ouvrirChiffrer(self):
        self.window = QtWidgets.QMainWindow()
        self.ui = Ui_ChiffrerWindow()
        self.ui.setupUi(self.window)
        self.window.show()

This is my chiffrerwindow.py

from ui_chiffrerwindow import Ui_ChiffrerWindow
class ChiffrerWindow(QMainWindow, Ui_ChiffrerWindow):
    def __init__(self,app):
        super().__init__()
        self.setupUi(self)
        self.ui = Ui_ChiffrerWindow()

        # self.getFileToEncrypt = self.findChild(QPushButton, "pushButtonFileDirCrypt")
        # self.getPubKeyToEncrypt = self.findChild(QPushButton, "pushButtonPubKeyCrypt")
        # self.line_edit_file_dir = self.findChild(QLineEdit, "lineEditFileDirCrypt")
        # self.ine_edit_pub_key = self.findChild(QLineEdit, "lineEditPubKeyCrypt")

        self.ui.pushButtonFileDirCrypt.clicked.connect(self.getFileToEncrypt)
        self.ui.pushButtonPubKeyCrypt.clicked.connect(self.getPubKeyToEncrypt)

    def getFileToEncrypt(self):
        fname = QFileDialog.getOpenFileName(self,"Open File","", "All Files (*);; Word Documents (*.docx)")

        # Output file name
        if fname:
            self.ui.lineEditFileDirCrypt.setText(fname[0])

    def getPubKeyToEncrypt(self):
        print("You want to get the keys to encrypt the file")

This is what my app looks like. This is the main window
This is the main window

This is the second window
This is the second window. Whenever I click the buttons on the second window I would like to open a File Dialog to permit to the user to select a file.

I am a beginner and this is a project of implementing PGP cryptography in a desktop app.
Thank you very much for your concern and your help


来源: stackexchange

问:
jest encountered an unexpected token when trying to import
I have written a test using jest for my create react app and have been having some issues with the most recent being that it complains about my imports inside the component I am trying to test saying:

```<code>  Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
</code>```

I have tried making some changes within my jest.config.js file but cannot seem to get to the route of the problem.

I have attached an image of the exact error within my project:

here is my current jest.config.js file:

```<code>module.exports = {
  collectCoverageFrom: ["<rootDir>/src/**/*.js", "<rootDir>/src/**/*.jsx"],
  moduleDirectories: ["node_modules", "src"],
  testPathIgnorePatterns: ["<rootDir>/test/setup/"],
  //   setupFilesAfterEnv: ["<rootDir>/test/setup/setupEnzyme.js"],
  transform: {
    "\\.jsx?$": "babel-jest",
  },
  transformIgnorePatterns: ["<rootDir>/node_modules/"],
  testRegex: "((\\.|/*.)(test))\\.js?$",

  moduleFileExtensions: ["ts", "tsx", "js", "jsx", ".css"],
};
</code>```

here is the test I have currently written inside my tests folder:

```<code>import { render, screen } from '@testing-library/react';
import App from './App';

test('renders learn react link', () => {
  render(<App />);
  const linkElement = screen.getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});
</code>```

I also added in the .babelrc file as I was having a previous issue complaining:  FAIL

```<code>src/App.test.js
  ● Test suite failed to run

    SyntaxError: ...\src\App.test.js: Support for the experimental syntax 'jsx' isn't currently enabled (5:10):
</code>```

.babelrc:

```<code>{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
}
</code>```

also included package.json file:

```<code>{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@mapbox/polyline": "github:mapbox/polyline",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.1.3",
    "cors": "^2.8.5",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-leaflet": "^4.2.0",
    "react-router-dom": "^6.5.0",
    "react-scripts": "4.0.3",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "jest --config ./jest.config.js",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      "last 2 Chrome versions",
      "last 2 Firefox versions",
      "last 2 Safari versions",
      "iOS >= 13",
      "unreleased versions"
    ],
    "development": [
      "last 2 Chrome versions",
      "last 2 Firefox versions",
      "last 10 Safari versions",
      "iOS >= 13",
      "unreleased versions"
    ]
  },

  "devDependencies": {
    "jest": "^26.6.0"
  }
}
</code>```

can anyone see what I am missing?

ContentLicense: CC BY-SA 4.0

Body:
I have written a test using jest for my create react app and have been having some issues with the most recent being that it complains about my imports inside the component I am trying to test saying:

  Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

I have tried making some changes within my jest.config.js file but cannot seem to get to the route of the problem.

I have attached an image of the exact error within my project:

here is my current jest.config.js file:

module.exports = {
  collectCoverageFrom: ["<rootDir>/src/**/*.js", "<rootDir>/src/**/*.jsx"],
  moduleDirectories: ["node_modules", "src"],
  testPathIgnorePatterns: ["<rootDir>/test/setup/"],
  //   setupFilesAfterEnv: ["<rootDir>/test/setup/setupEnzyme.js"],
  transform: {
    "\\.jsx?$": "babel-jest",
  },
  transformIgnorePatterns: ["<rootDir>/node_modules/"],
  testRegex: "((\\.|/*.)(test))\\.js?$",

  moduleFileExtensions: ["ts", "tsx", "js", "jsx", ".css"],
};

here is the test I have currently written inside my tests folder:

import { render, screen } from '@testing-library/react';
import App from './App';

test('renders learn react link', () => {
  render(<App />);
  const linkElement = screen.getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});

I also added in the .babelrc file as I was having a previous issue complaining:  FAIL

src/App.test.js
  ● Test suite failed to run

    SyntaxError: ...\src\App.test.js: Support for the experimental syntax 'jsx' isn't currently enabled (5:10):

.babelrc:

{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
}

also included package.json file:

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@mapbox/polyline": "github:mapbox/polyline",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.1.3",
    "cors": "^2.8.5",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-leaflet": "^4.2.0",
    "react-router-dom": "^6.5.0",
    "react-scripts": "4.0.3",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "jest --config ./jest.config.js",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      "last 2 Chrome versions",
      "last 2 Firefox versions",
      "last 2 Safari versions",
      "iOS >= 13",
      "unreleased versions"
    ],
    "development": [
      "last 2 Chrome versions",
      "last 2 Firefox versions",
      "last 10 Safari versions",
      "iOS >= 13",
      "unreleased versions"
    ]
  },

  "devDependencies": {
    "jest": "^26.6.0"
  }
}

can anyone see what I am missing?


问:
Hadoop distcp to S3
I am using Hadoop distcp command to move data from hdfs to s3. Recently after hadoop cdh to cdp upgrade I am facing a difference in -update option. Previously-update will move files with same file name, same size but with different content. now it ignores the file if name and size are same. Is there anyways to move achieve this kind of update in cloudera cdp version?

hadoop distcp -pu -update -delete hdfspath s3bucket

Title: Hadoop distcp to S3


问:
Send a message with information in GUI from an agent in Java after clicking a bottom
I'm creating a GUI in Java (Netbeans) and I want to create a multi-agent system on it. The GUI will have some Text Area and a Button, so I want to click that button and give all the text information to an agent to process but I don´t know how communicate the GUI with the Agents or the AgentContainer.

GUI Class (main):

```<code>public class GUI extends javax.swing.JFrame {
    Contenedor c;

    public GUI() {
        initComponents();
        c = new Contenedor();
        c.contenedor();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        txtArea = new javax.swing.JTextArea();
        btnDesplegar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

        btnDesplegar.setText("Desplegar");
        btnDesplegar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDesplegarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,     javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(38, 38, 38)
                .addComponent(btnDesplegar)
                .addContainerGap(47, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(43, 43, 43)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(82, 82, 82)
                        .addComponent(btnDesplegar)))
                .addContainerGap(171, Short.MAX_VALUE))
        );

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

    private void btnDesplegarActionPerformed(java.awt.event.ActionEvent evt) {
        System.out.println(txtArea.getText());

    }

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton btnDesplegar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtArea;
    // End of variables declaration
}
</code>```

AgentContainer:

```<code>import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.core.Runtime;
import jade.wrapper.AgentContainer;
import jade.wrapper.StaleProxyException;
import java.util.logging.Level;

public class Contenedor {
    private AgentContainer contenedorAgentes;

    public void contenedor(){
        Runtime runtime = Runtime.instance();
        Profile profile = new ProfileImpl(null, 1097, null);
        contenedorAgentes = runtime.createMainContainer(profile);
        agregarAgentes();
    }

    private void agregarAgentes(){
        try {
            contenedorAgentes.createNewAgent("Ag1", Ag1.class.getName(), null).start();
        }
        catch (StaleProxyException ex) {
            java.util.logging.Logger.getLogger(Contenedor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
</code>```

Agent:
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;

```<code>public class Ag1 extends Agent{

    @Override
    public void setup(){
        addBehaviour(new Comportamiento());
    }

    @Override
    public void takeDown(){

    }

    class Comportamiento extends CyclicBehaviour{

        @Override
        public void action() {
            System.out.println("pan");
        }

    }
}
</code>```

Body:
I'm creating a GUI in Java (Netbeans) and I want to create a multi-agent system on it. The GUI will have some Text Area and a Button, so I want to click that button and give all the text information to an agent to process but I don´t know how communicate the GUI with the Agents or the AgentContainer.

GUI Class (main):

public class GUI extends javax.swing.JFrame {
    Contenedor c;

    public GUI() {
        initComponents();
        c = new Contenedor();
        c.contenedor();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        txtArea = new javax.swing.JTextArea();
        btnDesplegar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

        btnDesplegar.setText("Desplegar");
        btnDesplegar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDesplegarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,     javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(38, 38, 38)
                .addComponent(btnDesplegar)
                .addContainerGap(47, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(43, 43, 43)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(82, 82, 82)
                        .addComponent(btnDesplegar)))
                .addContainerGap(171, Short.MAX_VALUE))
        );

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

    private void btnDesplegarActionPerformed(java.awt.event.ActionEvent evt) {
        System.out.println(txtArea.getText());

    }

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton btnDesplegar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtArea;
    // End of variables declaration
}

AgentContainer:

import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.core.Runtime;
import jade.wrapper.AgentContainer;
import jade.wrapper.StaleProxyException;
import java.util.logging.Level;

public class Contenedor {
    private AgentContainer contenedorAgentes;

    public void contenedor(){
        Runtime runtime = Runtime.instance();
        Profile profile = new ProfileImpl(null, 1097, null);
        contenedorAgentes = runtime.createMainContainer(profile);
        agregarAgentes();
    }

    private void agregarAgentes(){
        try {
            contenedorAgentes.createNewAgent("Ag1", Ag1.class.getName(), null).start();
        }
        catch (StaleProxyException ex) {
            java.util.logging.Logger.getLogger(Contenedor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Agent:
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;

public class Ag1 extends Agent{

    @Override
    public void setup(){
        addBehaviour(new Comportamiento());
    }

    @Override
    public void takeDown(){

    }

    class Comportamiento extends CyclicBehaviour{

        @Override
        public void action() {
            System.out.println("pan");
        }

    }
}


问:
Ember Data Serializer & Adapter with Supabase returns empty (Proxy { })
Struggling to create my customised adapter & serializer to integrate Supabase, how I'm stuck why no data in Ember Data.

Trying out with a simple findAll() method. See below:

Service ⬇:

```<code>export default class SupabaseService extends Service {
  client;

  constructor() {
    super(...arguments);
    const { url, key } = ENV.supabase;
    const supabase = createClient(url, key);
    this.client = supabase;
  }
}
</code>```

Model ⬇:

```<code>export default class CourseModel extends Model {
  @attr('string') name;
  @attr('date') date_added;
}
</code>```

Adapter ⬇:

```<code>export default class ApplicationAdapter extends RESTAdapter {
  @service supabase;

  async findAll(store, type, neverSet, snapshotRecordArray) {
    return new Promise(async (resolve, reject) => {
      try {
        const { data, error, status } = await this.supabase.client
          .from(pluralize(type.modelName))
          .select('*');

        if (error) {
          reject(error);
        } else {
          resolve(data);
        }

      } catch (error) {
        reject(error);
      }
    });
  }
}
</code>```

Serializer ⬇:

```<code>normalizeResponse(store, primaryModelClass, payload, id, requestType) {
    // parse the response data from the server and return it in the format that Ember Data expects
    let newPayload = {
        data: payload.map(item => {
        let attributes = JSON.parse(JSON.stringify(item));
        delete attributes.id;

        return {
            id: item.id,
            type: primaryModelClass.modelName,
            attributes: attributes
        }
        })
    }

    return super.normalizeResponse(store, primaryModelClass, newPayload, id, requestType);
}
</code>```

✅ The service works fine. The adapter manage to get data and returns as follows:

```<code>[
    {
        "id": "259f46fd-3321-4cc9-ad5e-6d6ec880f7f1",
        "date_added": "2022-12-31T00:03:14.618585+00:00",
        "name": "Science"
    },
    {
        "id": "62a6a085-604b-4600-8cc4-59a8c9af284a",
        "date_added": "2022-12-31T00:03:30.010963+00:00",
        "name": "Physics"
    }
]
</code>```

The serializer newPayload to follow JSON API schema, returns:

```<code>{
    "data": [
        {
            "id": "259f46fd-3321-4cc9-ad5e-6d6ec880f7f1",
            "type": "course",
            "attributes": {
                "name": "Science",
                "date_added": "2022-12-31T00:03:14.618585+00:00"
            }
        },
        {
            "id": "62a6a085-604b-4600-8cc4-59a8c9af284a",
            "type": "course",
            "attributes": {
                "name": "Physics",
                "date_added": "2022-12-31T00:03:30.010963+00:00"
            }
        }
    ]
}
</code>```

But the problem is no data in store. Logging model in template shows empty Proxy {}.

I have no idea why. Ember Inspector shows no model in Data.

Any suggestions?

Body:
Struggling to create my customised adapter & serializer to integrate Supabase, how I'm stuck why no data in Ember Data.

Trying out with a simple findAll() method. See below:

Service ⬇:

export default class SupabaseService extends Service {
  client;

  constructor() {
    super(...arguments);
    const { url, key } = ENV.supabase;
    const supabase = createClient(url, key);
    this.client = supabase;
  }
}

Model ⬇:

export default class CourseModel extends Model {
  @attr('string') name;
  @attr('date') date_added;
}

Adapter ⬇:

export default class ApplicationAdapter extends RESTAdapter {
  @service supabase;

  async findAll(store, type, neverSet, snapshotRecordArray) {
    return new Promise(async (resolve, reject) => {
      try {
        const { data, error, status } = await this.supabase.client
          .from(pluralize(type.modelName))
          .select('*');

        if (error) {
          reject(error);
        } else {
          resolve(data);
        }

      } catch (error) {
        reject(error);
      }
    });
  }
}

Serializer ⬇:

normalizeResponse(store, primaryModelClass, payload, id, requestType) {
    // parse the response data from the server and return it in the format that Ember Data expects
    let newPayload = {
        data: payload.map(item => {
        let attributes = JSON.parse(JSON.stringify(item));
        delete attributes.id;

        return {
            id: item.id,
            type: primaryModelClass.modelName,
            attributes: attributes
        }
        })
    }

    return super.normalizeResponse(store, primaryModelClass, newPayload, id, requestType);
}

✅ The service works fine. The adapter manage to get data and returns as follows:

[
    {
        "id": "259f46fd-3321-4cc9-ad5e-6d6ec880f7f1",
        "date_added": "2022-12-31T00:03:14.618585+00:00",
        "name": "Science"
    },
    {
        "id": "62a6a085-604b-4600-8cc4-59a8c9af284a",
        "date_added": "2022-12-31T00:03:30.010963+00:00",
        "name": "Physics"
    }
]

The serializer newPayload to follow JSON API schema, returns:

{
    "data": [
        {
            "id": "259f46fd-3321-4cc9-ad5e-6d6ec880f7f1",
            "type": "course",
            "attributes": {
                "name": "Science",
                "date_added": "2022-12-31T00:03:14.618585+00:00"
            }
        },
        {
            "id": "62a6a085-604b-4600-8cc4-59a8c9af284a",
            "type": "course",
            "attributes": {
                "name": "Physics",
                "date_added": "2022-12-31T00:03:30.010963+00:00"
            }
        }
    ]
}

But the problem is no data in store. Logging model in template shows empty Proxy {}.

I have no idea why. Ember Inspector shows no model in Data.

Any suggestions?


问:
Lost connection to MySQL server during query ([Errno 54] Connection reset by peer)')
I have a Flask Application running locally and there is using pymysql to query a MySQL DB hosted on AWS RDS. After the application has been idle for a few minutes (>5), I get an error: Lost connection to MySQL server during query ([Errno 54] Connection reset by peer)')

```<code>File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/pymysql/connections.py", line 738, in _read_bytes
        raise err.OperationalError(
    sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query ([Errno 54] Connection reset by peer)')
    [SQL: SELECT users.id AS users_id, users.fullname AS users_fullname, users.email AS users_email, users.password AS users_password, users.name AS users_name, users.jobtitle AS users_jobtitle, users.country AS users_country, users.emailverified AS users_emailverified, users.created_at AS users_created_at
    FROM users
    WHERE users.id = %(pk_1)s]
    [parameters: {'pk_1': 1}]
    (Background on this error at: https://sqlalche.me/e/14/e3q8)
</code>```

I tried updating the parameters on AWS RDS - specifically, the timeout params, but it didn't work. What else can I try? Is this an issue with the Application code (mysql queries) or with the DB configuration in AWS RDS?

Body:
I have a Flask Application running locally and there is using pymysql to query a MySQL DB hosted on AWS RDS. After the application has been idle for a few minutes (>5), I get an error: Lost connection to MySQL server during query ([Errno 54] Connection reset by peer)')

File "/Applications/Anaconda/anaconda3/lib/python3.9/site-packages/pymysql/connections.py", line 738, in _read_bytes
        raise err.OperationalError(
    sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query ([Errno 54] Connection reset by peer)')
    [SQL: SELECT users.id AS users_id, users.fullname AS users_fullname, users.email AS users_email, users.password AS users_password, users.name AS users_name, users.jobtitle AS users_jobtitle, users.country AS users_country, users.emailverified AS users_emailverified, users.created_at AS users_created_at
    FROM users
    WHERE users.id = %(pk_1)s]
    [parameters: {'pk_1': 1}]
    (Background on this error at: https://sqlalche.me/e/14/e3q8)

I tried updating the parameters on AWS RDS - specifically, the timeout params, but it didn't work. What else can I try? Is this an issue with the Application code (mysql queries) or with the DB configuration in AWS RDS?


问:
How to configure pyodbc to use with Databricks when using SQL Server as a driver
Overview: I am running a virtual machine for work. On that machine, I am connecting to our Databricks account. Rather than creating a connection to our data warehouse and repository, I prefer to use the python package pyodbc, to connect to our database and thus its corresponding tables. If I am running jupyter notebook on the VM and connect to our database that way, I can run this in a cell:

```<code>import pyodbc
pyodbc.drivers()
</code>```

And the output will be a list of available drivers, one of which is 'SQL Server'. This seems to be the only one that I could get to connect to my work's database through my jupyter notebook. So, in attempt to reproduce that environment, but in databricks.

Problem: I have seen other issues where the following code worked to add 'ODBC Driver 17 for SQL Server' to the list of drivers, which is good, but again, I can only seem to get SQL Server to work as a driver, when it comes to connecting to my work database.

```<code>%sh
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get -q -y install msodbcsql17
</code>```

Ideal Solution: Run something similar to the above, but one that installs 'SQL Server' to the list of available drivers for pyodbc.

Current Code being executed:

```<code>conn = pyodbc.connect("DRIVER={SQL Server};" +
                      "SERVER=my_server_name;" +
                      "DATABASE=my_db_name;" +
                      "Trusted_Connection=yes;")
</code>```

Note: even if I switch the driver to ODBC Driver 17 for SQL Server, which CAN be loaded/added, it still doesn't work. I prefer SQL Server for the driver, as it worked fine in my jupyter notebook.

Additional Info: I am wondering if when using Databricks, it's as though you are on a virtual machine? Since I am already using a VM, is it that I am technically on a VM within a VM? On my VM, when run that above code to connect to the sql server, it finds it no problem. Perhaps in databricks, it needs more specific information to connect to that SQL Server? A url perhaps?

Body:
Overview: I am running a virtual machine for work. On that machine, I am connecting to our Databricks account. Rather than creating a connection to our data warehouse and repository, I prefer to use the python package pyodbc, to connect to our database and thus its corresponding tables. If I am running jupyter notebook on the VM and connect to our database that way, I can run this in a cell:

import pyodbc
pyodbc.drivers()

And the output will be a list of available drivers, one of which is 'SQL Server'. This seems to be the only one that I could get to connect to my work's database through my jupyter notebook. So, in attempt to reproduce that environment, but in databricks.

Problem: I have seen other issues where the following code worked to add 'ODBC Driver 17 for SQL Server' to the list of drivers, which is good, but again, I can only seem to get SQL Server to work as a driver, when it comes to connecting to my work database.

%sh
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get -q -y install msodbcsql17

Ideal Solution: Run something similar to the above, but one that installs 'SQL Server' to the list of available drivers for pyodbc.

Current Code being executed:

conn = pyodbc.connect("DRIVER={SQL Server};" +
                      "SERVER=my_server_name;" +
                      "DATABASE=my_db_name;" +
                      "Trusted_Connection=yes;")

Note: even if I switch the driver to ODBC Driver 17 for SQL Server, which CAN be loaded/added, it still doesn't work. I prefer SQL Server for the driver, as it worked fine in my jupyter notebook.

Additional Info: I am wondering if when using Databricks, it's as though you are on a virtual machine? Since I am already using a VM, is it that I am technically on a VM within a VM? On my VM, when run that above code to connect to the sql server, it finds it no problem. Perhaps in databricks, it needs more specific information to connect to that SQL Server? A url perhaps?


问:
Signalr connection is closing on web garden with 404 code
A signalr API (.NET 6) is hosted on IIS with "web garden" mode. Client frequently closes a connection with the following message: "System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found)."

When IIS config is changed not to use webgarden (max worker processes is set to 1) - error does not occur.
I have read that redis backplane would be a solution in such case (webgarden) but inlcuding it in my project did not help - the same error message occurs in same scenarios.

Here is my sample code from the Startup:

```<code>services.AddSignalR(options =>
            {
                options.EnableDetailedErrors = true;
            })
            .AddHubOptions<MyHub>(options =>
            {
                options.AddFilter<MyFilter>();
            })
            .AddNewtonsoftJsonProtocol()
            .AddStackExchangeRedis(o =>
            {
                o.ConnectionFactory = async writer =>
                {
                    var config = new ConfigurationOptions
                    {
                        AbortOnConnectFail = false
                    };
                    config.EndPoints.Add(IP_ADDR, PORT_NO);
                    config.DefaultDatabase = DEFAULT_DB;
                    var connection = await ConnectionMultiplexer.ConnectAsync(config, writer);
                    connection.ConnectionFailed += (_, e) =>
                    {
                        Console.WriteLine("Connection to Redis failed.");
                    };

                    if (!connection.IsConnected)
                    {
                        Console.WriteLine("Did not connect to Redis.");
                    }
                    else
                    {
                        Console.WriteLine("Connected to Redis.");
                    }

                    return connection;
                };
            });
</code>```

Did I miss somethig in my code? Or maybe it is about IIS configuration?

Body:
A signalr API (.NET 6) is hosted on IIS with "web garden" mode. Client frequently closes a connection with the following message: "System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found)."

When IIS config is changed not to use webgarden (max worker processes is set to 1) - error does not occur.
I have read that redis backplane would be a solution in such case (webgarden) but inlcuding it in my project did not help - the same error message occurs in same scenarios.

Here is my sample code from the Startup:

services.AddSignalR(options =>
            {
                options.EnableDetailedErrors = true;
            })
            .AddHubOptions<MyHub>(options =>
            {
                options.AddFilter<MyFilter>();
            })
            .AddNewtonsoftJsonProtocol()
            .AddStackExchangeRedis(o =>
            {
                o.ConnectionFactory = async writer =>
                {
                    var config = new ConfigurationOptions
                    {
                        AbortOnConnectFail = false
                    };
                    config.EndPoints.Add(IP_ADDR, PORT_NO);
                    config.DefaultDatabase = DEFAULT_DB;
                    var connection = await ConnectionMultiplexer.ConnectAsync(config, writer);
                    connection.ConnectionFailed += (_, e) =>
                    {
                        Console.WriteLine("Connection to Redis failed.");
                    };

                    if (!connection.IsConnected)
                    {
                        Console.WriteLine("Did not connect to Redis.");
                    }
                    else
                    {
                        Console.WriteLine("Connected to Redis.");
                    }

                    return connection;
                };
            });

Did I miss somethig in my code? Or maybe it is about IIS configuration?


问:
Rails: Calling Devise authenticate_user! and handling invalid user/password exception
I have a popup that will only allow to view/save some information if the user is authenticated.

I am using devise.

In the controller before_filter it checks if user is signed in and if not, show a sign in page.

This sign in page is ripped down version of the site's sign in page, so that it fits nicely to the popup.

On the authenticate action I call authenticate_user!. Everything works fine when the user enters valid credentials. But when the credential is invalid, devise automatically redirects to site's sign in page (which as I stated is different and not fit for a popup)

I tried appending a rescue to the call, but to no avail.

Anyone could suggest a better/right way to do this please? :)

```<code>def authenticate

    authenticate_user! rescue redirect_to "/popup/sign_in"

    if user_signed_in?
      respond_to do |format|
        format.html {
          flash[:notice] = I18n.t("logged_in_succesfully")
          redirect_back_or_default(accounts_path)
        }

    else
      flash[:error] = I18n.t("devise.failure.invalid")
      render "/popup/sign_in"
    end
  end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a popup that will only allow to view/save some information if the user is authenticated.

I am using devise.

In the controller before_filter it checks if user is signed in and if not, show a sign in page.

This sign in page is ripped down version of the site's sign in page, so that it fits nicely to the popup.

On the authenticate action I call authenticate_user!. Everything works fine when the user enters valid credentials. But when the credential is invalid, devise automatically redirects to site's sign in page (which as I stated is different and not fit for a popup)

I tried appending a rescue to the call, but to no avail.

Anyone could suggest a better/right way to do this please? :)

def authenticate

    authenticate_user! rescue redirect_to "/popup/sign_in"

    if user_signed_in?
      respond_to do |format|
        format.html {
          flash[:notice] = I18n.t("logged_in_succesfully")
          redirect_back_or_default(accounts_path)
        }

    else
      flash[:error] = I18n.t("devise.failure.invalid")
      render "/popup/sign_in"
    end
  end


问:
Dsharp, edit a bot's message's embed
How can i edit/modify my bot's message's embed Title?

I tried this:
"await botMessage.ModifyAsync(NewEmbed).ConfigureAwait(false);"
but i got an error "NewEmbed is not null here" Why does it need to be null if I want to replace it?

Title: Dsharp, edit a bot's message's embed


问:
Best practices to persist data without a DB in Next.js?
I have a simple app don’t have a DB because there is no data I need to save other than some small things. For example: access tokens or functions that have timeouts that will trigger things in the future.

I can simply store them in a variable, but what if the server is being reset?
I am hosting on Vercel, is it something that might happen?

Are there good alternatives to save this kind of data without a DB?


问:
Loop through const in React JSX return
I am following along with this tutorial and came across an issue while trying to modify it.

(link to tutorial: https://blog.logrocket.com/mern-stack-tutorial/)

Instead of creating a book card, I want to list the book inside a table tag.
(for the question, please assume that there is, and there will be, only one book in the database)

```<code>import React, { useState, useEffect } from 'react';
import '../App.css';
import axios from 'axios';
import { Link } from 'react-router-dom';
import BookCard from './BookCard';

function ShowBookList() {
  const [books, setBooks] = useState([]);

  useEffect(() => {
    axios
      .get('http://localhost:8082/api/books')
      .then((res) => {
        setBooks(res.data);
      })
      .catch((err) => {
        console.log('Error from ShowBookList');
      });
  }, []);

  return (
    <div className='ShowBookList'>
      <div className='container'>
        <div className='row'>
          <div className='col-md-12'>
            <br />
            <h2 className='display-4 text-center'>Books List</h2>
          </div>

          <div className='col-md-11'>
            <Link
              to='/create-book'
              className='btn btn-outline-warning float-right'
            >
              + Add New Book
            </Link>
            <br />
            <br />
            <hr />
          </div>
        </div>

        <div className='list'>
          <table className="table" style={{'white-space': 'nowrap'}}>
                <thead>
                    <tr>
                        <th className="text-center" scope="col">book title</th>
                        <th className="text-center" scope="col">book author</th>
                        <th className="text-center" scope="col">book isbn</th>
                        <th className="text-center" scope="col">published date</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>{books[0].title}</td>
                        <td>{books[0].author}</td>
                        <td>{books[0].isbn}</td>
                        <td>{books[0].publishedDate}</td>
                    </tr>
                </tbody>
            </table>
        </div>
      </div>
    </div>
  );
}

export default ShowBookList;
</code>```

Whenever I load, I get the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'title')

How can I make sure that the setBooks(res.data) inside useEffect() is run before the page is rendered?

Title: Loop through const in React JSX return

Body:
I am following along with this tutorial and came across an issue while trying to modify it.

(link to tutorial: https://blog.logrocket.com/mern-stack-tutorial/)

Instead of creating a book card, I want to list the book inside a table tag.
(for the question, please assume that there is, and there will be, only one book in the database)

import React, { useState, useEffect } from 'react';
import '../App.css';
import axios from 'axios';
import { Link } from 'react-router-dom';
import BookCard from './BookCard';

function ShowBookList() {
  const [books, setBooks] = useState([]);

  useEffect(() => {
    axios
      .get('http://localhost:8082/api/books')
      .then((res) => {
        setBooks(res.data);
      })
      .catch((err) => {
        console.log('Error from ShowBookList');
      });
  }, []);

  return (

Books List

            <Link
              to='/create-book'
              className='btn btn-outline-warning float-right'
            >
              + Add New Book
            </Link>

                        book title
                        book author
                        book isbn
                        published date

                        {books[0].title}
                        {books[0].author}
                        {books[0].isbn}
                        {books[0].publishedDate}

  );
}

export default ShowBookList;

Whenever I load, I get the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'title')

How can I make sure that the setBooks(res.data) inside useEffect() is run before the page is rendered?


问:
Dplyr:: filter function working selectively
I am trying to filter a dataset by each month but the 2nd code line does not execute. The 1st and 3rd work fine. The 2nd gives me this error:

Error in filter():
! Problem while computing ..1 = CloseDate >= "2022-02-01" & CloseDate <= "2022-02-31".
Caused by error in as.POSIXlt.character():
! character string is not in a standard unambiguous format

Backtrace:

dplyr::filter(...)

lubridate (local) <=.POSIXt(CloseDate, "2022-02-31")

base::as.POSIXct.default(e2)

base::as.POSIXlt.character(x, tz, ...)

base::stop("character string is not in a standard unambiguous format")

The Code:

```<code>
ACntyJan2022 <- filter(AlamedaCnty, CloseDate >= "2022-01-01" &
 CloseDate <= "2022-01-31")

ACntyMeanSPJan2022 \<- mean(ACntyJan2022$SP)

ACntyFeb2022 <- filter(AlamedaCnty, CloseDate >= "2022-02-01" &
 CloseDate <= "2022-02-31")
ACntyMeanSPFeb2022 <- mean(ACntyFeb2022$SP)

ACntyMrch2022 <- filter(AlamedaCnty, CloseDate >= as.POSIXct("2022-03-01") &
 CloseDate <= as.POSIXct("2022-03-31"))

ACntyMeanSPMrch2022 <- mean(ACntyMrch2022$SP)

</code>```

I am losing my head over trying to figure out what the issue is. Please help me.

Body:
I am trying to filter a dataset by each month but the 2nd code line does not execute. The 1st and 3rd work fine. The 2nd gives me this error:

Error in filter():
! Problem while computing ..1 = CloseDate >= "2022-02-01" & CloseDate <= "2022-02-31".
Caused by error in as.POSIXlt.character():
! character string is not in a standard unambiguous format

Backtrace:

dplyr::filter(...)

lubridate (local) <=.POSIXt(CloseDate, "2022-02-31")

base::as.POSIXct.default(e2)

base::as.POSIXlt.character(x, tz, ...)

base::stop("character string is not in a standard unambiguous format")

The Code:

ACntyJan2022 <- filter(AlamedaCnty, CloseDate >= "2022-01-01" &
 CloseDate <= "2022-01-31")

ACntyMeanSPJan2022 \<- mean(ACntyJan2022$SP)

ACntyFeb2022 <- filter(AlamedaCnty, CloseDate >= "2022-02-01" &
 CloseDate <= "2022-02-31")
ACntyMeanSPFeb2022 <- mean(ACntyFeb2022$SP)

ACntyMrch2022 <- filter(AlamedaCnty, CloseDate >= as.POSIXct("2022-03-01") &
 CloseDate <= as.POSIXct("2022-03-31"))

ACntyMeanSPMrch2022 <- mean(ACntyMrch2022$SP)

I am losing my head over trying to figure out what the issue is. Please help me.


问:
Table rows selection is cleared on table page change
I have a table where I can select rows with a checkbox, and each selected row is saved in a state with a list of ids.

Every time I change the table page, a request is made that overwrites the list displayed in the table, which makes the list of selected rows disappears.

When I select a new row on the new page, and when I return to the page where I had the checkboxes selected, it is no longer there.

My row function:

```<code>const rowSelection: any = {
    selectedRowKeys: listRowKeys,
    onChange: (selectedRowKeys, selectedRow) => {
      setListRowKeys(selectedRowKeys);
    },
  };
</code>```

When I select:

Console print array:

I select a new row in the new page:

List overwritten:

I try to update the function by creating a new state and updating the new one with the old one, but it does not work.

```<code>const [selectedCloneList, setSelectedCloneList] = useState([]);
</code>```
```<code>const rowSelection: any = {
    selectedRowKeys: listRowKeys,
    onChange: (selectedRowKeys, selectedRow) => {
      setListRowKeys([...selectedRowKeys, selectedCloneList]);
      setSelectedCloneList([...selectedRowKeys])
    },
  };
</code>```

Body:
I have a table where I can select rows with a checkbox, and each selected row is saved in a state with a list of ids.

Every time I change the table page, a request is made that overwrites the list displayed in the table, which makes the list of selected rows disappears.

When I select a new row on the new page, and when I return to the page where I had the checkboxes selected, it is no longer there.

My row function:

const rowSelection: any = {
    selectedRowKeys: listRowKeys,
    onChange: (selectedRowKeys, selectedRow) => {
      setListRowKeys(selectedRowKeys);
    },
  };

When I select:

Console print array:

I select a new row in the new page:

List overwritten:

I try to update the function by creating a new state and updating the new one with the old one, but it does not work.

const [selectedCloneList, setSelectedCloneList] = useState([]);

const rowSelection: any = {
    selectedRowKeys: listRowKeys,
    onChange: (selectedRowKeys, selectedRow) => {
      setListRowKeys([...selectedRowKeys, selectedCloneList]);
      setSelectedCloneList([...selectedRowKeys])
    },
  };


问:
How to 'postMessage' from a Chrome Extension page to another domain opened in a pop-up window?
I have this code in a JS file imported into an HTML page of my Chrome Extension:

```<code>const pathTsr_1 = "../tsr/tsr_templates/mailbox_quota.txt";
const myTsr = new XMLHttpRequest();
myTsr.open("GET", pathTsr_1);
myTsr.send();

myTsr.addEventListener("load", () => {

    const linka = myTsr.responseText;

    document.getElementById("linkTSR_BT").addEventListener("click", () => {
        navigator.clipboard.writeText(linka);
        var tooltip = document.getElementById("myTooltip");
        tooltip.innerHTML = "COPIED!";
    });

    document.getElementById("linkTSR_BT_TSR").addEventListener("click", () => {
        window.receiver = window.open('https://teams.somepage.com/share?', 'ms-teams-share-popup', 'width=700,height=600');
        window.receiver.addEventListener("load", () => {
            setTimeout(() => {
                window.receiver.postMessage(linka, chrome.runtime.getURL(""));
            }, 1000); // Delay by 1 second (1000 milliseconds)
        });
        //alert(myMessage);
    });
});

function outFunc() {
    document.getElementById("myTooltip").innerHTML = "Copy to clipboard";
}
</code>```

In a content script that gets injected into domain "teams.somepage.com" (which gets injected into the popup opened above), I have this code:

```<code>window.addEventListener("message", (event) => {
    // Check the origin of the received message to make sure it's from the correct domain
    if (event.origin !== "https://teams.somepage.com") return;
    //alert(event);
    // Find the compose box element
    const compBox = document.querySelector("#share-form-compose > p");
    // Send text into compose box
    //alert(JSON.stringify(event.data));
    compBox.textContent = event.data;
});
</code>```

I am consistently getting console errors:
"Cannot set properties of null"

It seems the message does not get passed from the Extension page into the pop-up.
I have tried everything I can think of. What am I missing?

Body:
I have this code in a JS file imported into an HTML page of my Chrome Extension:

const pathTsr_1 = "../tsr/tsr_templates/mailbox_quota.txt";
const myTsr = new XMLHttpRequest();
myTsr.open("GET", pathTsr_1);
myTsr.send();

myTsr.addEventListener("load", () => {

    const linka = myTsr.responseText;

    document.getElementById("linkTSR_BT").addEventListener("click", () => {
        navigator.clipboard.writeText(linka);
        var tooltip = document.getElementById("myTooltip");
        tooltip.innerHTML = "COPIED!";
    });

    document.getElementById("linkTSR_BT_TSR").addEventListener("click", () => {
        window.receiver = window.open('https://teams.somepage.com/share?', 'ms-teams-share-popup', 'width=700,height=600');
        window.receiver.addEventListener("load", () => {
            setTimeout(() => {
                window.receiver.postMessage(linka, chrome.runtime.getURL(""));
            }, 1000); // Delay by 1 second (1000 milliseconds)
        });
        //alert(myMessage);
    });
});

function outFunc() {
    document.getElementById("myTooltip").innerHTML = "Copy to clipboard";
}

In a content script that gets injected into domain "teams.somepage.com" (which gets injected into the popup opened above), I have this code:

window.addEventListener("message", (event) => {
    // Check the origin of the received message to make sure it's from the correct domain
    if (event.origin !== "https://teams.somepage.com") return;
    //alert(event);
    // Find the compose box element
    const compBox = document.querySelector("#share-form-compose > p");
    // Send text into compose box
    //alert(JSON.stringify(event.data));
    compBox.textContent = event.data;
});

I am consistently getting console errors:
"Cannot set properties of null"

It seems the message does not get passed from the Extension page into the pop-up.
I have tried everything I can think of. What am I missing?


问:
BASH: problem with single and double quotes and variables in a script
I'm trying to make a bash script to use a program called bamql. The execution of bamql from the terminal would be something like this:

bamql -f <file_in> 'chr(<name>) & nt_exact(<number>,<letter>)' -o <file_out>

<file_in> is the input file to the program <name> is the name of the chromosome of the organism that I am studying <number> It is an integer indicating the position that I want to study <letter> is a letter (A, C, G or T) indicating the mutation that I want to study <file_out> is the output file of the program

An example of BAMQL execution would be the following

bamql -f BC02.sorted.bam 'chr(PB2) & nt_exact(482,T)' -o PB2_482_T.bam

So what I want is to make a bash script to be able to execute BAMQL with variables, like this:

bamql -f ${FILE_IN} 'chr(${CHRN}) & nt_exact(${SNV})' -o ${FILE_OUT}

The problem is that the previous code does not work, it gives me the error "Unexpected character", and the variables ${CHRN} and ${SNV} do not take their value. I have also tried to enclose the whole 'chr(${CHRN}) & nt_exact(${SNV})' part in an array and run the code:

args=('chr(${CHRN}) & nt_exact(${SNV})')

bamql -f ${FILE_IN} "${args[@]}" -o ${FILE_OUT}

but again the variables ${CHRN} and ${SNV} do not take their value.

I would be grateful if someone gives me some suggestion.


问:
Half-Even Rounding - 265.335 rounding to 2 digits gives 265.33 but should be 265.34?
I'm working on a bit of code where I'm implementing half-even rounding. I've been using this post (How to round a number to n decimal places in Java) as a guide and am running tests using the code below on an online Java compiler:

```<code>// Java code
public static void main(String []args){
        String precisionString = "#.##";
        double localValue = 265.335;
        DecimalFormat df = new DecimalFormat(precisionString);
        df.setRoundingMode(RoundingMode.HALF_EVEN);
        System.out.println(Double.parseDouble(df.format(localValue)));
     }
</code>```

It works fine for most test values, but for the value 265.335, rounding to 2 decimal places returns 265.33 when it should be 265.34.

I tested this out on an online C# compiler and got similar results (C# equivalent below), so I'm thinking this isn't a language bug but rather something to do with how the numbers are being read in binary. I'm not able to figure out exactly what/where the problem is though..

```<code>// C# code
public static void Main()
    {
        double a = 265.335;
        var rounded = Math.Round(a, 2, MidpointRounding.ToEven);
        Console.WriteLine(rounded);
    }
</code>```

Thoughts ?

Body:
I'm working on a bit of code where I'm implementing half-even rounding. I've been using this post (How to round a number to n decimal places in Java) as a guide and am running tests using the code below on an online Java compiler:

// Java code
public static void main(String []args){
        String precisionString = "#.##";
        double localValue = 265.335;
        DecimalFormat df = new DecimalFormat(precisionString);
        df.setRoundingMode(RoundingMode.HALF_EVEN);
        System.out.println(Double.parseDouble(df.format(localValue)));
     }

It works fine for most test values, but for the value 265.335, rounding to 2 decimal places returns 265.33 when it should be 265.34.

I tested this out on an online C# compiler and got similar results (C# equivalent below), so I'm thinking this isn't a language bug but rather something to do with how the numbers are being read in binary. I'm not able to figure out exactly what/where the problem is though..

// C# code
public static void Main()
    {
        double a = 265.335;
        var rounded = Math.Round(a, 2, MidpointRounding.ToEven);
        Console.WriteLine(rounded);
    }

Thoughts ?


问:
Is there a R-equivalent function for MATLAB's cross product and vector norm?
I'm trying to recreate some MATLAB code in R and am struggling to figure out the R-equivalent for cross() and norm()

Here's the MATLAB:

```<code>a = [0.7327, 2.9842, -0.069];

b = [1.095, -3.412, 1.656];

dot_test = dot(a,b)

cross_test = cross(a,b)

norm_test = norm(cross_test,dot_test)

dot_test =

   -9.4940

cross_test =

    4.7064   -1.2889   -5.7677

norm_test =

    1.2889
</code>```

I can calculate the dot product in R as such:

```<code>> a <- t(matrix(data = c(0.7327, 2.9842, -0.069)))
> b <- t(matrix(data = c(1.095, -3.412, 1.656)))

> dot_test <- tcrossprod(a,b)
> dot_test

 -9.494048
</code>```

but when I use crossprod(), results diverge:

```<code>> crossprod(a,b)
           [,1]       [,2]      [,3]
[1,]  0.8023065  -2.499972  1.213351
[2,]  3.2676990 -10.182090  4.941835
[3,] -0.0755550   0.235428 -0.114264
</code>```

Then there are 5 types of norm() function in R, but I can't test for the correct one until figuring out the cross product.

Edit: The pracma package cross function reproduces MATLAB's results

```<code>
> cross_test <- pracma::cross(a, b)
> pracma::cross(a,b)
         [,1]      [,2]      [,3]
[1,] 4.706407 -1.288906 -5.767671
</code>```

Edit2: In this case, MATLAB is returning the generalized vector p-norm which can be reproduced in R as follows:

```<code>sum(abs(cross_test)^dot_test[[1]])^(1/dot_test[[1]])

1.288905
</code>```

Body:
I'm trying to recreate some MATLAB code in R and am struggling to figure out the R-equivalent for cross() and norm()

Here's the MATLAB:

a = [0.7327, 2.9842, -0.069];

b = [1.095, -3.412, 1.656];

dot_test = dot(a,b)

cross_test = cross(a,b)

norm_test = norm(cross_test,dot_test)

dot_test =

   -9.4940

cross_test =

    4.7064   -1.2889   -5.7677

norm_test =

    1.2889

I can calculate the dot product in R as such:

> a <- t(matrix(data = c(0.7327, 2.9842, -0.069)))
> b <- t(matrix(data = c(1.095, -3.412, 1.656)))

> dot_test <- tcrossprod(a,b)
> dot_test

 -9.494048

but when I use crossprod(), results diverge:

> crossprod(a,b)
           [,1]       [,2]      [,3]
[1,]  0.8023065  -2.499972  1.213351
[2,]  3.2676990 -10.182090  4.941835
[3,] -0.0755550   0.235428 -0.114264

Then there are 5 types of norm() function in R, but I can't test for the correct one until figuring out the cross product.

Edit: The pracma package cross function reproduces MATLAB's results

> cross_test <- pracma::cross(a, b)
> pracma::cross(a,b)
         [,1]      [,2]      [,3]
[1,] 4.706407 -1.288906 -5.767671

Edit2: In this case, MATLAB is returning the generalized vector p-norm which can be reproduced in R as follows:

sum(abs(cross_test)^dot_test[[1]])^(1/dot_test[[1]])

1.288905


问:
R: Combining Multiple Maps Together
I am working with the R programming language.

I am following this tutorial here (https://www.johnmackintosh.net/blog/2017-09-01-easy-maps-with-tmap/) and trying to produce an output that looks something like this:

However, instead of plotting the same map with multiple variables, I am now trying to plot different maps.

As an example, suppose I has 8 separate "mini" maps - would something like this be possible?

```<code>library(tmap)
library(tmaptools)
library(viridis)

small_mult<- tm_shape(c(map1, map2, map3, map4, map5, map6, map7, map8)) +
  tm_fill(col = c("map1$var1","map2$var1","map3$var1","map4$var1",
                  "map5$var1","map6$var1","map7$var1","map8$var1"),
          palette = viridis(n = 5, direction = -1, option = "C"),
          title=c("title map 1 var 1", "title map 2 var 1","title map 3 var 1","title map 4 var 1", "title map 5 var 1","title map 6 var 1", "title map 7 var 1","title map 8 var 1"))
</code>```

Or is this not possible?

Thanks!

Title: R: Combining Multiple Maps Together

Body:
I am working with the R programming language.

I am following this tutorial here (https://www.johnmackintosh.net/blog/2017-09-01-easy-maps-with-tmap/) and trying to produce an output that looks something like this:

However, instead of plotting the same map with multiple variables, I am now trying to plot different maps.

As an example, suppose I has 8 separate "mini" maps - would something like this be possible?

library(tmap)
library(tmaptools)
library(viridis)

small_mult<- tm_shape(c(map1, map2, map3, map4, map5, map6, map7, map8)) +
  tm_fill(col = c("map1$var1","map2$var1","map3$var1","map4$var1",
                  "map5$var1","map6$var1","map7$var1","map8$var1"),
          palette = viridis(n = 5, direction = -1, option = "C"),
          title=c("title map 1 var 1", "title map 2 var 1","title map 3 var 1","title map 4 var 1", "title map 5 var 1","title map 6 var 1", "title map 7 var 1","title map 8 var 1"))

Or is this not possible?

Thanks!


问:
How can I read a table that is returned from a plpgsql function using Java?
I have a postgres plpgsql function that returns a table of cars:

CREATE OR REPLACE FUNCTION getCarsList()
RETURNS TABLE (
    model varchar,
    engine varchar,
    manufacturer varchar
) AS $$
    BEGIN
        RETURN QUERY SELECT * FROM cars;
    END;
$$ LANGUAGE plpgsql;
```
<p>Now, I want to retrieve all table columns from the function and print them using Java. I've tried to write the following code:</p>
<pre class="lang-java prettyprint-override"><code>result = statement.executeQuery("SELECT getCarsList()");
while (result.next()) {
    System.out.println(result.getString(("model")));
    System.out.println(result.getString(("engine")));
    System.out.println(result.getString(("manufacturer")));
}
</code>```

But got the following SQLSyntaxErrorException:

```<code>Message: The column name model was not found in this ResultSet.
SQLState: 42703
ErrorCode: 0
</code>```

So, since I don't really understand what is causing the message, is there a way to do what I want?

Body:
I have a postgres plpgsql function that returns a table of cars:

CREATE OR REPLACE FUNCTION getCarsList()
RETURNS TABLE (
    model varchar,
    engine varchar,
    manufacturer varchar
) AS $$
    BEGIN
        RETURN QUERY SELECT * FROM cars;
    END;
$$ LANGUAGE plpgsql;

Now, I want to retrieve all table columns from the function and print them using Java. I've tried to write the following code:

result = statement.executeQuery("SELECT getCarsList()");
while (result.next()) {
    System.out.println(result.getString(("model")));
    System.out.println(result.getString(("engine")));
    System.out.println(result.getString(("manufacturer")));
}

But got the following SQLSyntaxErrorException:

Message: The column name model was not found in this ResultSet.
SQLState: 42703
ErrorCode: 0

So, since I don't really understand what is causing the message, is there a way to do what I want?


问:
How do I access the JSON output of a command using the command line?
I'm running a command that contacts a server, and the server outputs JSON through the command to get the data. How do I get the data from the JSON output and use the data? I'm running the command from the command line in Linux.

For example:

```<code>~/jason$:command xyz
{
  name: "mary"
  eyecolor: "red"
}
</code>```

I thought that maybe putting the command in a variable would put me in the right direction but I don't know where to go from there:

```<code>result=$(command xyz)
# ...
</code>```

Body:
I'm running a command that contacts a server, and the server outputs JSON through the command to get the data. How do I get the data from the JSON output and use the data? I'm running the command from the command line in Linux.

For example:

~/jason$:command xyz
{
  name: "mary"
  eyecolor: "red"
}

I thought that maybe putting the command in a variable would put me in the right direction but I don't know where to go from there:

result=$(command xyz)
# ...


问:
Remove admin menu item Wordpress
I need to Remove an admin menu page Wordpress.

The URL is "/wp-admin/admin.php?page=alpha"

I try it:
```<code>function remove_item_from_menu() {
  global $user_ID;
  remove_menu_page('admin.php?page=alpha');
}
add_action( 'admin_init', 'remove_item_from_menu' );
</code>```

But I am not get success. Someone help me please?

Title: Remove admin menu item Wordpress

Body:
I need to Remove an admin menu page Wordpress.

The URL is "/wp-admin/admin.php?page=alpha"

I try it:

function remove_item_from_menu() {
  global $user_ID;
  remove_menu_page('admin.php?page=alpha');
}
add_action( 'admin_init', 'remove_item_from_menu' );

But I am not get success. Someone help me please?


问:
Facebook Ads API Debugging - Error with params
I can not get my Facebook Ad API up and running with Python. I keep receiving multiple errors specifically alluding to the fact that some of the breakdowns/params/fields are not available even though this is code that Facebook recommended I use.

```<code>from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.adsinsights import AdsInsights
from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.campaign import Campaign

access_token = ''
ad_account_id = ''
FacebookAdsApi.init(access_token=access_token)

fields = [
    'spend',
    'start_time',
    'stop_time',
    'reach',
    'action_values:omni_purchase',
    'action_values:offsite_conversion_fb_pixel_purchase',
    'unique_actions:link_click',
    'actions:link_click',
    'actions:landing_page_view',
]
params = {
    'time_range': {'since':'2022-12-06','until':'2023-01-05'},
    'filtering': [{'field':'impressions','operator':'GREATER_THAN','value':'0'}],
    'level': 'campaign',
    'breakdowns': ['days_1'],
}

print(AdAccount(ad_account_id).get_insights(
    fields=fields,
    params=params,))
</code>```

I was expecting the data to pull into the output but can not get it to work

Body:
I can not get my Facebook Ad API up and running with Python. I keep receiving multiple errors specifically alluding to the fact that some of the breakdowns/params/fields are not available even though this is code that Facebook recommended I use.

from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.adsinsights import AdsInsights
from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.campaign import Campaign

access_token = ''
ad_account_id = ''
FacebookAdsApi.init(access_token=access_token)

fields = [
    'spend',
    'start_time',
    'stop_time',
    'reach',
    'action_values:omni_purchase',
    'action_values:offsite_conversion_fb_pixel_purchase',
    'unique_actions:link_click',
    'actions:link_click',
    'actions:landing_page_view',
]
params = {
    'time_range': {'since':'2022-12-06','until':'2023-01-05'},
    'filtering': [{'field':'impressions','operator':'GREATER_THAN','value':'0'}],
    'level': 'campaign',
    'breakdowns': ['days_1'],
}

print(AdAccount(ad_account_id).get_insights(
    fields=fields,
    params=params,))

I was expecting the data to pull into the output but can not get it to work


问:
Mantine clear checked value of other chips when one is selected
I'm using the Mantine chip group component to let users add some default values.  When 'Custom' is selected, it opens a drawer with a textbox to allow custom input. (See image below)

I can't figure out though how to uncheck the previous four chips when Custom is selected though.

Here's my code:

```<code>  const Chips = chips.map((chip) => {
    return (
      <Chip
        classNames={classes}
        disabled={opened}
        key={chip.name}
        value={chip.value}
        defaultChecked={opened ? false : chip.defaultValue}
      >
        {chip.name}
      </Chip>
    )
  })

  return (
    <Chip.Group multiple value={textState} onChange={handleChange} spacing={30}>
      {chips.map((chip) => (
        <Chip
          classNames={classes}
          disabled={opened}
          key={chip.name}
          value={chip.value}
          defaultChecked={opened ? false : chip.defaultValue}
        >
          {chip.name}
        </Chip>
      ))}
      <Chip
        classNames={classes}
        checked={opened}
        onClick={() => {
          setOpen((o) => !o);
          //clear checked value of other chips
        }}
      >
        Custom
      </Chip>
    </Chip.Group>
  );
</code>```

Body:
I'm using the Mantine chip group component to let users add some default values.  When 'Custom' is selected, it opens a drawer with a textbox to allow custom input. (See image below)

I can't figure out though how to uncheck the previous four chips when Custom is selected though.

Here's my code:

  const Chips = chips.map((chip) => {
    return (
      <Chip
        classNames={classes}
        disabled={opened}
        key={chip.name}
        value={chip.value}
        defaultChecked={opened ? false : chip.defaultValue}
      >
        {chip.name}
      </Chip>
    )
  })

  return (
    <Chip.Group multiple value={textState} onChange={handleChange} spacing={30}>
      {chips.map((chip) => (
        <Chip
          classNames={classes}
          disabled={opened}
          key={chip.name}
          value={chip.value}
          defaultChecked={opened ? false : chip.defaultValue}
        >
          {chip.name}
        </Chip>
      ))}
      <Chip
        classNames={classes}
        checked={opened}
        onClick={() => {
          setOpen((o) => !o);
          //clear checked value of other chips
        }}
      >
        Custom
      </Chip>
    </Chip.Group>
  );


问:
JavaFX/IntelliJ Application Pathway Issue
I'm trying to set up an IntelliJ application, and can't get something quite right.

Being hit with an error when I try to run it:

"C:\Program Files\Java\jdk-19\bin\java.exe" ...
Error occurred during initialization of boot layer
java.lang.module.FindException: Module javafx.controls not found

Process finished with exit code 1
```

I uploaded the lib folder for openjfx, as well as the pathway to the lib folder in Project Structure.

I used these three pages in order to help me get to where I currently am:

Where can I find the "Create project from template" and the "Base package" settings when creating a new project?

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

Eclipse IDE Error: Could not find or load main class javafx.fxml Caused by: java.lang.ClassNotFoundException: javafx.fxml

In the VM Options under Run Configurations, I put the pathway to the lib folder:

--module-path C:\Users\wtfri\Downloads\openjfx-19_windows-x64_bin-sdk.zip\javafx-sdk-19\lib--add-modules=javafx.controls

I feel like I made a mistake somewhere in the snippet of code I put into the VM options, but I'm not experienced enough yet to know what's going on.

Body:
I'm trying to set up an IntelliJ application, and can't get something quite right.

Being hit with an error when I try to run it:

"C:\Program Files\Java\jdk-19\bin\java.exe" ...
Error occurred during initialization of boot layer
java.lang.module.FindException: Module javafx.controls not found

Process finished with exit code 1

I uploaded the lib folder for openjfx, as well as the pathway to the lib folder in Project Structure.

I used these three pages in order to help me get to where I currently am:

Where can I find the "Create project from template" and the "Base package" settings when creating a new project?

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

Eclipse IDE Error: Could not find or load main class javafx.fxml Caused by: java.lang.ClassNotFoundException: javafx.fxml

In the VM Options under Run Configurations, I put the pathway to the lib folder:

--module-path C:\Users\wtfri\Downloads\openjfx-19_windows-x64_bin-sdk.zip\javafx-sdk-19\lib--add-modules=javafx.controls

I feel like I made a mistake somewhere in the snippet of code I put into the VM options, but I'm not experienced enough yet to know what's going on.


问:
Error when loading object by using pickel.load(). Can't get attribute 'Company' on <module '__main__'> Traceback (most recent call last):
I have a Company.py

```<code>class Company(object):
    def __init__(self, name, value):
    self.name = name
    self.value = value

if __name__ == '__main__':
    fileObj = open('company.pkl', 'wb')
    pickle.dump(c1,fileObj)
</code>```

and load it from a different module, Second.py:

```<code>from Company import Company

fileObj = open('company.pkl', 'rb')
c2 = pickle.load(fileObj)
</code>```

but getting error:

```<code>Can't get attribute 'Company' on <module '__main__'>
Traceback (most recent call last):
</code>```

What am I missing?

Body:
I have a Company.py

class Company(object):
    def __init__(self, name, value):
    self.name = name
    self.value = value

if __name__ == '__main__':
    fileObj = open('company.pkl', 'wb')
    pickle.dump(c1,fileObj)

and load it from a different module, Second.py:

from Company import Company

fileObj = open('company.pkl', 'rb')
c2 = pickle.load(fileObj)

but getting error:

Can't get attribute 'Company' on <module '__main__'>
Traceback (most recent call last):

What am I missing?


问:
Pasting hundreds of lines of text into Emacs
Pasting 900 lines of text into console-mode Emacs (Shift-Ins) on an Ubuntu desktop machine results in only 842 lines of text appearing. I have experienced similar situations in the past where not all the text I've selected is pasted. Any ideas?</p>


问:
Long SwiftUI list causes visible lag on cell update
I have an app with a long list that triggers a server-pull when a cell gets displayed. This server pull will cause the cell to update. Items are stored in a dict and an index list locally, and shown in a lazy v stack. This doesn't seem to me to be the kind of update that should cause a modern iPhone to stutter but it definitely makes the animations less smooth. Seems like I'm doing something obvious wrong but I can't seem to find the issue. I wrote an example app here. The gist is:

struct ContentView: View {
    var body: some View {
        TestView()
            .environmentObject(globalState)
            .task {
                (0...10000).forEach { _ in
                    globalState.newItem()
                }
                updateLater()
            }
    }

    func updateLater() {
        DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 0.5) {
            update()
        }
    }

    func update() {
        DispatchQueue.main.async {
            let id = globalState.itemIds[3]
            var item = globalState.itemDict[id]!
            item.newColor()
            item.text = "changed"
            globalState.itemDict[id] = item
        }
        updateLater()
    }
}

extension State {
    func newItem() {
        let item = Item()
        itemDict[item.id] = item
        itemIds.append(item.id)
    }
}

let globalState = State()

struct TestView: View {
    @EnvironmentObject var state: State

    var items: [Item] {
        state.itemList.filter {
            !$0.text.isEmpty
        }
    }

    var body: some View {
        ScrollView {
            LazyVStack {
                ForEach(items, id: \.id) { item in
                    row(item)
                }
            }
        }
    }

    func row(_ item: Item) -> some View {
        Button {

        } label: {
            Text(item.text)
                .frame(maxWidth: .infinity)
                .padding()
                .background(item.color.opacity(0.2))
        }
    }
}

class State: ObservableObject {
    @Published var itemIds: [UUID] = []
    @Published var itemDict: [UUID: Item] = [:]

    var itemList: [Item] {
        itemIds.compactMap {
            itemDict[$0]
        }
    }
}

func randomColor() -> Color { Color(hue: .random(in: 0...1), saturation: 0.9, brightness: 0.5) }

struct Item {
    var id = UUID()
    var text = "Hello"
    var color = randomColor()

    mutating func newColor() {
        color = randomColor()
    }
}
```

I feel like there's a swiftui feature I'm missing here. There has to be a better way... my real app is way laggier than the example.

Body:
I have an app with a long list that triggers a server-pull when a cell gets displayed. This server pull will cause the cell to update. Items are stored in a dict and an index list locally, and shown in a lazy v stack. This doesn't seem to me to be the kind of update that should cause a modern iPhone to stutter but it definitely makes the animations less smooth. Seems like I'm doing something obvious wrong but I can't seem to find the issue. I wrote an example app here. The gist is:

struct ContentView: View {
    var body: some View {
        TestView()
            .environmentObject(globalState)
            .task {
                (0...10000).forEach { _ in
                    globalState.newItem()
                }
                updateLater()
            }
    }

    func updateLater() {
        DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 0.5) {
            update()
        }
    }

    func update() {
        DispatchQueue.main.async {
            let id = globalState.itemIds[3]
            var item = globalState.itemDict[id]!
            item.newColor()
            item.text = "changed"
            globalState.itemDict[id] = item
        }
        updateLater()
    }
}

extension State {
    func newItem() {
        let item = Item()
        itemDict[item.id] = item
        itemIds.append(item.id)
    }
}

let globalState = State()

struct TestView: View {
    @EnvironmentObject var state: State

    var items: [Item] {
        state.itemList.filter {
            !$0.text.isEmpty
        }
    }

    var body: some View {
        ScrollView {
            LazyVStack {
                ForEach(items, id: \.id) { item in
                    row(item)
                }
            }
        }
    }

    func row(_ item: Item) -> some View {
        Button {

        } label: {
            Text(item.text)
                .frame(maxWidth: .infinity)
                .padding()
                .background(item.color.opacity(0.2))
        }
    }
}

class State: ObservableObject {
    @Published var itemIds: [UUID] = []
    @Published var itemDict: [UUID: Item] = [:]

    var itemList: [Item] {
        itemIds.compactMap {
            itemDict[$0]
        }
    }
}

func randomColor() -> Color { Color(hue: .random(in: 0...1), saturation: 0.9, brightness: 0.5) }

struct Item {
    var id = UUID()
    var text = "Hello"
    var color = randomColor()

    mutating func newColor() {
        color = randomColor()
    }
}

I feel like there's a swiftui feature I'm missing here. There has to be a better way... my real app is way laggier than the example.


问:
Date histogram aggregation seems incorrect with calendar_interval and when offset >= 30 days
Based on this doc, elasticsearch supports Calendar-aware interval on data histogram aggregation. Specially for a "quarter" interval:

"One quarter is the interval between the start day of the month and time of day and the same day of the month and time of day three months later, so that the day of the month and time of day are the same at the start and end."

My understanding of this is every bucket in the response should start at the same day, but that's not the case when I use offset >= 30 days. Some buckets start at, say 5th of the month,  while one other bucket starts at the 6th of the month. Is this a bug or am I missing anything?

Elasticsearch Version: 7.17

Steps to reproduce:

```<code>PUT /test01
{
  "mappings": {
    "properties": {
      "date": { "type": "date" }
    }
  }
}

POST /test01/_doc { "date": 1642658400000 } // 01/20/2022, 6AM UTC
POST /test01/_doc { "date": 1645336800000 } // 02/20/2022, 6AM UTC
...
POST /test01/_doc { "date": 1660975200000 } // 08/20/2022, 6AM UTC
// basically one document every month from January to August
</code>```

Queries:

```<code>{
    "size": 0,
    "aggs": {
        "ShiftedQuarter": {
            "date_histogram": {
                "calendar_interval": "quarter",
                "min_doc_count": 1,
                "time_zone": "UTC",
                "offset": "+20d", // offset is less than 30 days
                "field": "date"
            }
        }
    }
}
</code>```

returns below as expected (every bucket starts at the 21st day of the month):

```<code>"aggregations": {
    "ShiftedQuarter": {
      "buckets": [
        {
          "key_as_string": "2021-10-21T00:00:00.000Z",
          "key": 1634774400000,
          "doc_count": 1
        },
        {
          "key_as_string": "2022-01-21T00:00:00.000Z",
          "key": 1642723200000,
          "doc_count": 3
        },
        {
          "key_as_string": "2022-04-21T00:00:00.000Z",
          "key": 1650499200000,
          "doc_count": 3
        },
        {
          "key_as_string": "2022-07-21T00:00:00.000Z",
          "key": 1658361600000,
          "doc_count": 1
        }
      ]
    }
  }
</code>```

However if the query use a offset that is large than 30, like

```<code>{
    "size": 0,
    "aggs": {
        "ShiftedQuarter": {
            "date_histogram": {
                "calendar_interval": "quarter",
                "min_doc_count": 1,
                "time_zone": "UTC",
                "offset": "+35d",
                "field": "date"
            }
        }
    }
}
</code>```

then some bucket starts at the 5th but some starts at the 6th:

```<code>"aggregations": {
    "ShiftedQuarter": {
      "buckets": [
        {
          "key_as_string": "2021-11-05T00:00:00.000Z",
          "key": 1636070400000,
          "doc_count": 1
        },
        {
          "key_as_string": "2022-02-05T00:00:00.000Z",
          "key": 1644019200000,
          "doc_count": 3
        },
        {
          "key_as_string": "2022-05-06T00:00:00.000Z", // 06 as opposed to 05 for other buckets
          "key": 1651795200000,
          "doc_count": 3
        },
        {
          "key_as_string": "2022-08-05T00:00:00.000Z",
          "key": 1659657600000,
          "doc_count": 1
        }
      ]
    }
  }
</code>```

Body:
Based on this doc, elasticsearch supports Calendar-aware interval on data histogram aggregation. Specially for a "quarter" interval:

"One quarter is the interval between the start day of the month and time of day and the same day of the month and time of day three months later, so that the day of the month and time of day are the same at the start and end."

My understanding of this is every bucket in the response should start at the same day, but that's not the case when I use offset >= 30 days. Some buckets start at, say 5th of the month,  while one other bucket starts at the 6th of the month. Is this a bug or am I missing anything?

Elasticsearch Version: 7.17

Steps to reproduce:

PUT /test01
{
  "mappings": {
    "properties": {
      "date": { "type": "date" }
    }
  }
}

POST /test01/_doc { "date": 1642658400000 } // 01/20/2022, 6AM UTC
POST /test01/_doc { "date": 1645336800000 } // 02/20/2022, 6AM UTC
...
POST /test01/_doc { "date": 1660975200000 } // 08/20/2022, 6AM UTC
// basically one document every month from January to August

Queries:

{
    "size": 0,
    "aggs": {
        "ShiftedQuarter": {
            "date_histogram": {
                "calendar_interval": "quarter",
                "min_doc_count": 1,
                "time_zone": "UTC",
                "offset": "+20d", // offset is less than 30 days
                "field": "date"
            }
        }
    }
}

returns below as expected (every bucket starts at the 21st day of the month):

"aggregations": {
    "ShiftedQuarter": {
      "buckets": [
        {
          "key_as_string": "2021-10-21T00:00:00.000Z",
          "key": 1634774400000,
          "doc_count": 1
        },
        {
          "key_as_string": "2022-01-21T00:00:00.000Z",
          "key": 1642723200000,
          "doc_count": 3
        },
        {
          "key_as_string": "2022-04-21T00:00:00.000Z",
          "key": 1650499200000,
          "doc_count": 3
        },
        {
          "key_as_string": "2022-07-21T00:00:00.000Z",
          "key": 1658361600000,
          "doc_count": 1
        }
      ]
    }
  }

However if the query use a offset that is large than 30, like

{
    "size": 0,
    "aggs": {
        "ShiftedQuarter": {
            "date_histogram": {
                "calendar_interval": "quarter",
                "min_doc_count": 1,
                "time_zone": "UTC",
                "offset": "+35d",
                "field": "date"
            }
        }
    }
}

then some bucket starts at the 5th but some starts at the 6th:

"aggregations": {
    "ShiftedQuarter": {
      "buckets": [
        {
          "key_as_string": "2021-11-05T00:00:00.000Z",
          "key": 1636070400000,
          "doc_count": 1
        },
        {
          "key_as_string": "2022-02-05T00:00:00.000Z",
          "key": 1644019200000,
          "doc_count": 3
        },
        {
          "key_as_string": "2022-05-06T00:00:00.000Z", // 06 as opposed to 05 for other buckets
          "key": 1651795200000,
          "doc_count": 3
        },
        {
          "key_as_string": "2022-08-05T00:00:00.000Z",
          "key": 1659657600000,
          "doc_count": 1
        }
      ]
    }
  }


问:
Storybook Cannot find module '@theme' Mui 4.n version
I use @stroybook/react.
npm run storybook
storybook cannnot find module.
only custom component not working.

use material-ui theme, react, typescript component
custom component is not class component
help!
difficult english!!

main.js

```<code>module.exports = {
  stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
  addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/addon-interactions",
    "@storybook/preset-create-react-app",
  ],
  framework: "@storybook/react",
  core: {
    builder: "@storybook/builder-webpack5",
  },
};
</code>```

preview.js

```<code>import "../src/index.css";

export const parameters = {
  actions: { argTypesRegex: "^on[A-Z].*" },
  controls: {
    expanded: true,
    matchers: {
      color: /(background|color)$/i,
      date: /Date$/,
    },
  },
};

</code>```

theme.ts

```<code>export const theme = {
  max_wrap: { maxWidth: 1920 },

  max_content: { maxWidth: 1272 },
  max_content_lg: { maxWidth: 940 },
  max_content_md: { maxWidth: 932 },

  max_section_lg: { maxWidth: 872 },

  base_container: {
    maxWidth: 1272 + 40,
    padding: "40px 20px 72px",

  },
  base_container_lg: {
    maxWidth: 940 + 40,
  },

  base_container_md: {
    maxWidth: 932 + 40,
    padding: "32px 20px 72px",

  },
...
}
</code>```

package-lock.json

```<code>      "devDependencies": {
        "@fullhuman/postcss-purgecss": "^4.0.3",
        "@storybook/addon-actions": "^6.5.12",
        "@storybook/addon-essentials": "^6.5.12",
        "@storybook/addon-interactions": "^6.5.12",
        "@storybook/addon-links": "^6.5.12",
        "@storybook/builder-webpack5": "^6.5.12",
        "@storybook/manager-webpack5": "^6.5.12",
        "@storybook/node-logger": "^6.5.12",
        "@storybook/preset-create-react-app": "^4.1.2",
        "@storybook/react": "^6.5.12",
        "@storybook/testing-library": "^0.0.13",
</code>```

storybook show my Custom component

Body:
I use @stroybook/react.
npm run storybook
storybook cannnot find module.
only custom component not working.

use material-ui theme, react, typescript component
custom component is not class component
help!
difficult english!!

main.js

module.exports = {
  stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
  addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/addon-interactions",
    "@storybook/preset-create-react-app",
  ],
  framework: "@storybook/react",
  core: {
    builder: "@storybook/builder-webpack5",
  },
};

preview.js

import "../src/index.css";

export const parameters = {
  actions: { argTypesRegex: "^on[A-Z].*" },
  controls: {
    expanded: true,
    matchers: {
      color: /(background|color)$/i,
      date: /Date$/,
    },
  },
};

theme.ts

export const theme = {
  max_wrap: { maxWidth: 1920 },

  max_content: { maxWidth: 1272 },
  max_content_lg: { maxWidth: 940 },
  max_content_md: { maxWidth: 932 },

  max_section_lg: { maxWidth: 872 },

  base_container: {
    maxWidth: 1272 + 40,
    padding: "40px 20px 72px",

  },
  base_container_lg: {
    maxWidth: 940 + 40,
  },

  base_container_md: {
    maxWidth: 932 + 40,
    padding: "32px 20px 72px",

  },
...
}

package-lock.json

      "devDependencies": {
        "@fullhuman/postcss-purgecss": "^4.0.3",
        "@storybook/addon-actions": "^6.5.12",
        "@storybook/addon-essentials": "^6.5.12",
        "@storybook/addon-interactions": "^6.5.12",
        "@storybook/addon-links": "^6.5.12",
        "@storybook/builder-webpack5": "^6.5.12",
        "@storybook/manager-webpack5": "^6.5.12",
        "@storybook/node-logger": "^6.5.12",
        "@storybook/preset-create-react-app": "^4.1.2",
        "@storybook/react": "^6.5.12",
        "@storybook/testing-library": "^0.0.13",

storybook show my Custom component


问:
how to assemble a sql query to return the following data?
i have the following schema of database in prisma and mysql:

```<code>
model User {
id      Int   @default(autoincrement()) @id
name    String
email   String @unique
password String
massiva Massive[]
city_alert City_alert[]
status String @default("Normal")
department Departments @relation(fields: [department_id], references: [id])
department_id Int
user_in_city User_in_city[]
user_in_work User_in_work[]
historic_pausa Historic_pause[]
client_massive Client_massive[]
coffee Coffee[]
services  Services[] @relation("suport")
services_user Services[] @relation("user")
created_at DateTime @default(now())
updated_at DateTime @updatedAt
}

model Services {
  id      Int   @default(autoincrement()) @id
  protocol String
  incident incidentType @relation( fields: [incident_id], references: [id])
  incident_id Int
  status String
  suport User @relation(name: "suport", fields: [suport_id], references: [id])
  suport_id Int
  user User @relation(name: "user", fields: [user_id], references: [id])
  user_id Int
  created_at DateTime @default(now())
  updated_at DateTime @updatedAt
}

model incidentType  {
  id      Int   @default(autoincrement()) @id
  name String
  value Int
  services Services[]
  created_at DateTime @default(now())
  updated_at DateTime @updatedAt
}

</code>```

but I need to get the following data:

```<code>[
[user,
quantities_of_services_per_incientType_1,
quantities_of_services_per_incientType_1,
quantities_of_services_per_incientType_1
],
[user2,
quantities_of_services_per_incientType_1,
quantities_of_services_per_incientType_1,
quantities_of_services_per_incientType_1
]]

exemple:
[
[jhon, 0,4,3,5],
[Maria, 0,3,4,3],
]

</code>```

I have a user table and each user has several services, each service belonging to an incent, I need to bring the amount of service for each user per incident, even if a user does not have services for a given incident

how do i do this with raw sql or with prisma query?

Body:
i have the following schema of database in prisma and mysql:

model User {
id      Int   @default(autoincrement()) @id
name    String
email   String @unique
password String
massiva Massive[]
city_alert City_alert[]
status String @default("Normal")
department Departments @relation(fields: [department_id], references: [id])
department_id Int
user_in_city User_in_city[]
user_in_work User_in_work[]
historic_pausa Historic_pause[]
client_massive Client_massive[]
coffee Coffee[]
services  Services[] @relation("suport")
services_user Services[] @relation("user")
created_at DateTime @default(now())
updated_at DateTime @updatedAt
}

model Services {
  id      Int   @default(autoincrement()) @id
  protocol String
  incident incidentType @relation( fields: [incident_id], references: [id])
  incident_id Int
  status String
  suport User @relation(name: "suport", fields: [suport_id], references: [id])
  suport_id Int
  user User @relation(name: "user", fields: [user_id], references: [id])
  user_id Int
  created_at DateTime @default(now())
  updated_at DateTime @updatedAt
}

model incidentType  {
  id      Int   @default(autoincrement()) @id
  name String
  value Int
  services Services[]
  created_at DateTime @default(now())
  updated_at DateTime @updatedAt
}

but I need to get the following data:

[
[user,
quantities_of_services_per_incientType_1,
quantities_of_services_per_incientType_1,
quantities_of_services_per_incientType_1
],
[user2,
quantities_of_services_per_incientType_1,
quantities_of_services_per_incientType_1,
quantities_of_services_per_incientType_1
]]

exemple:
[
[jhon, 0,4,3,5],
[Maria, 0,3,4,3],
]

I have a user table and each user has several services, each service belonging to an incent, I need to bring the amount of service for each user per incident, even if a user does not have services for a given incident

how do i do this with raw sql or with prisma query?


问:
IQueryable<string> orderby is not working in ASP.NET
I am trying to sort an IQueryable<String> and bind to a selectList.

Issue: my code is able to pull list of all FirstName from the database, but it's not sorting. It seem like Distinct() function is removing OrderBy. How can I keep both?

```<code><select asp-for="FirstName" asp-items="@Model.Firstname_SELECT">
</select>

public SelectList? Firstname_SELECT { get; set; }

IQueryable<string> Query = (from m in _context.My_DbSet
                            where !string.IsNullOrEmpty(m.FirstName)
                            orderby m.FirstName
                            select m.FirstName).Distinct();
Firstname_SELECT = new SelectList(await Query.ToListAsync());
</code>```

I also tried this but getting an error

string doesn't contain ref of m.FirstName

```<code>IQueryable<string> Query = (from m in _context.My_DbSet
                            where !string.IsNullOrEmpty(m.FirstName )
                            orderby m.FirstName
                            select m.FirstName).Distinct().OrderBy(m => m.FirstName);
</code>```

Body:
I am trying to sort an IQueryable<String> and bind to a selectList.

Issue: my code is able to pull list of all FirstName from the database, but it's not sorting. It seem like Distinct() function is removing OrderBy. How can I keep both?

<select asp-for="FirstName" asp-items="@Model.Firstname_SELECT">
</select>

public SelectList? Firstname_SELECT { get; set; }

IQueryable<string> Query = (from m in _context.My_DbSet
                            where !string.IsNullOrEmpty(m.FirstName)
                            orderby m.FirstName
                            select m.FirstName).Distinct();
Firstname_SELECT = new SelectList(await Query.ToListAsync());

I also tried this but getting an error

string doesn't contain ref of m.FirstName

IQueryable<string> Query = (from m in _context.My_DbSet
                            where !string.IsNullOrEmpty(m.FirstName )
                            orderby m.FirstName
                            select m.FirstName).Distinct().OrderBy(m => m.FirstName);