问:
Customizing YAxis in Oracle Apex Chart
I have the following situation in Apex (v22.11): I have a chart with the type 'Combination'; so the series are one line chart and 4 bar charts. The format of the y axis is 'Percent' (so the numbers are <= 1). The line chart has a fixed value (85% or .85) and the bar charts have variable (percent) numbers.
I have the following problem: I can't customize the y axis of this chart and I can't explain why.

The best solution for me in this case is, when the chart show the fixed value on this y axis on one side and on the other side the y axis customize the steps automatically. Because I am a beginner in JavaScript I could not make it happen.

Because I am a beginner, I tried the following under Attributes -> Advanced -> JavaScript Initialization Code:

```<code>function(options){
   options.yAxis.step = .05;
   return options;
}
</code>```

Among other things, it should display the number 85%, but he only displays the numbers 0%, 10%, 20%, 30%, and so on. When I change the step to '= .5' (for example) then it works and Apex customize it. And I don't know why?? I searched on the attributes of oj-chart but I don't find another possiblities to change the Y Axis.

This point is also important:
On this line chart (Series) I can not activate the label 'Show' because my SQL Query is something like this:

```<code>SELECT DISTINCT CLASSROOM,
--Calculation for Bar1
--Calculation for Bar2
--Calculation for Bar3
--Calculation for Bar4
.85 AS Target
FROM EMP_SAMPLE
GROUP BY (CLASSROOM)
</code>```

And when I activate this, the percent number of this line will be shown three or four times on the chart depending on how much classroom (for the x axis) you have in the database. And I need the value only one time for this line.

Of course another solution could be the following: I write the percent number on or left-side or right-side or under this line with JavaScript (but of course only one time), but here I have the same problem as a beginner and I don't know how. (Or is it possible to customize it with HTML and CSS?)

Can anyone help me? Thanks in advance.

Title: Customizing YAxis in Oracle Apex Chart

Body:
I have the following situation in Apex (v22.11): I have a chart with the type 'Combination'; so the series are one line chart and 4 bar charts. The format of the y axis is 'Percent' (so the numbers are <= 1). The line chart has a fixed value (85% or .85) and the bar charts have variable (percent) numbers.
I have the following problem: I can't customize the y axis of this chart and I can't explain why.

The best solution for me in this case is, when the chart show the fixed value on this y axis on one side and on the other side the y axis customize the steps automatically. Because I am a beginner in JavaScript I could not make it happen.

Because I am a beginner, I tried the following under Attributes -> Advanced -> JavaScript Initialization Code:

function(options){
   options.yAxis.step = .05;
   return options;
}

Among other things, it should display the number 85%, but he only displays the numbers 0%, 10%, 20%, 30%, and so on. When I change the step to '= .5' (for example) then it works and Apex customize it. And I don't know why?? I searched on the attributes of oj-chart but I don't find another possiblities to change the Y Axis.

This point is also important:
On this line chart (Series) I can not activate the label 'Show' because my SQL Query is something like this:

SELECT DISTINCT CLASSROOM,
--Calculation for Bar1
--Calculation for Bar2
--Calculation for Bar3
--Calculation for Bar4
.85 AS Target
FROM EMP_SAMPLE
GROUP BY (CLASSROOM)

And when I activate this, the percent number of this line will be shown three or four times on the chart depending on how much classroom (for the x axis) you have in the database. And I need the value only one time for this line.

Of course another solution could be the following: I write the percent number on or left-side or right-side or under this line with JavaScript (but of course only one time), but here I have the same problem as a beginner and I don't know how. (Or is it possible to customize it with HTML and CSS?)

Can anyone help me? Thanks in advance.


来源: stackexchange

问:
Jest test that simulates throwing an Axios exception fails with empty error message
I am trying to write a Jest test to cover a scenario whereby an axios.post (in the code I am trying to test) throws and handles an exception. The test successfully throws an error for a mocked axios instance and the appropriate catch block in the code I am wishing to test is reached. However, the error/exception message is empty. This then causes some assertions that I am trying to do in the test to fail.

The relevant section of the code to test looks as follows:

```<code>try {
  // Call the token endpoint with the client/user credentials and check the response.
  const { status, data } = axios.post(authenticationConfig.tokenEndpoint,
   'grant_type=client_credentials', { headers });

  if (status === StatusCodes.OK) {
    ...
  }
}
catch(err) {
  console.log(JSON.stringify(err));
  res.status(StatusCodes.UNAUTHORIZED);
  res.json(err.response.data.error);
}
</code>```

The corresponding test looks like:

```<code>it('cannot get access token', async () => {
  const response = {
    response: {
      data: {
        error: 'My error'
      }
    }
  };

  const req = {
    headers: {
      'authorization': 'Basic client_id:client_secret'
    }
  };

  mockedAxios.mockImplementation(() => {
    throw new Error(response);
  });

  const provide = await authenticationMiddleware.provide(req, res, next);
  await provide(req, res, next);
  expect(mockedAxios).toBeCalledTimes(1);
  expect(res.status).toHaveBeenCalledTimes(1);
  expect(res.status).toHaveBeenCalledWith(StatusCodes.UNAUTHORIZED);
});
</code>```

The err object in the catch block is logged out as an empty object even though from the test I'm throwing an error with a fully populated object. The test passes if I remove the 'res.json' statement from the catch block.

```<code>● authentication middleware › cannot get access token

    TypeError: Cannot read property 'data' of undefined

      89 |         console.log(JSON.stringify(err));
      90 |         res.status(StatusCodes.UNAUTHORIZED);
    > 91 |         res.json(err.response.data.error);
</code>```

Any ideas most welcome please. No doubt the way that I'm mocking Axios and causing it to throw an exception is wrong. The code does enter the catch block but the 'err' object is empty for some reason.

Many thanks.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write a Jest test to cover a scenario whereby an axios.post (in the code I am trying to test) throws and handles an exception. The test successfully throws an error for a mocked axios instance and the appropriate catch block in the code I am wishing to test is reached. However, the error/exception message is empty. This then causes some assertions that I am trying to do in the test to fail.

The relevant section of the code to test looks as follows:

try {
  // Call the token endpoint with the client/user credentials and check the response.
  const { status, data } = axios.post(authenticationConfig.tokenEndpoint,
   'grant_type=client_credentials', { headers });

  if (status === StatusCodes.OK) {
    ...
  }
}
catch(err) {
  console.log(JSON.stringify(err));
  res.status(StatusCodes.UNAUTHORIZED);
  res.json(err.response.data.error);
}

The corresponding test looks like:

it('cannot get access token', async () => {
  const response = {
    response: {
      data: {
        error: 'My error'
      }
    }
  };

  const req = {
    headers: {
      'authorization': 'Basic client_id:client_secret'
    }
  };

  mockedAxios.mockImplementation(() => {
    throw new Error(response);
  });

  const provide = await authenticationMiddleware.provide(req, res, next);
  await provide(req, res, next);
  expect(mockedAxios).toBeCalledTimes(1);
  expect(res.status).toHaveBeenCalledTimes(1);
  expect(res.status).toHaveBeenCalledWith(StatusCodes.UNAUTHORIZED);
});

The err object in the catch block is logged out as an empty object even though from the test I'm throwing an error with a fully populated object. The test passes if I remove the 'res.json' statement from the catch block.

● authentication middleware › cannot get access token

    TypeError: Cannot read property 'data' of undefined

      89 |         console.log(JSON.stringify(err));
      90 |         res.status(StatusCodes.UNAUTHORIZED);
    > 91 |         res.json(err.response.data.error);

Any ideas most welcome please. No doubt the way that I'm mocking Axios and causing it to throw an exception is wrong. The code does enter the catch block but the 'err' object is empty for some reason.

Many thanks.


问:
how to create pivot table using apache POI API
so below is the data for which pivot table is created already by a non technical person now she is asking me to automate that means she already have the data but with some java code lets say Apache POI API the pivot table should get automatically created
any ideas or suggestion how to automatically create Pivot table

below are the 3 columns for which pivot table needs to be created

enter image description here

below is pivot table format for which sheet should look alike

enter image description here


问:
FLUTTER BLOC - Infinite List and Filter features
I am learning Bloc state management in Flutter and trying to apply infinite list and filter functions on a screen. However, it seems complicated to me. Do you have any idea how I should handle them?

API Endpoint for getting records:

```<code>POST http://example.com/api/recruitment_requests/filter?limit={number}&page={number}
</code>```

body:

```<code>{
    "filterBody": [],
    "searchString": "",
    "startDate": "",
    "endDate": ""
}
</code>```

Infinite List:

https://bloclibrary.dev/#/flutterinfinitelisttutorial

Body:
I am learning Bloc state management in Flutter and trying to apply infinite list and filter functions on a screen. However, it seems complicated to me. Do you have any idea how I should handle them?

API Endpoint for getting records:

POST http://example.com/api/recruitment_requests/filter?limit={number}&page={number}

body:

{
    "filterBody": [],
    "searchString": "",
    "startDate": "",
    "endDate": ""
}

Infinite List:

https://bloclibrary.dev/#/flutterinfinitelisttutorial


问:
How to get items from a People Picker Feld to my SharePoint List with SPFx/React?
I'm working on a SharePoint Webpart and I use the People Picker Field, to get the names of people to my List. People Picker works fine, i get the name, I can push all my items to my List, except the items from People Picker field. When i enter some name, I get the name on the console in Chrome/EDGE/Firefox, but the Array stays 0. And here ist my #1 problem: [[Prototype]]: Array(0)

Here is my code

```<code>import { PeoplePicker } from "@pnp/spfx-controls-react/lib/PeoplePicker"

export default class Test extends React.Component<
ITestProps,
IPeoplePickerState,

{}
> {

 constructor(props: ITestProps, state: IPeoplePickerState){
    super(props);
    this.addListItem = this.addListItem.bind(this);
    this.getPeoplePicker = this.getPeoplePicker.bind(this);
    this.state = { user:[] };
 }

public render(): React.ReactElement<ITestProps> {
    return (
      <section>
          <div>
            <PeoplePicker context={this.props.context} data-automation-id="addSelectedUsers" placeholder=" Name:" personSelectionLimit={3} ensureUser={true} onChange={this. getPeoplePicker}></PeoplePicker><br></br>
          </div>
        <div>
          <DefaultButton className={styles.btn1} id='btn' onClick={this.addListItem} > Eintragen </DefaultButton>
       </div>
      </section>
    );
  }

 public getPeoplePicker(items: any[]){
    console.log('Items:', items);

    let selectedUsers: any[] = [];
    items.map((item) => {
      selectedUsers.push(item.id);
    });
     this.setState({user: selectedUsers});

    this.setState({user: selectedUsers});

}

public addListItem(): void {
  pnp.sp.web.lists.getByTitle("Test123")
  .items.add({
    'Person': { results: this.state.user },
  })
  .then(i => console.log(i))
  .then(()=> alert("Vielen Dank!"));
}
}
</code>```

