问:
Jqueryui dialog "resizeable: false" not working?
Below is my code.  When it opens the modal, it IS resizeable even though it's set to false.  This is not expected.  All other parameters work as expected (height, width, position, draggable, modal).

```<code>    //MODAL IFRAME POPUP FOR EDITS/adds
    $("#modalDiv").dialog({
        modal: true,
        autoOpen: false,
        height: '400',
        width: '400',
        position: ['150','200'],
        draggable: true,
        resizeable: false,
        title: ''
    });

    //catch a click on an item with the class "add" open modal div.
    $('.add').live('click', function () {
        var thing = $(this).attr('add')
        url = 'add/' + thing + '.aspx?appid=' + $('.lblAppID').html();
        $('#modalIFrame').attr('src', url);
        $('#modalDiv').dialog('open');
        return false;
    });
</code>```

However, if I call the following code from within the modal iframe, it makes it unresizeable (as expected).

```<code>window.parent.$("#modalDiv").dialog("option", "resizable", false);
</code>```

This works, but preferably I'd like to know what I'm missing... I'm sure it's something stupid.  Help?

答: You're spelling the word two different ways :-)</p>

Body:
Below is my code.  When it opens the modal, it IS resizeable even though it's set to false.  This is not expected.  All other parameters work as expected (height, width, position, draggable, modal).

    //MODAL IFRAME POPUP FOR EDITS/adds
    $("#modalDiv").dialog({
        modal: true,
        autoOpen: false,
        height: '400',
        width: '400',
        position: ['150','200'],
        draggable: true,
        resizeable: false,
        title: ''
    });

    //catch a click on an item with the class "add" open modal div.
    $('.add').live('click', function () {
        var thing = $(this).attr('add')
        url = 'add/' + thing + '.aspx?appid=' + $('.lblAppID').html();
        $('#modalIFrame').attr('src', url);
        $('#modalDiv').dialog('open');
        return false;
    });

However, if I call the following code from within the modal iframe, it makes it unresizeable (as expected).

window.parent.$("#modalDiv").dialog("option", "resizable", false);

This works, but preferably I'd like to know what I'm missing... I'm sure it's something stupid.  Help?


来源: stackexchange

问:
JSP Search Function Using Mysql not working
I want to create search option on my project. And it is working when I am searching my records by id or phone_number (in my example named br_telefona) but it wont work when I search by first name or last name.

Also phone_number is set to be varchar in database setup same as first name and last name.

Here is my code for search:

```<code><%
                    Connection connection = null;
                    Statement statement = null;
                    ResultSet resultSet = null;
                    String id = request.getParameter("q");
                    try {
                        connection = DriverManager.getConnection(connectionUrl + database, userid, password);
                        statement = connection.createStatement();
                        String sql = "select * from buyers where first_name=" + id;
                        resultSet = statement.executeQuery(sql);
                        while (resultSet.next()) {
                %>
                <tr>
                    <td><%=resultSet.getString("first_name")%></td>
                    <td><%=resultSet.getString("last_name")%></td>
                    <td><%=resultSet.getString("email")%></td>
                    <td><%=resultSet.getString("phone_number")%></td>
                </tr>
                <%
                        }
                        connection.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                %>
</code>```

Above code wont work but following one where I do query by phone_number is working just fine

```<code><%
                    Connection connection = null;
                    Statement statement = null;
                    ResultSet resultSet = null;
                    String id = request.getParameter("q");
                    try {
                        connection = DriverManager.getConnection(connectionUrl + database, userid, password);
                        statement = connection.createStatement();
                        String sql = "select * from buyers where phone_number=" + id;
                        resultSet = statement.executeQuery(sql);
                        while (resultSet.next()) {
                %>
                <tr>
                    <td><%=resultSet.getString("first_name")%></td>
                    <td><%=resultSet.getString("last_name")%></td>
                    <td><%=resultSet.getString("email")%></td>
                    <td><%=resultSet.getString("phone_number")%></td>
                </tr>
                <%
                        }
                        connection.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                %>
</code>```

I also change first name from 'John' to 987654 and did

```<code>"select * from buyers where first_name=" + id;
</code>```

and it is working.

For some reason request.getParameter("q"); is only working when integer is inputed but not working for varchar.

Database engine is InnoDB, Charset/Collation latin1 / latin1_bin

答:
Add quote characters to the query:</p>

```<code> String sql = "select * from buyers where phone_number='" + id + "'";
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to create search option on my project. And it is working when I am searching my records by id or phone_number (in my example named br_telefona) but it wont work when I search by first name or last name.

Also phone_number is set to be varchar in database setup same as first name and last name.

Here is my code for search:

<%
                    Connection connection = null;
                    Statement statement = null;
                    ResultSet resultSet = null;
                    String id = request.getParameter("q");
                    try {
                        connection = DriverManager.getConnection(connectionUrl + database, userid, password);
                        statement = connection.createStatement();
                        String sql = "select * from buyers where first_name=" + id;
                        resultSet = statement.executeQuery(sql);
                        while (resultSet.next()) {
                %>

                    <%=resultSet.getString("first_name")%>
                    <%=resultSet.getString("last_name")%>
                    <%=resultSet.getString("email")%>
                    <%=resultSet.getString("phone_number")%>

                <%
                        }
                        connection.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                %>

Above code wont work but following one where I do query by phone_number is working just fine

<%
                    Connection connection = null;
                    Statement statement = null;
                    ResultSet resultSet = null;
                    String id = request.getParameter("q");
                    try {
                        connection = DriverManager.getConnection(connectionUrl + database, userid, password);
                        statement = connection.createStatement();
                        String sql = "select * from buyers where phone_number=" + id;
                        resultSet = statement.executeQuery(sql);
                        while (resultSet.next()) {
                %>

                    <%=resultSet.getString("first_name")%>
                    <%=resultSet.getString("last_name")%>
                    <%=resultSet.getString("email")%>
                    <%=resultSet.getString("phone_number")%>

                <%
                        }
                        connection.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                %>

I also change first name from 'John' to 987654 and did

"select * from buyers where first_name=" + id;

and it is working.

For some reason request.getParameter("q"); is only working when integer is inputed but not working for varchar.

Database engine is InnoDB, Charset/Collation latin1 / latin1_bin

Body:
Add quote characters to the query:

 String sql = "select * from buyers where phone_number='" + id + "'";


问:
Using the loop integer to define variables: c++
I have a for-loop which runs over i. For every iteration, I wish that it creates a variable with the name var_i i.e if my loop runs over i=0 to i=4, it should create variables like
var_0, var_1, var_2, var_3 and var_4. How to do this in c++?

答:
You can also use an array of the required size and initialize it with a default value in the loop</p>

```<code>int var[4];
for(int i=0; i < 4; i++){
    var[i] = 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can also use an array of the required size and initialize it with a default value in the loop

int var[4];
for(int i=0; i < 4; i++){
    var[i] = 0;
}


问:
Azure File-Sharing Solutions Compatible With Databricks
I am in search of a file-sharing solution within the Azure ecosystem of tools/services.

The current need is to be able to write thousands of files (3-4 thousand per week) from a script that runs in Databricks, to a storage solution that allows for access from a few other non-technical users. The script that generates the reports is a Python script, not PySpark, although it does run in databricks (a number of PySpark jobs precede it). The storage solution must allow for:

1) writing/saving excel and html files from Python

2) users to view and download multiple files at a time (I believe this knocks out Blob storage?)

Thanks!

答:
Thank you for sharing your question.  If

Azure does offer a data-share service you can use.  Azure Data Share can let you separate the store your Python script writes to, from the store your non-technical users read from.

For point number 1, I do not see any issues.  The storage solutions on Azure are mostly file-type agnostic.  It is technically possible to write to any of the storage solutions, the main difference is how easy or long the process is to do so.

In point number 2, I think what you are hinting at, is the ease with which your non-technical people can access the storage.  It is possible to download multiple files at a time from Blob storage, but the the Portal may not be the most user-friendly way to do this.  I recommend you look into Azure Storage Explorer.  Azure Storage Explorer provides one client application with which your users can manage or download the files from all the Azure Storage solutions.

Given how you specified html files, and viewing multiple files at a time, I suspect you want to render the files like a browser.  Many resources have a URI.  If a self-contained html file is made publicly accessible in Blob storage or ADLS gen2, and you navigate to it in a browser, the html page will render.


答: It's resizable, not resizeable.

Title: Jqueryui dialog "resizeable: false" not working?

Body: It's resizable, not resizeable.


问:
ffmpeg buffering stdin when spawned from node
I'm trying to use node.js to write png data to ffmpeg to create video. I've verified that the following code works:

let ffmpeg = spawn(
  "ffmpeg",
  [
    "-y",
    "-loglevel", "info",
    "-f", "image2pipe",
    "-c:v", "png",
    "-r", `${this.fps}`,
    "-i", "-",

    "-an",
    "-vcodec", "libx264",
    "-pix_fmt", "yuv420p",
    "output.mp4",
  ],
);
ffmpeg.stdout.on('data', data => {
  console.log(`ffmpeg stdout: ${data}`);
});
ffmpeg.stderr.on('data', data => {
  console.log(`ffmpeg stderr: ${data}`);
});

let bufs = [];
let p = Promise.resolve();
for (let i = 0; i < this.frameData.length; i++) {
  p = p.then(_ => new Promise(resolve => {
    this.renderFrame(i);
    this.renderer.domElement.toBlob(blob => {
      blob.arrayBuffer().then(arr => {
        console.log('writing...');
        let uInt8Arr = new Uint8Array(arr);
        // ffmpeg.stdin.write(uInt8Arr);
        bufs.push(uInt8Arr);
        resolve();
      });
    });
  }));
}
p = p.then(_ => {
  for (let buf of bufs) {
    ffmpeg.stdin.write(buf);
  }
  ffmpeg.stdin.end();
});

```

Sorry if it seems complicated, the promises are used as a workaround for the fact that toBlob() runs asynchronously but the frames must be written in order.

That code works correctly as written, but it's needlessly inefficient because it writes the frame data to an array only to write it to ffmpeg later. However if I uncomment ffmpeg.stdin.write(uInt8Arr); and comment the loop where the array data is copied to ffmpeg, ffmpeg will simply hang at the end without generating any video. If I then perform a "large enough" action like save a file or spawn a new process, ffmpeg will generate the video correctly.

I suspect that there's some sort of buffering issue causing this, but I don't fully understand it or know how to fix it. I've already tried sending various signals with to ffmpeg with ffmpeg.kill() and running it through stdbuf as suggested here to no avail. Is there any workaround for this?

答: For anyone who chanced upon this, the solution was to replace the call to ffmpeg.stdin.close() with ffmpeg.stdin.destroy().

Body:
I'm trying to use node.js to write png data to ffmpeg to create video. I've verified that the following code works:

let ffmpeg = spawn(
  "ffmpeg",
  [
    "-y",
    "-loglevel", "info",
    "-f", "image2pipe",
    "-c:v", "png",
    "-r", `${this.fps}`,
    "-i", "-",

    "-an",
    "-vcodec", "libx264",
    "-pix_fmt", "yuv420p",
    "output.mp4",
  ],
);
ffmpeg.stdout.on('data', data => {
  console.log(`ffmpeg stdout: ${data}`);
});
ffmpeg.stderr.on('data', data => {
  console.log(`ffmpeg stderr: ${data}`);
});

let bufs = [];
let p = Promise.resolve();
for (let i = 0; i < this.frameData.length; i++) {
  p = p.then(_ => new Promise(resolve => {
    this.renderFrame(i);
    this.renderer.domElement.toBlob(blob => {
      blob.arrayBuffer().then(arr => {
        console.log('writing...');
        let uInt8Arr = new Uint8Array(arr);
        // ffmpeg.stdin.write(uInt8Arr);
        bufs.push(uInt8Arr);
        resolve();
      });
    });
  }));
}
p = p.then(_ => {
  for (let buf of bufs) {
    ffmpeg.stdin.write(buf);
  }
  ffmpeg.stdin.end();
});

Sorry if it seems complicated, the promises are used as a workaround for the fact that toBlob() runs asynchronously but the frames must be written in order.

That code works correctly as written, but it's needlessly inefficient because it writes the frame data to an array only to write it to ffmpeg later. However if I uncomment ffmpeg.stdin.write(uInt8Arr); and comment the loop where the array data is copied to ffmpeg, ffmpeg will simply hang at the end without generating any video. If I then perform a "large enough" action like save a file or spawn a new process, ffmpeg will generate the video correctly.

I suspect that there's some sort of buffering issue causing this, but I don't fully understand it or know how to fix it. I've already tried sending various signals with to ffmpeg with ffmpeg.kill() and running it through stdbuf as suggested here to no avail. Is there any workaround for this?


问:
Service call fails when app goes into background mode
Have made a service call inside DispatchQueue.global qos .background mode.

```<code>    override func viewDidLoad() {
        super.viewDidLoad()
  DispatchQueue.global(qos: .background).async {
        self.modelClass.fetchData(page: self.pageCount){
            DispatchQueue.main.async {
                self.tbl_View.reloadData()
            }
        }
    }
}
</code>```

// ViewModel

```<code>func fetchData(page: Int, completion: @escaping () -> ()){
    let urlString = "ServiceURL"
    ClientModel.getDataLists(urlString: urlString) { DataModel in
        DispatchQueue.main.async {
            self.delegate?.reloadTableData()
        }
        completion()
    }
}
</code>```

// ClientModel

```<code>func getDataLists(urlString: String, completion: @escaping ([DataModel]) -> ()){

    guard let url = URL(string: urlString) else { return }
    var request = URLRequest(url: url)
    request.httpMethod = RequestType.get
    request.setValue("Application/json", forHTTPHeaderField: "Content-Type")

       let task = URLSession.shared.DataModelTask(with: url) { dataModel, response, error in
    if error != nil || dataModel == nil {
        print("Client error!")
        return
    }
         if let dataModel = dataModel {
            completion([dataModel])
        }
    }

    task.resume()
}
</code>```

After invoking service call, then immediately open another application, the service call fails to get response.

How to get response when app goes into background mode after invoking a service call?

答:
Try using the below code. sample code here: https://github.com/achuaswani/iTunesSearchExample.git</p>

```<code>var taskeid = UIBackgroundTaskIdentifier.invalid
taskeid = UIApplication.shared.beginBackgroundTask {
      let ti = taskeid
      taskeid = UIBackgroundTaskIdentifier.invalid
      if ti != UIBackgroundTaskIdentifier.invalid {
         UIApplication.shared.endBackgroundTask(ti)
       }
}

//Your service call
//End the background task after getting the response
let ti = taskIdentifier
taskeid = UIBackgroundTaskIdentifier.invalid
if ti != UIBackgroundTaskIdentifier.invalid {
     UIApplication.shared.endBackgroundTask(ti)
 }
</code>```

Body:
Have made a service call inside DispatchQueue.global qos .background mode.

    override func viewDidLoad() {
        super.viewDidLoad()
  DispatchQueue.global(qos: .background).async {
        self.modelClass.fetchData(page: self.pageCount){
            DispatchQueue.main.async {
                self.tbl_View.reloadData()
            }
        }
    }
}

// ViewModel

func fetchData(page: Int, completion: @escaping () -> ()){
    let urlString = "ServiceURL"
    ClientModel.getDataLists(urlString: urlString) { DataModel in
        DispatchQueue.main.async {
            self.delegate?.reloadTableData()
        }
        completion()
    }
}

// ClientModel

func getDataLists(urlString: String, completion: @escaping ([DataModel]) -> ()){

    guard let url = URL(string: urlString) else { return }
    var request = URLRequest(url: url)
    request.httpMethod = RequestType.get
    request.setValue("Application/json", forHTTPHeaderField: "Content-Type")

       let task = URLSession.shared.DataModelTask(with: url) { dataModel, response, error in
    if error != nil || dataModel == nil {
        print("Client error!")
        return
    }
         if let dataModel = dataModel {
            completion([dataModel])
        }
    }

    task.resume()
}

After invoking service call, then immediately open another application, the service call fails to get response.

How to get response when app goes into background mode after invoking a service call?

Body:
Try using the below code. sample code here: https://github.com/achuaswani/iTunesSearchExample.git

var taskeid = UIBackgroundTaskIdentifier.invalid
taskeid = UIApplication.shared.beginBackgroundTask {
      let ti = taskeid
      taskeid = UIBackgroundTaskIdentifier.invalid
      if ti != UIBackgroundTaskIdentifier.invalid {
         UIApplication.shared.endBackgroundTask(ti)
       }
}

//Your service call
//End the background task after getting the response
let ti = taskIdentifier
taskeid = UIBackgroundTaskIdentifier.invalid
if ti != UIBackgroundTaskIdentifier.invalid {
     UIApplication.shared.endBackgroundTask(ti)
 }


问:
I am getting an error while executing this stored function in Oracle
My stored function requires an input and should return the number of members that have won atleast two awards ...

Here is my Code;

```<code>CREATE OR REPLACE FUNCTION calculateaward
(
  i_PLAYERID VARCHAR2
) RETURN VARCHAR2 AS
cnt NUMBER;
BEGIN

