问:
Calculating the 3 largest colums in excel and summing them
I am trying to calculate the total for the PT colums. I want it to calculate the top 3 PT colums and add them together. Excell noob so hoping someone can point me in the right direction. You can see my attempt in the screenshot below

答:
Some alternative ways, to get the expected output, where you don't need to confirm press CTRL SHIFT ENTER, based on your Excel Version

Alternative One:

```<code>• =SUMPRODUCT(AGGREGATE(14,6,($B2:$P2)/($B$1:$P$1="PT"),{1,2,3}))
</code>```

Alternative Two:

```<code>• =SUMPRODUCT(LARGE(IF($B$1:$P$1="PT",$B2:$P2),ROW(INDIRECT("1:3"))))
</code>```

Alternative Three:

```<code>• =SUMPRODUCT(LARGE(IF($B$1:$P$1="PT",$B2:$P2),COLUMN($A$1:$C$1)))
</code>```

Alternative Four:

```<code>• =SUMPRODUCT(AGGREGATE(14,6,($B2:$P2)/($B$1:$P$1="PT"),COLUMN($A$1:$C$1)))
</code>```

Body:
Some alternative ways, to get the expected output, where you don't need to confirm press CTRL SHIFT ENTER, based on your Excel Version

Alternative One:

• =SUMPRODUCT(AGGREGATE(14,6,($B2:$P2)/($B$1:$P$1="PT"),{1,2,3}))

Alternative Two:

• =SUMPRODUCT(LARGE(IF($B$1:$P$1="PT",$B2:$P2),ROW(INDIRECT("1:3"))))

Alternative Three:

• =SUMPRODUCT(LARGE(IF($B$1:$P$1="PT",$B2:$P2),COLUMN($A$1:$C$1)))

Alternative Four:

• =SUMPRODUCT(AGGREGATE(14,6,($B2:$P2)/($B$1:$P$1="PT"),COLUMN($A$1:$C$1)))


来源: stackexchange

问:
How do I get the status.podIP within the container program in GCP Cloud Run?
I am trying to run a container image in GCP Cloud run.

Tech Stack:
.NET 6, C#, Orleans.NET, ASP.NET

My code requires the podIP to work properly.

This programs works properly in a regular Kubernetes cluster, because I am able to set an environment variable with the assigned podIP with the following configuration in the "env" section of the deployment.yaml file:

```<code>  - name: POD_IP
    valueFrom:
      fieldRef:
        fieldPath: status.podIP
</code>```

When I try to provide the same in Cloud Run yaml, I get:

When I tried digging into the documentation of k8s.io.api.core.v1,

GCP Documentation - Kubernetes

This is saying that "Not supported by Cloud Run".

Is there any way to set podIP in the environment variable of GCP - Cloud Run?

答:
Cloud Run is a serverless product. As serverless product, you don't manage the servers and the network. Therefore, asking for the podIP make no sense and has no value (at least, it will be a private IP in the Google Cloud serverless network).

So, the answer is "NO, you can't get the podIP".

But why do you need it? You can set a dummy value and see what happens we your container. Or to update your code to make optional that value.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to run a container image in GCP Cloud run.

Tech Stack:
.NET 6, C#, Orleans.NET, ASP.NET

My code requires the podIP to work properly.

This programs works properly in a regular Kubernetes cluster, because I am able to set an environment variable with the assigned podIP with the following configuration in the "env" section of the deployment.yaml file:

  - name: POD_IP
    valueFrom:
      fieldRef:
        fieldPath: status.podIP

When I try to provide the same in Cloud Run yaml, I get:

When I tried digging into the documentation of k8s.io.api.core.v1,

GCP Documentation - Kubernetes

This is saying that "Not supported by Cloud Run".

Is there any way to set podIP in the environment variable of GCP - Cloud Run?


问:
Should I deploy my Ruby on Rails application on Heroku
A little about myself. I am 24 years old, I graduated from NC State with a Master's in Analytics last year. Statistics, mathematics, that kind of thing. I don't have a strong programming background, which is pretty important for my question. If I say anything that doesn't make any sense, that is why. Ever since graduation, I have been working full time on a Rails app with a few other people. My programming experience is mainly Ruby on Rails (1.2 years.) I know R, SAS (statistical languages, not helpful for this question.)

Obviously, that means it has been over a year in development, and we aren't done yet. The main developer is an excellent programmer, just that he has a full time job already, and does this app in his spare time. Due to him not having enough time recently, I have been given practically full responsibility for the app.

We have it deployed on Slicehost right now. The app is at a point where we don't need to program anything else (unless we think of more features.) The reason I am asking if we should migrate to Heroku is that it seems to me that Heroku is a simple platform to which to deploy. Slicehost seems too complicated for me. The other developer dealt with it, and not me. I looked at how to deploy the app on Heroku, and it looks like I would be able to do it. We need our app to scale if it needs to, which Heroku offers. As far as money, I would start it at the minimum (free) and see how it goes. I can pay for additional features if I need to.

We are using Redmine for project management and repository (not git, which I think we need to use on Heroku.) Is git similar to Redmine? Is it easy to use?

Right now, on Slicehost, we have 4 daemons (constantly running processes.) We have 8 delayed_job workers. I know the command line to start the daemons and delayed_job workers. Would these work on Heroku?

I am wondering if I can still use RAILS_ENV=production script/console with Heroku.

The user interface is a javascript file. In development mode, if I do script/server in a terminal, and go to http://localhost:3000 in a browser, I can see it. Would Heroku load this page the way I want?

We have a working website for the app, with our own domain name. I don't really know what DNS is, so I probably wouldn't be able to link the Heroku app to it, unless there is an easy way. I think Heroku links it to appname.heroku.com as a default.

Based on my programming experience, would Heroku be easy enough for me to use, should I find another job, or should I commit seppuku?

答:
If you have the free time, you might as well sign up for a free account and give it a shot.

HOWEVER, this is going to come with some pretty severe headaches.

Version control will be one, since heroku uses git, but another one that no one's mentioned yet is that your 12 processes ("dynos" in heroku speak) would cost you $35 * 11 = $385 per month! You can set up an hourly cron for $3/month that will flush your delayed_job queue (instead of having workers running at all times), but is that going to be adequate? (If you're running 8 workers, I'm guessing not). This may or may not require some code changes.

Once you get it set up, deployment and admin is really easy (nonexistent), but it'll cost you if you start needing new features.

ContentLicense: CC BY-SA 3.0


问:
How to print unknown for not available values in sql
I have 2 tables: Users and cities.

Users has user_id and city.
Cities has city and country_name.

I am trying to print the user_id and the corresponding country and if the city is not present in the cities table, I want an unknown to be there in that case.

My Query:

```<code>Select users.id, cities.country as country
from cities join users on
cities.city=users.city
</code>```

How do I include the unknown part?

答:
You can use RIGHT JOIN:

```<code>SELECT users.id, IFNULL(cities.country, 'unknown') as country
FROM cities
RIGHT JOIN users ON cities.city = users.city
</code>```

Body:
I have 2 tables: Users and cities.

Users has user_id and city.
Cities has city and country_name.

I am trying to print the user_id and the corresponding country and if the city is not present in the cities table, I want an unknown to be there in that case.

My Query:

Select users.id, cities.country as country
from cities join users on
cities.city=users.city

How do I include the unknown part?

Body:
You can use RIGHT JOIN:

SELECT users.id, IFNULL(cities.country, 'unknown') as country
FROM cities
RIGHT JOIN users ON cities.city = users.city


问:
How can I read / write a local json or text in Cordova?
I'm trying to read a JSON file inside the www with Cordova.

I'm trying with a lot of systems, tests and solutions which, however, are failing one after the other.

The simplest concept (fetch)

Result: locally work. On app: "fetch fail" if use cordova.file.dataDirectory. The result is: "NetworkError when attempting to fetch resource".

```<code>document.addEventListener('click', test ,true);
document.addEventListener('touchstart', test ,true);

function test(){

  alert("try fetch");

  const jsonFile = "./geoita.json"; // fail on app
  const jsonFile = cordova.file.dataDirectory+"geoita.json"; //security

  var headers = new Headers({
      "Content-Type": "text/plain",
      "Accept": "text/plain"
   });
  window.fetch( jsonFile, headers )
  .then( resp => resp.json() )
  .then( json => {

    console.log(json);
    alert("Result: "+json);
    document.body.innerHTML=JSON.stringify(json);

  })
  .catch(function(error) {
    console.log('ERROR: ' + error.message);
    alert('ERROR: ' + error.message);
  });

 };
</code>```

TEST 2 (request)

Result: security on file. You can't get file, so you can't read it.

```<code>  var req = new XMLHttpRequest();
  req.onreadystatechange = () =>
  {
    console.log("try in api style...");
    if (req.readyState==4 && req.status==200)
    {
        console.log("reading...");
        let json = JSON.parse(req.responseText);
        console.log(json);
    }
    else {
      console.log("try in api style - error: "+req.readyState);
    }
  }

  req.open("GET",(cordova.file.dataDirectory+"geoita.json"),true);
  req.send();
</code>```

TEST 3 (follow official guideline)

Result: file not found or encoding error.

```<code>const filePath = cordova.file.applicationDirectory+"geoita.json"; //return error code 5 ENCODING_ERR
//const filePath = "www/geoita.json"; // return error  1 NOT_FOUND_ERR
//const filePath ="geoita.json";
//const filePath = cordova.file.applicationDirectory+"geoita.txt"; // not changed

window.resolveLocalFileSystemURL( filePath ,
fileEntry => {

  console.log("file object ready");

  fileEntry.file(
    File => {

      console.log("content: ",File);

      var reader = new FileReader();
      reader.onloadend = function(evt)
      {
          console.log("read success",evt.target.result);
      };
      reader.readAsText(File);

    });

}, error => console.error(error) );
</code>```

I'm continuing to do many tests but I don't understand what is going wrong. I don't understand why it is so difficult to read a local file in the www folder of Cordova.

How can I do this?

Update

Over 32 tests after, the solution was wrong.

Unfortunately I just realized that he doesn't write the file from the www folder. What you can do is "create a file from the variable, historicize it in the permanent and then reread it. It still doesn't read as I wanted then.

What happened during the test is simply the result of previous tests where I had "copied the file into the variable by hand", therefore I had unknowingly saved it and was subsequently recovered as if it were reading the local one (which, of course, was identical)

Unfortunately I still can't find a solution to read the file. If you are aware of it, write!

For this example we have 2 type of data.

1) is a simple var within a json message;

2) It's a local file in the directory www (then create a file by hand that you can recover ... a text with false json data similar to the one in 1)

Step 00

add cordova-file-plugin in your project

https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html

Step 01

In config.xml