I tried 2 solutions for "getPeoplePicker()", but no one works right.

```<code>public getPeoplePicker(items: any[]){
    console.log('Items:', items);

    let selectedUsers: any[] = [];
    items.map((item) => {
      selectedUsers.push(item.id);
    });
     this.setState({user: selectedUsers});

  }
</code>```

and

```<code>public getPeoplePicker(items: any[]){
    console.log('Items:', items);

    let selectedUsers = [];
    for(let item in items){
       selectedUsers.push(items[item].id);
    }
    this.setState({user: selectedUsers});

  }
</code>```

I get always the same alert.

Body:
I'm working on a SharePoint Webpart and I use the People Picker Field, to get the names of people to my List. People Picker works fine, i get the name, I can push all my items to my List, except the items from People Picker field. When i enter some name, I get the name on the console in Chrome/EDGE/Firefox, but the Array stays 0. And here ist my #1 problem: [[Prototype]]: Array(0)

Here is my code

import { PeoplePicker } from "@pnp/spfx-controls-react/lib/PeoplePicker"

export default class Test extends React.Component<
ITestProps,
IPeoplePickerState,

{}
> {

 constructor(props: ITestProps, state: IPeoplePickerState){
    super(props);
    this.addListItem = this.addListItem.bind(this);
    this.getPeoplePicker = this.getPeoplePicker.bind(this);
    this.state = { user:[] };
 }

public render(): React.ReactElement<ITestProps> {
    return (

            <PeoplePicker context={this.props.context} data-automation-id="addSelectedUsers" placeholder=" Name:" personSelectionLimit={3} ensureUser={true} onChange={this. getPeoplePicker}></PeoplePicker>

          <DefaultButton className={styles.btn1} id='btn' onClick={this.addListItem} > Eintragen </DefaultButton>

    );
  }

 public getPeoplePicker(items: any[]){
    console.log('Items:', items);

    let selectedUsers: any[] = [];
    items.map((item) => {
      selectedUsers.push(item.id);
    });
     this.setState({user: selectedUsers});

    this.setState({user: selectedUsers});

}

public addListItem(): void {
  pnp.sp.web.lists.getByTitle("Test123")
  .items.add({
    'Person': { results: this.state.user },
  })
  .then(i => console.log(i))
  .then(()=> alert("Vielen Dank!"));
}
}

I tried 2 solutions for "getPeoplePicker()", but no one works right.

public getPeoplePicker(items: any[]){
    console.log('Items:', items);

    let selectedUsers: any[] = [];
    items.map((item) => {
      selectedUsers.push(item.id);
    });
     this.setState({user: selectedUsers});

  }

and

public getPeoplePicker(items: any[]){
    console.log('Items:', items);

    let selectedUsers = [];
    for(let item in items){
       selectedUsers.push(items[item].id);
    }
    this.setState({user: selectedUsers});

  }

I get always the same alert.


问:
How to insert dynamically *multiple* input fields in a row to mysql using java
I have an exact/similar problem with: How to insert dynamically created field values to MySQL db using Java/JDBC? on How to insert dynamically created field values to MySQL db using Java/JDBC?

There's one answer that solved the problem above, but instead of one dynamically created field values (multiple phone numbers) I have to insert multiple dynamic field values in a row for example (size, price, stocks)
Image of multiple input fields

Solution that I found: https://stackoverflow.com/a/66691466/20958522

Here is the code following the guide from the solution:

Aside from inserting multiple fields value from quantity, I also need to insert multiple weight, rate, and price into MySQL. What can I do to modify the code to be able to insert multiple input fields in a row to the database?