SELECT * INTO cnt FROM
(
  SELECT COUNT(*) AS NOM FROM
  (
    SELECT PLAYERID, USERNAME FROM MEMBER R
    WHERE R.USERNAME IN
    (
      SELECT USERNAME FROM
      (
        SELECT USERNAME, COUNT(*) AS cnt FROM MEMBERAWARD
        GROUP BY USERNAME
      )
      WHERE cnt >= 2
    )
  )
  WHERE player= I_PLAYERID
  GROUP BY PLAYERID
);

  RETURN cnt;
END calculateaward;
</code>```

I am trying to execute the function as follow
exec calculateaward('P0001') but it does not work , please help .

答:
You cannot execute a function using exec unlike stored procedures..Instead try this:

```<code>SELECT calculateaward('P0001') FROM DUAL;
</code>```

Also, why define the function as returning a VARCHAR2 when you are returning a NUMBER, it's not an error since the number will be cast to  VARCHAR2 automatically, but its always better to return the same datatype as defined by returns

Body:
My stored function requires an input and should return the number of members that have won atleast two awards ...

Here is my Code;

CREATE OR REPLACE FUNCTION calculateaward
(
  i_PLAYERID VARCHAR2
) RETURN VARCHAR2 AS
cnt NUMBER;
BEGIN

SELECT * INTO cnt FROM
(
  SELECT COUNT(*) AS NOM FROM
  (
    SELECT PLAYERID, USERNAME FROM MEMBER R
    WHERE R.USERNAME IN
    (
      SELECT USERNAME FROM
      (
        SELECT USERNAME, COUNT(*) AS cnt FROM MEMBERAWARD
        GROUP BY USERNAME
      )
      WHERE cnt >= 2
    )
  )
  WHERE player= I_PLAYERID
  GROUP BY PLAYERID
);

  RETURN cnt;
END calculateaward;

I am trying to execute the function as follow
exec calculateaward('P0001') but it does not work , please help .

Body:
You cannot execute a function using exec unlike stored procedures..Instead try this:

SELECT calculateaward('P0001') FROM DUAL;

Also, why define the function as returning a VARCHAR2 when you are returning a NUMBER, it's not an error since the number will be cast to  VARCHAR2 automatically, but its always better to return the same datatype as defined by returns


问:
Where do you go to file a bug report for Jackson JSON?
does anyone know where to file a bug report for Jackson JSON?  thank you

I can't get Jackson to deserialize a JSON file. The inbound JSON has JSON null values, which I need to retain. ???

com.fasterxml.jackson.databind.JsonMappingException: Unrecognized Type: [null]

答: You can create an issue on their Github Repository: https://github.com/FasterXML/jackson-databind</p>


问:
Dynamically set property name of JavaScript object inside a function
I'm learning to build APIs with Express. I figured that every time I have to send a successful JSON response, I have to duplicate most of the code. So I tried to put it in a function like so in one of my controller modules:

```<code>const successResponse = (res, statusCode, obj, coll = false) => {
  const successObj = { status: "success" };
  if (coll) successObj.results = obj.length;
  successObj.data = { obj };
  return res.status(statusCode).json(successObj);
};