```<code>  <platform name="android">
        <preference name="AndroidPersistentFileLocation" value="Compatibility" />
        <preference name="AndroidExtraFilesystems" value="assets,root, files, cache, sdcard, cache-external, files-external" />
    </platform>
    <platform name="ios">
        <preference name="iosPersistentFileLocation" value="Compatibility" />
        <preference name="iosExtraFilesystems" value="assets,root, files,cache, sdcard, cache-external, files-external" />
    </platform>
</code>```

Potentially you may also need to enter:

<access origin="*" /> <access origin="cdvfile://*"/> <access origin="file:///*"/>

Step 02

Now, after app is ready, example:

```<code>  if('cordova' in window)
  {
    document.addEventListener('deviceready', mytest);
    // console.log('device');
  }
  else
  {
    document.addEventListener('DOMContentLoaded', mytest);
    // console.log('web device');
  }
</code>```

in alternative joint it on event:

```<code>  document.addEventListener('click', mytest,true);
  document.addEventListener('touchstart', mytest,true);
</code>```

Step 03

Into your function of app

```<code>  function mytest(){

      // start for read (get the file and pass it on readFile method)
      window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
      (fs)=> {

        var fileName = "test.txt",
            fileDir =  cordova.file.applicationDirectory.replace( cordova.file.applicationDirectory, ''), //cordova.file.applicationDirectory only get error on entry file
            filePath = fileDir + fileName;

        fs.root.getFile(
          filePath,
          null,
          (fileEntry) => {
            readFile(fileEntry)
          }, fileEntryFail);

      }, filesystemFail);

      // start for write (set a file creator -> get data via var -> pass var on writeFile method)
      window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
      (fs)=> {

        var fileName = "test.txt",
            fileDir =  cordova.file.applicationDirectory.replace( cordova.file.applicationDirectory, ''), //cordova.file.applicationDirectory only get error on entry file
            filePath = fileDir + fileName;

        fs.root.getFile(
          filePath,
          { create: true, exclusive: false },
          (fileEntry) => {
            writeFile(fileEntry, filetowrite );
          }, fileEntryFail);

      }, filesystemFail);

      // write a file whit data
      function writeFile(fileEntry, dataObj) {
          fileEntry.createWriter(function (fileWriter) {

              fileWriter.onwrite = function() {
                  alert("file write");
                  // readFile(fileEntry); // if you wont read after write it
              };

              fileWriter.onerror = function (e) {
                  alert("Failed file write: " + e.toString());
              };

              fileWriter.write(dataObj);
          });
      }

      // read a file getted
      function readFile(fileEntry) {

        alert('Reading file....');

        fileEntry.file(function (fileEntry)
        {

            console.log("path to file: ",fileEntry.fullPath);
            console.log("file to read: ",fileEntry.file);

            var reader = new FileReader();
            reader.onloadend = function()
            {
                alert("Successful file read");
                // document.body.innerHTML = ""+this.result;
                console.log("Successful file read: ",this.result);
                // window.dataActive = JSON.parse(this.result);
                // alert('dataActive was read as: ' + dataActive)
                // displayFileData(fileEntry.fullPath + ": " + this.result);
            };
            reader.readAsText(fileEntry);

        }, readFail );

      };

      // fails
      function filesystemFail (err) { alert("FS: DATA FAIL"); console.log(err.code);};
      function fileEntryFail (err) { alert("File entry: FAIL"); };
      function writeFail (err) { alert("Writing: DATA FAIL"); };
      function readFail (err) { alert("Reading: DATA FAIL"); };

      //data test via var
      var filetowrite =  `{"message": "THIS IS SIMPLE TEST MESSAGE"}`

    };
</code>```

Now some important closing notes

It is obviously useless to keep both start read and start write which test on the same file or data. Either write the file and then read it or take it locally and read it directly. So for your tests comment one of the two at a time.

It's also stupid to keep them separate because it would be easy to optimize the system by calling the file system only once.

However, I left them separate to give a clear and functional example to those who, like me, are stuck on logic.

Update

Solution:

While waiting for the whole plugin I am testing to be built:

A) you have to "unlock" access to files in config.xml as I explained above.

B) cordova-file-plugin can only write, read, delete files in the permanent memory inside the app. (I will release a better model than the one above as soon as I can)

C) fetch does not work in any case. BE CAREFUL, it only works on the browser but not in the app

D-1) I am testing the writing and deleting of files in the www. I still need time.

D-2) it is possible to read through an XML request the file in the www in the following way:

```<code>var _filename = 'MYFILENAMEINWWW.txt',
    _mimetype = 'text/plain'; // or application/json

    function readfromwww(_mimetype,_filename,callback)
    {

        var request = new XMLHttpRequest();
            request.overrideMimeType(_mimetype );
            request.open("GET", _filename );
            request.onreadystatechange = () =>
            {

              if(request.status > 300)
              {
                if(rs==404) console.log('file not found in www: ',request.status);
                else console.log('error on request: ',request.status);
              }

              else if(request.responseText!=undefined && request.responseText!='')
              {

                //from json string to js obj content
                if(_mimetype == "application/json")
                  callback(JSON.parse(request.responseText));

                //return string into your file
                else
                  callback(request.responseText);

              }

            }
            request.send();

          }

    }

          // now you can read a file in www calling the method:

          readfromwww('text/plain', 'test.txt',
            filecontent => {

               console.log('OLE! INTO THE FILE: ',filecontent);

               //not filecontent is the content of your file but... remember... the contents is loaded via ajax, isn't easy to storize it out this function.

            });
</code>```

答:
I created a function that returns a promise with a string, then it can be parsed with JSON or whatever you want.

This solution was checked only on Android platform

I also tried to do this with fetch and XMLHttpRequest, but there were no successful results.

Typescript:

```<code>export function readFileFromWWW(filename: string) {
  return new Promise<string>((resolve, reject) => {
    getWWWFileEntry(filename, (fileEntry) => {
      ;(fileEntry as FileEntry).file(
        (file) => {
          const reader = new FileReader()

          reader.onloadend = () => {
            resolve(reader.result as string)
          }

          reader.readAsText(file)
        },
        () => {
          reject(new Error('read went wrong'))
        }
      )
    })
  })
}

function getWWWFileEntry(
  filename: string,
  callback: (fileEntry: Entry) => void
) {
  window.resolveLocalFileSystemURL(
    `${window.cordova.file.applicationDirectory}www/${filename}`,
    callback
  )
}
</code>```

Body:
I'm trying to read a JSON file inside the www with Cordova.

I'm trying with a lot of systems, tests and solutions which, however, are failing one after the other.

The simplest concept (fetch)

Result: locally work. On app: "fetch fail" if use cordova.file.dataDirectory. The result is: "NetworkError when attempting to fetch resource".

document.addEventListener('click', test ,true);
document.addEventListener('touchstart', test ,true);

function test(){

  alert("try fetch");

  const jsonFile = "./geoita.json"; // fail on app
  const jsonFile = cordova.file.dataDirectory+"geoita.json"; //security

  var headers = new Headers({
      "Content-Type": "text/plain",
      "Accept": "text/plain"
   });
  window.fetch( jsonFile, headers )
  .then( resp => resp.json() )
  .then( json => {

    console.log(json);
    alert("Result: "+json);
    document.body.innerHTML=JSON.stringify(json);

  })
  .catch(function(error) {
    console.log('ERROR: ' + error.message);
    alert('ERROR: ' + error.message);
  });

 };

TEST 2 (request)

Result: security on file. You can't get file, so you can't read it.

  var req = new XMLHttpRequest();
  req.onreadystatechange = () =>
  {
    console.log("try in api style...");
    if (req.readyState==4 && req.status==200)
    {
        console.log("reading...");
        let json = JSON.parse(req.responseText);
        console.log(json);
    }
    else {
      console.log("try in api style - error: "+req.readyState);
    }
  }

  req.open("GET",(cordova.file.dataDirectory+"geoita.json"),true);
  req.send();

TEST 3 (follow official guideline)

Result: file not found or encoding error.

const filePath = cordova.file.applicationDirectory+"geoita.json"; //return error code 5 ENCODING_ERR
//const filePath = "www/geoita.json"; // return error  1 NOT_FOUND_ERR
//const filePath ="geoita.json";
//const filePath = cordova.file.applicationDirectory+"geoita.txt"; // not changed

window.resolveLocalFileSystemURL( filePath ,
fileEntry => {

  console.log("file object ready");

  fileEntry.file(
    File => {

      console.log("content: ",File);

      var reader = new FileReader();
      reader.onloadend = function(evt)
      {
          console.log("read success",evt.target.result);
      };
      reader.readAsText(File);

    });

}, error => console.error(error) );

I'm continuing to do many tests but I don't understand what is going wrong. I don't understand why it is so difficult to read a local file in the www folder of Cordova.

How can I do this?

Update

Over 32 tests after, the solution was wrong.

Unfortunately I just realized that he doesn't write the file from the www folder. What you can do is "create a file from the variable, historicize it in the permanent and then reread it. It still doesn't read as I wanted then.

What happened during the test is simply the result of previous tests where I had "copied the file into the variable by hand", therefore I had unknowingly saved it and was subsequently recovered as if it were reading the local one (which, of course, was identical)

Unfortunately I still can't find a solution to read the file. If you are aware of it, write!

For this example we have 2 type of data.

1) is a simple var within a json message;

2) It's a local file in the directory www (then create a file by hand that you can recover ... a text with false json data similar to the one in 1)

Step 00

add cordova-file-plugin in your project

https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html

Step 01

In config.xml

  <platform name="android">
        <preference name="AndroidPersistentFileLocation" value="Compatibility" />
        <preference name="AndroidExtraFilesystems" value="assets,root, files, cache, sdcard, cache-external, files-external" />
    </platform>
    <platform name="ios">
        <preference name="iosPersistentFileLocation" value="Compatibility" />
        <preference name="iosExtraFilesystems" value="assets,root, files,cache, sdcard, cache-external, files-external" />
    </platform>

Potentially you may also need to enter:

<access origin="*" /> <access origin="cdvfile://*"/> <access origin="file:///*"/>

Step 02

Now, after app is ready, example:

  if('cordova' in window)
  {
    document.addEventListener('deviceready', mytest);
    // console.log('device');
  }
  else
  {
    document.addEventListener('DOMContentLoaded', mytest);
    // console.log('web device');
  }

in alternative joint it on event:

  document.addEventListener('click', mytest,true);
  document.addEventListener('touchstart', mytest,true);

Step 03