/Insert servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        String shoe_name= request.getParameter("shoe_name");
        String[] quantity = request.getParameterValues("quantity");

        List<String> qty = new ArrayList<>();
        if (quantity != null) {
          qty = Arrays.asList(quantity);
        }

        String weight = request.getParameter("weight");
        String rate= request.getParameter("rate");
        String price = request.getParameter("price");
        String status = "2";

        User newUser = new User(shoe_name, qty, weight, rate, price, status);

        userDAO.insertUser(newUser);
        response.sendRedirect("List");
        System.out.println("Added Successfully");
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
```
<p><strong>userDAO.java code</strong>
(insert to database)</p>
```
//INSERT ITEMS
public void insertUser(User user) throws SQLException, FileNotFoundException {
    List<String> quantity = user.getQuantity();
    PreparedStatement preparedStatement = null;

    if (quantity != null && !quantity.isEmpty()) {

    try (Connection connection = getConnection()){
     preparedStatement = connection.prepareStatement(INSERT_USERS_SQL);

     for (String qty : quantity) {

        preparedStatement.setString(1, user.getShoe_name());
  //    preparedStatement.setString(2, user.getQuantity());

        preparedStatement.setString(2, qty);
        preparedStatement.setString(3, user.getWeight());
        preparedStatement.setString(4, user.getRate());
        preparedStatement.setString(5, user.getPrice());
        preparedStatement.setString(6, user.getStatus());
        preparedStatement.addBatch(); //remove

     }

     System.out.println(preparedStatement);
//     preparedStatement.executeUpdate();
     preparedStatement.executeBatch();

    } catch (SQLException e) {
        printSQLException(e);
    }catch(Exception ex) {
        ex.printStackTrace();
    }
   }
}
```
<p><strong>user.java</strong></p>
```public class User {

    private int product_id;
    private String shoe_name;
    private List<String> quantity = new ArrayList<>();
    private String qty;
    private String weight;
    private String rate;
    private String price;
    private String status = "2";

    public User(String shoe_name, List<String> quantity, String weight, String rate, String price, String status) {
        super();
        this.shoe_name = shoe_name;
        this.quantity = quantity;
        this.weight = weight;
        this.rate = rate;
        this.price = price;
        this.status = status;

    }

    public void addQty(String quantity) {
        if (this.quantity == null) {
          this.quantity = new ArrayList<>();
        }

        this.quantity.add(quantity);
      }

/*
* SETTERS AND GETTERS */
```

Body:
I have an exact/similar problem with: How to insert dynamically created field values to MySQL db using Java/JDBC? on How to insert dynamically created field values to MySQL db using Java/JDBC?

There's one answer that solved the problem above, but instead of one dynamically created field values (multiple phone numbers) I have to insert multiple dynamic field values in a row for example (size, price, stocks)
Image of multiple input fields

Solution that I found: https://stackoverflow.com/a/66691466/20958522

Here is the code following the guide from the solution:

Aside from inserting multiple fields value from quantity, I also need to insert multiple weight, rate, and price into MySQL. What can I do to modify the code to be able to insert multiple input fields in a row to the database?

/Insert servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        String shoe_name= request.getParameter("shoe_name");
        String[] quantity = request.getParameterValues("quantity");

        List<String> qty = new ArrayList<>();
        if (quantity != null) {
          qty = Arrays.asList(quantity);
        }

        String weight = request.getParameter("weight");
        String rate= request.getParameter("rate");
        String price = request.getParameter("price");
        String status = "2";

        User newUser = new User(shoe_name, qty, weight, rate, price, status);

        userDAO.insertUser(newUser);
        response.sendRedirect("List");
        System.out.println("Added Successfully");
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

userDAO.java code
(insert to database)

//INSERT ITEMS
public void insertUser(User user) throws SQLException, FileNotFoundException {
    List<String> quantity = user.getQuantity();
    PreparedStatement preparedStatement = null;

    if (quantity != null && !quantity.isEmpty()) {

    try (Connection connection = getConnection()){
     preparedStatement = connection.prepareStatement(INSERT_USERS_SQL);

     for (String qty : quantity) {

        preparedStatement.setString(1, user.getShoe_name());
  //    preparedStatement.setString(2, user.getQuantity());

        preparedStatement.setString(2, qty);
        preparedStatement.setString(3, user.getWeight());
        preparedStatement.setString(4, user.getRate());
        preparedStatement.setString(5, user.getPrice());
        preparedStatement.setString(6, user.getStatus());
        preparedStatement.addBatch(); //remove

     }

     System.out.println(preparedStatement);
//     preparedStatement.executeUpdate();
     preparedStatement.executeBatch();

    } catch (SQLException e) {
        printSQLException(e);
    }catch(Exception ex) {
        ex.printStackTrace();
    }
   }
}

user.java

public class User {

    private int product_id;
    private String shoe_name;
    private List<String> quantity = new ArrayList<>();
    private String qty;
    private String weight;
    private String rate;
    private String price;
    private String status = "2";

    public User(String shoe_name, List<String> quantity, String weight, String rate, String price, String status) {
        super();
        this.shoe_name = shoe_name;
        this.quantity = quantity;
        this.weight = weight;
        this.rate = rate;
        this.price = price;
        this.status = status;

    }

    public void addQty(String quantity) {
        if (this.quantity == null) {
          this.quantity = new ArrayList<>();
        }

        this.quantity.add(quantity);
      }

/*
* SETTERS AND GETTERS */


问:
Using Scrapy itemloaders and XPath/CSS selector to extract data
I'm using the Scrapy framework to crawl and scrape data from a url and I'm not sure whether it's better to extract the value attribute from a progress bar using CSS selectors or to extract the text data from a nested div & span tag using XPath.
This is the URL

This is the HTML code

```<code><div class="grid-x grid-margin-x">
    <div class="cell small-1 medium-1 large-1">
        <span class="vote-button-legend">12</span>
    </div>
    <div class="cell small-6 medium-6 large-6" style="display: inline-flex; align-items: center; justify-content: center;">
        <progress class="alert" max="297" value="12" style="color: crimson; cursor: pointer;"></progress>
    </div>
</div>
</code>```

Using the inspector I can verify with XPath selectors that I'm able to retrieve the text data:

```<code>$x('//div[@class="cell small-1 medium-1 large-1"]/span[@class="vote-button-legend"]/text()')
</code>```

I can also use CSS Selectors to find the div class for the progress bar before extracting the value attribute

```<code>$('div progress.alert ')
</code>```

From here I tried to use ItemLoaders to populate Items in Scrapy using the add_xpath and add_css methods:

```<code>l = ItemLoader(item=PropertiesItem(), response=response)

l.add_xpath('votes', '//div[@class="cell small-1 medium-1 large-1"]/span[@class="vote-button-legend"]/text()')

l.add_css('votes', 'div.cell.small-1.medium-1.large-1 span.vote-button-legend ::attr[value]')
</code>```

When running my spider to check for the resulting items it doesn't appear in the console and when  I try to see if the output appears using a log it returns an empty list:

```<code>self.log("voteCount: %s" % response.css('div.cell.small-1.medium-1.large-1 span.vote-button-legend ::attr[value]').extract())

self.log("value: %s" % response.xpath('//div[@class="cell small-1 medium-1 large-1"]/span[@class="vote-button-legend"]/text()').extract())
</code>```

Any help would be greatly appreciated

Body:
I'm using the Scrapy framework to crawl and scrape data from a url and I'm not sure whether it's better to extract the value attribute from a progress bar using CSS selectors or to extract the text data from a nested div & span tag using XPath.
This is the URL

This is the HTML code

        12

        <progress class="alert" max="297" value="12" style="color: crimson; cursor: pointer;"></progress>

Using the inspector I can verify with XPath selectors that I'm able to retrieve the text data:

$x('//div[@class="cell small-1 medium-1 large-1"]/span[@class="vote-button-legend"]/text()')

I can also use CSS Selectors to find the div class for the progress bar before extracting the value attribute

$('div progress.alert ')

From here I tried to use ItemLoaders to populate Items in Scrapy using the add_xpath and add_css methods:

l = ItemLoader(item=PropertiesItem(), response=response)

l.add_xpath('votes', '//div[@class="cell small-1 medium-1 large-1"]/span[@class="vote-button-legend"]/text()')

l.add_css('votes', 'div.cell.small-1.medium-1.large-1 span.vote-button-legend ::attr[value]')

When running my spider to check for the resulting items it doesn't appear in the console and when  I try to see if the output appears using a log it returns an empty list:

self.log("voteCount: %s" % response.css('div.cell.small-1.medium-1.large-1 span.vote-button-legend ::attr[value]').extract())

self.log("value: %s" % response.xpath('//div[@class="cell small-1 medium-1 large-1"]/span[@class="vote-button-legend"]/text()').extract())

Any help would be greatly appreciated


问:
ZEOSLib: Error Message from TZReadOnlyQuery
I have been using ZeosLib Components with Delphi and Lazarus for the past 10 years or so. I'm mostly using it to access MySQL Databases.
Now I have run into a strange Problem with TZReadOnlyQuery.

In my MariaDB database I have a pretty complex stored procedure that takes some input parameters, one inout param and one out param. Because of the error I get, when I try to call it with TZReadOnlyQuery, I have made a very simple procedure to test it.

This is my test procedure:

```<code>CREATE PROCEDURE MyProc(INOUT a VARCHAR(255), OUT r VARCHAR(255))
BEGIN
  set a = 'inparam changed';
  set r = 'outparam set';
END

</code>```

I tried to call this procedure from different MySQL query/managment tools with this statement:

```<code>set @x = 'inputparam';
call MyProc(@x, @y);
select @x, @y;
</code>```

I get the expected answer: a dataset with one record and two fields like this:

But when I add the same query statement to a TZReadOnlyQuery and try to open it I get an error message:

Any ideas why this happens and how to work around it?

Thanks!

Body:
I have been using ZeosLib Components with Delphi and Lazarus for the past 10 years or so. I'm mostly using it to access MySQL Databases.
Now I have run into a strange Problem with TZReadOnlyQuery.

In my MariaDB database I have a pretty complex stored procedure that takes some input parameters, one inout param and one out param. Because of the error I get, when I try to call it with TZReadOnlyQuery, I have made a very simple procedure to test it.

This is my test procedure:

CREATE PROCEDURE MyProc(INOUT a VARCHAR(255), OUT r VARCHAR(255))
BEGIN
  set a = 'inparam changed';
  set r = 'outparam set';
END

I tried to call this procedure from different MySQL query/managment tools with this statement:

set @x = 'inputparam';
call MyProc(@x, @y);
select @x, @y;

I get the expected answer: a dataset with one record and two fields like this:

But when I add the same query statement to a TZReadOnlyQuery and try to open it I get an error message:

Any ideas why this happens and how to work around it?

Thanks!


问:
Toggling through days to select with puppeteer
I've been playing around with puppeteer for some time now and can't seem to work out the best approach.

My goal is to be able to select one of the days which once automatically clicked loads different data which I will then extract.

I'm having a hard time trying to work out the best way to navigate between the days with puppeteer.

I want to have the ability to input the day I want to select and when launching the page it will navigate to that selected day.

I did have more code written in, however stripped it back.

async function scrapeData(page) {
  await page.goto(newPageURL);

  // Select the day you want to go to.
  let spanDay = await page.$(".MuiTab-wrapper");

  await page.$eval(".MuiTab-wrapper", (el) =>
    el.forEach((element) => {
      console.log(element);
    })
  );
}```


问:
Google Speech-to-text API
I want to use the Speech-to-text API for an application made in nocode.

I get this error message:

There was a problem setting up your call.

Raw response for API
401 status code
{
"Mistake": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie, or other valid authentication credentials. See https://developers.google.com/identity/sign- in/web/devconsole-project.",
"status": "NOT AUTHENTICATED"

Thanks in advance

I may be able to transcribe an audio file to text.

Title: Google Speech-to-text API


问:
How to pass value into Hubspot form field based on id
Below is my component:

```<code>import React from "react";
import ContentMetaTags from "../components/ContentMetaTags";
import { parseToReact} from "../utils/helpers";
import { useEffect } from "react";

export default function HubspotContactForm(formRender) {
  useEffect(() => {
    if (typeof window !== "undefined") {
    document.getElementById("firstname-3478d953-3c8d-4bea-8501-af6ab93cac87").value = "abc"  // here I am assigning value to firstname field based on hubspot id
    }
});

  return (
      <div>
        {parseToReact(formRender)}
      </div>
  );
}
export const Head = () => <ContentMetaTags title="Hubspot Form" />;
</code>```

and here is my Hubspot form case where I am calling above component:

```<code> case "hubspot_form":
              if (paragraphEntity.entityRendered) {
                returnElement = (
                  <HubspotContactForm
                    key={paragraphNewID + "-"}
                    formRender={paragraphEntity.entityRendered}

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

How can I pass value "abc" into firstname field?

Body:
Below is my component:

import React from "react";
import ContentMetaTags from "../components/ContentMetaTags";
import { parseToReact} from "../utils/helpers";
import { useEffect } from "react";

export default function HubspotContactForm(formRender) {
  useEffect(() => {
    if (typeof window !== "undefined") {
    document.getElementById("firstname-3478d953-3c8d-4bea-8501-af6ab93cac87").value = "abc"  // here I am assigning value to firstname field based on hubspot id
    }
});

  return (

        {parseToReact(formRender)}

  );
}
export const Head = () => <ContentMetaTags title="Hubspot Form" />;

and here is my Hubspot form case where I am calling above component:

 case "hubspot_form":
              if (paragraphEntity.entityRendered) {
                returnElement = (
                  <HubspotContactForm
                    key={paragraphNewID + "-"}
                    formRender={paragraphEntity.entityRendered}

                  />
                );
              }

How can I pass value "abc" into firstname field?


问:
.NET Core application running on fargate with memory issues
We are running a .NET application in fargate via terraform where we specify CPU and memory in the aws_ecs_task_definition resource.

The service has just 1 task e.g.

```<code> resource "aws_ecs_task_definition" "test" {
   ....
   cpu                      = 256
   memory                   = 512
   ....
</code>```

From the documentation this is required for Fargate.

You can also specify cpu and memory in the container_definitions, but the documentation states that the field is optional, and as we are already setting values at the task level we did not set them here.

We have observed that our memory was growing after the tasks started, depending on application, sometimes quite fast and others over a period of time.

So we starting thinking we had a memory leak and went to profile using the dotnet-monitor tool as a sidecar.

As part of introducing the sidecar we set cpu and memory values for our .NET application at the container_definitions level.

After we done this, we have observed that our memory in our applications is behaving much better.

From .NET monitor traces we are seeing that when we set memory at the container_definitions level:

Working Set is much smaller

Gen 0/1/2 GC Count is above 1(GC occurring early)

GC 0/1/2 Size is less

GC Committed Bytes is smaller

So to summarize when we do not set memory at container_definitions level, memory continues to grow and no GC occurring until we are almost running out of memory.

When we set memory at container_definitions level, GC occurring regularly and memory not spiking up.

So we have a solution, but do not understand why this is the case.
Would like to know why it is so

Body:
We are running a .NET application in fargate via terraform where we specify CPU and memory in the aws_ecs_task_definition resource.

The service has just 1 task e.g.

 resource "aws_ecs_task_definition" "test" {
   ....
   cpu                      = 256
   memory                   = 512
   ....

From the documentation this is required for Fargate.

You can also specify cpu and memory in the container_definitions, but the documentation states that the field is optional, and as we are already setting values at the task level we did not set them here.

We have observed that our memory was growing after the tasks started, depending on application, sometimes quite fast and others over a period of time.

So we starting thinking we had a memory leak and went to profile using the dotnet-monitor tool as a sidecar.

As part of introducing the sidecar we set cpu and memory values for our .NET application at the container_definitions level.

After we done this, we have observed that our memory in our applications is behaving much better.

From .NET monitor traces we are seeing that when we set memory at the container_definitions level:

Working Set is much smaller

Gen 0/1/2 GC Count is above 1(GC occurring early)

GC 0/1/2 Size is less

GC Committed Bytes is smaller

So to summarize when we do not set memory at container_definitions level, memory continues to grow and no GC occurring until we are almost running out of memory.

When we set memory at container_definitions level, GC occurring regularly and memory not spiking up.

So we have a solution, but do not understand why this is the case.
Would like to know why it is so


问:
Graph API : Live Event Attedence Report
I am trying to get attendence report of a live meeting through Graph API, but it is returning an empty array.I have used both Beta & V1.0. I am not sure what am missing.

I can download the excel file of attedence repot from teams

please help me out!

Title: Graph API : Live Event Attedence Report


问:
How to make native query for nested projection in Spring Data JPA
I need to write a native query for my projection with nested interfaces.

My TransactionView interface:

public interface TransactionView {

    Long getId();

    TransactionType getType();

    LocalDate getDate();

    AccountProjection getAcc1();

    AccountProjection getAcc2();

    interface AccountProjection {
        String getName();
        CurrencyName getCurrencyCode();
        BigDecimal getBalance();
    }

    BigDecimal getAmount();

    PartnerView getPartner();

    interface PartnerView {
        String getName();
    }

    String getComment();

    CategoryView getCategory();

    interface CategoryView {
        String getName();
    }
}
```
<p><code>JpaRepository</code>:</p>
<pre class="lang-java prettyprint-override"><code>public interface TransactionsRepository extends JpaRepository<Transaction, Long> {
  List<TransactionView> findByAcc1PersonIdOrderByDateDesc(int personId);
}
</code>```

This approach works good and I get JSON like this:

[{
 "id":34,
 "type":"TRANSFER",
 "comment":"test comment",
 "date":"2022-12-23",
 "amount":200.00,
 "acc2":
        {
         "name":"cash",
         "currencyCode":"USD",
         "balance":200.00
        },
 "acc1":
        {
         "name":"test acc",
         "currencyCode":"USD",
         "balance":700.00
         },
 "partner":null,
 "category":null
 },
 {
 "id":20,
 "type":"EXPENCE",
 "comment":"",
 "date":"2022-12-13",
 "amount":33.07,
 "acc2":null,
 "acc1":
       {
        "name":"cash",
        "currencyCode":"BYN",
        "balance":322.33
       },
 "partner":
       {
        "name":"bmw"
       },
 "category":
       {
        "name":"auto"
       }
}]
```
<p>But Hibernate generates a very complex query with a lot of extra columns fetching.</p>
<p>My native query returns null nested objects:</p>
<pre class="lang-java prettyprint-override"><code>@Query(value = "SELECT t.id AS id, " +
        "t.transaction_type AS type, " +
        "t.transaction_date AS date, " +
        "t.amount AS amount, " +
        "t.comment AS comment, " +
        "a1.balance AS acc1Balance, " +
        "a1.currency_code AS acc1CurrencyCode, " +
        "a1.name AS acc1Name, " +
        "a2.balance AS acc2Balance, " +
        "a2.currency_code AS acc2CurrencyCode, " +
        "a2.name AS acc2Name, " +
        "par.name AS partnerName, " +
        "cat.name AS categoryName, " +
        "cat.category_type AS categoryType " +
        "FROM transaction t " +
        "LEFT OUTER JOIN account a1 ON t.acc1_id=a1.id " +
        "LEFT OUTER JOIN person per ON a1.person_id=per.id " +
        "LEFT OUTER JOIN account a2 ON t.acc2_id=a2.id " +
        "LEFT OUTER JOIN partner par ON t.partner_id=par.id " +
        "LEFT OUTER JOIN category cat ON t.category_id=cat.id " +
        "WHERE per.id=?1 ORDER BY t.transaction_date DESC", nativeQuery = true)
    List<TransactionView> findByAcc1PersonIdOrderByDateDescTest(int personId);
</code>```

[{
 "id":34,
 "type":"TRANSFER",
 "comment":"test comment",
 "date":"2022-12-23",
 "amount":200.00,
 "acc2":null,
 "acc1":null,
 "partner":null,
 "category":null
 },
 {
 "id":20,
 "type":"EXPENCE",
 "comment":"",
 "date":"2022-12-13",
 "amount":33.07,
 "acc2":null,
 "acc1":null,
 "partner":null,
 "category":null
}]
```

Also I tried approach from Peter Gyschuk, but it doesn't work.

How can I solve it using native query?

Body:
I need to write a native query for my projection with nested interfaces.

My TransactionView interface:

public interface TransactionView {

    Long getId();

    TransactionType getType();

    LocalDate getDate();

    AccountProjection getAcc1();

    AccountProjection getAcc2();

    interface AccountProjection {
        String getName();
        CurrencyName getCurrencyCode();
        BigDecimal getBalance();
    }

    BigDecimal getAmount();

    PartnerView getPartner();

    interface PartnerView {
        String getName();
    }

    String getComment();

    CategoryView getCategory();

    interface CategoryView {
        String getName();
    }
}

JpaRepository:

public interface TransactionsRepository extends JpaRepository<Transaction, Long> {
  List<TransactionView> findByAcc1PersonIdOrderByDateDesc(int personId);
}

This approach works good and I get JSON like this:

[{
 "id":34,
 "type":"TRANSFER",
 "comment":"test comment",
 "date":"2022-12-23",
 "amount":200.00,
 "acc2":
        {
         "name":"cash",
         "currencyCode":"USD",
         "balance":200.00
        },
 "acc1":
        {
         "name":"test acc",
         "currencyCode":"USD",
         "balance":700.00
         },
 "partner":null,
 "category":null
 },
 {
 "id":20,
 "type":"EXPENCE",
 "comment":"",
 "date":"2022-12-13",
 "amount":33.07,
 "acc2":null,
 "acc1":
       {
        "name":"cash",
        "currencyCode":"BYN",
        "balance":322.33
       },
 "partner":
       {
        "name":"bmw"
       },
 "category":
       {
        "name":"auto"
       }
}]

But Hibernate generates a very complex query with a lot of extra columns fetching.

My native query returns null nested objects:

@Query(value = "SELECT t.id AS id, " +
        "t.transaction_type AS type, " +
        "t.transaction_date AS date, " +
        "t.amount AS amount, " +
        "t.comment AS comment, " +
        "a1.balance AS acc1Balance, " +
        "a1.currency_code AS acc1CurrencyCode, " +
        "a1.name AS acc1Name, " +
        "a2.balance AS acc2Balance, " +
        "a2.currency_code AS acc2CurrencyCode, " +
        "a2.name AS acc2Name, " +
        "par.name AS partnerName, " +
        "cat.name AS categoryName, " +
        "cat.category_type AS categoryType " +
        "FROM transaction t " +
        "LEFT OUTER JOIN account a1 ON t.acc1_id=a1.id " +
        "LEFT OUTER JOIN person per ON a1.person_id=per.id " +
        "LEFT OUTER JOIN account a2 ON t.acc2_id=a2.id " +
        "LEFT OUTER JOIN partner par ON t.partner_id=par.id " +
        "LEFT OUTER JOIN category cat ON t.category_id=cat.id " +
        "WHERE per.id=?1 ORDER BY t.transaction_date DESC", nativeQuery = true)
    List<TransactionView> findByAcc1PersonIdOrderByDateDescTest(int personId);

[{
 "id":34,
 "type":"TRANSFER",
 "comment":"test comment",
 "date":"2022-12-23",
 "amount":200.00,
 "acc2":null,
 "acc1":null,
 "partner":null,
 "category":null
 },
 {
 "id":20,
 "type":"EXPENCE",
 "comment":"",
 "date":"2022-12-13",
 "amount":33.07,
 "acc2":null,
 "acc1":null,
 "partner":null,
 "category":null
}]

Also I tried approach from Peter Gyschuk, but it doesn't work.

How can I solve it using native query?


问:
Error in connection establishment: net::ERR_CONNECTION_REFUSED
I am new to websockets. I tried to create a websocket with the following address ws://localhost:8000 in order to send data continuously from my python program to a js program which takes care of retrieving them and displaying them in boxes. At the beginning, when I put this address it did not work and show me the following error: Error in connection establishment: net::ERR_CONNECTION_REFUSED.

I had to put my IPV4 address instead of localhost for it to work. Except that I tried to restart my program with the previous address and it worked. I have absolutely no idea why I no longer have the error I had previously?

I also specify that all this is developed using electron.

Here is my python and js code :

Python :

```<code>import asyncio
import random
import datetime
import websockets
import json

async def handler(websocket, path):
    while True:
        data = [random.randint(0, 100) for _ in range(10)]
        await websocket.send(json.dumps(data))
        await asyncio.sleep(1)

start_server = websockets.serve(handler, "localhost", 8000)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
</code>```

JS :

```<code>import React, { useState, useEffect } from 'react';
import Home from './pages/home';

export default function App() {
  const [data, setData] = useState(null);

  useEffect(() => {
    const socket = new WebSocket('ws://localhost:8000');

    socket.addEventListener('message', (event) => {
      setData(JSON.parse(event.data));
    });
  }, []);

  return (
    <div>
      <div>
            <div class="home">
                <div class="template-1" id="temp1">
                <div class="panel-1">
                    <div class="panel-header">
                    <h1>Panel 1</h1>
                    <i class='bx bx-cog modal-trigger-panel'></i>
                    </div>
                    <div class="panel-body">
                    <div class="sec-5 modal-trigger-data" id="hs-sec-5">
                        {data ? <span class="h1" id="h1-fs-s5">{data[0]}</span> : <p>Loading...</p>}
                        <h2>TWIST</h2>
                        <h3>s5</h3>
                    </div>
                    <div class="sec-4 modal-trigger-data" id="hs-sec-4">
                        {data ? <span class="h1" id="h1-fs-s5">{data[1]}</span> : <p>Loading...</p>}
                        <h2>TWIST</h2>
                        <h3>s4</h3>
                    </div>
                    <div class="sec-3 modal-trigger-data" id="hs-sec-3">
                        {data ? <span class="h1" id="h1-fs-s5">{data[2]}</span> : <p>Loading...</p>}
                        <h2>TWIST</h2>
                        <h3>s3</h3>
                    </div>
                    <div class="sec-2 modal-trigger-data" id="hs-sec-2">
                        {data ? <span class="h1" id="h1-fs-s5">{data[3]}</span> : <p>Loading...</p>}
                        <h2>TWIST</h2>
                        <h3>s2</h3>
                    </div>
                    <div class="sec-1 modal-trigger-data" id="hs-sec-1">
                        {data ? <span class="h1" id="h1-fs-s5">{data[4]}</span> : <p>Loading...</p>}
                        <h2>TWIST</h2>
                        <h3>s1</h3>
                    </div>
                    </div>
                </div>
                </div>
            </div>
        </div>
    </div>
  );
}

</code>```

Regards,

Body:
I am new to websockets. I tried to create a websocket with the following address ws://localhost:8000 in order to send data continuously from my python program to a js program which takes care of retrieving them and displaying them in boxes. At the beginning, when I put this address it did not work and show me the following error: Error in connection establishment: net::ERR_CONNECTION_REFUSED.

I had to put my IPV4 address instead of localhost for it to work. Except that I tried to restart my program with the previous address and it worked. I have absolutely no idea why I no longer have the error I had previously?

I also specify that all this is developed using electron.

Here is my python and js code :

Python :

import asyncio
import random
import datetime
import websockets
import json

async def handler(websocket, path):
    while True:
        data = [random.randint(0, 100) for _ in range(10)]
        await websocket.send(json.dumps(data))
        await asyncio.sleep(1)

start_server = websockets.serve(handler, "localhost", 8000)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

JS :

import React, { useState, useEffect } from 'react';
import Home from './pages/home';

export default function App() {
  const [data, setData] = useState(null);

  useEffect(() => {
    const socket = new WebSocket('ws://localhost:8000');

    socket.addEventListener('message', (event) => {
      setData(JSON.parse(event.data));
    });
  }, []);

  return (

Panel 1

                        {data ? {data[0]} :
Loading...
}

TWIST

s5

                        {data ? {data[1]} :
Loading...
}

TWIST

s4

                        {data ? {data[2]} :
Loading...
}

TWIST

s3

                        {data ? {data[3]} :
Loading...
}

TWIST

s2

                        {data ? {data[4]} :
Loading...
}

TWIST

s1

  );
}

Regards,


问:
how to Open electron app from browser in both windows and mac
```<code>const { app, BrowserWindow, ipcMain, dialog, screen,Tray } = require('electron');

try {
  require('electron-reloader')(module)
} catch (_) { }

const path = require('path')
let deeplinkingUrl;
let mainWindow;

const createWindow = () => {
  let { width, height } = screen.getPrimaryDisplay().size

  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: width,
    height: height,
    minWidth: width,
    minHeight: height,
    productName: "abc",
    copyright: "Copyright © 2022 ${author}",
    // mac: {
    //   icon: "./img/abc_256x256px.ico"
    // },
    icon: __dirname + "/img/icon.ico",

    // icon: "./img/abc_256x256px.ico",
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      contextIsolation: false,
      devTools: false,
    }
  })
  mainWindow.setClosable(false);
  mainWindow.setMenuBarVisibility(false);
  mainWindow.maximize();
  mainWindow.setMovable(false);
  mainWindow.setResizable(false);

  if (process.platform == 'win32') {
    // Keep only command line / deep linked arguments
    deeplinkingUrl = process.argv.slice(1)

  }
  logEverywhere("createWindow# " + deeplinkingUrl)

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()

//tray

let tray = null;
mainWindow.on('minimize', function (event) {
  event.preventDefault();
  mainWindow.hide();
  tray = createTray();
});

mainWindow.on('restore', function (event) {
  mainWindow.maximize();
  mainWindow.show();
  tray.destroy();
});

function createTray() {
  let appIcon = new Tray(path.join(__dirname + "/img/icon.ico"));

  appIcon.on('click', function (event) {
      mainWindow.show();
  });
  appIcon.setToolTip('abc');
  return appIcon;
}
}

app.whenReady().then(() => {
  createWindow()
  if (isDev && process.platform === 'win32') {
    // Set the path of electron.exe and your app.
    // These two additional parameters are only available on windows.
    // Setting this is required to get this working in dev mode.
    app.setAsDefaultProtocolClient('pro', process.execPath, [
      resolve(process.argv[1])
    ]);
  } else {
    app.setAsDefaultProtocolClient('pro');
  }
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
  app.on('open-url', function (event, url) {
  event.preventDefault();
  deeplinkingUrl = url;})

})

const gotTheLock = app.requestSingleInstanceLock();

if (!gotTheLock) {
  app.quit();
  return;
} else {
  app.on('second-instance', (e, argv) => {
    if (process.platform !== 'darwin') {
      // Find the arg that is our custom protocol url and store it
      deeplinkingUrl = argv.find((arg) => arg.startsWith('custom://'));
    }

    if (myWindow) {
      if (myWindow.isMinimized()) myWindow.restore();
      myWindow.focus();
    }
  });
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

function logEverywhere(s) {
  console.log(s)
  if (mainWindow && mainWindow.webContents) {
    mainWindow.webContents.executeJavaScript(`console.log("${s}")`)
  }
}

//to allow self signed certificate
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
  // Verification logic.
  event.preventDefault()
  callback(true)

})

ipcMain.handle('download', async (someArgument) => {
  const result = await download(someArgument)
  return result;
})

const download = async (data) => {
  let value = 100;
  console.log(data.name)
  dialog.showSaveDialog({
    title: 'Select the File Path to save',
    defaultPath: path.join(__dirname, data.name + '.p12'),
    buttonLabel: 'Save',
    filters: [
      {
        name: 'Personal Information Exchnage',
        extensions: ['.p12']
      }
    ],
    properties: []
  }).then((path) => {
    value = 1;
    console.log('success')
    mainWindow.webContents.send('success', path);
  }).catch((value) => {
    value = 2;
    mainWindow.webContents.send('failed', path);
    console.log('error')
  });
  return value;
}
</code>```

This code throws some error when I type 'pro://something' in the browser.

Erorr description: Error launching app, unable to find Electron app at C:\Windows\system32\pro:\something

I have also tried some other code which opens my app but in a different window.

I want to open the App but in the existing window of my app.

Body:
const { app, BrowserWindow, ipcMain, dialog, screen,Tray } = require('electron');

try {
  require('electron-reloader')(module)
} catch (_) { }

const path = require('path')
let deeplinkingUrl;
let mainWindow;

const createWindow = () => {
  let { width, height } = screen.getPrimaryDisplay().size

  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: width,
    height: height,
    minWidth: width,
    minHeight: height,
    productName: "abc",
    copyright: "Copyright © 2022 ${author}",
    // mac: {
    //   icon: "./img/abc_256x256px.ico"
    // },
    icon: __dirname + "/img/icon.ico",

    // icon: "./img/abc_256x256px.ico",
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      contextIsolation: false,
      devTools: false,
    }
  })
  mainWindow.setClosable(false);
  mainWindow.setMenuBarVisibility(false);
  mainWindow.maximize();
  mainWindow.setMovable(false);
  mainWindow.setResizable(false);

  if (process.platform == 'win32') {
    // Keep only command line / deep linked arguments
    deeplinkingUrl = process.argv.slice(1)

  }
  logEverywhere("createWindow# " + deeplinkingUrl)

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()

//tray

let tray = null;
mainWindow.on('minimize', function (event) {
  event.preventDefault();
  mainWindow.hide();
  tray = createTray();
});

mainWindow.on('restore', function (event) {
  mainWindow.maximize();
  mainWindow.show();
  tray.destroy();
});

function createTray() {
  let appIcon = new Tray(path.join(__dirname + "/img/icon.ico"));

  appIcon.on('click', function (event) {
      mainWindow.show();
  });
  appIcon.setToolTip('abc');
  return appIcon;
}
}