exports.getPlayer = asyncErrorHandler(async (req, res, next) => {
  const player = await Player.findById(req.params.id);
  if (!player) return next(new AppError("Player not found", 404));

  successResponse(res, 200, player);
}
</code>```

The problem is in the line successObj.data = { obj } where I want the result to be the name of the argument that is passed as key and the object as value(s). The result I currently get is:

```<code>{
    "status": "success",
    "data": {
        "obj": { // I want this key to be "player" here
            "name": "Sal"
        }
    }
}
</code>```

As the comment says I would like the key to be the string that I passed as the object name. I can do it by passing another argument as a string but it will always be the same as the object name that I pass. Is there a better way to do this?

答:
You pass the name to the successResponse like this:

exports.getPlayer = asyncErrorHandler(async (req, res, next) => {
  const player = await Player.findById(req.params.id);
  if (!player) return next(new AppError("Player not found", 404));

  successResponse(res, 200, {objName: "player" , value: player);
}
```

<p>And then change your successResponse like this: </p>

<pre class="lang-js prettyprint-override"><code>// Set a suitable default value for objName (e.g. "obj") if you don't want to send it every time
const successResponse = (res, statusCode, {objName = "obj", value}, coll = false) => {
  const successObj = { status: "success" };
  if (coll) successObj.results = obj.length;
  successObj.data = { [objName]: {value}}; // { player : { name : "Sal"} }
  return res.status(statusCode).json(successObj);
};
</code>```

EDIT 1 => NOTE: You can't access the name of the variable that passed to a function unless the name string was explicitly passed. Because only the value that a variable held is passed along not the name. This why you have to pass it the name. The solution I gave would not need another argument to function but it will need another key/value inside the object passed.

**EDIT 2 => ** Even more cleaner solution

exports.getPlayer = asyncErrorHandler(async (req, res, next) => {
  const player = await Player.findById(req.params.id);
  if (!player) return next(new AppError("Player not found", 404));

  successResponse(res, 200, {player}); //Same as {"player" : player}
}
```

<p>And then change your successResponse like this: </p>

<pre class="lang-js prettyprint-override"><code>const successResponse = (res, statusCode, obj, coll = false) => {
  const successObj = { status: "success" };
  if (coll) successObj.results = obj.length;
  successObj.data = { ...obj };
  return res.status(statusCode).json(successObj);
};
</code>```

Body:
I'm learning to build APIs with Express. I figured that every time I have to send a successful JSON response, I have to duplicate most of the code. So I tried to put it in a function like so in one of my controller modules:

const successResponse = (res, statusCode, obj, coll = false) => {
  const successObj = { status: "success" };
  if (coll) successObj.results = obj.length;
  successObj.data = { obj };
  return res.status(statusCode).json(successObj);
};

exports.getPlayer = asyncErrorHandler(async (req, res, next) => {
  const player = await Player.findById(req.params.id);
  if (!player) return next(new AppError("Player not found", 404));

  successResponse(res, 200, player);
}

The problem is in the line successObj.data = { obj } where I want the result to be the name of the argument that is passed as key and the object as value(s). The result I currently get is:

{
    "status": "success",
    "data": {
        "obj": { // I want this key to be "player" here
            "name": "Sal"
        }
    }
}

As the comment says I would like the key to be the string that I passed as the object name. I can do it by passing another argument as a string but it will always be the same as the object name that I pass. Is there a better way to do this?

Body:
You pass the name to the successResponse like this:

exports.getPlayer = asyncErrorHandler(async (req, res, next) => {
  const player = await Player.findById(req.params.id);
  if (!player) return next(new AppError("Player not found", 404));

  successResponse(res, 200, {objName: "player" , value: player);
}

And then change your successResponse like this:

// Set a suitable default value for objName (e.g. "obj") if you don't want to send it every time
const successResponse = (res, statusCode, {objName = "obj", value}, coll = false) => {
  const successObj = { status: "success" };
  if (coll) successObj.results = obj.length;
  successObj.data = { [objName]: {value}}; // { player : { name : "Sal"} }
  return res.status(statusCode).json(successObj);
};

EDIT 1 => NOTE: You can't access the name of the variable that passed to a function unless the name string was explicitly passed. Because only the value that a variable held is passed along not the name. This why you have to pass it the name. The solution I gave would not need another argument to function but it will need another key/value inside the object passed.

**EDIT 2 => ** Even more cleaner solution

exports.getPlayer = asyncErrorHandler(async (req, res, next) => {
  const player = await Player.findById(req.params.id);
  if (!player) return next(new AppError("Player not found", 404));

  successResponse(res, 200, {player}); //Same as {"player" : player}
}

And then change your successResponse like this:

const successResponse = (res, statusCode, obj, coll = false) => {
  const successObj = { status: "success" };
  if (coll) successObj.results = obj.length;
  successObj.data = { ...obj };
  return res.status(statusCode).json(successObj);
};


问:
Async function don't await for result in Unity
i would like to wait with next function to finish previous one first. But i have return before it is finished. Here is code:

```<code>private async Task SetupPlayerDatabase()
{
    Task<string> signInWithPlayGames = SignIn.SignInWithPlayGames();
    userId = await signInWithPlayGames;
    Debug.Log("USER ID: " + userId);
}
</code>```

and the sceound class:

```<code>and SignInWithPlayGames:
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using Firebase.Auth;

public class SignIn : MonoBehaviour
{
    private static string userId;

    void Awake () {
        // Initialize Play Games Configuration and Activate it.
        PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().RequestServerAuthCode(false /*forceRefresh*/).Build();
        PlayGamesPlatform.InitializeInstance(config);
        PlayGamesPlatform.Activate();
        //Debug.LogFormat("SignInOnClick: Play Games Configuration initialized");
    }

                // HERE IS THIS FUNCTION ↓ ↓ ↓ ↓ ↓ ↓

    public static async Task<string> SignInWithPlayGames () {
        await Task.Run(() => {
        Debug.LogError("SignIn.SignInWithGooglePlay Task is running");
        // Initialize Firebase Auth
        Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance; // Sign In and Get a server auth code.
        UnityEngine.Social.localUser.Authenticate((bool success) =>
        {
            if (!success) {
                Debug.LogError ("SignInOnClick: Failed to Sign into Play Games Services.");
                return;
            }
            string authCode = PlayGamesPlatform.Instance.GetServerAuthCode();
            if (string.IsNullOrEmpty(authCode))
            {
                Debug.LogError("SignInOnClick: Signed into Play Games Services but failed to get the server auth code.");
                return;
            }
            //Debug.LogFormat("SignInOnClick: Auth code is: {0}", authCode); // Use Server Auth Code to make a credential
            Firebase.Auth.Credential credential = Firebase.Auth.PlayGamesAuthProvider.GetCredential(authCode); // Sign In to Firebase with the credential
            auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
            if (task.IsCanceled) {
                Debug.LogError ("SignInOnClick was canceled.");
                return;
            }
            if (task.IsFaulted) {
                Debug.LogError("SignInOnClick encountered an error: " + task.Exception);
                return;
            }
            Firebase.Auth.FirebaseUser newUser = task.Result;
            Debug.LogFormat("SignInOnClick: User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);
            userId = newUser.UserId;
            // i would like to return userId here, but i cannot
            });
        });
        });
        Debug.LogError("SignIn.SignInWithGooglePlay return: " + userId);
        return userId; // here i return before it have value
    }
}
</code>```

Debugg shows me that first i had return userId; and after this i have userId = newUser.UserId;. So first i have return empty string and next userId get value.

I cannot write return userId; one line under userId = newUser.UserId; becouse it's lambda and return void.

How can i fix it to finish this function in good place and moment? To return userId after make value in this string?

答:
The return statement on your code will execute before the task ends because the task that you are creating with Task.Run has no result. By changing the task to return a string i.e. create a Task<string> as bellow, it will wait for a result before continuing to next line.

```<code>public static async Task<string> SignInWithPlayGames () {
    TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
    Task.Run(() => {
        Debug.LogError("SignIn.SignInWithGooglePlay Task is running");
        // Initialize Firebase Auth
        Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance; // Sign In and Get a server auth code.
        UnityEngine.Social.localUser.Authenticate((bool success) =>
        {
            if (!success) {
                Debug.LogError ("SignInOnClick: Failed to Sign into Play Games Services.");
                tcs.SetResult(null);
            }
            string authCode = PlayGamesPlatform.Instance.GetServerAuthCode();
            if (string.IsNullOrEmpty(authCode))
            {
                Debug.LogError("SignInOnClick: Signed into Play Games Services but failed to get the server auth code.");
                tcs.SetResult(null);
            }
            //Debug.LogFormat("SignInOnClick: Auth code is: {0}", authCode); // Use Server Auth Code to make a credential
            Firebase.Auth.Credential credential = Firebase.Auth.PlayGamesAuthProvider.GetCredential(authCode); // Sign In to Firebase with the credential
            auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
            if (task.IsCanceled) {
                Debug.LogError ("SignInOnClick was canceled.");
                tcs.SetResult(null);
            }
            if (task.IsFaulted) {
                Debug.LogError("SignInOnClick encountered an error: " + task.Exception);
                tcs.SetResult(null);
            }
            Firebase.Auth.FirebaseUser newUser = task.Result;
            Debug.LogFormat("SignInOnClick: User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);
            tcs.SetResult(newUser.UserId);
            });
        });
    });
    return await tcs.Task;
}
</code>```

Body:
i would like to wait with next function to finish previous one first. But i have return before it is finished. Here is code:

private async Task SetupPlayerDatabase()
{
    Task<string> signInWithPlayGames = SignIn.SignInWithPlayGames();
    userId = await signInWithPlayGames;
    Debug.Log("USER ID: " + userId);
}

and the sceound class:

and SignInWithPlayGames:
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using Firebase.Auth;

public class SignIn : MonoBehaviour
{
    private static string userId;

    void Awake () {
        // Initialize Play Games Configuration and Activate it.
        PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().RequestServerAuthCode(false /*forceRefresh*/).Build();
        PlayGamesPlatform.InitializeInstance(config);
        PlayGamesPlatform.Activate();
        //Debug.LogFormat("SignInOnClick: Play Games Configuration initialized");
    }

                // HERE IS THIS FUNCTION ↓ ↓ ↓ ↓ ↓ ↓

    public static async Task<string> SignInWithPlayGames () {
        await Task.Run(() => {
        Debug.LogError("SignIn.SignInWithGooglePlay Task is running");
        // Initialize Firebase Auth
        Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance; // Sign In and Get a server auth code.
        UnityEngine.Social.localUser.Authenticate((bool success) =>
        {
            if (!success) {
                Debug.LogError ("SignInOnClick: Failed to Sign into Play Games Services.");
                return;
            }
            string authCode = PlayGamesPlatform.Instance.GetServerAuthCode();
            if (string.IsNullOrEmpty(authCode))
            {
                Debug.LogError("SignInOnClick: Signed into Play Games Services but failed to get the server auth code.");
                return;
            }
            //Debug.LogFormat("SignInOnClick: Auth code is: {0}", authCode); // Use Server Auth Code to make a credential
            Firebase.Auth.Credential credential = Firebase.Auth.PlayGamesAuthProvider.GetCredential(authCode); // Sign In to Firebase with the credential
            auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
            if (task.IsCanceled) {
                Debug.LogError ("SignInOnClick was canceled.");
                return;
            }
            if (task.IsFaulted) {
                Debug.LogError("SignInOnClick encountered an error: " + task.Exception);
                return;
            }
            Firebase.Auth.FirebaseUser newUser = task.Result;
            Debug.LogFormat("SignInOnClick: User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);
            userId = newUser.UserId;
            // i would like to return userId here, but i cannot
            });
        });
        });
        Debug.LogError("SignIn.SignInWithGooglePlay return: " + userId);
        return userId; // here i return before it have value
    }
}

Debugg shows me that first i had return userId; and after this i have userId = newUser.UserId;. So first i have return empty string and next userId get value.

I cannot write return userId; one line under userId = newUser.UserId; becouse it's lambda and return void.

How can i fix it to finish this function in good place and moment? To return userId after make value in this string?

Body:
The return statement on your code will execute before the task ends because the task that you are creating with Task.Run has no result. By changing the task to return a string i.e. create a Task<string> as bellow, it will wait for a result before continuing to next line.

public static async Task<string> SignInWithPlayGames () {
    TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
    Task.Run(() => {
        Debug.LogError("SignIn.SignInWithGooglePlay Task is running");
        // Initialize Firebase Auth
        Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance; // Sign In and Get a server auth code.
        UnityEngine.Social.localUser.Authenticate((bool success) =>
        {
            if (!success) {
                Debug.LogError ("SignInOnClick: Failed to Sign into Play Games Services.");
                tcs.SetResult(null);
            }
            string authCode = PlayGamesPlatform.Instance.GetServerAuthCode();
            if (string.IsNullOrEmpty(authCode))
            {
                Debug.LogError("SignInOnClick: Signed into Play Games Services but failed to get the server auth code.");
                tcs.SetResult(null);
            }
            //Debug.LogFormat("SignInOnClick: Auth code is: {0}", authCode); // Use Server Auth Code to make a credential
            Firebase.Auth.Credential credential = Firebase.Auth.PlayGamesAuthProvider.GetCredential(authCode); // Sign In to Firebase with the credential
            auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
            if (task.IsCanceled) {
                Debug.LogError ("SignInOnClick was canceled.");
                tcs.SetResult(null);
            }
            if (task.IsFaulted) {
                Debug.LogError("SignInOnClick encountered an error: " + task.Exception);
                tcs.SetResult(null);
            }
            Firebase.Auth.FirebaseUser newUser = task.Result;
            Debug.LogFormat("SignInOnClick: User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);
            tcs.SetResult(newUser.UserId);
            });
        });
    });
    return await tcs.Task;
}


问:
How can I pass a 2D String array (unknown dimensions) as a parameter to a function in Rust
I have a 2D array of Strings, and I'm trying to pass it to a function as a parameter. I successfully have done this with a 2D array of i32, but with Strings I've had no luck.

An example array:

```<code>let my_string_array_2d = [
  ["Two", "Arrays", "Of"],
  ["Three", "Strings", "Each"]
];
</code>```

Here is the function I'm using for a 2d Array of i32:

```<code>fn print2DIntArray<Matrix: AsRef<[Row]>, Row: AsRef<[i32]>>(x: Matrix) {
    for row in x.as_ref() {
        for cell in row.as_ref() {
            print!("{} ", cell);
        }
        println!("");
    }
}
</code>```

I've tried replacing i32 with String, str and &str with no luck. I'm not a Rust developer, so it could be something simple I'm missing.

I know I can do it with a fixed dimension but I'm trying to find a generic solution.

Thanks in advance for any help.

答:
You were on the right track - the inner items are string slices, so &str is the correct type. However you needed to add a lifetime annotation:

```<code>fn print_2d_int_array<'a, Matrix: AsRef<[Row]>, Row: AsRef<[&'a str]>>(x: Matrix)
</code>```

Playground Link

You could make it even more generic in this case: if the objective is to be able to print the matrix, you just need to constrain the cells to be Display:

```<code>use std::fmt::Display;