Into your function of app

  function mytest(){

      // start for read (get the file and pass it on readFile method)
      window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
      (fs)=> {

        var fileName = "test.txt",
            fileDir =  cordova.file.applicationDirectory.replace( cordova.file.applicationDirectory, ''), //cordova.file.applicationDirectory only get error on entry file
            filePath = fileDir + fileName;

        fs.root.getFile(
          filePath,
          null,
          (fileEntry) => {
            readFile(fileEntry)
          }, fileEntryFail);

      }, filesystemFail);

      // start for write (set a file creator -> get data via var -> pass var on writeFile method)
      window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
      (fs)=> {

        var fileName = "test.txt",
            fileDir =  cordova.file.applicationDirectory.replace( cordova.file.applicationDirectory, ''), //cordova.file.applicationDirectory only get error on entry file
            filePath = fileDir + fileName;

        fs.root.getFile(
          filePath,
          { create: true, exclusive: false },
          (fileEntry) => {
            writeFile(fileEntry, filetowrite );
          }, fileEntryFail);

      }, filesystemFail);

      // write a file whit data
      function writeFile(fileEntry, dataObj) {
          fileEntry.createWriter(function (fileWriter) {

              fileWriter.onwrite = function() {
                  alert("file write");
                  // readFile(fileEntry); // if you wont read after write it
              };

              fileWriter.onerror = function (e) {
                  alert("Failed file write: " + e.toString());
              };

              fileWriter.write(dataObj);
          });
      }

      // read a file getted
      function readFile(fileEntry) {

        alert('Reading file....');

        fileEntry.file(function (fileEntry)
        {

            console.log("path to file: ",fileEntry.fullPath);
            console.log("file to read: ",fileEntry.file);

            var reader = new FileReader();
            reader.onloadend = function()
            {
                alert("Successful file read");
                // document.body.innerHTML = ""+this.result;
                console.log("Successful file read: ",this.result);
                // window.dataActive = JSON.parse(this.result);
                // alert('dataActive was read as: ' + dataActive)
                // displayFileData(fileEntry.fullPath + ": " + this.result);
            };
            reader.readAsText(fileEntry);

        }, readFail );

      };

      // fails
      function filesystemFail (err) { alert("FS: DATA FAIL"); console.log(err.code);};
      function fileEntryFail (err) { alert("File entry: FAIL"); };
      function writeFail (err) { alert("Writing: DATA FAIL"); };
      function readFail (err) { alert("Reading: DATA FAIL"); };

      //data test via var
      var filetowrite =  `{"message": "THIS IS SIMPLE TEST MESSAGE"}`

    };

Now some important closing notes

It is obviously useless to keep both start read and start write which test on the same file or data. Either write the file and then read it or take it locally and read it directly. So for your tests comment one of the two at a time.

It's also stupid to keep them separate because it would be easy to optimize the system by calling the file system only once.

However, I left them separate to give a clear and functional example to those who, like me, are stuck on logic.

Update

Solution:

While waiting for the whole plugin I am testing to be built:

A) you have to "unlock" access to files in config.xml as I explained above.

B) cordova-file-plugin can only write, read, delete files in the permanent memory inside the app. (I will release a better model than the one above as soon as I can)

C) fetch does not work in any case. BE CAREFUL, it only works on the browser but not in the app

D-1) I am testing the writing and deleting of files in the www. I still need time.

D-2) it is possible to read through an XML request the file in the www in the following way:

var _filename = 'MYFILENAMEINWWW.txt',
    _mimetype = 'text/plain'; // or application/json

    function readfromwww(_mimetype,_filename,callback)
    {

        var request = new XMLHttpRequest();
            request.overrideMimeType(_mimetype );
            request.open("GET", _filename );
            request.onreadystatechange = () =>
            {

              if(request.status > 300)
              {
                if(rs==404) console.log('file not found in www: ',request.status);
                else console.log('error on request: ',request.status);
              }

              else if(request.responseText!=undefined && request.responseText!='')
              {

                //from json string to js obj content
                if(_mimetype == "application/json")
                  callback(JSON.parse(request.responseText));

                //return string into your file
                else
                  callback(request.responseText);

              }

            }
            request.send();

          }

    }

          // now you can read a file in www calling the method:

          readfromwww('text/plain', 'test.txt',
            filecontent => {

               console.log('OLE! INTO THE FILE: ',filecontent);

               //not filecontent is the content of your file but... remember... the contents is loaded via ajax, isn't easy to storize it out this function.

            });

Body:
I created a function that returns a promise with a string, then it can be parsed with JSON or whatever you want.

This solution was checked only on Android platform

I also tried to do this with fetch and XMLHttpRequest, but there were no successful results.

Typescript:

export function readFileFromWWW(filename: string) {
  return new Promise<string>((resolve, reject) => {
    getWWWFileEntry(filename, (fileEntry) => {
      ;(fileEntry as FileEntry).file(
        (file) => {
          const reader = new FileReader()

          reader.onloadend = () => {
            resolve(reader.result as string)
          }

          reader.readAsText(file)
        },
        () => {
          reject(new Error('read went wrong'))
        }
      )
    })
  })
}

function getWWWFileEntry(
  filename: string,
  callback: (fileEntry: Entry) => void
) {
  window.resolveLocalFileSystemURL(
    `${window.cordova.file.applicationDirectory}www/${filename}`,
    callback
  )
}


问:
How to read textbox.Text value from another thread in WPF?
In my WPF form I have a textbox.

When a timer elapses, the content of the textbox needs to be fetched.

The timer elapsed is working in a different thread then the UI.

The question is kinda two-fold:

What is the easiest, most readable way to read the value from a GUI thread cross thread (I found several and they look too verbose for what should be something really basic)?

Can't I read the text in a non-blocking way? I don't care about thread safety in this case.

--EDIT--

I used the Dispatcher, but had a more verbose call then what John had:

```<code>originalTextBox.Dispatcher.Invoke(
    DispatcherPriority.Normal,
    (ThreadStart) delegate{text=originalTextBox.Text;}
);
</code>```

Wouldn't mind even terser though. Accessing a text property should be utterly basic.

答:
You can either:

Use the Dispatcher to schedule a message to execute on the UI thread from a background thread. A DispatcherPriority of Send will get you the fastest response possible.

Use a DispatcherTimer to periodically execute messages on the UI thread.

Use a OneWayToSource binding to connect the Text property to a property on your background component. That way, you won't have to do any work to get the property value - it will already have been supplied to your component.

OwnerDisplayName: boris callens

ContentLicense: CC BY-SA 2.5

Body:
In my WPF form I have a textbox.

When a timer elapses, the content of the textbox needs to be fetched.

The timer elapsed is working in a different thread then the UI.

The question is kinda two-fold:

What is the easiest, most readable way to read the value from a GUI thread cross thread (I found several and they look too verbose for what should be something really basic)?

Can't I read the text in a non-blocking way? I don't care about thread safety in this case.

--EDIT--

I used the Dispatcher, but had a more verbose call then what John had:

originalTextBox.Dispatcher.Invoke(
    DispatcherPriority.Normal,
    (ThreadStart) delegate{text=originalTextBox.Text;}
);

Wouldn't mind even terser though. Accessing a text property should be utterly basic.

LastEditorDisplayName: boris callens

OwnerDisplayName: Kent Boogaart

LastEditorDisplayName: Kent Boogaart


问:
On click function to toggleClass exclude click on children
Basically trying to remove/toggle the 'active' class from the div, but if I click inside the children of 'parent-div' the function happens as well, and it should only work on the parent-div. It's a fixed background that should act as "click outside to close" function, and I can't disable clicking inside the children because there is a form inside in them.

Tried event.stopPropagation as well but that didn't do anything.

HTML

```<code><div class="ims-search active">
  <div class="ims-search-content">
    <div class=ims-search-input">
      <form>
      </form>
    </div>
  </div>
</div>
</code>```
```<code>$(".ims-search").click(function(event){
    if (!$(event.target).is('.ims-search .active')){
        $(this).removeClass('active');
    }
});
</code>```

答:
You can compare event.target === event.currentTarget to see if the element clicked is the one the event is assigned to.

Events bubble up: .target will match the actually clicked element, while .currentTarget will match the selector / element the event is assigned to.

Giving:

$(".parent-div").click(function(event) {
  if (event.target === event.currentTarget)
    $(this).hide();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent-div { height:150px; width:150px; border:1px solid blue; position:relative; }
#inner { left:50px;top:50px;height:50px;width:50px; background-color: pink; position:relative; }</code>```

  don't click here

```

Body:
Basically trying to remove/toggle the 'active' class from the div, but if I click inside the children of 'parent-div' the function happens as well, and it should only work on the parent-div. It's a fixed background that should act as "click outside to close" function, and I can't disable clicking inside the children because there is a form inside in them.

Tried event.stopPropagation as well but that didn't do anything.

HTML

      <form>
      </form>

$(".ims-search").click(function(event){
    if (!$(event.target).is('.ims-search .active')){
        $(this).removeClass('active');
    }
});

Body:
You can compare event.target === event.currentTarget to see if the element clicked is the one the event is assigned to.

Events bubble up: .target will match the actually clicked element, while .currentTarget will match the selector / element the event is assigned to.

Giving:

$(".parent-div").click(function(event) {
  if (event.target === event.currentTarget)
    $(this).hide();
});

.parent-div { height:150px; width:150px; border:1px solid blue; position:relative; }
#inner { left:50px;top:50px;height:50px;width:50px; background-color: pink; position:relative; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent-div">
 <div id="inner">
  don't click here
 </div>
</div>


问:
data not inserting into firebase realtime database
The code executes without any error but firebase realtime database shows :-

testapp-a212c-default-rtdb: null

I have created the model class User. How do I insert data into firebase realtime database?

```<code>public class MainActivity extends AppCompatActivity {

private DatabaseReference mDatabase;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mDatabase = FirebaseDatabase.getInstance().getReference();
    writeNewUser("123","asdf","asdf@gmail.com");
 }

 public void writeNewUser(String userId, String name, String email) {
    User user = new User(name, email);

    mDatabase.child("users").child(userId).setValue(user);
}
</code>```

答: In my case, I forgot to insert stream: FirebaseAuth.instance.onAuthStateChanged, in main.dart file. Which is ended up with uploading data to firebase Real Time Database.

Body:
The code executes without any error but firebase realtime database shows :-

testapp-a212c-default-rtdb: null

I have created the model class User. How do I insert data into firebase realtime database?

public class MainActivity extends AppCompatActivity {

private DatabaseReference mDatabase;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mDatabase = FirebaseDatabase.getInstance().getReference();
    writeNewUser("123","asdf","asdf@gmail.com");
 }

 public void writeNewUser(String userId, String name, String email) {
    User user = new User(name, email);

    mDatabase.child("users").child(userId).setValue(user);
}


问:
Kotlin-Android serialize json without using third party library
is there any solution other than Moshi, Gson, KotlinX-Serialization to serialize json in Android? We should not add anything to build.gradle while using technology. We should not download a library from here.

Is there a method on Android just like Codable on iOS? Also, I think how we should do this part is important since Converter will be passed when using it with Retrofit.

Does anyone have experience and advice on this subject?

答:
You can use JSONObject for that.

```<code>val json = JSONObject("""{"some":"json"}""")
</code>```

However, easiest is to use one of the third party frameworks you mentioned to do this.

Body:
You can use JSONObject for that.

val json = JSONObject("""{"some":"json"}""")

However, easiest is to use one of the third party frameworks you mentioned to do this.


问:
In ggplot2, how to add a white hole in the middle of the pie chart
In ggplot2, how to add a white hole in the middle of the pie chart?
Please refer to below code for current plot (the left plot) . Thanks!

```<code>library(tidyverse)
pie_data <- data.frame(category=c('A','B','C','A','B','C'),
                       year=c(2020,2020,2020,2021,2021,2021),
                       sales=c(40,30,20,10,15,10))

pie_data %>% ggplot(aes(x=factor(year),y=sales,fill=category))+
  geom_col(position='fill',width=1,color='white')+
 coord_polar(theta = 'y')+
  theme_void()
</code>```

答:
You can add an hollow bar at the center:

```<code>  pie_data %>% ggplot(aes(x=factor(year),y=sales,fill=category))+
      geom_col(position='fill',width=1,color='white')+
      coord_polar(theta = 'y')+
      geom_col(aes(x=0,y=0))+
      theme_void()
</code>```

if you want a larger circle, use a negative x coordinate:

```<code>geom_col(aes(x=-1,y=0))
</code>```

Body:
In ggplot2, how to add a white hole in the middle of the pie chart?
Please refer to below code for current plot (the left plot) . Thanks!

library(tidyverse)
pie_data <- data.frame(category=c('A','B','C','A','B','C'),
                       year=c(2020,2020,2020,2021,2021,2021),
                       sales=c(40,30,20,10,15,10))

pie_data %>% ggplot(aes(x=factor(year),y=sales,fill=category))+
  geom_col(position='fill',width=1,color='white')+
 coord_polar(theta = 'y')+
  theme_void()

Body:
You can add an hollow bar at the center:

  pie_data %>% ggplot(aes(x=factor(year),y=sales,fill=category))+
      geom_col(position='fill',width=1,color='white')+
      coord_polar(theta = 'y')+
      geom_col(aes(x=0,y=0))+
      theme_void()

if you want a larger circle, use a negative x coordinate:

geom_col(aes(x=-1,y=0))


问:
JsonBackReference is working for collection
in official documentation I have read that jsonbackreference cannot be applied for collection

Value type of the property must be a bean: it can not be a Collection,
  Map, Array or enumeration.

but is is working on my machine for collection does anybody know why?

And by the way I found in tutorial that they are using it for collection.

答:
Well the tutorial which you have linked stated that:
We can switch around the @JsonManaged and @JsonbackReference annotations when we are trying to do the serialization.

But when we try to do the same when we try to do the deserialization then hibernate is gonna throw an exception.

Something like this:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (java.util.List<io.adarsh.springdatajpaexp.model.PayStub>) not compatible with managed type (io.adarsh.springdatajpaexp.model.PayStub).

which means that during the deserialization we can not annotate @JsonBackReference on the List or set because, during deserialization, its value is set to an instance that has the "managed" (forward) link.

So let's say first we have set the

```<code>@Entity
public class Employee {

@OneToMany
@JsonManagedReference
List<PayStub> pasytubs;

}
and,
@Entity
public class PayStub {

@ManyToOne
@JsonBackReference
Employee employee;

}
</code>```

so during deserialization hibernate will get to know that here parent is Employee and the child is PayStub which is having the @JsonBackReference, so while deserializing it will try to set the value of the employee field which is in the PayStub entity with the one which has the "managed" (forward) link (Employee entity) and it will successfully perform it.

But when we will switch the annotation

```<code>@Entity
public class Employee {

@OneToMany
@JsonBackReference
List<PayStub> pasytubs;

}
and,
@Entity
public class PayStub {

@ManyToOne
@JsonManagedReference
Employee employee;

}
</code>```

Now when it goes to the @JsonBackRefernece and tries to set the value with the one which has managed reference (so it can't set a List value with a normal bean value(Paystub)).

Body:
Well the tutorial which you have linked stated that:
We can switch around the @JsonManaged and @JsonbackReference annotations when we are trying to do the serialization.

But when we try to do the same when we try to do the deserialization then hibernate is gonna throw an exception.

Something like this:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (java.util.List<io.adarsh.springdatajpaexp.model.PayStub>) not compatible with managed type (io.adarsh.springdatajpaexp.model.PayStub).

which means that during the deserialization we can not annotate @JsonBackReference on the List or set because, during deserialization, its value is set to an instance that has the "managed" (forward) link.

So let's say first we have set the

@Entity
public class Employee {

@OneToMany
@JsonManagedReference
List<PayStub> pasytubs;

}
and,
@Entity
public class PayStub {

@ManyToOne
@JsonBackReference
Employee employee;

}

so during deserialization hibernate will get to know that here parent is Employee and the child is PayStub which is having the @JsonBackReference, so while deserializing it will try to set the value of the employee field which is in the PayStub entity with the one which has the "managed" (forward) link (Employee entity) and it will successfully perform it.

But when we will switch the annotation

@Entity
public class Employee {

@OneToMany
@JsonBackReference
List<PayStub> pasytubs;

}
and,
@Entity
public class PayStub {

@ManyToOne
@JsonManagedReference
Employee employee;

}

Now when it goes to the @JsonBackRefernece and tries to set the value with the one which has managed reference (so it can't set a List value with a normal bean value(Paystub)).


问:
Change the condition in while loop pyhton
Instead of repeating the "if while block" due to different condition of variable "Default_factor" for every per 12 i would prefer to find a solution to change the condition ever 12th loop since I otherwise need to construct these blocks of "if while" until I have 500</p>
```<code>if Months >= 1 :
    while per <= 12:

        Defaults = (
            1-(1-PdefaultValue['Default_factor'].iloc[0])**(1/12))*PrincipalAmount
        ActualPrincipal = (PrincipalAmount-(1-(1-PdefaultValue['Default_factor'].iloc[0])**(
            1/12))*PrincipalAmount)/(Months+Exp_ext-per+1)
        RecoovyWithLag = ((1-(1-PdefaultValue['Default_factor'].iloc[0])**(1/12))*PrincipalAmount) - (
            (1-(1-PdefaultValue['Default_factor'].iloc[0])**(1/12))*PrincipalAmount*Severity)
        ActualInterest = -npv.ipmt(Interest_Rate/12, 1, Months, PrincipalAmount-Defaults)
        CashInterest = ActualInterest - Cap_int
        PrincipalAmount = PrincipalAmount - ActualPrincipal - Defaults
        TotalCashFlow = RecoovyWithLag + ActualPrincipal + CashInterest
        CF.append(TotalCashFlow)

        per += 1

if Months >= 13:
    while per > 12 and per <= 24:
        Defaults = (
            1-(1-PdefaultValue['Default_factor'].iloc[1])**(1/12))*PrincipalAmount
        ActualPrincipal = (PrincipalAmount-(1-(1-PdefaultValue['Default_factor'].iloc[1])**(
            1/12))*PrincipalAmount)/(Months+Exp_ext-per+1)
        RecoovyWithLag = ((1-(1-PdefaultValue['Default_factor'].iloc[1])**(1/12))*PrincipalAmount) - (
            (1-(1-PdefaultValue['Default_factor'].iloc[1])**(1/12))*PrincipalAmount*Severity)
        ActualInterest = - npv.ipmt(Interest_Rate/12, 1, Months, PrincipalAmount-Defaults)
        CashInterest = ActualInterest - Cap_int
        PrincipalAmount = PrincipalAmount - ActualPrincipal - Defaults
        TotalCashFlow = RecoovyWithLag + ActualPrincipal + CashInterest
        CF.append(TotalCashFlow)

        per += 1
</code>```

答:
It's a bit hard to tell what your code is doing, but I believe you're asking for a way to execute a certain bit of code on every 12th iteration of a loop. Here's a generic example of how you might do this:

for month in range(100):
    if month % 12 == 0:
        print(month)

```
<p>Which prints the following:</p>
<pre class="lang-py prettyprint-override"><code>0
12
24
36
48
60
72
84
96
</code>```

This is because of the 'modulo' operator %, which calculates the remainder when dividing one number by another. With the line if month % 12 == 0: we're checking if the current value of month can be divided by 12 without any remainder, effectively returning True every 12 iterations (plus the 0th one, watch out for that).

Body:
Instead of repeating the "if while block" due to different condition of variable "Default_factor" for every per 12 i would prefer to find a solution to change the condition ever 12th loop since I otherwise need to construct these blocks of "if while" until I have 500

if Months >= 1 :
    while per <= 12:

        Defaults = (
            1-(1-PdefaultValue['Default_factor'].iloc[0])**(1/12))*PrincipalAmount
        ActualPrincipal = (PrincipalAmount-(1-(1-PdefaultValue['Default_factor'].iloc[0])**(
            1/12))*PrincipalAmount)/(Months+Exp_ext-per+1)
        RecoovyWithLag = ((1-(1-PdefaultValue['Default_factor'].iloc[0])**(1/12))*PrincipalAmount) - (
            (1-(1-PdefaultValue['Default_factor'].iloc[0])**(1/12))*PrincipalAmount*Severity)
        ActualInterest = -npv.ipmt(Interest_Rate/12, 1, Months, PrincipalAmount-Defaults)
        CashInterest = ActualInterest - Cap_int
        PrincipalAmount = PrincipalAmount - ActualPrincipal - Defaults
        TotalCashFlow = RecoovyWithLag + ActualPrincipal + CashInterest
        CF.append(TotalCashFlow)

        per += 1

if Months >= 13:
    while per > 12 and per <= 24:
        Defaults = (
            1-(1-PdefaultValue['Default_factor'].iloc[1])**(1/12))*PrincipalAmount
        ActualPrincipal = (PrincipalAmount-(1-(1-PdefaultValue['Default_factor'].iloc[1])**(
            1/12))*PrincipalAmount)/(Months+Exp_ext-per+1)
        RecoovyWithLag = ((1-(1-PdefaultValue['Default_factor'].iloc[1])**(1/12))*PrincipalAmount) - (
            (1-(1-PdefaultValue['Default_factor'].iloc[1])**(1/12))*PrincipalAmount*Severity)
        ActualInterest = - npv.ipmt(Interest_Rate/12, 1, Months, PrincipalAmount-Defaults)
        CashInterest = ActualInterest - Cap_int
        PrincipalAmount = PrincipalAmount - ActualPrincipal - Defaults
        TotalCashFlow = RecoovyWithLag + ActualPrincipal + CashInterest
        CF.append(TotalCashFlow)

        per += 1

Body:
It's a bit hard to tell what your code is doing, but I believe you're asking for a way to execute a certain bit of code on every 12th iteration of a loop. Here's a generic example of how you might do this:

for month in range(100):
    if month % 12 == 0:
        print(month)

Which prints the following:

0
12
24
36
48
60
72
84
96

This is because of the 'modulo' operator %, which calculates the remainder when dividing one number by another. With the line if month % 12 == 0: we're checking if the current value of month can be divided by 12 without any remainder, effectively returning True every 12 iterations (plus the 0th one, watch out for that).


问:
MTLocation how-to
Hi I just came across MTLocation here: https://github.com/darkseed/MTLocation.

I want to use a locate me button in my app which will be located in navigation bar and when pressed will move the map to current location.

The author proposes to use the code like this:

```<code>// Configure Location Manager
[MTLocationManager sharedInstance].locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[MTLocationManager sharedInstance].locationManager.distanceFilter = kCLDistanceFilterNone;
[MTLocationManager sharedInstance].locationManager.headingFilter = 5; // 5 Degrees

// create locate-me item
MTLocateMeBarButtonItem *locateMeItem = [[[MTLocateMeBarButtonItem alloc] initWithLocationStatus:MTLocationStatusIdle] autorelease];
// set delegate that is called when mode of Button changes
locateMeItem.delegate = [MTLocationManager sharedInstance];
// add target-action
[locateMeItem addTarget:self action:@selector(myCustomSelector:) forControlEvents:UIControlEventTouchUpInside];
// disable heading
locateMeItem.headingEnabled = NO;

// create array with ToolbarItems
NSArray *toolbarItems = [NSArray arrayWithObject:locateMeItem];
// set toolbar items
[self.toolbar setItems:toolbarItems animated:NO];
</code>```

which is great to show a locate me button in toolbar but how can we make this work to show current location through gps? I guess tha we have to implement myCustomSelector method but I do not know how. Any help?

答:
Make sure that you have

```<code>self.mapView.showsUserLocation = YES;
</code>```

And then implement myCustomSelector:, for example like this:

```<code>- (void) myCustomSelector:(MTLocateMeBarButtonItem*) button {
    [self.mapView setCenterCoordinate:self.mapView.userLocation.location.coordinate];
}
</code>```

You'll need to take care of a proper functionality at different button modes (whether MTLocateMeBarButton is Idle, or something else), but that should give you a direction.

Title: MTLocation how-to

Body:
Hi I just came across MTLocation here: https://github.com/darkseed/MTLocation.

I want to use a locate me button in my app which will be located in navigation bar and when pressed will move the map to current location.

The author proposes to use the code like this:

// Configure Location Manager
[MTLocationManager sharedInstance].locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[MTLocationManager sharedInstance].locationManager.distanceFilter = kCLDistanceFilterNone;
[MTLocationManager sharedInstance].locationManager.headingFilter = 5; // 5 Degrees

// create locate-me item
MTLocateMeBarButtonItem *locateMeItem = [[[MTLocateMeBarButtonItem alloc] initWithLocationStatus:MTLocationStatusIdle] autorelease];
// set delegate that is called when mode of Button changes
locateMeItem.delegate = [MTLocationManager sharedInstance];
// add target-action
[locateMeItem addTarget:self action:@selector(myCustomSelector:) forControlEvents:UIControlEventTouchUpInside];
// disable heading
locateMeItem.headingEnabled = NO;

// create array with ToolbarItems
NSArray *toolbarItems = [NSArray arrayWithObject:locateMeItem];
// set toolbar items
[self.toolbar setItems:toolbarItems animated:NO];

which is great to show a locate me button in toolbar but how can we make this work to show current location through gps? I guess tha we have to implement myCustomSelector method but I do not know how. Any help?

Body:
Make sure that you have

self.mapView.showsUserLocation = YES;

And then implement myCustomSelector:, for example like this:

- (void) myCustomSelector:(MTLocateMeBarButtonItem*) button {
    [self.mapView setCenterCoordinate:self.mapView.userLocation.location.coordinate];
}

You'll need to take care of a proper functionality at different button modes (whether MTLocateMeBarButton is Idle, or something else), but that should give you a direction.


问:
Transaction Recent Blockhash Required - Phantom Wallet Solana
```<code>Uncaught (in promise) WalletSignTransactionError: Transaction recentBlockhash required
at PhantomWalletAdapter.signTransaction (adapter.ts:215:1)
at async WalletProvider.tsx:247:1
at async mintNFT (luckoo.tsx:100:1)
</code>```

I got this when im trying to send transaction using solana wallet, what should i do?

答:
You need to provide a recentBlockhash in your transaction in order for it to be signed.  Most likely, you need to fetch a blockhash and add it before signing the transaction using getLatestBlockhash, ie:

```<code>let blockhash = (await connection.getLatestBlockhash('finalized')).blockhash;
transaction.recentBlockhash = blockhash;
</code>```

Previously, you would use the similar deprecated function getRecentBlockhash:

```<code>let blockhash = await connection.getRecentBlockhash('finalized').blockhash;
transaction.recentBlockhash = blockhash;
</code>```

Your better bet is to directly use sendTransaction, which does all of that work for you.  As you can see in the source code, sendTransaction is filling in the recent blockhash if it isn't already present: https://github.com/solana-labs/wallet-adapter/blob/a5b1ebd70ae9753d188fec60e95e252402f3f371/packages/core/base/src/signer.ts#L13

More info about blockhashes: https://docs.solana.com/developing/programming-model/transactions#recent-blockhash

More info about fetching blockhashes: https://docs.solana.com/developing/clients/jsonrpc-api#getlatestblockhash

More info about using sendTransaction: https://github.com/solana-labs/wallet-adapter#usage

Body:
Uncaught (in promise) WalletSignTransactionError: Transaction recentBlockhash required
at PhantomWalletAdapter.signTransaction (adapter.ts:215:1)
at async WalletProvider.tsx:247:1
at async mintNFT (luckoo.tsx:100:1)

I got this when im trying to send transaction using solana wallet, what should i do?

Body:
You need to provide a recentBlockhash in your transaction in order for it to be signed.  Most likely, you need to fetch a blockhash and add it before signing the transaction using getLatestBlockhash, ie:

let blockhash = (await connection.getLatestBlockhash('finalized')).blockhash;
transaction.recentBlockhash = blockhash;

Previously, you would use the similar deprecated function getRecentBlockhash:

let blockhash = await connection.getRecentBlockhash('finalized').blockhash;
transaction.recentBlockhash = blockhash;

Your better bet is to directly use sendTransaction, which does all of that work for you.  As you can see in the source code, sendTransaction is filling in the recent blockhash if it isn't already present: https://github.com/solana-labs/wallet-adapter/blob/a5b1ebd70ae9753d188fec60e95e252402f3f371/packages/core/base/src/signer.ts#L13

More info about blockhashes: https://docs.solana.com/developing/programming-model/transactions#recent-blockhash

More info about fetching blockhashes: https://docs.solana.com/developing/clients/jsonrpc-api#getlatestblockhash

More info about using sendTransaction: https://github.com/solana-labs/wallet-adapter#usage


问:
Self Join to get employee manager name
Hello I have a Employee Table with following columns

```<code>Emp_id, Emp_Name and Mgr_id.
</code>```

I am trying to create a view which will list

Emp_id, Emp_name, Mgr_id and Mgr_name (by cross joining the Employee table). I tried outer join, inner join etc, but I am not able to get it right.

Any help is highly appreciated.

```<code>CREATE TABLE [dbo].[tblEmployeeDetails](
[emp_id] [bigint] NOT NULL,
[emp_name] [nvarchar](200) NULL,
[emp_mgr_id] [bigint] NULL, CONSTRAINT [PK_tblEmployeeDetails] PRIMARY KEY CLUSTERED (
[emp_id] ASC )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] ) ON [PRIMARY]
</code>```

答:
```<code>select distinct( e1.id), e1.emp_name from employee as e1
inner join employee as e2 on e1.id = e2.manager_id;
</code>```

Title: Self Join to get employee manager name

Body:
Hello I have a Employee Table with following columns

Emp_id, Emp_Name and Mgr_id.

I am trying to create a view which will list

Emp_id, Emp_name, Mgr_id and Mgr_name (by cross joining the Employee table). I tried outer join, inner join etc, but I am not able to get it right.

Any help is highly appreciated.

CREATE TABLE [dbo].[tblEmployeeDetails](
[emp_id] [bigint] NOT NULL,
[emp_name] [nvarchar](200) NULL,
[emp_mgr_id] [bigint] NULL, CONSTRAINT [PK_tblEmployeeDetails] PRIMARY KEY CLUSTERED (
[emp_id] ASC )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] ) ON [PRIMARY]


问:
Computed interface values in TypeScript?
So basically, I was looking around discordjs's typings folder and found this:

```<code>export interface ClientEvents {
  ...
  messageCreate: [message: Message] <- what?
  messageDelete: [message: Message | PartialMessage]
}
</code>```

What exactly are they trying to do here? I've heard of index signatures, like in this example here:

```<code>interface Foo {
  [bar: string]: any
}
</code>```

But I've never seen any syntax that resembles this in both TS and JS.

答:
Credits to jonrsharpe's comment under the question. The syntax mentioned was a variation of a tuple in TypeScript 4.0 which includes labels:

Regular tuple:

```<code>// has no indication of parameter names
type Range = [number, number]
</code>```

Labelled tuple:

```<code>type Range = [start: number, end: number]
</code>```
```<code>// spreading this labelled tuple in a function's parameters...
function getRange(...range: Range)

// ... results in the following at compile time:
function getRange(start: number, end: number)
</code>```

Very cool!

Body:
So basically, I was looking around discordjs's typings folder and found this:

export interface ClientEvents {
  ...
  messageCreate: [message: Message] <- what?
  messageDelete: [message: Message | PartialMessage]
}

What exactly are they trying to do here? I've heard of index signatures, like in this example here:

interface Foo {
  [bar: string]: any
}

But I've never seen any syntax that resembles this in both TS and JS.

Body:
Credits to jonrsharpe's comment under the question. The syntax mentioned was a variation of a tuple in TypeScript 4.0 which includes labels:

Regular tuple:

// has no indication of parameter names
type Range = [number, number]

Labelled tuple:

type Range = [start: number, end: number]

// spreading this labelled tuple in a function's parameters...
function getRange(...range: Range)

// ... results in the following at compile time:
function getRange(start: number, end: number)

Very cool!


问:
Format an amount to a specific display
I have a measure in Tabular that calculates an amount I want the display to be like below :

```<code>1 990K
</code>```

I tried to use FORMAT but in vain.

```<code>MyMeasure :=FORMAT ( SUM(MyTable[Salary]), "#, 0.,,.0#K" )& "€"
</code>```

答:
Try the following in the Properties :

```<code>#,##0, K€
</code>```

Title: Format an amount to a specific display

Body:
I have a measure in Tabular that calculates an amount I want the display to be like below :

1 990K

I tried to use FORMAT but in vain.

MyMeasure :=FORMAT ( SUM(MyTable[Salary]), "#, 0.,,.0#K" )& "€"

Body:
Try the following in the Properties :

#,##0, K€


问:
Replace the element with the searched value in an array of objects in Javascript
Having the following array of objects:

```<code>const input = [ {id: 3, data: {name: 'john'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} }
              ];
</code>```

I want to write a method that recevies a new object, if the object's id is in the array, it replaces that one with the new one, otherwise it creates a new object.

For example, if the method receives this object: {id: 1, data: {name: 'maria' }}, it will add it to the array, so the array will look like:

```<code>const input = [ {id: 3, data: {name: 'john'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} },
                {id: 2, data: {name: 'maria'} }
              ];
</code>```

If it receives {id: 3, data: {name: 'jack' }} it should replace the object with id=3 so the result would be:

```<code>const input = [ {id: 3, data: {name: 'jack'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} },
                {id: 2, data: {name: 'maria'} }
              ];
</code>```

The code:

```<code>function doMagic(input, newObj) {
  if (input.some(el => el.id === newObj.id) {
    // replace it
  } else {
    // add the object to the array
  }
}
</code>```

答:
You can do it this way:

function doMagic(input, newObj) {
 const i = input.findIndex(element => element.id === newObj.id);
  if (i > -1) input[i] = newObj;
  else input.push(newObj);
}

const input = [ {id: 3, data: {name: 'jack'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} }
              ];

newObj = {id: 1, data: {name: 'maria' }};
oldObj = {id: 3, data: {name: 'john' }}

doMagic(input, newObj);

console.log(input);

doMagic(input, oldObj);

console.log(input);```

Body:
Having the following array of objects:

const input = [ {id: 3, data: {name: 'john'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} }
              ];

I want to write a method that recevies a new object, if the object's id is in the array, it replaces that one with the new one, otherwise it creates a new object.

For example, if the method receives this object: {id: 1, data: {name: 'maria' }}, it will add it to the array, so the array will look like:

const input = [ {id: 3, data: {name: 'john'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} },
                {id: 2, data: {name: 'maria'} }
              ];

If it receives {id: 3, data: {name: 'jack' }} it should replace the object with id=3 so the result would be:

const input = [ {id: 3, data: {name: 'jack'} },
                {id: 6, data: {name: 'mike'} },
                {id: 2, data: {name: 'anna'} },
                {id: 2, data: {name: 'maria'} }
              ];

The code:

function doMagic(input, newObj) {
  if (input.some(el => el.id === newObj.id) {
    // replace it
  } else {
    // add the object to the array
  }
}


问:
Error : I want to convert the file from XLSX to csv using google script
Hi Facing error while running code of Coverting excel to csv. Please guide what to edit to solve the query.</p>
```<code> function makeCSV() {
 var SourceFolder = DriveApp.getFolderById("1aoonhCebvI5DddvJVGTzBvWs2BPn_yXN")
 var DestinationFolder = DriveApp.getFolderById("1LB0Em4vYFJV8vJIEiLt6Tg5pnzPATZEj")
 var searchQuery = "mimeType='" + MimeType.MICROSOFT_EXCEL + "' or mimeType='" +
  MimeType.MICROSOFT_EXCEL_LEGACY + "'";
 var sourceFiles = SourceFolder.searchFiles(searchQuery);

 var now = new Date();
var properties = PropertiesService.getScriptProperties();
 var cutoff_datetime = properties.getProperty('last_execution_time');
if(cutoff_datetime)
 cutoff_datetime = new Date(cutoff_datetime);
while (sourceFiles.hasNext()){
var sourceFile = sourceFiles.next();

 if(!cutoff_datetime || sourceFile.getDateCreated() > cutoff_datetime){
  var fileId = sourceFile.getId();

var Spreadsheet = Drive.Files.copy({mimeType: MimeType.csv, parents:
[{id:"1LB0Em4vYFJV8vJIEiLt6Tg5pnzPATZEj"}]}, fileId);
}
}
properties.setProperty('last_execution_time',now.toString());
}
</code>```

答:
Unfortunately, XLSX data cannot be directly converted to CSV data using Google Apps Script. And, Drive.Files.copy can convert non-Google Docs files to Google Docs files. Please be careful about this. I think that this is the reason for your current issue. In order to convert XLSX data to CSV data using Google Apps Script, it is required to do the following flow.

Convert XLSX data to Google Spreadsheet.

Convert Google Spreadsheet to CSV data.

Remove Google Spreadsheet.

When this flow is reflected in your script, it becomes as follows.

Modified script:

function makeCSV() {
  var SourceFolder = DriveApp.getFolderById("1aoonhCebvI5DddvJVGTzBvWs2BPn_yXN");
  var DestinationFolder = DriveApp.getFolderById("1LB0Em4vYFJV8vJIEiLt6Tg5pnzPATZEj");
  var searchQuery = "mimeType='" + MimeType.MICROSOFT_EXCEL + "' or mimeType='" + MimeType.MICROSOFT_EXCEL_LEGACY + "'";
  var sourceFiles = SourceFolder.searchFiles(searchQuery);
  var now = new Date();
  var properties = PropertiesService.getScriptProperties();
  var cutoff_datetime = properties.getProperty('last_execution_time');
  if (cutoff_datetime) cutoff_datetime = new Date(cutoff_datetime);
  var token = ScriptApp.getOAuthToken();
  while (sourceFiles.hasNext()) {
    var sourceFile = sourceFiles.next();
    if (!cutoff_datetime || sourceFile.getDateCreated() > cutoff_datetime) {
      var fileId = sourceFile.getId();
      var ssId = Drive.Files.copy({mimeType: MimeType.GOOGLE_SHEETS, parents: [{ id: "1LB0Em4vYFJV8vJIEiLt6Tg5pnzPATZEj" }]}, fileId).id;
      var url = "https://docs.google.com/spreadsheets/export?exportFormat=csv&id=" + ssId;
      var blob = UrlFetchApp.fetch(url, {headers: {authorization: "Bearer " + token}}).getBlob();
      DestinationFolder.createFile(blob.setName(sourceFile.getName().split(".")[0] + ".csv"));
      DriveApp.getFileById(ssId).setTrashed(true);
    }
  }
  properties.setProperty('last_execution_time', now.toString());
}
```

When this script is run, the XLSX data is converted to Google Spreadsheet, and Google Spreadsheet is converted to CSV data. The CSV file is created to DestinationFolder folder.

Note:

This script used Drive API. So, please enable Drive API at Advanced Google services.

References:

Files: copy

fetch(url, params)

Body:
Hi Facing error while running code of Coverting excel to csv. Please guide what to edit to solve the query.

 function makeCSV() {
 var SourceFolder = DriveApp.getFolderById("1aoonhCebvI5DddvJVGTzBvWs2BPn_yXN")
 var DestinationFolder = DriveApp.getFolderById("1LB0Em4vYFJV8vJIEiLt6Tg5pnzPATZEj")
 var searchQuery = "mimeType='" + MimeType.MICROSOFT_EXCEL + "' or mimeType='" +
  MimeType.MICROSOFT_EXCEL_LEGACY + "'";
 var sourceFiles = SourceFolder.searchFiles(searchQuery);

 var now = new Date();
var properties = PropertiesService.getScriptProperties();
 var cutoff_datetime = properties.getProperty('last_execution_time');
if(cutoff_datetime)
 cutoff_datetime = new Date(cutoff_datetime);
while (sourceFiles.hasNext()){
var sourceFile = sourceFiles.next();

 if(!cutoff_datetime || sourceFile.getDateCreated() > cutoff_datetime){
  var fileId = sourceFile.getId();

var Spreadsheet = Drive.Files.copy({mimeType: MimeType.csv, parents:
[{id:"1LB0Em4vYFJV8vJIEiLt6Tg5pnzPATZEj"}]}, fileId);
}
}
properties.setProperty('last_execution_time',now.toString());
}

Body:
Unfortunately, XLSX data cannot be directly converted to CSV data using Google Apps Script. And, Drive.Files.copy can convert non-Google Docs files to Google Docs files. Please be careful about this. I think that this is the reason for your current issue. In order to convert XLSX data to CSV data using Google Apps Script, it is required to do the following flow.

Convert XLSX data to Google Spreadsheet.

Convert Google Spreadsheet to CSV data.

Remove Google Spreadsheet.

When this flow is reflected in your script, it becomes as follows.

Modified script:

function makeCSV() {
  var SourceFolder = DriveApp.getFolderById("1aoonhCebvI5DddvJVGTzBvWs2BPn_yXN");
  var DestinationFolder = DriveApp.getFolderById("1LB0Em4vYFJV8vJIEiLt6Tg5pnzPATZEj");
  var searchQuery = "mimeType='" + MimeType.MICROSOFT_EXCEL + "' or mimeType='" + MimeType.MICROSOFT_EXCEL_LEGACY + "'";
  var sourceFiles = SourceFolder.searchFiles(searchQuery);
  var now = new Date();
  var properties = PropertiesService.getScriptProperties();
  var cutoff_datetime = properties.getProperty('last_execution_time');
  if (cutoff_datetime) cutoff_datetime = new Date(cutoff_datetime);
  var token = ScriptApp.getOAuthToken();
  while (sourceFiles.hasNext()) {
    var sourceFile = sourceFiles.next();
    if (!cutoff_datetime || sourceFile.getDateCreated() > cutoff_datetime) {
      var fileId = sourceFile.getId();
      var ssId = Drive.Files.copy({mimeType: MimeType.GOOGLE_SHEETS, parents: [{ id: "1LB0Em4vYFJV8vJIEiLt6Tg5pnzPATZEj" }]}, fileId).id;
      var url = "https://docs.google.com/spreadsheets/export?exportFormat=csv&id=" + ssId;
      var blob = UrlFetchApp.fetch(url, {headers: {authorization: "Bearer " + token}}).getBlob();
      DestinationFolder.createFile(blob.setName(sourceFile.getName().split(".")[0] + ".csv"));
      DriveApp.getFileById(ssId).setTrashed(true);
    }
  }
  properties.setProperty('last_execution_time', now.toString());
}

When this script is run, the XLSX data is converted to Google Spreadsheet, and Google Spreadsheet is converted to CSV data. The CSV file is created to DestinationFolder folder.

Note:

This script used Drive API. So, please enable Drive API at Advanced Google services.

References:

Files: copy

fetch(url, params)


问:
Picking the right metric for a model ending with TimeDistributed layer
I am trying to train a model for a NER task, with the model below. I am a bit confused about the right metrics to use here, I was expecting to use a classic CategoricalCrossentropy, but:

the model evaluates the accuracy to zero when training and testing

however when calculating the accuracy manually it's definitely not zero

I am not familiar with the TimeDistributed layer and I think the issue might be coming from here...
The shape of the output of the TD layer and the shape of my targets are the same

What am I am missing?

See below my code:

```<code>def init_model():
    input_ids = tf.keras.layers.Input(shape=(SEQ_LEN,),dtype='int32')
    attention_mask = tf.keras.layers.Input(shape=(SEQ_LEN,),dtype='int32')

    x = backbone({'input_ids':input_ids,
                 'attention_mask':attention_mask})[0]

    backbone.trainable = False

    x = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(units = 512,
                                                           activation = 'tanh',
                                                           #recurrent_dropout=.2,
                                                           dropout=.2,
                                                           return_sequences=True))(x)
    #x = tf.keras.layers.LayerNormalization()(x)
    x_res = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(units = 512,
                                                           activation = 'tanh',
                                                           #recurrent_dropout=.2,
                                                           dropout=.2,
                                                           return_sequences=True))(x)

    x = tf.keras.layers.add([x,x_res])
    output = tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(16,activation = 'softmax'))(x)

    model = tf.keras.models.Model(inputs={'input_ids':input_ids,
                                          'attention_mask':attention_mask},outputs=output)

    return model