app.whenReady().then(() => {
  createWindow()
  if (isDev && process.platform === 'win32') {
    // Set the path of electron.exe and your app.
    // These two additional parameters are only available on windows.
    // Setting this is required to get this working in dev mode.
    app.setAsDefaultProtocolClient('pro', process.execPath, [
      resolve(process.argv[1])
    ]);
  } else {
    app.setAsDefaultProtocolClient('pro');
  }
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
  app.on('open-url', function (event, url) {
  event.preventDefault();
  deeplinkingUrl = url;})

})

const gotTheLock = app.requestSingleInstanceLock();

if (!gotTheLock) {
  app.quit();
  return;
} else {
  app.on('second-instance', (e, argv) => {
    if (process.platform !== 'darwin') {
      // Find the arg that is our custom protocol url and store it
      deeplinkingUrl = argv.find((arg) => arg.startsWith('custom://'));
    }

    if (myWindow) {
      if (myWindow.isMinimized()) myWindow.restore();
      myWindow.focus();
    }
  });
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

function logEverywhere(s) {
  console.log(s)
  if (mainWindow && mainWindow.webContents) {
    mainWindow.webContents.executeJavaScript(`console.log("${s}")`)
  }
}

//to allow self signed certificate
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
  // Verification logic.
  event.preventDefault()
  callback(true)

})