fn print_2d_int_array<Matrix: AsRef<[Row]>, Row: AsRef<[P]>, P: Display>(x: Matrix)
</code>```

Body:
I have a 2D array of Strings, and I'm trying to pass it to a function as a parameter. I successfully have done this with a 2D array of i32, but with Strings I've had no luck.

An example array:

let my_string_array_2d = [
  ["Two", "Arrays", "Of"],
  ["Three", "Strings", "Each"]
];

Here is the function I'm using for a 2d Array of i32:

fn print2DIntArray<Matrix: AsRef<[Row]>, Row: AsRef<[i32]>>(x: Matrix) {
    for row in x.as_ref() {
        for cell in row.as_ref() {
            print!("{} ", cell);
        }
        println!("");
    }
}

I've tried replacing i32 with String, str and &str with no luck. I'm not a Rust developer, so it could be something simple I'm missing.

I know I can do it with a fixed dimension but I'm trying to find a generic solution.

Thanks in advance for any help.

Body:
You were on the right track - the inner items are string slices, so &str is the correct type. However you needed to add a lifetime annotation:

fn print_2d_int_array<'a, Matrix: AsRef<[Row]>, Row: AsRef<[&'a str]>>(x: Matrix)

Playground Link

You could make it even more generic in this case: if the objective is to be able to print the matrix, you just need to constrain the cells to be Display:

use std::fmt::Display;

fn print_2d_int_array<Matrix: AsRef<[Row]>, Row: AsRef<[P]>, P: Display>(x: Matrix)


问:
How can I use an href link within a "data" attribute - or rewrite it with jQuery?
I'm using the data attribute to show a credit for a photo on a site:

```<code><div id="test" data-credit="name">
</code>```

But how do I do use a link, like this?:

```<code><div id="test" data-credit="<a href="http://mydomain.com">name</a>">
</code>```

Escaping the html, like this, doesn't work:

```<code><a href="http://mydomain.com" >name</a>
</code>```

It that can't be done, how would I use jQuery to rewrite the data-credit "name" into "name" on document ready?

JSfiddle here: http://jsfiddle.net/8muBm/58/

答:
The data attribute is just a holder for string information. You could probably add another attribute like data-credlink="http://mydomain.com"

```<code>$(document).ready(function () {
    $('div[data-credit]').each(function () {
        var THIS = $(this),
            link = $('<a>', {'href': THIS.attr('data-credlink'),
                              'text': THIS.attr('data-credit')
                            });
        THIS.append(link);
    });
})

<div id="test" data-credit="name" data-credlink="http://mydomain.com"></div>
</code>```

Body:
I'm using the data attribute to show a credit for a photo on a site:

But how do I do use a link, like this?:

<div id="test" data-credit="name">

Escaping the html, like this, doesn't work:

name

It that can't be done, how would I use jQuery to rewrite the data-credit "name" into "name" on document ready?

JSfiddle here: http://jsfiddle.net/8muBm/58/

Body:
The data attribute is just a holder for string information. You could probably add another attribute like data-credlink="http://mydomain.com"

$(document).ready(function () {
    $('div[data-credit]').each(function () {
        var THIS = $(this),
            link = $('<a>', {'href': THIS.attr('data-credlink'),
                              'text': THIS.attr('data-credit')
                            });
        THIS.append(link);
    });
})

<div id="test" data-credit="name" data-credlink="http://mydomain.com"></div>


问:
On back button shows same activity over and over
I have activity A which can open Activity B. The problem that I am having is, if I open Activity B and then close Activity B and re open Activity B, when i pressed the back button I will see Activity B again. It seems every time I open the activity the activity gets added on the stack and not being destroyed when using finish() or onBackPressed(). Any help would be appreciated!

This is how I open my activity B from Activity A:

```<code>    Intent intent = new Intent();
    intent.setClass(this, ActivityB.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    startActivity(intent);
</code>```

Activity B back button is called using:

```<code>    public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home: {
            onBackPressed();
            //finish();
            return true;
        }
    }
    return super.onOptionsItemSelected(item);
}
</code>```

Manifest XML:

```<code>        <activity
        android:name="com.example.project.FirstActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan">

        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>

        </activity>

      <activity
        android:name="com.example.project.ActivityA"
        android:screenOrientation="portrait">
    </activity>

    <activity
        android:name="com.example.project.ActivityB"
        android:screenOrientation="portrait">
    </activity>
</code>```

答:
in mainfest.xml  >> add

```<code><activity
        android:name=".ActivityB"
        <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value=".ActivityA" />
</code>```

`

Body:
I have activity A which can open Activity B. The problem that I am having is, if I open Activity B and then close Activity B and re open Activity B, when i pressed the back button I will see Activity B again. It seems every time I open the activity the activity gets added on the stack and not being destroyed when using finish() or onBackPressed(). Any help would be appreciated!

This is how I open my activity B from Activity A:

    Intent intent = new Intent();
    intent.setClass(this, ActivityB.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    startActivity(intent);

Activity B back button is called using:

    public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home: {
            onBackPressed();
            //finish();
            return true;
        }
    }
    return super.onOptionsItemSelected(item);
}

Manifest XML:

        <activity
        android:name="com.example.project.FirstActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan">

        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>

        </activity>

      <activity
        android:name="com.example.project.ActivityA"
        android:screenOrientation="portrait">
    </activity>

    <activity
        android:name="com.example.project.ActivityB"
        android:screenOrientation="portrait">
    </activity>

Body:
in mainfest.xml  >> add

<activity
        android:name=".ActivityB"
        <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value=".ActivityA" />

`


问:
Based on the attached error output, why is my Unity3D build failing?
I've got a unity game which I have built several times before. Today, build mysteriously failed with a large error message, the meaning of which is a mystery to me. Any help would be appreciated. I've tried reverting to a former working copy of my code and shutting down and restarting, to no avail. The error is as follows:</p>

```<code>Failed running "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten_Win\python\2.7.5.3_64bit\python.exe" "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emcc" @"C:\Users\Owner\Documents\Destructo\Assets\..\Temp\emcc_arguments.resp"