</code>```

and the compiling:

```<code>loss = tf.keras.losses.CategoricalCrossentropy(name='categorical_crossentropy')
metric = tf.keras.metrics.Accuracy(name='accuracy')
opt = tf.keras.optimizers.Adam()

model.compile(optimizer=opt,loss=loss,metrics=[metric])
</code>```

答:
Note that tf.keras.metrics.Accuracy is the same as binary accuracy.

In your case, you are dealing with a multiclass problem with categorical cross-entropy as the objective function. To properly calculate the accuracy use tf.keras.metrics.CategoricalAccuracy.

Another related answer to the issue is here

Body:
I am trying to train a model for a NER task, with the model below. I am a bit confused about the right metrics to use here, I was expecting to use a classic CategoricalCrossentropy, but:

the model evaluates the accuracy to zero when training and testing

however when calculating the accuracy manually it's definitely not zero

I am not familiar with the TimeDistributed layer and I think the issue might be coming from here...
The shape of the output of the TD layer and the shape of my targets are the same

What am I am missing?

See below my code:

def init_model():
    input_ids = tf.keras.layers.Input(shape=(SEQ_LEN,),dtype='int32')
    attention_mask = tf.keras.layers.Input(shape=(SEQ_LEN,),dtype='int32')

    x = backbone({'input_ids':input_ids,
                 'attention_mask':attention_mask})[0]

    backbone.trainable = False

    x = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(units = 512,
                                                           activation = 'tanh',
                                                           #recurrent_dropout=.2,
                                                           dropout=.2,
                                                           return_sequences=True))(x)
    #x = tf.keras.layers.LayerNormalization()(x)
    x_res = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(units = 512,
                                                           activation = 'tanh',
                                                           #recurrent_dropout=.2,
                                                           dropout=.2,
                                                           return_sequences=True))(x)

    x = tf.keras.layers.add([x,x_res])
    output = tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(16,activation = 'softmax'))(x)

    model = tf.keras.models.Model(inputs={'input_ids':input_ids,
                                          'attention_mask':attention_mask},outputs=output)

    return model

and the compiling:

loss = tf.keras.losses.CategoricalCrossentropy(name='categorical_crossentropy')
metric = tf.keras.metrics.Accuracy(name='accuracy')
opt = tf.keras.optimizers.Adam()

model.compile(optimizer=opt,loss=loss,metrics=[metric])


问:
Uncaught (in promise) TypeError: this.~(...).then is not a function
I'm building something that will get data from a database.
Right now I'm trying call to function getUserById() (that will call to DB via axios later), and at this time I want the line- this.getUserById(id).then((res) to retrieve the dummydata from inside getUserByID().

But I'm getting this error:

```<code>Uncaught (in promise) TypeError: this.getUserById(...).then is not a function
</code>```

I might have added unnecessary code by trying to fix the problem aswell..

UserProfile.js

```<code>import React, { Component } from "react";