ipcMain.handle('download', async (someArgument) => {
  const result = await download(someArgument)
  return result;
})

const download = async (data) => {
  let value = 100;
  console.log(data.name)
  dialog.showSaveDialog({
    title: 'Select the File Path to save',
    defaultPath: path.join(__dirname, data.name + '.p12'),
    buttonLabel: 'Save',
    filters: [
      {
        name: 'Personal Information Exchnage',
        extensions: ['.p12']
      }
    ],
    properties: []
  }).then((path) => {
    value = 1;
    console.log('success')
    mainWindow.webContents.send('success', path);
  }).catch((value) => {
    value = 2;
    mainWindow.webContents.send('failed', path);
    console.log('error')
  });
  return value;
}

This code throws some error when I type 'pro://something' in the browser.

Erorr description: Error launching app, unable to find Electron app at C:\Windows\system32\pro:\something

I have also tried some other code which opens my app but in a different window.

I want to open the App but in the existing window of my app.


问:
Criteria Unable to locate appropriate constructor on class
I have classes:

Account.java

```<code>@Entity
@Table(name = "accounts")
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Account extends BaseEntity {
    private String username;
    private String password;
    private int status;
    private int type;
}
</code>```

Student.java

```<code>@Entity
@Table(name = "students")
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Student extends BaseEntity {
    @OneToOne
    @JoinColumn(name = "account_id")
    private Account account;

    private String fullName;
    private long classId;
    private long titleId;
}
</code>```

UserResDto.java

```<code>@SuperBuilder
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class UserResDto {
    private long accountId;
    private String username;
    private String fullName;
    private int type;
    private List<Ability> abilities;
}
</code>```

StudentResDto.java

```<code>@SuperBuilder
@Getter
@Setter
public class StudentResDto extends UserResDto {
    private long classId;
    private long titleId;
}
</code>```

I get students list use criteria:

```<code>public List<StudentResDto> getStudent(String username) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<StudentResDto> cq = cb.createQuery(StudentResDto.class);
        Root<Student> student = cq.from(Student.class);
        Join<Student, Account> account = student.join("account");
        cq.multiselect(
                account.get("id").alias("accountId"),
                account.get("username"),
                account.get("type"),
                student.get("fullName"),
                student.get("classId"),
                student.get("titleId")
        );
        return em.createQuery(cq).getResultList();
    }
</code>```

But got errors:

Unable to locate appropriate constructor on class [com.example.qldtback.dto.response.UserRes.StudentResDto]. Expected arguments are: long, java.lang.String, int, java.lang.String, long, long [select new com.example.qldtback.dto.response.UserRes.StudentResDto(generatedAlias0.id, generatedAlias0.username, generatedAlias0.type, generatedAlias1.fullName, generatedAlias1.classId, generatedAlias1.titleId) from com.example.qldtback.modules.student.Student as generatedAlias1 inner join generatedAlias1.account as generatedAlias0]

So how to fix it? Thank you very much!

Body:
I have classes:

Account.java