stdout:WARNING: sanity check failed to run [Errno 13] Permission denied: 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\emscripten.config_sanity'
stderr:WARNING:root:did not see a source tree above or next to the LLVM root directory (guessing based on directory of C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten_FastComp_Win\llc), could not verify version numbers match
INFO:root:(Emscripten: Running sanity checks)
WARNING:root:java does not seem to exist, required for closure compiler, which is optional (define JAVA in C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\emscripten.config if you want it)
WARNING:root:closure compiler will not be available
WARNING:root:--separate-asm works best when compiling to HTML. otherwise, you must yourself load the '.asm.js' file that is emitted separately, and must do so before loading the main '.js` file
error: failure to execute js library "C:\Users\Owner\Documents\Destructo\Assets\Plugins\plugin.jslib": SyntaxError: Unexpected identifier,,SyntaxError: Unexpected identifier    at Object.load (eval at globalEval (C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\src\compiler.js:105:8), <anonymous>:173:14)    at JSify (eval at globalEval (C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\src\compiler.js:105:8), <anonymous>:59:20)    at C:\Users\Owner\Documents\Destructo\Assets\Plugins\plugin.jslib (C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\src\compiler.js:208:3)    at Module._compile (module.js:570:32)    at Object.Module._extensions..js (module.js:579:10)    at Module.load (module.js:487:32)    at tryModuleLoad (module.js:446:12)    at Function.Module._load (module.js:438:3)    at Module.runMain (module.js:604:10)    at run (bootstrap_node.js:394:7)preprocessed source (you can run a js engine on this to get a clearer error message sometimes):=============ï»¿mergeInto(LibraryManager.library, { SaveString: function(s){        fix = InterfaceOut;     url = "../interface/kabooka.php";       string = "save="+Pointer_stringify(s);      request(fix, url, string);  }   ReadString: function(){     string = "";        if(interfaceInput != null){         return string+interfaceInput;       }       return string;  }});=============Internal compiler error in src/compiler.js! Please raise a bug report at https://github.com/kripken/emscripten/issues/ with a log of the build and the input files used to run. Exception message: "SyntaxError: Unexpected identifier" | SyntaxError: Unexpected identifier    at Object.load (eval at globalEval (C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\src\compiler.js:105:8), <anonymous>:173:14)    at JSify (eval at globalEval (C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\src\compiler.js:105:8), <anonymous>:59:20)    at Object.<anonymous> (C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\src\compiler.js:208:3)    at Module._compile (module.js:570:32)    at Object.Module._extensions..js (module.js:579:10)    at Module.load (module.js:487:32)    at tryModuleLoad (module.js:446:12)    at Function.Module._load (module.js:438:3)    at Module.runMain (module.js:604:10)    at run (bootstrap_node.js:394:7)Traceback (most recent call last):
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emcc", line 13, in <module>
  emcc.run()
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emcc.py", line 1670, in run
final = shared.Building.emscripten(final, append_ext=False, extra_args=extra_args)
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\tools\shared.py", line 1745, in emscripten
  call_emscripten(cmdline)
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 1842, in _main
  temp_files.run_and_clean(lambda: main(
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\tools\tempfiles.py", line 78, in run_and_clean
  return func()
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 1847, in <lambda>
  DEBUG=DEBUG,
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 1748, in main
  temp_files=temp_files, DEBUG=DEBUG)
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 93, in emscript
  glue, forwarded_data = compiler_glue(metadata, settings, libraries, compiler_engine, temp_files, DEBUG)
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 296, in compiler_glue
  cwd=path_from_root('src'), error_limit=300)
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\tools\jsrun.py", line 122, in run_js
  raise Exception('Expected the command ' + str(command) + ' to finish with return code ' + str(assert_returncode) + ', but it returned with code ' + str(proc.returncode) + ' instead! Output: ' + str(ret)[:error_limit])