export default class UserProfile extends Component {

    constructor(props) {
        super(props);
        this.getUserById = this.getUserById.bind(this);

        this.state = this.initialState;
    };

    initialState = {
        id: "",
        firstName: "Initial",
        lastName: "",
        email: "",
        phoneNumber: "",
        address: "",
        dateOfBirth: "",
        country: "Initial",
        city: "Initial"
    };

    getUserById(userId){

        console.log("Inside Function - ID: " + userId);

        const user = {
            "firstName": "Test",
            "lastName": "Testsson",
            "email": "test@barkr.bork",
            "phoneNumber": "123456",
            "address": "Test 12b",
            "dateOfBirth": "1990-01-01",
            "country": "England",
            "city": "London"
        }

        console.log(user);
        return user;
    }

    async componentDidMount() {

        const {location} = this.props;
        const query = new URLSearchParams(location.search);

        const id = query.get('id');

        console.log("Inside UserProfile - ID: " + id);

     this.getUserById(id).then((res) => {
            this.setState({
                firstName: res.data.firstName,
                lastName: res.data.lastName,
                email: res.data.email,
                phoneNumber: res.data.phoneNumber,
                address: res.data.address,
                dateOfBirth: res.data.dateOfBirth,
                country: res.data.country,
                city: res.data.city
            })

        });

    };