@Entity
@Table(name = "accounts")
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Account extends BaseEntity {
    private String username;
    private String password;
    private int status;
    private int type;
}

Student.java

@Entity
@Table(name = "students")
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Student extends BaseEntity {
    @OneToOne
    @JoinColumn(name = "account_id")
    private Account account;

    private String fullName;
    private long classId;
    private long titleId;
}

UserResDto.java

@SuperBuilder
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class UserResDto {
    private long accountId;
    private String username;
    private String fullName;
    private int type;
    private List<Ability> abilities;
}

StudentResDto.java

@SuperBuilder
@Getter
@Setter
public class StudentResDto extends UserResDto {
    private long classId;
    private long titleId;
}

I get students list use criteria:

public List<StudentResDto> getStudent(String username) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<StudentResDto> cq = cb.createQuery(StudentResDto.class);
        Root<Student> student = cq.from(Student.class);
        Join<Student, Account> account = student.join("account");
        cq.multiselect(
                account.get("id").alias("accountId"),
                account.get("username"),
                account.get("type"),
                student.get("fullName"),
                student.get("classId"),
                student.get("titleId")
        );
        return em.createQuery(cq).getResultList();
    }

But got errors:

Unable to locate appropriate constructor on class [com.example.qldtback.dto.response.UserRes.StudentResDto]. Expected arguments are: long, java.lang.String, int, java.lang.String, long, long [select new com.example.qldtback.dto.response.UserRes.StudentResDto(generatedAlias0.id, generatedAlias0.username, generatedAlias0.type, generatedAlias1.fullName, generatedAlias1.classId, generatedAlias1.titleId) from com.example.qldtback.modules.student.Student as generatedAlias1 inner join generatedAlias1.account as generatedAlias0]

So how to fix it? Thank you very much!


问:
Vaadin Login view Chrome not save password
Update:
If I disable https redirection its works, can you help me what I am doing wrong with redirection?
application.prioerties:

```<code>server.http.port=8080
## SSL
server.port=443
</code>```

Redirect:

```<code>import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class HttpsConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(redirectConnector());
        return tomcat;
    }

//  @Value("${server.port2}") // Defined in application.properties file
//  int httpPort = ;

//  @Value("${server.port}") // Defined in application.properties file
//  int httpsPort =;

    private Connector redirectConnector() {
        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setScheme("http");
        connector.setPort(Integer.parseInt(environment.getProperty("server.http.port")));
        connector.setSecure(false);
        connector.setRedirectPort( Integer.parseInt(environment.getProperty("server.port")));
        return connector;
    }
}
</code>```

SecurityConfig:

```<code>@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends VaadinWebSecurityConfigurerAdapter {

    @Autowired
    private RequestUtil requestUtil;

    @Autowired
    private VaadinDefaultRequestCache vaadinDefaultRequestCache;

    @Autowired
    private ViewAccessChecker viewAccessChecker;

    @Lazy
    @Autowired
    CustomAuthenticationProvider customAuthenticationProvider;

    @Autowired
    ReportService reportService;

    public static final String LOGOUT_URL = "/";

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

//      super.configure(http);

//

        http.csrf().ignoringRequestMatchers(requestUtil::isFrameworkInternalRequest);
        // nor with endpoints
        http.csrf().ignoringRequestMatchers(requestUtil::isEndpointRequest);

        // Ensure automated requests to e.g. closing push channels, service
        // workers,
        // endpoints are not counted as valid targets to redirect user to on
        // login
        http.requestCache().requestCache(vaadinDefaultRequestCache);

        http.authorizeRequests().antMatchers("/api/**").permitAll();
        // TODO LOCAL HOST ENABLE AND ADMIN
        // .hasIpAddress(LOGOUT_URL , hasROle

        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry urlRegistry = http
                .authorizeRequests();

        // Vaadin internal requests must always be allowed to allow public Flow
        // pages
        // and/or login page implemented using Flow.
        urlRegistry.requestMatchers(requestUtil::isFrameworkInternalRequest).permitAll();
        // Public endpoints are OK to access
        urlRegistry.requestMatchers(requestUtil::isAnonymousEndpoint).permitAll();
        // Public routes are OK to access
        urlRegistry.requestMatchers(requestUtil::isAnonymousRoute).permitAll();
        urlRegistry.requestMatchers(getDefaultHttpSecurityPermitMatcher()).permitAll();

        // all other requests require authentication
        urlRegistry.anyRequest().authenticated();

        // Enable view access control
        viewAccessChecker.enable();

        setLoginView(http, LoginView.class, LOGOUT_URL);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        /*
         * auth.ldapAuthentication().userDnPatterns("uid={0},ou=people").groupSearchBase
         * ("ou=Budapest,ou=Hungary,ou=Users,ou=Company_OU,dc=groupad1,dc=com").
         * contextSource()
         * .url("ldap:///dc=springframework,dc=org").and().
         * passwordCompare() .passwordEncoder(new
         * BCryptPasswordEncoder()).passwordAttribute("userPassword");
         */
        // Custom authentication provider - Order 1
        auth.authenticationProvider(customAuthenticationProvider);

//       Built-in authentication provider - Order 2
//      auth.inMemoryAuthentication().withUser("admin").password("{noop}admin@password")
//              // {noop} makes sure that the password encoder doesn't do anything
//              .roles("ADMIN") // Role of the user
//              .and().withUser("user").password("{noop}user@password").credentialsExpired(true).accountExpired(true)
//              .accountLocked(true).roles("USER");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        web.ignoring().antMatchers("/images/*.png");
//      web.ignoring().antMatchers("/api/*");
    }
}
</code>```

I have a basic fresh Vaadin tutorial based login view (https://vaadin.com/docs/latest/security/enabling-security)

EDIT: I think the main problem that the browsers think the login form is a simple form... and not a login form . eg: it pops up my email address for username and I click manage it brings me to chrome address form options and not the password...

My main problem is that Chrome or any other browser not ask to save the password after login.. and neither fill out the form even if its stored at the same host (eg: localhost:8080)
The problem is in the login view, because the chrome work properly and store passwords others sites for me and for other test users .

The other problem is that the following configure part is deprecated and I couldnt find the updated one, since all tutorial use this.

```<code>protected void configure(HttpSecurity http) throws Exception {
    ...
        setLoginView(http, LoginView.class, LOGOUT_URL);
</code>```

this function is deprecated and I do

```<code>@Route("login")
@PageTitle("Login | My App")
public class LoginView extends VerticalLayout implements BeforeEnterObserver {

    private final LoginForm login = new LoginForm();

    public LoginView() {
        addClassName("login-view");
        setSizeFull();
        setAlignItems(Alignment.CENTER);
        setJustifyContentMode(JustifyContentMode.CENTER);

        login.setAction("login");
        login.setForgotPasswordButtonVisible(false);

        add(new H1("My App"), login);
    }

    @Override
    public void beforeEnter(BeforeEnterEvent beforeEnterEvent) {
        // inform the user about an authentication error
        if (beforeEnterEvent.getLocation().getQueryParameters().getParameters().containsKey("error")) {
            login.setError(true);
        }
    }
}
</code>```

Maven pom with versions:

```<code>   <properties>
            <java.version>17</java.version>
            <vaadin.version>23.3.0</vaadin.version>
        </properties>

        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <!-- <version>2.5.4</version> -->
            <version>2.7.0</version>
        </parent>
</code>```

Body:
Update:
If I disable https redirection its works, can you help me what I am doing wrong with redirection?
application.prioerties:

server.http.port=8080
## SSL
server.port=443

Redirect:

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class HttpsConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(redirectConnector());
        return tomcat;
    }

//  @Value("${server.port2}") // Defined in application.properties file
//  int httpPort = ;

//  @Value("${server.port}") // Defined in application.properties file
//  int httpsPort =;

    private Connector redirectConnector() {
        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setScheme("http");
        connector.setPort(Integer.parseInt(environment.getProperty("server.http.port")));
        connector.setSecure(false);
        connector.setRedirectPort( Integer.parseInt(environment.getProperty("server.port")));
        return connector;
    }
}

SecurityConfig:

@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends VaadinWebSecurityConfigurerAdapter {

    @Autowired
    private RequestUtil requestUtil;

    @Autowired
    private VaadinDefaultRequestCache vaadinDefaultRequestCache;

    @Autowired
    private ViewAccessChecker viewAccessChecker;

    @Lazy
    @Autowired
    CustomAuthenticationProvider customAuthenticationProvider;

    @Autowired
    ReportService reportService;

    public static final String LOGOUT_URL = "/";

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

//      super.configure(http);

//

        http.csrf().ignoringRequestMatchers(requestUtil::isFrameworkInternalRequest);
        // nor with endpoints
        http.csrf().ignoringRequestMatchers(requestUtil::isEndpointRequest);

        // Ensure automated requests to e.g. closing push channels, service
        // workers,
        // endpoints are not counted as valid targets to redirect user to on
        // login
        http.requestCache().requestCache(vaadinDefaultRequestCache);

        http.authorizeRequests().antMatchers("/api/**").permitAll();
        // TODO LOCAL HOST ENABLE AND ADMIN
        // .hasIpAddress(LOGOUT_URL , hasROle

        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry urlRegistry = http
                .authorizeRequests();

        // Vaadin internal requests must always be allowed to allow public Flow
        // pages
        // and/or login page implemented using Flow.
        urlRegistry.requestMatchers(requestUtil::isFrameworkInternalRequest).permitAll();
        // Public endpoints are OK to access
        urlRegistry.requestMatchers(requestUtil::isAnonymousEndpoint).permitAll();
        // Public routes are OK to access
        urlRegistry.requestMatchers(requestUtil::isAnonymousRoute).permitAll();
        urlRegistry.requestMatchers(getDefaultHttpSecurityPermitMatcher()).permitAll();

        // all other requests require authentication
        urlRegistry.anyRequest().authenticated();

        // Enable view access control
        viewAccessChecker.enable();

        setLoginView(http, LoginView.class, LOGOUT_URL);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        /*
         * auth.ldapAuthentication().userDnPatterns("uid={0},ou=people").groupSearchBase
         * ("ou=Budapest,ou=Hungary,ou=Users,ou=Company_OU,dc=groupad1,dc=com").
         * contextSource()
         * .url("ldap:///dc=springframework,dc=org").and().
         * passwordCompare() .passwordEncoder(new
         * BCryptPasswordEncoder()).passwordAttribute("userPassword");
         */
        // Custom authentication provider - Order 1
        auth.authenticationProvider(customAuthenticationProvider);

//       Built-in authentication provider - Order 2
//      auth.inMemoryAuthentication().withUser("admin").password("{noop}admin@password")
//              // {noop} makes sure that the password encoder doesn't do anything
//              .roles("ADMIN") // Role of the user
//              .and().withUser("user").password("{noop}user@password").credentialsExpired(true).accountExpired(true)
//              .accountLocked(true).roles("USER");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        web.ignoring().antMatchers("/images/*.png");
//      web.ignoring().antMatchers("/api/*");
    }
}