Exception: Expected the command ['C:/Program Files/Unity/Editor/Data\\Tools\\nodejs\\node.exe', '--stack_size=8192', '--max-old-space-size=2048', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\Emscripten\\src\\compiler.js', 'C:\\Users\\Owner\\Documents\\Destructo\\Temp\\EmscriptenTemp\\tmpm5ff0e.txt', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Audio.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Cursor.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Eval.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\FileSystem.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Logging.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Profiler.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\SystemInfo.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\UnetWebSocket.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Video.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\WebCam.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\WebRequest.js', 'C:\\Users\\Owner\\Documents\\Destructo\\Assets\\Plugins\\plugin.jslib', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\Emscripten\\src\\library_pthread_stub.js'] to finish with return code 0, but it returned with code 1 instead! Output: // The Module object: Our interface to the outside world. We import
// and export values on it, and do the work to get that through
// closure compiler if necessary. There are various ways Module can be used:
// 1. Not defined. We create it here
// 2. A function parameter, function(Module) { ..gener
UnityEditor.HostView:OnGUI()
</code>```

答:
For the sake of anyone else who might run into the same problem, I have found a solution.

I have been attempted to employ an interface between scripts in my game and scripts in the browser using a javascript plug-in. You can find unity's documentation on this here: https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html

Turns out that I foolishly failed to put a comma between method declarations in my javascript object. Monodevelop doesn't flag this error, and evidently it is possible to run the game in the Unity Editor without the commas, but not possible to build it (leading to my incorrect belief that I had reverted to code which was previously working).

It's a pretty big error message for a pretty small problem. So, make sure you put a comma between your method declarations.

Body:
I've got a unity game which I have built several times before. Today, build mysteriously failed with a large error message, the meaning of which is a mystery to me. Any help would be appreciated. I've tried reverting to a former working copy of my code and shutting down and restarting, to no avail. The error is as follows:

Failed running "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten_Win\python\2.7.5.3_64bit\python.exe" "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emcc" @"C:\Users\Owner\Documents\Destructo\Assets\..\Temp\emcc_arguments.resp"

stdout:WARNING: sanity check failed to run [Errno 13] Permission denied: 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\emscripten.config_sanity'
stderr:WARNING:root:did not see a source tree above or next to the LLVM root directory (guessing based on directory of C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten_FastComp_Win\llc), could not verify version numbers match
INFO:root:(Emscripten: Running sanity checks)
WARNING:root:java does not seem to exist, required for closure compiler, which is optional (define JAVA in C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\emscripten.config if you want it)
WARNING:root:closure compiler will not be available
WARNING:root:--separate-asm works best when compiling to HTML. otherwise, you must yourself load the '.asm.js' file that is emitted separately, and must do so before loading the main '.js` file
error: failure to execute js library "C:\Users\Owner\Documents\Destructo\Assets\Plugins\plugin.jslib": SyntaxError: Unexpected identifier,,SyntaxError: Unexpected identifier    at Object.load (eval at globalEval (C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\src\compiler.js:105:8), <anonymous>:173:14)    at JSify (eval at globalEval (C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\src\compiler.js:105:8), <anonymous>:59:20)    at C:\Users\Owner\Documents\Destructo\Assets\Plugins\plugin.jslib (C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\src\compiler.js:208:3)    at Module._compile (module.js:570:32)    at Object.Module._extensions..js (module.js:579:10)    at Module.load (module.js:487:32)    at tryModuleLoad (module.js:446:12)    at Function.Module._load (module.js:438:3)    at Module.runMain (module.js:604:10)    at run (bootstrap_node.js:394:7)preprocessed source (you can run a js engine on this to get a clearer error message sometimes):=============ï»¿mergeInto(LibraryManager.library, { SaveString: function(s){        fix = InterfaceOut;     url = "../interface/kabooka.php";       string = "save="+Pointer_stringify(s);      request(fix, url, string);  }   ReadString: function(){     string = "";        if(interfaceInput != null){         return string+interfaceInput;       }       return string;  }});=============Internal compiler error in src/compiler.js! Please raise a bug report at https://github.com/kripken/emscripten/issues/ with a log of the build and the input files used to run. Exception message: "SyntaxError: Unexpected identifier" | SyntaxError: Unexpected identifier    at Object.load (eval at globalEval (C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\src\compiler.js:105:8), <anonymous>:173:14)    at JSify (eval at globalEval (C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\src\compiler.js:105:8), <anonymous>:59:20)    at Object.<anonymous> (C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\src\compiler.js:208:3)    at Module._compile (module.js:570:32)    at Object.Module._extensions..js (module.js:579:10)    at Module.load (module.js:487:32)    at tryModuleLoad (module.js:446:12)    at Function.Module._load (module.js:438:3)    at Module.runMain (module.js:604:10)    at run (bootstrap_node.js:394:7)Traceback (most recent call last):
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emcc", line 13, in <module>
  emcc.run()
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emcc.py", line 1670, in run
final = shared.Building.emscripten(final, append_ext=False, extra_args=extra_args)
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\tools\shared.py", line 1745, in emscripten
  call_emscripten(cmdline)
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 1842, in _main
  temp_files.run_and_clean(lambda: main(
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\tools\tempfiles.py", line 78, in run_and_clean
  return func()
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 1847, in <lambda>
  DEBUG=DEBUG,
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 1748, in main
  temp_files=temp_files, DEBUG=DEBUG)
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 93, in emscript
  glue, forwarded_data = compiler_glue(metadata, settings, libraries, compiler_engine, temp_files, DEBUG)
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 296, in compiler_glue
  cwd=path_from_root('src'), error_limit=300)
  File "C:\Program Files\Unity\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\tools\jsrun.py", line 122, in run_js
  raise Exception('Expected the command ' + str(command) + ' to finish with return code ' + str(assert_returncode) + ', but it returned with code ' + str(proc.returncode) + ' instead! Output: ' + str(ret)[:error_limit])
Exception: Expected the command ['C:/Program Files/Unity/Editor/Data\\Tools\\nodejs\\node.exe', '--stack_size=8192', '--max-old-space-size=2048', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\Emscripten\\src\\compiler.js', 'C:\\Users\\Owner\\Documents\\Destructo\\Temp\\EmscriptenTemp\\tmpm5ff0e.txt', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Audio.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Cursor.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Eval.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\FileSystem.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Logging.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Profiler.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\SystemInfo.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\UnetWebSocket.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\Video.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\WebCam.js', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\lib\\WebRequest.js', 'C:\\Users\\Owner\\Documents\\Destructo\\Assets\\Plugins\\plugin.jslib', 'C:\\Program Files\\Unity\\Editor\\Data\\PlaybackEngines\\WebGLSupport\\BuildTools\\Emscripten\\src\\library_pthread_stub.js'] to finish with return code 0, but it returned with code 1 instead! Output: // The Module object: Our interface to the outside world. We import
// and export values on it, and do the work to get that through
// closure compiler if necessary. There are various ways Module can be used:
// 1. Not defined. We create it here
// 2. A function parameter, function(Module) { ..gener
UnityEditor.HostView:OnGUI()


问:
Nested Nuxt instances
Not really a code problem more a discussion/brainstroming-post.
I would like to build some light CMS in Vue/Nuxt, which will output a static website in the end.

So I thought about going for one Nuxt-page (does not have to be a Nuxt-page necessarily) containing all the CMS-related stuff and handle the actual website inside a nuxt-child component to keep code tidy.
Problem is, that i can not access the inner Nuxt page, so any editing will be impossible (I want to achieve some simple inline-editing).

For visualization the editor of webflow may be helpful (Directlink to the video). What i want to achieve is a similar version. I would like to have the page separated from the CMS. The CMS would be the lower bottom-bar and provide stuff like the editor for the inline-editing.

Currently my best solution was to define the editing directly inside the page, which is working, but needs to be stripped out for production and makes a future separation impossible.

Is there any solution for this? Or am I thinking the wrong way?
Can I link both instances with a common vuex-store?

答:
You could created two seperate components, one for editing and one for rendering.
These could utilize components themselves to keep the overhead to a minimun.

You could also use the same component, but lazy load the editor features based on some condition like:

If youre fine with having the Editor only available during development you can create an env variable and check for process.env.NODE_ENV !== 'production'

Another way would be to have some sort of authorization that combined with v-if would show the editor or hide it.

Title: Nested Nuxt instances


问:
Can't assign multiple HTML elements in the .css() function
I have 4 divs filter1, filter2, filter3, filter4 and I have an anchor tag inside of them and an image, I want to make it so that when you hover on a filter div, the anchor tag gets the other color, the only problem is that I cannot change the color via JavaScript, which is what I am trying to achieve.

I want to change the color of the anchor when I hover (or in JS mouseOver) any of the filter div.

The only problem is I cannot define multiple HTML tags in the .css function in JavaScript.

I am trying to achieve this:

$(".filter1").mouseover(function () {
  $(".filter , li , a").css("color", "pink");
});
```

<p>The only problem is, now every .filter function, every <code>li</code> tag and every <code>anchor</code> tag in my HTML documents get color pink when I hover over any of these.</p>

<p>What I have right now:</p>

<pre class="lang-js prettyprint-override"><code>$(document).ready(function () {
  $(".filter1").mouseover(function () {
    $(".filter ").css("color", "pink");
  });
  $(".filter1").mouseout(function () {
    $(".filter li a").css("color", "#FFFF");
  });

  //also filter2, filter3, filter4 etc

});
</code>```

How can I resolve this?

答:
A few observations.

First, imvain is correct: you do not need JS to do this, and honestly, you should do this using CSS.

html { background: black; }

.filter1 li a {
  color: white;
}

.filter1 li a:hover {
  color: pink;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="filter1">
  <ul>
    <li>
      <a>Link 1</a>
    </li>
    <li>
      <a>Link 2</a>
    </li>
  </ul>
</div></code>```

Second, although it's the wrong approach, some advice on what was wrong with your code.

You attached your event handlers to the .filter1 element, then changed the text colour on every single link on mouseover. Instead, consider listening for mouse events directly on the links; the specific element on which an event was triggered will be bound to this in your event handler.

You can refine this further by using the hover shorthand to set mouseenter and mouseleave events.

$('.filter1')
  .find('li a')
    .hover(
      function () {
        $(this).css('color', 'pink');
      },
      function () {
        $(this).css('color', 'white');
      }
    );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html { background: black; }

.filter1 li a { color: white; }</code>```

      Link 1

      Link 2

```

Body:
I have 4 divs filter1, filter2, filter3, filter4 and I have an anchor tag inside of them and an image, I want to make it so that when you hover on a filter div, the anchor tag gets the other color, the only problem is that I cannot change the color via JavaScript, which is what I am trying to achieve.

I want to change the color of the anchor when I hover (or in JS mouseOver) any of the filter div.

The only problem is I cannot define multiple HTML tags in the .css function in JavaScript.

I am trying to achieve this:

$(".filter1").mouseover(function () {
  $(".filter , li , a").css("color", "pink");
});

The only problem is, now every .filter function, every li tag and every anchor tag in my HTML documents get color pink when I hover over any of these.

What I have right now:

$(document).ready(function () {
  $(".filter1").mouseover(function () {
    $(".filter ").css("color", "pink");
  });
  $(".filter1").mouseout(function () {
    $(".filter li a").css("color", "#FFFF");
  });

  //also filter2, filter3, filter4 etc

});

How can I resolve this?

Body:
A few observations.

First, imvain is correct: you do not need JS to do this, and honestly, you should do this using CSS.

html { background: black; }

.filter1 li a {
  color: white;
}

.filter1 li a:hover {
  color: pink;
}

<div class="filter1">
  <ul>
    <li>
      <a>Link 1</a>
    </li>
    <li>
      <a>Link 2</a>
    </li>
  </ul>
</div>

Second, although it's the wrong approach, some advice on what was wrong with your code.

You attached your event handlers to the .filter1 element, then changed the text colour on every single link on mouseover. Instead, consider listening for mouse events directly on the links; the specific element on which an event was triggered will be bound to this in your event handler.

You can refine this further by using the hover shorthand to set mouseenter and mouseleave events.

$('.filter1')
  .find('li a')
    .hover(
      function () {
        $(this).css('color', 'pink');
      },
      function () {
        $(this).css('color', 'white');
      }
    );

html { background: black; }

.filter1 li a { color: white; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="filter1">
  <ul>
    <li>
      <a>Link 1</a>
    </li>
    <li>
      <a>Link 2</a>
    </li>
  </ul>
</div>


问:
Nginx random variables
Good morning programmers,
I'm trying to create random variables on nginx, (I have OpenResty nginx+lua).
Here is an example of a static variable:

```<code>set $teste 123;
</code>```

So is it possible to turn this static variable random?

答:
If you're using openresty, you can do it with the help of lua, for example (generating 3 digits):</p>

```<code>set_by_lua_block $teste { return string.format('%03d', math.random(1, 999)) }
</code>```

Title: Nginx random variables

Body:
Good morning programmers,
I'm trying to create random variables on nginx, (I have OpenResty nginx+lua).
Here is an example of a static variable:

set $teste 123;

So is it possible to turn this static variable random?

Body:
If you're using openresty, you can do it with the help of lua, for example (generating 3 digits):

set_by_lua_block $teste { return string.format('%03d', math.random(1, 999)) }


问:
ClickOnce - Secure Alternative to ActiveX for Launching Local Application from IE?
Need to have ASP.NET page running on intranet launch a local windows application (VB6 exe). Originally planning to use an ActiveX control, however general security concerns with ActiveX controls (real and perceptual) have led us to consider a ClickOnce approach to the problem. The user would click on a link that would launch the ClickOnce application (the ClickOnce application would just be a .NET windows app to launch the VB6 app). Is this a better solution from a security perspective?</p>

答:
Is there a reason why you couldn't simply publish the application that you want to launch as a ClickOnce application?

When a ClickOnce application is published, it always checks the server for any updates and, if there are none, it launches the cached installation of the application.  This is the same effect as the "launch" link on the default ClickOnce installation page that is generated when you publish the application.  You could publish the application and then copy the URL from the launch link to your website for the same effect.

I wouldn't recommend your method above.  I don't know your specific scenario but, obviously, your ClickOnce application that you mention above would not work if the VB6 application did not exist on the users computer or if it was located in a different installation location.

In response to your security concerns, I'm not an Active X expert but I wouldn't think launching an ActiveX component would be a problem if it's being used from within your intranet.  In fact, I think the problem with ActiveX is when it's enabled, malicious websites can inject harmful ActiveX viruses.  I'm not a security expert, so I could be wrong.  I'd be surprised, however, that hosting an ActiveX service would be a security problem (assuming your code is legit ;)


问:
Why doesn't a const reference extend the life of a temporary object passed via a function?
In the following simple example, why can't ref2 be bound to the result of min(x,y+1)?

```<code>#include <cstdio>
template< typename T > const T& min(const T& a, const T& b){ return a < b ? a : b ; }

int main(){
      int x = 10, y = 2;
      const int& ref = min(x,y); //OK
      const int& ref2 = min(x,y+1); //NOT OK, WHY?
      return ref2; // Compiles to return 0
}
</code>```

live example - produces:

```<code>main:
  xor eax, eax
  ret
</code>```

EDIT:
  Below example better described a situation, I think.

```<code>#include <stdio.h>

template< typename T >
constexpr T const& min( T const& a, T const& b ) { return a < b ? a : b ; }

constexpr int x = 10;
constexpr int y = 2;

constexpr int const& ref = min(x,y);  // OK

constexpr int const& ref2 = min(x,y+1); // Compiler Error

int main()
{
      return 0;
}
</code>```

live example produces:

```<code><source>:14:38: error: '<anonymous>' is not a constant expression

 constexpr int const& ref2 = min(x,y+1);

                                      ^

Compiler returned: 1
</code>```

答:
[The answer should be updated since non-constexpr version in fact compiles]

Non-constexpr version

Demo: https://godbolt.org/z/_p3njK

Explanation: The lifetime of the rvalue in question produced by y + 1 is in fact extended. This is because the return type of min is reference-to-const i.e const T& and whenever you have a reference-to-const binding directly to a rvalue type, the lifetime of the underlying rvalue value is extended till reference-to-const exists.

Going further, the reference-to-const output of min is then assigned directly to the lvalue name ref2 whose type is const int&; an int type should work here too (i.e int ref2 = min(x, y+1);) in which case the underlying rvalue will be copied over and reference-to-const will be destroyed.

In summary, the non-constexpr version should always produce the desired output at least in the latest version of compilers conforming with the modern C++'s standard.

constexpr version

The issue here is different since the type specifier of ref2 requires it to be a constexpr which in turn requires the expression to be a compile-time literal. Although in theory the lifetime extension could be applied here for constexpr reference-to-const types, C++ doesn't permit it yet (i.e it doesn't create temporary constexpr types to hold the underlying rvalues), perhaps because it prohibits some optimizations or makes the compiler's job harder -- not sure which one is it.

However, you should be able to workaround this case trivially by:

```<code>constexpr int value = min(x, y + 1);
constexpr int const& ref2 = value;
</code>```

Body:
In the following simple example, why can't ref2 be bound to the result of min(x,y+1)?

#include <cstdio>
template< typename T > const T& min(const T& a, const T& b){ return a < b ? a : b ; }

int main(){
      int x = 10, y = 2;
      const int& ref = min(x,y); //OK
      const int& ref2 = min(x,y+1); //NOT OK, WHY?
      return ref2; // Compiles to return 0
}

live example - produces:

main:
  xor eax, eax
  ret

EDIT:
  Below example better described a situation, I think.

#include <stdio.h>

template< typename T >
constexpr T const& min( T const& a, T const& b ) { return a < b ? a : b ; }

constexpr int x = 10;
constexpr int y = 2;

constexpr int const& ref = min(x,y);  // OK

constexpr int const& ref2 = min(x,y+1); // Compiler Error

int main()
{
      return 0;
}

live example produces:

<source>:14:38: error: '<anonymous>' is not a constant expression

 constexpr int const& ref2 = min(x,y+1);

                                      ^

Compiler returned: 1

Body:
[The answer should be updated since non-constexpr version in fact compiles]

Non-constexpr version

Demo: https://godbolt.org/z/_p3njK

Explanation: The lifetime of the rvalue in question produced by y + 1 is in fact extended. This is because the return type of min is reference-to-const i.e const T& and whenever you have a reference-to-const binding directly to a rvalue type, the lifetime of the underlying rvalue value is extended till reference-to-const exists.

Going further, the reference-to-const output of min is then assigned directly to the lvalue name ref2 whose type is const int&; an int type should work here too (i.e int ref2 = min(x, y+1);) in which case the underlying rvalue will be copied over and reference-to-const will be destroyed.

In summary, the non-constexpr version should always produce the desired output at least in the latest version of compilers conforming with the modern C++'s standard.

constexpr version

The issue here is different since the type specifier of ref2 requires it to be a constexpr which in turn requires the expression to be a compile-time literal. Although in theory the lifetime extension could be applied here for constexpr reference-to-const types, C++ doesn't permit it yet (i.e it doesn't create temporary constexpr types to hold the underlying rvalues), perhaps because it prohibits some optimizations or makes the compiler's job harder -- not sure which one is it.

However, you should be able to workaround this case trivially by:

constexpr int value = min(x, y + 1);
constexpr int const& ref2 = value;


问:
How to change/edit a specific VoiceChannel's name to show server member count
I need help to edit the name of the voice channel. I've tried everything in my power to research and find the answer, but nobody has the same problem as me :/
Code:

```<code>async def member_count():
            activeServers = bot.servers
            channel = bot.get_channel(549692930294677525) #Collects the voicechannel id I want to change name on
            sum = 0
            for s in activeServers:
                sum += len(s.members)
            await bot.edit_channel(channel, name="MEMBERS: {}".format(int(sum))) #Here am I trying to edit the channels name to "MEMBERS: (number of members in the server atm)"
            await asyncio.sleep(1) #Sleeps for one second before running the code again

    bot.loop.create_task(member_count()) #Creates a loop for the code above
</code>```

Error message:

```<code>Task exception was never retrieved
future: <Task finished coro=<member_count() done, defined at C:\Users\bjha0\desktop\koding\bot.py:26> exception=AttributeError("'NoneType' object has no attribute 'topic'",)>
Traceback (most recent call last):
  File "C:\Users\bjha0\desktop\koding\bot.py", line 32, in member_count
    await bot.edit_channel(channel, name="MEMBERS: {}".format(int(sum)))
  File "C:\Users\bjha0\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 2007, in edit_channel
    options[key] = getattr(channel, key)
AttributeError: 'NoneType' object has no attribute 'topic'
</code>```

答:
I found this to work perfectly, for me at least.

async 0.16.12:

```<code>async def members():
    activeServers = bot.servers
    channel = bot.get_channel("<channel id here>")
    sum = 0
    for s in activeServers:
        sum += len(s.members)
    await bot.edit_channel(channel, name="❎ MEMBERS: {} ❎".format(int(sum)))
    await asyncio.sleep(1)

@bot.event
async def on_member_join(member):
    await members()

@bot.event
async def on_member_remove(member):
    await members()
</code>```

rewrite 1.3.3:

```<code>async def members():
    activeGuilds = bot.guilds
    channel = bot.get_channel(<channel id here>)
    sum = 0
    for s in activeGuilds:
        sum += len(s.members)
    await channel.edit(name='❎ MEMBERS: {} ❎'.format(int(sum)))
    await asyncio.sleep(1)

@bot.event
async def on_member_join(member):
    await members()

@bot.event
async def on_member_remove(member):
    await members()
</code>```

Body:
I need help to edit the name of the voice channel. I've tried everything in my power to research and find the answer, but nobody has the same problem as me :/
Code:

async def member_count():
            activeServers = bot.servers
            channel = bot.get_channel(549692930294677525) #Collects the voicechannel id I want to change name on
            sum = 0
            for s in activeServers:
                sum += len(s.members)
            await bot.edit_channel(channel, name="MEMBERS: {}".format(int(sum))) #Here am I trying to edit the channels name to "MEMBERS: (number of members in the server atm)"
            await asyncio.sleep(1) #Sleeps for one second before running the code again

    bot.loop.create_task(member_count()) #Creates a loop for the code above

Error message:

Task exception was never retrieved
future: <Task finished coro=<member_count() done, defined at C:\Users\bjha0\desktop\koding\bot.py:26> exception=AttributeError("'NoneType' object has no attribute 'topic'",)>
Traceback (most recent call last):
  File "C:\Users\bjha0\desktop\koding\bot.py", line 32, in member_count
    await bot.edit_channel(channel, name="MEMBERS: {}".format(int(sum)))
  File "C:\Users\bjha0\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 2007, in edit_channel
    options[key] = getattr(channel, key)
AttributeError: 'NoneType' object has no attribute 'topic'

Body:
I found this to work perfectly, for me at least.

async 0.16.12:

async def members():
    activeServers = bot.servers
    channel = bot.get_channel("<channel id here>")
    sum = 0
    for s in activeServers:
        sum += len(s.members)
    await bot.edit_channel(channel, name="❎ MEMBERS: {} ❎".format(int(sum)))
    await asyncio.sleep(1)

@bot.event
async def on_member_join(member):
    await members()

@bot.event
async def on_member_remove(member):
    await members()

rewrite 1.3.3:

async def members():
    activeGuilds = bot.guilds
    channel = bot.get_channel(<channel id here>)
    sum = 0
    for s in activeGuilds:
        sum += len(s.members)
    await channel.edit(name='❎ MEMBERS: {} ❎'.format(int(sum)))
    await asyncio.sleep(1)

@bot.event
async def on_member_join(member):
    await members()

@bot.event
async def on_member_remove(member):
    await members()