    render() {
        return (
        <section id="userprofile-section">
            <div className="userprofile-box">
                <div id="userprofile-container1">
                    <div className="userprofile-card">

                        <div className="userprofile-cardframe">

                            <div id="userprofile-picture">
                                <h2 id="userprofile-avatartext">Avatar/Picture</h2>
                            </div>
                            <h2 className="userprofile-h1" >{this.state.firstName}</h2>
                            <h3 className="userprofile-h2">{this.state.city}</h3>
                            <h3 className="userprofile-h2">{this.state.country}</h3>

                        </div>

                    </div>
                </div>
                <div id="userprofile-container2">

                </div>
            </div>
        </section>

        );
    }
}
</code>```

Picture of error:
Error in Web Browser

Appreciate the help.

答:
Your getUserById function does not return a promise, but a user object. As it seems you want to later use this function for an asynchronous operation, this problem should get solved when you do so (and return the promise).

To make it work with the temporary implementation, declare getUserById as an async function, and it should work.

Body:
I'm building something that will get data from a database.
Right now I'm trying call to function getUserById() (that will call to DB via axios later), and at this time I want the line- this.getUserById(id).then((res) to retrieve the dummydata from inside getUserByID().

But I'm getting this error:

Uncaught (in promise) TypeError: this.getUserById(...).then is not a function

I might have added unnecessary code by trying to fix the problem aswell..

UserProfile.js

import React, { Component } from "react";

export default class UserProfile extends Component {

    constructor(props) {
        super(props);
        this.getUserById = this.getUserById.bind(this);

        this.state = this.initialState;
    };

    initialState = {
        id: "",
        firstName: "Initial",
        lastName: "",
        email: "",
        phoneNumber: "",
        address: "",
        dateOfBirth: "",
        country: "Initial",
        city: "Initial"
    };

    getUserById(userId){

        console.log("Inside Function - ID: " + userId);

        const user = {
            "firstName": "Test",
            "lastName": "Testsson",
            "email": "test@barkr.bork",
            "phoneNumber": "123456",
            "address": "Test 12b",
            "dateOfBirth": "1990-01-01",
            "country": "England",
            "city": "London"
        }

        console.log(user);
        return user;
    }

    async componentDidMount() {

        const {location} = this.props;
        const query = new URLSearchParams(location.search);

        const id = query.get('id');

        console.log("Inside UserProfile - ID: " + id);

     this.getUserById(id).then((res) => {
            this.setState({
                firstName: res.data.firstName,
                lastName: res.data.lastName,
                email: res.data.email,
                phoneNumber: res.data.phoneNumber,
                address: res.data.address,
                dateOfBirth: res.data.dateOfBirth,
                country: res.data.country,
                city: res.data.city
            })

        });

    };

    render() {
        return (

Avatar/Picture

{this.state.firstName}

{this.state.city}

{this.state.country}

        );
    }
}

Picture of error:
Error in Web Browser

Appreciate the help.


问:
React useEffect hook dependency array
I'm learning about the React useEffect hook, especially the dependency array. Having such simple counter:

```<code>import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, []); // Only re-run the effect if count changes!?

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>You clicked {count} times!</h2>

      <button onClick={() => setCount(count - 1)}>Decrement</button>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
</code>```

Even if the dependency array is empty the counter still works - the counter value is still increased/decreased when I click the button.

As far as I understand from the doc, setting the dependency array empty should just disable the useEffect to run if the dependency array doesn't explicitly list/include the changing value.

答:
useEffect either runs on every render (if you do not use a dependency array) or once every time the dependency array changes.

On first render, the dependency array always changes from "no prior call" to "this is my dependency array" - useEffect will always be executed on the first render. If your dependency array is empty it will just not be executed any more after that.

Title: React useEffect hook dependency array

Body:
I'm learning about the React useEffect hook, especially the dependency array. Having such simple counter:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, []); // Only re-run the effect if count changes!?

  return (

Hello CodeSandbox

You clicked {count} times!

      <button onClick={() => setCount(count - 1)}>Decrement</button>
      <button onClick={() => setCount(count + 1)}>Increment</button>

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Even if the dependency array is empty the counter still works - the counter value is still increased/decreased when I click the button.

As far as I understand from the doc, setting the dependency array empty should just disable the useEffect to run if the dependency array doesn't explicitly list/include the changing value.


问:
perform calculation on column of a dataframe using data from another dataframe
I have two dataframes, one called order_values & the other fx_rates. They look like below.

What I need to do is convert the value_loc value in the order_values dataframe into EUR's using the fx_rates dataframe.

In reality I won't know how many different currency there are & its likely to be more than shown below.

My current solution I believe is far from optimal. I loop through each different currency (i.e. USD, JPY etc) and merge that currency column (EURUSD, EURJPY) to the order_values dataframe & perform the calculation to convert the value_loc into value_eur & then drop the currency column from the order_values dataframe.

```<code>  order_values
  order_num   value_loc  currency   date
  1           2,345      USD        2-12-2021
  2           104        EUR        2-12-2021
  3           20,000     JPY        2-15-2021
  4           550        USD        3-06-2021

  fx_rates
  date       pair    rate
  2-12-2021  EURUSD  1.5
  2-12-2021  EURJPY  5
  2-12-2021  EUREUR  1
  ...
  3-06-2021  EURUSD  1.56
  3-06-2021  EURJPY  5.6
  3-06-2021  EUREUR  1
</code>```

答:
You can merge by currency with dates and then multiple by new Series, which has same number of values like order_num, because used left join.

For currency helper column is stripped first 3 letters of column pair and column value_loc is converted to numeric.

```<code>df = fx_rates.assign(currency = fx_rates['pair'].str[3:])
df1 = order_values.assign(value_loc = order_values['value_loc'].str.replace(',','').astype(float))

s = df1.merge(df, how='left', on=['date','currency'])['rate']
df1['value_loc'] *= s
print (df1)
   order_num  value_loc currency       date