I have a basic fresh Vaadin tutorial based login view (https://vaadin.com/docs/latest/security/enabling-security)

EDIT: I think the main problem that the browsers think the login form is a simple form... and not a login form . eg: it pops up my email address for username and I click manage it brings me to chrome address form options and not the password...

My main problem is that Chrome or any other browser not ask to save the password after login.. and neither fill out the form even if its stored at the same host (eg: localhost:8080)
The problem is in the login view, because the chrome work properly and store passwords others sites for me and for other test users .

The other problem is that the following configure part is deprecated and I couldnt find the updated one, since all tutorial use this.

protected void configure(HttpSecurity http) throws Exception {
    ...
        setLoginView(http, LoginView.class, LOGOUT_URL);

this function is deprecated and I do

@Route("login")
@PageTitle("Login | My App")
public class LoginView extends VerticalLayout implements BeforeEnterObserver {

    private final LoginForm login = new LoginForm();

    public LoginView() {
        addClassName("login-view");
        setSizeFull();
        setAlignItems(Alignment.CENTER);
        setJustifyContentMode(JustifyContentMode.CENTER);

        login.setAction("login");
        login.setForgotPasswordButtonVisible(false);

        add(new H1("My App"), login);
    }

    @Override
    public void beforeEnter(BeforeEnterEvent beforeEnterEvent) {
        // inform the user about an authentication error
        if (beforeEnterEvent.getLocation().getQueryParameters().getParameters().containsKey("error")) {
            login.setError(true);
        }
    }
}

Maven pom with versions:

   <properties>
            <java.version>17</java.version>
            <vaadin.version>23.3.0</vaadin.version>
        </properties>

        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>

            <version>2.7.0</version>
        </parent>


问:
Nginx Ingress path rewriting does not forward to specified endpoint in Kubernetes Cluster
In our Kubernetes Cluster we have a micro frontend, which is accessable under image-self-service:8080 without any additional path. To be able to use it in a bigger application I want to use an Nginx-Ingress to reroute from url-to-site/profile to image-self-service:8080/.

I have found and read this SO post, thats basically asking the same thing:
Remove routing path from Kubernetes ingress and the linked documentation here:
https://github.com/kubernetes/ingress-nginx/blob/main/docs/examples/rewrite/README.md

which resulted in me using a .yaml for my Ingress that looks like this: (sensitive Information removed)

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/proxy-body-size: "50m"
    traefik.ingress.kubernetes.io/router.entrypoints: websecure
    traefik.ingress.kubernetes.io/router.tls: "true"
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/cors-allow-origin: "*"
    nginx.ingress.kubernetes.io/cors-allow-methods: "PUT, GET, POST, OPTIONS, DELETE"
    nginx.ingress.kubernetes.io/cors-allow-headers: "DNT,X-CustomHeader,X-LANG,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,X-Api-Key,X-Device-Id,Access-Control-Allow-Origin"
    nginx.ingress.kubernetes.io/rewrite-target: /
  name: intranet-backend-ingress
  namespace: intranet

spec:
  rules:
  - host: xxx-test.xxx.xxx
    http:
      paths:
      - backend:
          service:
            name: image-self-service
            port:
              number: 8080
        path: /profile(/|$)(.*)
        pathType: Prefix
      - backend:
          service:
            name: intranet-ui
            port:
              number: 8080
        path: /
        pathType: Prefix
    ...

</code>```

For readability I also removed other endpoints which are more specific as I don't think those interfere.
I have tried using nginx.ingress.kubernetes.io/rewrite-target: / and nginx.ingress.kubernetes.io/rewrite-target: /$2

If I remove the rewrite-target and add a specific path, the forwarding works but with the additional path, so it results in a 404 from the underlying webservice. The Response I get using the rewriting is simply: 404 page not found which I believe to be an Ingress message.

Body:
In our Kubernetes Cluster we have a micro frontend, which is accessable under image-self-service:8080 without any additional path. To be able to use it in a bigger application I want to use an Nginx-Ingress to reroute from url-to-site/profile to image-self-service:8080/.

I have found and read this SO post, thats basically asking the same thing:
Remove routing path from Kubernetes ingress and the linked documentation here:
https://github.com/kubernetes/ingress-nginx/blob/main/docs/examples/rewrite/README.md

which resulted in me using a .yaml for my Ingress that looks like this: (sensitive Information removed)

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/proxy-body-size: "50m"
    traefik.ingress.kubernetes.io/router.entrypoints: websecure
    traefik.ingress.kubernetes.io/router.tls: "true"
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/cors-allow-origin: "*"
    nginx.ingress.kubernetes.io/cors-allow-methods: "PUT, GET, POST, OPTIONS, DELETE"
    nginx.ingress.kubernetes.io/cors-allow-headers: "DNT,X-CustomHeader,X-LANG,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,X-Api-Key,X-Device-Id,Access-Control-Allow-Origin"
    nginx.ingress.kubernetes.io/rewrite-target: /
  name: intranet-backend-ingress
  namespace: intranet

spec:
  rules:
  - host: xxx-test.xxx.xxx
    http:
      paths:
      - backend:
          service:
            name: image-self-service
            port:
              number: 8080
        path: /profile(/|$)(.*)
        pathType: Prefix
      - backend:
          service:
            name: intranet-ui
            port:
              number: 8080
        path: /
        pathType: Prefix
    ...

For readability I also removed other endpoints which are more specific as I don't think those interfere.
I have tried using nginx.ingress.kubernetes.io/rewrite-target: / and nginx.ingress.kubernetes.io/rewrite-target: /$2

If I remove the rewrite-target and add a specific path, the forwarding works but with the additional path, so it results in a 404 from the underlying webservice. The Response I get using the rewriting is simply: 404 page not found which I believe to be an Ingress message.


问:
How to keep adb connecting after reseting android device?
How to keep adb connecting after reseting android device?

I am doing a andorid automation test which need me to factory reset device after executing test case. But if i reset my android device, i need to reopen developer mode and turn on USB Debugging to keep android device connect to my computer.

Do you have any ideas? Thanks!


问:
OSRM Configure blocking hours for a specific road
i'm working with OSRM(Open Source Routing Machine) and ran into some problems.
I want configure blocking hours for a specific road(like Grab)
Ex: The street called Cau Giay block taxis from 4.00pm to 7.00pm

code detail:

```<code>function restrict(way, result)
  -- Check if the way is named contain Cau Giay
  local name = way:get_value_by_key('name')
  if name and string.find(name, 'Cau Giay') then
    -- Add a restriction to the way
    result.restriction = '* @ (Mo-Fr 16:00-19:00)'
  end
end

function way_function(way)
  local result = {
    -- Other routing rules and restrictions go here
  }
  restrict(way, result)
  return result
end
</code>```

but nothing changed.

please tell me where the above code is wrong and suggest some ways you have done it!

Thanks and best regards!

https://github.com/Project-OSRM/osrm-backend/issues/33 and
https://github.com/Project-OSRM/osrm-backend/issues/735

Body:
i'm working with OSRM(Open Source Routing Machine) and ran into some problems.
I want configure blocking hours for a specific road(like Grab)
Ex: The street called Cau Giay block taxis from 4.00pm to 7.00pm

code detail:

function restrict(way, result)
  -- Check if the way is named contain Cau Giay
  local name = way:get_value_by_key('name')
  if name and string.find(name, 'Cau Giay') then
    -- Add a restriction to the way
    result.restriction = '* @ (Mo-Fr 16:00-19:00)'
  end
end

function way_function(way)
  local result = {
    -- Other routing rules and restrictions go here
  }
  restrict(way, result)
  return result
end

but nothing changed.

please tell me where the above code is wrong and suggest some ways you have done it!

Thanks and best regards!

https://github.com/Project-OSRM/osrm-backend/issues/33 and
https://github.com/Project-OSRM/osrm-backend/issues/735


问:
Calculating Periodic values from YTD
I have a dataset which has 12 columns which includes an amount column which is arriving as YTD.
I need to convert the Ytd into a periodic and populate in a new column.
We are receiving 300-400k records per month with the month column changing and the respective amount column.

So i need to convert this amount column into periodic values.
For ex for jan the periodic should be same as YTD.
For feb it should be the difference of Feb and Jan.
For mar it should be the difference of Mar and Feb  and so on..
We have to consider all the columns while calculating the difference between the months.. (Assuming same amount of data will be populated every month).

I tried lag but still I can see some error.

Ps: calculating YTD is not required but the periodic

Title: Calculating Periodic values from YTD


问:
Afer deploying an express server to vercel, by vercel deployment url, ports are not working
After deployment, deployed link's home route works fine. But with different path, it keeps through an error, Cannot GET /pathname in Vercel.

```<code>// vercel.json

{
"version": 2,
"builds": [
{
  "src": "./index.js",
  "use": "@vercel/node"
}
],
"routes": [
{
  "src": "/(.*)",
  "dest": "/"
}
]
}

// package.json

{
  "name": "tools-manufacture-server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.0.1",
    "express": "^4.18.1",
    "jsonwebtoken": "^8.5.1",
    "mongodb": "^4.6.0",
    "stripe": "^9.4.0"
  }
}
</code>```

The home route is working fine. But when I try to go to another route, for example, localhost:5000/tools, it shows, can not get tools. but it works fine on the local server.

Body:
After deployment, deployed link's home route works fine. But with different path, it keeps through an error, Cannot GET /pathname in Vercel.

// vercel.json

{
"version": 2,
"builds": [
{
  "src": "./index.js",
  "use": "@vercel/node"
}
],
"routes": [
{
  "src": "/(.*)",
  "dest": "/"
}
]
}

// package.json

{
  "name": "tools-manufacture-server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.0.1",
    "express": "^4.18.1",
    "jsonwebtoken": "^8.5.1",
    "mongodb": "^4.6.0",
    "stripe": "^9.4.0"
  }
}

The home route is working fine. But when I try to go to another route, for example, localhost:5000/tools, it shows, can not get tools. but it works fine on the local server.


问:
ROS melodic ssh launch issue
So I have a setup where I want to launch my ROS nodes via a launch file, which in turn will ssh into a udoo board and the launch the necessary files for hardware communication. The launch file works great normally when I do roslaunch, and I have set up a passwordless connection between the PC running ROS and udoo, using the ssh-rsa protocol.
I wanted to launch this on the robot upstart so used the robot-upstart package to create a service for launching. This is where my errors start, as the service does not be able to establish a ssh connection between the PC running ROS and the udoo board.
The error is as follows:

```<code> Jan 09 15:12:26 seven-robot-2 systemd[1]: Started "bringup test_ru_launch".
    Jan 09 15:12:26 seven-robot-2 root[3298]: test_ru_launch: Using workspace setup file /home/seven-robot-2/Seven_ROS/devel/setup.bash
    Jan 09 15:12:26 seven-robot-2 test_ru_launch-start[3297]: <14>Jan  9 15:12:26 root: test_ru_launch: Using workspace setup file /home/seven-robot-2/Seven_ROS/devel/setup.bash
    Jan 09 15:12:27 seven-robot-2 test_ru_launch-start[3297]: <14>Jan  9 15:12:27 root: test_ru_launch: Launching ROS_HOSTNAME=seven-robot-2, ROS_IP=, ROS_MASTER_URI=http://sevenrobot2:11311/, ROS_HOME=/root/.ros, ROS_LOG_DIR=/tmp
Jan 09 15:12:27 seven-robot-2 test_ru_launch-start[3297]: ls: cannot access '/etc/ros/melodic/test_ru_launch.d/*.xacro': No such file or directory
    Jan 09 15:12:27 seven-robot-2 test_ru_launch-start[3297]: <14>Jan  9 15:12:27 root: test_ru_launch: Generated launchfile: /tmp/test_ru_launch.launch
    Jan 09 15:12:27 seven-robot-2 root[3359]: test_ru_launch: Started roslaunch as background process, PID 3358, ROS_LOG_DIR=/tmp
    Jan 09 15:12:27 seven-robot-2 test_ru_launch-start[3297]: <14>Jan  9 15:12:27 root: test_ru_launch: Started roslaunch as background process, PID 3358, ROS_LOG_DIR=/tmp
    Jan 09 15:12:28 seven-robot-2 test_ru_launch-start[3297]: xacro: in-order processing became default in ROS Melodic. You can drop the option.
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: remote[192.168.2.23-0]: failed to launch on udooqdl:
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: Unable to establish ssh connection to [root@192.168.2.23:22]: Server u'192.168.2.23' not found in known_hosts
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]:
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: RLException: unable to start remote roslaunch child: 192.168.2.23-0
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: The traceback for the exception was written to the log file
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: ... logging to /tmp/edd14b60-9001-11ed-8c81-7c8334b0242e/roslaunch-seven-robot-2-3358.log
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: Checking log directory for disk usage. This may take a while.
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: Press Ctrl-C to interrupt
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: Done checking log file disk usage. Usage is <1GB.
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: [31B blob data]
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: started roslaunch server http://seven-robot-2:46315/
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: remote[192.168.2.23-0] starting roslaunch
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: remote[192.168.2.23-0]: creating ssh connection to 192.168.2.23:22, user[root]
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: [192.168.2.23-0] killing on exit
    Jan 09 15:12:29 seven-robot-2 systemd[1]: test_ru_launch.service: Main process exited, code=exited, status=1/FAILURE
    Jan 09 15:12:29 seven-robot-2 systemd[1]: test_ru_launch.service: Failed with result 'exit-code'.
    Jan 09 15:12:29 seven-robot-2 systemd[1]: test_ru_launch.service: Service hold-off time over, scheduling restart.
</code>```

The service and launch file is as follows:

Service file:

```<code># THIS IS A GENERATED FILE, NOT RECOMMENDED TO EDIT.

[Unit]
Description="bringup test_ru_launch"
After=network.target
Wants=network.target
After=network-online.target
Wants=network-online.target
After=multi-user.target
Wants=multi-user.target

[Service]
Type=simple
ExecStart=/usr/sbin/test_ru_launch-start
Restart=on-failure

[Install]
WantedBy=graphical.target
</code>```

roslaunch file (part where ssh is established):

```<code><group>
        <machine name="udooqdl" address="IP of the udoo" user="root" env-loader="/home/root/Seven_ROS/env_loader_udooqdl.sh" default="true"/>
      <rosparam file="$(find seven_robot_base)/params/robotParams.yaml" command="load" ns="$(arg uavcanNs)/uavcan_ros_bridge"/>
      <rosparam file="$(find seven_robot_localization)/params/diff_drive.yaml" command="load" ns="$(arg uavcanNs)/uavcan_ros_bridge"/>
      <include file="$(find uavcan_ros_bridge)/launch/uavcan_ros_bridge.launch">
        <arg name="uavcanNs" value="$(arg uavcanNs)"/>
        <arg name="laser_enabled" default="$(arg enable_Laser)"/>
        <arg name="publishuavcanTf" default="$(arg publishcanTf)"/>
        <arg name="enableMotors" default="$(arg motors_enabled)"/>
      </include>
    </group>
</code>```

Not sure what is causing the error, any help/suggestions is appreciated. Happy to provide more information if needed. I am running ROS melodic on Ubuntu 18.04.IP of the udoo is replaced by the actual IP in the code.

Title: ROS melodic ssh launch issue

Body:
So I have a setup where I want to launch my ROS nodes via a launch file, which in turn will ssh into a udoo board and the launch the necessary files for hardware communication. The launch file works great normally when I do roslaunch, and I have set up a passwordless connection between the PC running ROS and udoo, using the ssh-rsa protocol.
I wanted to launch this on the robot upstart so used the robot-upstart package to create a service for launching. This is where my errors start, as the service does not be able to establish a ssh connection between the PC running ROS and the udoo board.
The error is as follows:

 Jan 09 15:12:26 seven-robot-2 systemd[1]: Started "bringup test_ru_launch".
    Jan 09 15:12:26 seven-robot-2 root[3298]: test_ru_launch: Using workspace setup file /home/seven-robot-2/Seven_ROS/devel/setup.bash
    Jan 09 15:12:26 seven-robot-2 test_ru_launch-start[3297]: <14>Jan  9 15:12:26 root: test_ru_launch: Using workspace setup file /home/seven-robot-2/Seven_ROS/devel/setup.bash
    Jan 09 15:12:27 seven-robot-2 test_ru_launch-start[3297]: <14>Jan  9 15:12:27 root: test_ru_launch: Launching ROS_HOSTNAME=seven-robot-2, ROS_IP=, ROS_MASTER_URI=http://sevenrobot2:11311/, ROS_HOME=/root/.ros, ROS_LOG_DIR=/tmp
Jan 09 15:12:27 seven-robot-2 test_ru_launch-start[3297]: ls: cannot access '/etc/ros/melodic/test_ru_launch.d/*.xacro': No such file or directory
    Jan 09 15:12:27 seven-robot-2 test_ru_launch-start[3297]: <14>Jan  9 15:12:27 root: test_ru_launch: Generated launchfile: /tmp/test_ru_launch.launch
    Jan 09 15:12:27 seven-robot-2 root[3359]: test_ru_launch: Started roslaunch as background process, PID 3358, ROS_LOG_DIR=/tmp
    Jan 09 15:12:27 seven-robot-2 test_ru_launch-start[3297]: <14>Jan  9 15:12:27 root: test_ru_launch: Started roslaunch as background process, PID 3358, ROS_LOG_DIR=/tmp
    Jan 09 15:12:28 seven-robot-2 test_ru_launch-start[3297]: xacro: in-order processing became default in ROS Melodic. You can drop the option.
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: remote[192.168.2.23-0]: failed to launch on udooqdl:
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: Unable to establish ssh connection to [root@192.168.2.23:22]: Server u'192.168.2.23' not found in known_hosts
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]:
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: RLException: unable to start remote roslaunch child: 192.168.2.23-0
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: The traceback for the exception was written to the log file
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: ... logging to /tmp/edd14b60-9001-11ed-8c81-7c8334b0242e/roslaunch-seven-robot-2-3358.log
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: Checking log directory for disk usage. This may take a while.
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: Press Ctrl-C to interrupt
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: Done checking log file disk usage. Usage is <1GB.
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: [31B blob data]
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: started roslaunch server http://seven-robot-2:46315/
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: remote[192.168.2.23-0] starting roslaunch
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: remote[192.168.2.23-0]: creating ssh connection to 192.168.2.23:22, user[root]
    Jan 09 15:12:29 seven-robot-2 test_ru_launch-start[3297]: [192.168.2.23-0] killing on exit
    Jan 09 15:12:29 seven-robot-2 systemd[1]: test_ru_launch.service: Main process exited, code=exited, status=1/FAILURE
    Jan 09 15:12:29 seven-robot-2 systemd[1]: test_ru_launch.service: Failed with result 'exit-code'.
    Jan 09 15:12:29 seven-robot-2 systemd[1]: test_ru_launch.service: Service hold-off time over, scheduling restart.

The service and launch file is as follows:

Service file:

# THIS IS A GENERATED FILE, NOT RECOMMENDED TO EDIT.

[Unit]
Description="bringup test_ru_launch"
After=network.target
Wants=network.target
After=network-online.target
Wants=network-online.target
After=multi-user.target
Wants=multi-user.target

[Service]
Type=simple
ExecStart=/usr/sbin/test_ru_launch-start
Restart=on-failure

[Install]
WantedBy=graphical.target

roslaunch file (part where ssh is established):

<group>
        <machine name="udooqdl" address="IP of the udoo" user="root" env-loader="/home/root/Seven_ROS/env_loader_udooqdl.sh" default="true"/>
      <rosparam file="$(find seven_robot_base)/params/robotParams.yaml" command="load" ns="$(arg uavcanNs)/uavcan_ros_bridge"/>
      <rosparam file="$(find seven_robot_localization)/params/diff_drive.yaml" command="load" ns="$(arg uavcanNs)/uavcan_ros_bridge"/>
      <include file="$(find uavcan_ros_bridge)/launch/uavcan_ros_bridge.launch">
        <arg name="uavcanNs" value="$(arg uavcanNs)"/>
        <arg name="laser_enabled" default="$(arg enable_Laser)"/>
        <arg name="publishuavcanTf" default="$(arg publishcanTf)"/>
        <arg name="enableMotors" default="$(arg motors_enabled)"/>
      </include>
    </group>

Not sure what is causing the error, any help/suggestions is appreciated. Happy to provide more information if needed. I am running ROS melodic on Ubuntu 18.04.IP of the udoo is replaced by the actual IP in the code.