0          1     3517.5      USD  2-12-2021
1          2      104.0      EUR  2-12-2021
2          3        NaN      JPY  2-15-2021 <- no match create NaN
3          4      858.0      USD  3-06-2021
</code>```

Details:

```<code>print (s)
0    1.50
1    1.00
2     NaN
3    1.56
Name: rate, dtype: float64
</code>```

Body:
I have two dataframes, one called order_values & the other fx_rates. They look like below.

What I need to do is convert the value_loc value in the order_values dataframe into EUR's using the fx_rates dataframe.

In reality I won't know how many different currency there are & its likely to be more than shown below.

My current solution I believe is far from optimal. I loop through each different currency (i.e. USD, JPY etc) and merge that currency column (EURUSD, EURJPY) to the order_values dataframe & perform the calculation to convert the value_loc into value_eur & then drop the currency column from the order_values dataframe.

  order_values
  order_num   value_loc  currency   date
  1           2,345      USD        2-12-2021
  2           104        EUR        2-12-2021
  3           20,000     JPY        2-15-2021
  4           550        USD        3-06-2021

  fx_rates
  date       pair    rate
  2-12-2021  EURUSD  1.5
  2-12-2021  EURJPY  5
  2-12-2021  EUREUR  1
  ...
  3-06-2021  EURUSD  1.56
  3-06-2021  EURJPY  5.6
  3-06-2021  EUREUR  1

Body:
You can merge by currency with dates and then multiple by new Series, which has same number of values like order_num, because used left join.

For currency helper column is stripped first 3 letters of column pair and column value_loc is converted to numeric.

df = fx_rates.assign(currency = fx_rates['pair'].str[3:])
df1 = order_values.assign(value_loc = order_values['value_loc'].str.replace(',','').astype(float))

s = df1.merge(df, how='left', on=['date','currency'])['rate']
df1['value_loc'] *= s
print (df1)
   order_num  value_loc currency       date
0          1     3517.5      USD  2-12-2021
1          2      104.0      EUR  2-12-2021
2          3        NaN      JPY  2-15-2021 <- no match create NaN
3          4      858.0      USD  3-06-2021

Details:

print (s)
0    1.50
1    1.00
2     NaN
3    1.56
Name: rate, dtype: float64


答:
```<code>function doMagic(input, newObj) {
    input.map((el, i, arr) => {
        if (input.some(el => el.id === newObj.id)) {
            input.splice(i, 1, newObj);
        } else {
            input.push(newObj);
        }
    })
}
</code>```

Title: Replace the element with the searched value in an array of objects in Javascript


问:
Android: How to make UI thread to wait till AsycTask completes
Currently, I'm executing a heavy task inside AsycTask which uploads images. When I do it via AsycTask, the application closes and no error message appear in the logcat.

```<code>    private class SendIncidentTask extends AsyncTask<Double, Void, Void>{

            @Override
            protected Void doInBackground(Double... params) {
                lat1 = params[0];
                log1 = params[1];
                SendingIncident sincident  = new SendingIncident();
                sincident.sendInciWithoutAttachment(lat1, log1);
                sincident.submitWithAttachment(lat1, log1);
                return null;
            }

   }
</code>```

I think issues occur when the UI thread and AsycTask execute in parallel. How can I make the UI thread wait until the AsycTask finishes?

Thanks in advance.

答: I think you miss the real problem, and doing what you want will cause ANR. But if you want the UI thread to wait, just execute it as a method of the activity, and not as AsyncTask.</p>

Body:
Currently, I'm executing a heavy task inside AsycTask which uploads images. When I do it via AsycTask, the application closes and no error message appear in the logcat.

    private class SendIncidentTask extends AsyncTask<Double, Void, Void>{

            @Override
            protected Void doInBackground(Double... params) {
                lat1 = params[0];
                log1 = params[1];
                SendingIncident sincident  = new SendingIncident();
                sincident.sendInciWithoutAttachment(lat1, log1);
                sincident.submitWithAttachment(lat1, log1);
                return null;
            }

   }

I think issues occur when the UI thread and AsycTask execute in parallel. How can I make the UI thread wait until the AsycTask finishes?

Thanks in advance.


问:
How to filter null returning method in stream?
I have a list, it has some method like getSummary(), and this method returns null in some cases. How can I filter to avoid getting the null result?

Here is my code:

```<code>List<Event> items = getEvents(sharedCalendarId, startDateTime, endDateTime, zoneId);

if (CollectionUtils.isNotEmpty(items)) {
    openingHoursDto.setBranches(items.stream()
            .collect(Collectors.groupingBy(Event::getSummary))
            .entrySet()
            .stream()
            .map(e -> {
                LibraryBranchOpeningHoursDto lBOHDto = new LibraryBranchOpeningHoursDto();
                lBOHDto.setName(e.getKey());
                lBOHDto.setDates(getHoursDtoMap(e.getValue(), startDateTime, endDateTime, selfServicePattern, specialHoursColorId, zoneId));
                return lBOHDto;
            })
            .sorted(comparing(LibraryBranchOpeningHoursDto::getName))
            .collect(Collectors.toList()));
    return openingHoursDto;
}
</code>```

答:
Add a filter step:</p>
```<code>openingHoursDto.setBranches(items.stream()
        .filter (e -> e.getSummary() != null)
        .collect(Collectors.groupingBy(Event::getSummary))
        ...
</code>```

Body:
I have a list, it has some method like getSummary(), and this method returns null in some cases. How can I filter to avoid getting the null result?

Here is my code:

List<Event> items = getEvents(sharedCalendarId, startDateTime, endDateTime, zoneId);

if (CollectionUtils.isNotEmpty(items)) {
    openingHoursDto.setBranches(items.stream()
            .collect(Collectors.groupingBy(Event::getSummary))
            .entrySet()
            .stream()
            .map(e -> {
                LibraryBranchOpeningHoursDto lBOHDto = new LibraryBranchOpeningHoursDto();
                lBOHDto.setName(e.getKey());
                lBOHDto.setDates(getHoursDtoMap(e.getValue(), startDateTime, endDateTime, selfServicePattern, specialHoursColorId, zoneId));
                return lBOHDto;
            })
            .sorted(comparing(LibraryBranchOpeningHoursDto::getName))
            .collect(Collectors.toList()));
    return openingHoursDto;
}

Body:
Add a filter step:

openingHoursDto.setBranches(items.stream()
        .filter (e -> e.getSummary() != null)
        .collect(Collectors.groupingBy(Event::getSummary))
        ...


问:
Why can't I use `using` in a multiple inheritance c++?
I tried to implement some interfaces and their children. This is my idea:

```<code>         Interface
         /       \
  Interface2    InterfaceDefination
        |        /
  Interface2Defination
</code>```

And this is my code:

#include <iostream>

class Interface {
public:
  virtual void method1() = 0;
  virtual void print() = 0;
};

class Interface2 : public Interface {
public:
  virtual void method2() = 0;
};

class InterfaceDefination : public Interface {
public:
  virtual void method1() override {
    std::cout << "method1 from InterfaceDefination\n";
  }
};

class Interface2Defination : public Interface2, public InterfaceDefination {
public:
  using InterfaceDefination::method1;
  virtual void print() override {
    std::cout << "print from Interface2Defination\n";
  }
  virtual void method2() override {
    std::cout << "method2 from Interface2Defination\n";
  }
};

int main() {
  Interface2Defination c;
  c.method1();
  c.method2();
  c.print();
}
```
<p>My expected output is:</p>
```method1 from InterfaceDefination
method2 from Interface2Defination
print from Interface2Defination
```
<p>But accidentally i received these errors:</p>
```main.cpp:33:24: error: variable type 'Interface2Defination' is an abstract class
  Interface2Defination c;
                       ^
main.cpp:5:16: note: unimplemented pure virtual method 'method1' in 'Interface2Defination'
  virtual void method1() = 0;
               ^
1 error generated.
make: *** [<builtin>: main.o] Error 1
exit status 2
```

https://godbolt.org/z/9ncoGfn4P

In this case, the error means using keyword is not making method method1 usable in class Interface2Defination. What should i do with it?

答:
As it stands, there are two Interface::method1s in Interface2Defination, and only one of them has an implementation. If you virtually inherit Interface, you have one, with a definition.

```<code>#include <iostream>

class Interface {
public:
  virtual void method1() = 0;
  virtual void print() = 0;
};

class Interface2 : public virtual Interface {
public:
  virtual void method2() = 0;
};

class InterfaceDefination : public virtual Interface {
public:
  virtual void method1() override {
    std::cout << "method1 from InterfaceDefination\n";
  }
};

class Interface2Defination : public Interface2, public InterfaceDefination {
public:
  virtual void print() override {
    std::cout << "print from Interface2Defination\n";
  }
  virtual void method2() override {
    std::cout << "method2 from Interface2Defination\n";
  }
};

int main() {
  Interface2Defination c;
  c.method1();
  c.method2();
  c.print();
}
</code>```

Body:
I tried to implement some interfaces and their children. This is my idea:

         Interface
         /       \
  Interface2    InterfaceDefination
        |        /
  Interface2Defination

And this is my code:

#include <iostream>

class Interface {
public:
  virtual void method1() = 0;
  virtual void print() = 0;
};

class Interface2 : public Interface {
public:
  virtual void method2() = 0;
};

class InterfaceDefination : public Interface {
public:
  virtual void method1() override {
    std::cout << "method1 from InterfaceDefination\n";
  }
};

class Interface2Defination : public Interface2, public InterfaceDefination {
public:
  using InterfaceDefination::method1;
  virtual void print() override {
    std::cout << "print from Interface2Defination\n";
  }
  virtual void method2() override {
    std::cout << "method2 from Interface2Defination\n";
  }
};

int main() {
  Interface2Defination c;
  c.method1();
  c.method2();
  c.print();
}

My expected output is:

method1 from InterfaceDefination
method2 from Interface2Defination
print from Interface2Defination

But accidentally i received these errors:

main.cpp:33:24: error: variable type 'Interface2Defination' is an abstract class
  Interface2Defination c;
                       ^
main.cpp:5:16: note: unimplemented pure virtual method 'method1' in 'Interface2Defination'
  virtual void method1() = 0;
               ^
1 error generated.
make: *** [<builtin>: main.o] Error 1
exit status 2

https://godbolt.org/z/9ncoGfn4P

In this case, the error means using keyword is not making method method1 usable in class Interface2Defination. What should i do with it?

Body:
As it stands, there are two Interface::method1s in Interface2Defination, and only one of them has an implementation. If you virtually inherit Interface, you have one, with a definition.

#include <iostream>

class Interface {
public:
  virtual void method1() = 0;
  virtual void print() = 0;
};

class Interface2 : public virtual Interface {
public:
  virtual void method2() = 0;
};

class InterfaceDefination : public virtual Interface {
public:
  virtual void method1() override {
    std::cout << "method1 from InterfaceDefination\n";
  }
};

class Interface2Defination : public Interface2, public InterfaceDefination {
public:
  virtual void print() override {
    std::cout << "print from Interface2Defination\n";
  }
  virtual void method2() override {
    std::cout << "method2 from Interface2Defination\n";
  }
};

int main() {
  Interface2Defination c;
  c.method1();
  c.method2();
  c.print();
}