问:
Matlab code that needs some clarification
I'm very beginner in Matlab and can't convert the following code to c++

suppose that conv is already written in C++, I don't know if the code is implementing a 2D conv or 1D actually

How would I convert the following code to C++

```<code>% Description:
%   Function that evaluates the equivalent loop transfer function from the
%   loop integrator gain
%
% Input:
%   KK      [real,vector]:  Integrator gains
%   N       [integer]    :  Order of the loop filter

% Output:
%   A      [real, vector]:  Coefficients of the denominator
%   B      [real, vector]:  Coefficients of the numerator
%
% Remarks:
%   o A rate-only NCO is assumed

% construct the loop filter transfer function
v1 = 1;
v2 = 1;

B = zeros(1, N);
for ii = N:-1:1,
    v1 = conv( v1, [1 -1] );
    B = B + KK(ii)*[v2 zeros(1, ii - 1)];
    v2 = conv(v2, [1 -1]);
end

v1 = conv( v1, [1 0]);

% Account for the rate-only NCO - Change this code to implement different
% NCO models
B = conv(B, [1 1])*1/2;
B = [ 0 B ];

A = v1 + B;
</code>```

答:
<pre class="lang-cpp prettyprint-override"><code>#include <vector>
#include <algorithm>
using std::vector;
int main() {
    // v1 = 1;
    double v1 = 1;
    // v2 = 1;
    double v2 = 1;

    // B = zeros(1, N);
    vector<double> B(N, 0);
    //for ii = N:-1:1,
    for (int ii=N; ii>=1; ii--) {
        // v1 = conv( v1, [1 -1] );
        v1 = conv(v1, {1, -1});
        // B = B + KK(ii)*[v2 zeros(1, ii - 1)];
        vector<double> temp(v2.size() + ii - 1, 0); // initialize with zeros
        std::copy(v2.begin(), v2.end(), temp.begin()); // copy v2 to temp
        B += temp * KK[ii];
        // v2 = conv(v2, [1 -1]);
        v2 = conv(v2, {1, -1});
    // end
    }

    // v1 = conv( v1, [1 0]);
    v1 = conv(v1, {1, 0});

    // B = conv(B, [1 1])*1/2;
    B = conv(B, {1, 1}) * 0.5;
    // B = [ 0 B ];
    B.insert(B.begin(), 0);

    // A = v1 + B;
    vector<double> A = v1 + B;
}
</code>```

Body:
I'm very beginner in Matlab and can't convert the following code to c++

suppose that conv is already written in C++, I don't know if the code is implementing a 2D conv or 1D actually

How would I convert the following code to C++

% Description:
%   Function that evaluates the equivalent loop transfer function from the
%   loop integrator gain
%
% Input:
%   KK      [real,vector]:  Integrator gains
%   N       [integer]    :  Order of the loop filter

% Output:
%   A      [real, vector]:  Coefficients of the denominator
%   B      [real, vector]:  Coefficients of the numerator
%
% Remarks:
%   o A rate-only NCO is assumed

% construct the loop filter transfer function
v1 = 1;
v2 = 1;

B = zeros(1, N);
for ii = N:-1:1,
    v1 = conv( v1, [1 -1] );
    B = B + KK(ii)*[v2 zeros(1, ii - 1)];
    v2 = conv(v2, [1 -1]);
end

v1 = conv( v1, [1 0]);

% Account for the rate-only NCO - Change this code to implement different
% NCO models
B = conv(B, [1 1])*1/2;
B = [ 0 B ];

A = v1 + B;


来源: stackexchange

问:
NodeJS - How to deal with UnhandledPromiseRejectionWarning?
I am fairly new to Node JS and so I am struggling a bit.

I am trying to read files for google drive using their API, from my Node Js code.

I am having the following code

```<code>router.get('/', function (req, res, next) {

  var pageToken = null;
// Using the NPM module 'async'
async.doWhilst(function (callback) {
  drive.files.list({
    q: "mimeType='image/jpeg'",
    fields: 'nextPageToken, files(id, name)',
    spaces: 'drive',
    pageToken: pageToken
  }, function (err, res) {
    if (err) {
      // Handle error
      console.error(err);
      callback(err)
    } else {
      res.files.forEach(function (file) {
        console.log('Found file: ', file.name, file.id);
      });
      pageToken = res.nextPageToken;
      callback();
    }
  });
}, function () {
  return !!pageToken;
}, function (err) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    // All pages fetched
  }
})

  res.render('index', { title: 'Express' });

});
</code>```

The above code is giving me the following error when i send the get request

```<code>(node:13884) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined
    at E:\nodejs\newcelebapi\routes\index.js:49:17
    at E:\nodejs\newcelebapi\node_modules\googleapis-common\build\src\apirequest.js:43:53
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13884) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13884) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

The issue is in the following line

```<code>  res.files.forEach(function (file) {
</code>```

I've tried everything I could and gave up understanding the problem.

Could you please help me with this?

Thanks!

答:
Per this example in the doc, you want to be using:

```<code>res.data.files.forEach(...)
</code>```

not:

```<code>res.files.forEach(...)
</code>```

And, it looks like as soon as you get by that problem, you will have another problem because you are calling res.render() in the wrong place.  And, when you fix that, you will have an issue with redefining res in your Google callback which will hide the higher level res that you need for res.render().

I would strongly recommend that you not use the async library here.  It doesn't seem like it's needed here and it just complicates things.  And, if you did need help doing coordination of asynchronous operations, promises is the modern way to do so.

You don't show what you're trying to do with the resulting files (other than logging them), but here's a simple implementation that does that:

```<code>router.get('/', function (req, res, next) {
  var pageToken = null;
  drive.files.list({
    q: "mimeType='image/jpeg'",
    fields: 'nextPageToken, files(id, name)',
    spaces: 'drive',
    pageToken: pageToken
  }).then(response => {
      let files = response.data.files;
      files.forEach(file => console.log('Found file: ', file.name, file.id))
      res.render('index', { title: 'Express' });
  }).catch(err => {
      console.log(err);
      res.sendStatus(500);
  });
});
</code>```

Note, that I named the parameter from drive.files.list() to be named response instead of res so I can access both res from the router.get() callback and response from the drive.files.list() callback.  You gave them both the same name res which means you can't access the router.get() parameter of the same name.

ContentLicense: CC BY-SA 4.0

Body:
I am fairly new to Node JS and so I am struggling a bit.

I am trying to read files for google drive using their API, from my Node Js code.

I am having the following code

router.get('/', function (req, res, next) {

  var pageToken = null;
// Using the NPM module 'async'
async.doWhilst(function (callback) {
  drive.files.list({
    q: "mimeType='image/jpeg'",
    fields: 'nextPageToken, files(id, name)',
    spaces: 'drive',
    pageToken: pageToken
  }, function (err, res) {
    if (err) {
      // Handle error
      console.error(err);
      callback(err)
    } else {
      res.files.forEach(function (file) {
        console.log('Found file: ', file.name, file.id);
      });
      pageToken = res.nextPageToken;
      callback();
    }
  });
}, function () {
  return !!pageToken;
}, function (err) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    // All pages fetched
  }
})

  res.render('index', { title: 'Express' });

});

The above code is giving me the following error when i send the get request

(node:13884) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined
    at E:\nodejs\newcelebapi\routes\index.js:49:17
    at E:\nodejs\newcelebapi\node_modules\googleapis-common\build\src\apirequest.js:43:53
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13884) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13884) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

The issue is in the following line

  res.files.forEach(function (file) {

I've tried everything I could and gave up understanding the problem.

Could you please help me with this?

Thanks!

Body:
Per this example in the doc, you want to be using:

res.data.files.forEach(...)

not:

res.files.forEach(...)

And, it looks like as soon as you get by that problem, you will have another problem because you are calling res.render() in the wrong place.  And, when you fix that, you will have an issue with redefining res in your Google callback which will hide the higher level res that you need for res.render().

I would strongly recommend that you not use the async library here.  It doesn't seem like it's needed here and it just complicates things.  And, if you did need help doing coordination of asynchronous operations, promises is the modern way to do so.

You don't show what you're trying to do with the resulting files (other than logging them), but here's a simple implementation that does that:

router.get('/', function (req, res, next) {
  var pageToken = null;
  drive.files.list({
    q: "mimeType='image/jpeg'",
    fields: 'nextPageToken, files(id, name)',
    spaces: 'drive',
    pageToken: pageToken
  }).then(response => {
      let files = response.data.files;
      files.forEach(file => console.log('Found file: ', file.name, file.id))
      res.render('index', { title: 'Express' });
  }).catch(err => {
      console.log(err);
      res.sendStatus(500);
  });
});

Note, that I named the parameter from drive.files.list() to be named response instead of res so I can access both res from the router.get() callback and response from the drive.files.list() callback.  You gave them both the same name res which means you can't access the router.get() parameter of the same name.


问:
Join two tables so foreign key column data (integer) changes to text data from parent table (concerned column in parent table is not primary key)
I am a beginner with SQLite, and I am still a little unfamiliar with joining tables (and the limitations therein). I would like to know how to join 2 tables so that the column data in Table B (several columns) changes to reflect data from Table A.

```<code>CREATE TABLE "A" (
      "person_id"   INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
      "person_name" TEXT NOT NULL,
      "email"   TEXT NOT NULL
);

    CREATE TABLE "B" (
          "company_id"  INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
          "company_name"    TEXT NOT NULL,
          "contact_one" INTEGER NOT NULL,
          "contact_two" INTEGER,
          "contact_three"   INTEGER,
          FOREIGN KEY("contact_one") REFERENCES "A"("person_id") ON DELETE SET NULL
          FOREIGN KEY("contact_two") REFERENCES "A"("person_id") ON DELETE SET NULL
          FOREIGN KEY("contact_three") REFERENCES "A"("person_id") ON DELETE SET NULL
);
</code>```

How do I write a query so that the resulting table shows columns "company_name", "contact_one", "contact_two" and "contact_three" BUT with the contact tables showing the contact name rather than the integer (as it would appear in Table B).

See below an image representing Tables A and B and the desired output of SQLite query:

When I do a left join, the query succeeds only for a single contact column.

```<code>SELECT B.company_name, A.person_name
FROM B
LEFT JOIN A ON B.contact_one = A.person_id
</code>```

I tried to add an "OR" to the query (I know "AND" will not work), but I get an "ambiguous column name: A.person_name" error when I try to run the query:

```<code>SELECT B.company_name, A.person_name
FROM B
LEFT JOIN A ON B.contact_one = A.person_id
OR LEFT JOIN A ON B.contact_two = A.person_id
OR LEFT JOIN A ON B.contact_three = A.person_id
</code>```

How do I write the query so that I can get contact_two and contact_three also in the resulting table, with all three contacts' names displayed?

Any guidance will be greatly appreciated!

答:
You need to join the table A 3 times like this:</p>

```<code>SELECT B.company_name,
  a1.person_name name1,
  a2.person_name name2,
  a3.person_name name3
FROM B
LEFT JOIN A a1 ON B.contact_one = a1.person_id
LEFT JOIN A a2 ON B.contact_two = a2.person_id
LEFT JOIN A a3 ON B.contact_three = a3.person_id
</code>```

Body:
I am a beginner with SQLite, and I am still a little unfamiliar with joining tables (and the limitations therein). I would like to know how to join 2 tables so that the column data in Table B (several columns) changes to reflect data from Table A.

CREATE TABLE "A" (
      "person_id"   INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
      "person_name" TEXT NOT NULL,
      "email"   TEXT NOT NULL
);

    CREATE TABLE "B" (
          "company_id"  INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
          "company_name"    TEXT NOT NULL,
          "contact_one" INTEGER NOT NULL,
          "contact_two" INTEGER,
          "contact_three"   INTEGER,
          FOREIGN KEY("contact_one") REFERENCES "A"("person_id") ON DELETE SET NULL
          FOREIGN KEY("contact_two") REFERENCES "A"("person_id") ON DELETE SET NULL
          FOREIGN KEY("contact_three") REFERENCES "A"("person_id") ON DELETE SET NULL
);

How do I write a query so that the resulting table shows columns "company_name", "contact_one", "contact_two" and "contact_three" BUT with the contact tables showing the contact name rather than the integer (as it would appear in Table B).

See below an image representing Tables A and B and the desired output of SQLite query:

When I do a left join, the query succeeds only for a single contact column.

SELECT B.company_name, A.person_name
FROM B
LEFT JOIN A ON B.contact_one = A.person_id

I tried to add an "OR" to the query (I know "AND" will not work), but I get an "ambiguous column name: A.person_name" error when I try to run the query:

SELECT B.company_name, A.person_name
FROM B
LEFT JOIN A ON B.contact_one = A.person_id
OR LEFT JOIN A ON B.contact_two = A.person_id
OR LEFT JOIN A ON B.contact_three = A.person_id

How do I write the query so that I can get contact_two and contact_three also in the resulting table, with all three contacts' names displayed?

Any guidance will be greatly appreciated!

Body:
You need to join the table A 3 times like this:

SELECT B.company_name,
  a1.person_name name1,
  a2.person_name name2,
  a3.person_name name3
FROM B
LEFT JOIN A a1 ON B.contact_one = a1.person_id
LEFT JOIN A a2 ON B.contact_two = a2.person_id
LEFT JOIN A a3 ON B.contact_three = a3.person_id


问:
What does this Typescript syntax mean
```<code>export declare type SomeType = {
   [key: string] : string
};
</code>```

What exactly does this syntax mean? We are exporting a custom type alias called SomeType that is an object that has a property that is called ____ and is of value ____ ?

答:
This is a key/value structure. The key is a string and the value is a string</p>

```<code>SomeType = {
   'a-string-key' : 'a-string-value'
};
</code>```

Title: What does this Typescript syntax mean

Body:
export declare type SomeType = {
   [key: string] : string
};

What exactly does this syntax mean? We are exporting a custom type alias called SomeType that is an object that has a property that is called ____ and is of value ____ ?

Body:
This is a key/value structure. The key is a string and the value is a string

SomeType = {
   'a-string-key' : 'a-string-value'
};


问:
How to find all the colors between two colors?
I need to pick two colors, then find X colors (or tones) between them, each one separated with the same 'distance' of the other.

I still don't understand how colors are formed. Should I try using HSV, RGB, or hex?

答:
Unless you really know what kind of colors do you need, this is almost impossible to get all the colors between two colors.

Just look at the representations of the colors - there are wheels with colors like that:

and you can pick colors on some straight line, going clockwise or counter-clockwise and you will get different results.

In case of RGB colors, their number is limites and is equal to 16 777 216 (245^3). But do you really want to pick all of these colors? Choose a method to distinguish colors "between" two other colors and then just apply it and find these intermediate colors. There is no "single and only" best method to pick colors 'between' two different colors.

EDIT:

Alternatively, you can just make use of Color Difference concept and pick all the colors that are closer to both base colors than these base colors are close to each other. But I will leave you all the calculations.

ContentLicense: CC BY-SA 3.0


问:
JAVA return longest value if a string contains any of the items from a List
I have the following array of code types:

```<code>["sample_code","code","formal_code"]
</code>```

and the following ids:

```<code>String id="123456789_sample_code_xyz";
String id2="91343486_code_zxy";
</code>```

I want to extract the code type from the ids

this is my code snippet:

```<code>    String codeTypes[] = {"sample_code","code","formal_code"};
    String id= "123456789_sample_code_xyz";
    String codeType = Arrays.stream(codeTypes).parallel().filter(id::contains).findAny().get();
    System.out.println(codeType);
</code>```

it doesnt work with the 1st id, because it returns "code" instead of "sample_code", I want to get the longest code type.

```<code>for the 1st id the code type should be "sample_code"
for the 2nd id the code type should be "code"
</code>```

答:
Since you run the strem in parallel, you cannot predict which of the streams finds first a matching pattern. I your case (also in mine when I tried your code snippet) the second stream which looked for "code" was faster, and the whole stream terminates because you just want "findAny()".

Remove the "parallel" and your code works as you expect.

Body:
I have the following array of code types:

["sample_code","code","formal_code"]

and the following ids:

String id="123456789_sample_code_xyz";
String id2="91343486_code_zxy";

I want to extract the code type from the ids

this is my code snippet:

    String codeTypes[] = {"sample_code","code","formal_code"};
    String id= "123456789_sample_code_xyz";
    String codeType = Arrays.stream(codeTypes).parallel().filter(id::contains).findAny().get();
    System.out.println(codeType);

it doesnt work with the 1st id, because it returns "code" instead of "sample_code", I want to get the longest code type.

for the 1st id the code type should be "sample_code"
for the 2nd id the code type should be "code"


问:
Default permission and ownership in WSL
I'm currently in the process of switching from an Ubuntu 18.04 VirtualBox to the WSL.
Everything is up and running to have a complete web dev environment.
Unfortunately, the file permission and ownership is kind of a problem for me right now.

--- Disclaimer---
I know that in a server environment this would be pretty bad and wouldn't be done.
This is just for my local development process and this requirement will stay there.

What I want to achieve is, to have a consistent set of permissions and ownerships within my /var/www (and all below).

Every element within /var/www should be owned by my shell user, regardless if file or dir.

Every element should have the group www-dataso that the webserver user have access.

Each file should have permission 0664 and each directory 0775.

every new element should follow these requirements.

What I researched so far:
If I make a new directory/ file from the shell or within VSCode, my user and group are used.
If I make a new directory from the windows explorer, the ownership is root:root. Nevertheless, I also have to figure out how to set default permissions for new objects.

I just want an easy to use way to CRUD my files from anywhere I am on my system.

Is there anyone with an idea for this?

Thanks a lot, Danaq.

Edit: It would also be ok, to set everything to www-data:ww-data and add my shell user to the www-data-group if the permissions are applied like explained above.

答:
For everyone encountering the same issue and find this question:

Under ~[USER~/.profile I uncommented the umask-property and set it to 002.
This will, according to this guide, set all new created file to 0664 and all new directories to 0775.

I then added the www-data-user to the group of my shell-user with

sudo usermod -a -G www-data [GROUP].

So now, every file I'm creating is owned by and within the group of my shell user. But it can be red by the www-data-user too. This should lead to not always using the

find ./ -type d -exec chmod 775 {} \;

the command to set the right permissions on all directories of a web project after migration for example.

This solution does only help, if the files and directories are created from the WSL-bash. If you are using the explorer or trying to create a file from the VSCode-terminal, the default umask of 022 will be still applied.

Title: Default permission and ownership in WSL


问:
nodejs-dialogflow library returning TypeError: dialogflow.SessionsClient is not a constructor
I am trying to make a script that takes input from the user, runs it through Dialogflow, then returns it back to the user. The platform I am taking input from only supports Node.js. I am hosting the bot through glitch.com, but I don't think that's what's causing the issue. I wanted to check on here before I submit a bug report onto the GitHub repo.

var bot = 'the platform i use to accept inputs and send outputs'

bot.on("message", async message => {

  console.log(message.content); // Log chat to console for debugging/testing

  if (message.content.indexOf(config.prefix) === 0) { // Message starts with your prefix

    let msg = message.content.slice(config.prefix.length); // slice of the prefix on the message

    let args = msg.split(" "); // break the message into part by spaces

    let cmd = args[0].toLowerCase(); // set the first word as the command in lowercase just in case

    args.shift(); // delete the first word from the args

    // You can find your project ID in your Dialogflow agent settings
    const projectId = process.env.PROJECT_ID; //https://dialogflow.com/docs/agents#settings
    const sessionId = 'quickstart-session-id';
    var query = msg;
    const languageCode = 'en-US';

    // Instantiate a DialogFlow client.
    const dialogflow = require('dialogflow');
    const sessionClient = new dialogflow.SessionsClient();

    // Define session path
    const sessionPath = sessionClient.sessionPath(projectId, sessionId);

    // The text query request.
    const request = {
      session: sessionPath,
      queryInput: {
        text: {
          text: query,
          languageCode: languageCode,
        },
      },
    };

    // Send request and log result
    sessionClient
      .detectIntent(request)
      .then(responses => {
        console.log('Detected intent');
        const result = responses[0].queryResult;
        console.log(`  Query: ${result.queryText}`);
        console.log(`  Response: ${result.fulfillmentText}`);
        if (result.intent) {
          console.log(`  Intent: ${result.intent.displayName}`);
        } else {
          console.log(`  No intent matched.`);
        }
      })
      .catch(err => {
        console.error('ERROR:', err);
      });
  }
  return;
});```

That is the relevant part of the code. For those wondering, the process.env.PROJECT_ID is something glitch.com uses for anything private. Because I don't want random people getting their hands on my project id, I hide it in there and glitch hides it from anyone I don't explicitly invite.

Every time I execute this and try to query the bot, it returns an error Uncaught Promise Error:  TypeError: dialogflow.SessionsClient is not a constructor.

If someone can direct me to what I'm missing, or what the problem is, that would be great!

答: put the code inside try and catch block. In my case by doing this, this error was removed.</p>

Body:
I am trying to make a script that takes input from the user, runs it through Dialogflow, then returns it back to the user. The platform I am taking input from only supports Node.js. I am hosting the bot through glitch.com, but I don't think that's what's causing the issue. I wanted to check on here before I submit a bug report onto the GitHub repo.

var bot = 'the platform i use to accept inputs and send outputs'

bot.on("message", async message => {

  console.log(message.content); // Log chat to console for debugging/testing

  if (message.content.indexOf(config.prefix) === 0) { // Message starts with your prefix

    let msg = message.content.slice(config.prefix.length); // slice of the prefix on the message

    let args = msg.split(" "); // break the message into part by spaces

    let cmd = args[0].toLowerCase(); // set the first word as the command in lowercase just in case

    args.shift(); // delete the first word from the args

    // You can find your project ID in your Dialogflow agent settings
    const projectId = process.env.PROJECT_ID; //https://dialogflow.com/docs/agents#settings
    const sessionId = 'quickstart-session-id';
    var query = msg;
    const languageCode = 'en-US';

    // Instantiate a DialogFlow client.
    const dialogflow = require('dialogflow');
    const sessionClient = new dialogflow.SessionsClient();

    // Define session path
    const sessionPath = sessionClient.sessionPath(projectId, sessionId);

    // The text query request.
    const request = {
      session: sessionPath,
      queryInput: {
        text: {
          text: query,
          languageCode: languageCode,
        },
      },
    };

    // Send request and log result
    sessionClient
      .detectIntent(request)
      .then(responses => {
        console.log('Detected intent');
        const result = responses[0].queryResult;
        console.log(`  Query: ${result.queryText}`);
        console.log(`  Response: ${result.fulfillmentText}`);
        if (result.intent) {
          console.log(`  Intent: ${result.intent.displayName}`);
        } else {
          console.log(`  No intent matched.`);
        }
      })
      .catch(err => {
        console.error('ERROR:', err);
      });
  }
  return;
});

That is the relevant part of the code. For those wondering, the process.env.PROJECT_ID is something glitch.com uses for anything private. Because I don't want random people getting their hands on my project id, I hide it in there and glitch hides it from anyone I don't explicitly invite.

Every time I execute this and try to query the bot, it returns an error Uncaught Promise Error:  TypeError: dialogflow.SessionsClient is not a constructor.

If someone can direct me to what I'm missing, or what the problem is, that would be great!


问:
Error: Requires Babel "^7.0.0-0", but was loaded with "6.26.3"
I am using express-react-views package to render react components in serverside(NodeJs). I tried to render my react component as in the example https://github.com/reactjs/express-react-views/tree/master/examples/dynamic. But when I tried npm start, it throws an error that:
Error: Requires Babel "^7.0.0-0", but was loaded with "6.26.3". I tried upgrading babel as per the doc on https://github.com/babel/babel-upgrade. But still there is same error.

How can I fix this issue? Please help as I'm stuck on this error

My package.json file

```<code>{
"name": "dynamic-views",
"version": "0.1.0",
"description": "Example of creating a dynamic app using express-react-
 views",
"author": "Chris Johnson <tenorviol@yahoo.com>",
"private": true,
"scripts": {
"start":
"browserify -t babelify views/main.js --standalone main -o
public/main.js  && node app.js"
},
"dependencies": {
"@babel/preset-env": "^7.0.0",
"@babel/preset-react": "^7.0.0",
"babelify": "^7.3.0",
"browserify": "^14.3.0",
"express": "^4.15.3",
"express-react-views": "^0.11.0",
"react": "^16.0.0",
"react-dom": "^16.0.0"
}
}
</code>```

My package-lock.json file

```<code>{
"name": "dynamic-views",
"version": "0.1.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@babel/code-frame": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-
frame-7.0.0.tgz",
"integrity": "sha512-   OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==",
"requires": {
"@babel/highlight": "^7.0.0"
}
},
"@babel/core": {
"version": "7.4.5",
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.4.5.tgz",
"integrity": "sha512-OvjIh6aqXtlsA8ujtGKfC7LYWksYSX8yQcM8Ay3LuvVeQ63lcOKgoZWVqcpFwkd29aYU9rVx7jxhfhiEDV9MZA==",
"requires": {
"@babel/code-frame": "^7.0.0",
"@babel/generator": "^7.4.4",
"@babel/helpers": "^7.4.4",
"@babel/parser": "^7.4.5",
"@babel/template": "^7.4.4",
"@babel/traverse": "^7.4.5",
"@babel/types": "^7.4.4",
"convert-source-map": "^1.1.0",
"debug": "^4.1.0",
"json5": "^2.1.0",
"lodash": "^4.17.11",
"resolve": "^1.3.2",
"semver": "^5.4.1",
"source-map": "^0.5.0"
}
},
</code>```

答:
I found this post helped a lot along with below posts for the errors that followed. :)

Jest TypeError: Path must be a string. Received undefined

TypeError: Cannot read property 'cwd' of undefined

For me the below solution worked. I hope it works for you too!

```<code>yarn add babel-jest@22.4.3 --dev
yarn add jest@21.0.2 --dev
babel-core@^7.0.0-0
                 ---> (Choose "7.0.0-bridge.0")
</code>```

Body:
I am using express-react-views package to render react components in serverside(NodeJs). I tried to render my react component as in the example https://github.com/reactjs/express-react-views/tree/master/examples/dynamic. But when I tried npm start, it throws an error that:
Error: Requires Babel "^7.0.0-0", but was loaded with "6.26.3". I tried upgrading babel as per the doc on https://github.com/babel/babel-upgrade. But still there is same error.

How can I fix this issue? Please help as I'm stuck on this error

My package.json file

{
"name": "dynamic-views",
"version": "0.1.0",
"description": "Example of creating a dynamic app using express-react-
 views",
"author": "Chris Johnson <tenorviol@yahoo.com>",
"private": true,
"scripts": {
"start":
"browserify -t babelify views/main.js --standalone main -o
public/main.js  && node app.js"
},
"dependencies": {
"@babel/preset-env": "^7.0.0",
"@babel/preset-react": "^7.0.0",
"babelify": "^7.3.0",
"browserify": "^14.3.0",
"express": "^4.15.3",
"express-react-views": "^0.11.0",
"react": "^16.0.0",
"react-dom": "^16.0.0"
}
}

My package-lock.json file

{
"name": "dynamic-views",
"version": "0.1.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@babel/code-frame": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-
frame-7.0.0.tgz",
"integrity": "sha512-   OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==",
"requires": {
"@babel/highlight": "^7.0.0"
}
},
"@babel/core": {
"version": "7.4.5",
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.4.5.tgz",
"integrity": "sha512-OvjIh6aqXtlsA8ujtGKfC7LYWksYSX8yQcM8Ay3LuvVeQ63lcOKgoZWVqcpFwkd29aYU9rVx7jxhfhiEDV9MZA==",
"requires": {
"@babel/code-frame": "^7.0.0",
"@babel/generator": "^7.4.4",
"@babel/helpers": "^7.4.4",
"@babel/parser": "^7.4.5",
"@babel/template": "^7.4.4",
"@babel/traverse": "^7.4.5",
"@babel/types": "^7.4.4",
"convert-source-map": "^1.1.0",
"debug": "^4.1.0",
"json5": "^2.1.0",
"lodash": "^4.17.11",
"resolve": "^1.3.2",
"semver": "^5.4.1",
"source-map": "^0.5.0"
}
},

Body:
I found this post helped a lot along with below posts for the errors that followed. :)

Jest TypeError: Path must be a string. Received undefined

TypeError: Cannot read property 'cwd' of undefined

For me the below solution worked. I hope it works for you too!

yarn add babel-jest@22.4.3 --dev
yarn add jest@21.0.2 --dev
babel-core@^7.0.0-0
                 ---> (Choose "7.0.0-bridge.0")


答:
Colors are represented by bits, just like anything else in computers.

#FFFFFF represents white and #000000 represents black.  This is the RGB notation, which is in hex.  To get the numeric value for each, convert it to an unsigned integer.  Then you have your range that you need to divide up.

Title: How to find all the colors between two colors?

Body:
I need to pick two colors, then find X colors (or tones) between them, each one separated with the same 'distance' of the other.

I still don't understand how colors are formed. Should I try using HSV, RGB, or hex?


问:
avrdude: stk500v2_ReceiveMessage(): timeout
This is the main error that I get when I try to run my ARDUINO program. The full list of errors is as follows:

```<code>avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer
</code>```

My code is as follows:

```<code>int led=13;
void setup()
{
    pinMode(13,OUTPUT);
}

void loop()
{
    digitalWrite(13,HIGH);
    delay(1000);
    digitalWrite(13,LOW);
    delay(1000);
}
</code>```

I have tried updating the drivers (they are fully updated) and downloading some programs. I have Windows 7 and my arduino is a MEGA 2560. It shows up in the Device Manager and all of my connections are correct. The green PWR light is on and so is the flashing L light. The RX and TX lights flash when I update. I have tried almost everything on the web. What is the problem?

答:
Open Terminal and type:

```<code>$ sudo usermod -a -G dialout
</code>```

(This command is optional)

```<code>$ **sudo chmod a+rw /dev/ttyACM0**
</code>```

(This command must succeed)

Body:
This is the main error that I get when I try to run my ARDUINO program. The full list of errors is as follows:

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

My code is as follows:

int led=13;
void setup()
{
    pinMode(13,OUTPUT);
}

void loop()
{
    digitalWrite(13,HIGH);
    delay(1000);
    digitalWrite(13,LOW);
    delay(1000);
}

I have tried updating the drivers (they are fully updated) and downloading some programs. I have Windows 7 and my arduino is a MEGA 2560. It shows up in the Device Manager and all of my connections are correct. The green PWR light is on and so is the flashing L light. The RX and TX lights flash when I update. I have tried almost everything on the web. What is the problem?

Body:
Open Terminal and type:

$ sudo usermod -a -G dialout

(This command is optional)

$ **sudo chmod a+rw /dev/ttyACM0**

(This command must succeed)


问:
JQuery/Javascript Reordering rows
I have a aspx page that looks something like this:

```<code><tr id="Row1">
  <td>Some label</td>
  <td>Some complex control</td>
</tr>
<tr id="Row2">
  <td>Some label</td>
  <td>Some complex control</td>
</tr>
<tr id="Row3">
  <td>Some label</td>
  <td>Some complex control</td>
</tr>
</code>```

As soon as the page is loaded, I would want to reorder these rows based on the user's previously selected order (stored in a database)

How would I use JQuery/JS to accomplish this?

EDIT:

I have run into a performance issue with the appendTo code. It takes 400ms for a table of 10 rows which is really unacceptable. Can anyone help me tweak it for performance?

```<code>function RearrangeTable(csvOrder, tableId)
{
  var arrCSVOrder = csvOrder.split(',');

  //No need to rearrange if array length is 1
  if (arrCSVOrder.length > 1)
  {
    for (var i = 0; i < arrCSVOrder.length; i++)
    {
      $('#' + tableId).find('[fieldname = ' + arrCSVOrder[i] + ']').eq(0).parents('tr').eq(0).appendTo('#' + tableId);
    }
  }
}
</code>```

答:
If the last sorting done by the user is stored as a list containing the row id, you could do this:

```<code>loop through list from db {
    $("#"+rowId).appendTo("#tableId")
}
</code>```

This way, the rows will be taken out of their current location and replaced inside the table in the order they are stored in the database.

OwnerDisplayName: DotnetDude

ContentLicense: CC BY-SA 2.5

Title: JQuery/Javascript Reordering rows

Body:
I have a aspx page that looks something like this:

  Some label
  Some complex control

  Some label
  Some complex control

  Some label
  Some complex control

As soon as the page is loaded, I would want to reorder these rows based on the user's previously selected order (stored in a database)

How would I use JQuery/JS to accomplish this?

EDIT:

I have run into a performance issue with the appendTo code. It takes 400ms for a table of 10 rows which is really unacceptable. Can anyone help me tweak it for performance?

function RearrangeTable(csvOrder, tableId)
{
  var arrCSVOrder = csvOrder.split(',');

  //No need to rearrange if array length is 1
  if (arrCSVOrder.length > 1)
  {
    for (var i = 0; i < arrCSVOrder.length; i++)
    {
      $('#' + tableId).find('[fieldname = ' + arrCSVOrder[i] + ']').eq(0).parents('tr').eq(0).appendTo('#' + tableId);
    }
  }
}

LastEditorDisplayName: DotnetDude

Body:
If the last sorting done by the user is stored as a list containing the row id, you could do this:

loop through list from db {
    $("#"+rowId).appendTo("#tableId")
}

This way, the rows will be taken out of their current location and replaced inside the table in the order they are stored in the database.

OwnerDisplayName: peirix


问:
How many classes can be put in a Java package?
Is there any limit on number of Java classes(Both Public and Non Public) that can be put in a Java Package?</p>

答:
tl;dr: the value is implementation-dependent since it's not defined anywhere in the JVM or Java spec.

Practically speaking, it could be somewhere between maxUint16 and maxUint64.

There many limits due to the nature of JVM, but classes and packages count is not one of them.

I find this sentence from a Java spec worthwhile in this context (source 7.2):

For example, a system that uses a database to store packages may not enforce a maximum of one public class or interface per compilation unit.

It does encourage JVM implementation to avoid such a limit even if it uses something other than a file system for storing compilation artifacts like packages and classes.

As noted in one of the comments to your question, there can be technical limits, but they're probably high enough for most use cases. It can also vary a lot depending on the implementation you're using. That being said, you probably can have millions of packages and classes without any issues.

For completeness and reachability, I'll inline a @Holger comment here:

There is no limit in the specification, so you can put classes into the package until hitting a technical limitation. If not hitting a limit at the file system or archive format, the runtime implementation likely uses arrays or collections to hold the classes, which limits the number to something close to 2³¹. You may hit memory limitations before…


问:
Facebook key hash does not match any stored key hashes
I'm really having troubles with the Facebook hash key.
I generated it in my Eclipse.. proof:

Then I went to https://developers.facebook.com/ and registered a new app.

And finally I've set my hashkey at the settings of Facebook developers:

But no whatter I do I keep getting the same error log:
"Key hash B5dWUEYfZJL/...........jyA= does not match any stored key hashes"

Does anybody know what I did wrong or how I can fix this problem?
If I used the id and name from the HelloFacebookSample inside my own app everything works.
So it HAS to do with the key hash, id or name I've set somewhere most likely..

Thank you,
Yenthe

答: I have tried everything on this page but no success, until i took a break, then when I continue working on this, without changing anything, it suddenly works. Maybe (just maybe) facebook needs times to register the key


问:
What's wrong with this Python code? PermissionError: [Errno 13]
This program is supposed to be able to download the contents from an http: URL and save it to a user's directory of choice.

```<code>import urllib.request
import urllib.error

def run_user_interface() -> None:
    url = _choose_url()
    if len(url) == 0:
    return
    else:
        print()
        save_path = _choose_save_path()

        if len(save_path) == 0:
            return
        else:
            _download_url(url, save_path)

def _choose_url() -> str:
    print('Choose a URL to download (press Enter or Return to quit)')
    return input('URL: ').strip()

def _choose_save_path() -> str:
    print('Choose where you\'d like to save the file you download')
    return input('Path: ').strip()

def _download_url(url_to_download: str, file_path: str) -> None:
    response = None
    file_to_save = None

    try:
        response = urllib.request.urlopen(url_to_download)
        file_to_save = open(file_path, 'wb')
        file_to_save.write(response.read())

    except urllib.error.HTTPError as e:
        print('Failed to download contents of URL')
    print('Status code: {}'.format(e.code))
    print()

    finally:
        if file_to_save != None:
            file_to_save.close()

        if response != None:
        response.close()

if __name__ == '__main__':
    run_user_interface()
</code>```

Executing the program on my friend's computer works fine. However, when I execute it on my computer, I receive the following error.

```<code>Traceback (most recent call last):
File "C:\Users\garci\Desktop\ICS_32_Winter_2020\new_download_file.py", line 63, in <module>
run_user_interface()

  File "C:\Users\garci\Desktop\ICS_32_Winter_2020\new_download_file.py", line 20, in run_user_interface
_download_url(url, save_path)

  File "C:\Users\garci\Desktop\ICS_32_Winter_2020\new_download_file.py", line 40, in _download_url
file_to_save = open(file_path, 'wb')

PermissionError: [Errno 13] Permission denied: 'C:\\Users\\garci\\Desktop\\ICS_32_Winter_2020'
</code>```

How could I fix this permission error? Thank you.

答:
There are 3 reasons why this could be happening:

The file is being used while being written. To get around this, CLOSE THE FILE

The directory you're writing to is write protected (highly unlikely) unless you did this yourself.

Not enough permissions are granted to python to read/write files. To overcome this, use Windows Key + X and then press A, which shall open a cmd promt with admin priveleges. Change directory and try running the script.

Body:
This program is supposed to be able to download the contents from an http: URL and save it to a user's directory of choice.

import urllib.request
import urllib.error

def run_user_interface() -> None:
    url = _choose_url()
    if len(url) == 0:
    return
    else:
        print()
        save_path = _choose_save_path()

        if len(save_path) == 0:
            return
        else:
            _download_url(url, save_path)

def _choose_url() -> str:
    print('Choose a URL to download (press Enter or Return to quit)')
    return input('URL: ').strip()

def _choose_save_path() -> str:
    print('Choose where you\'d like to save the file you download')
    return input('Path: ').strip()

def _download_url(url_to_download: str, file_path: str) -> None:
    response = None
    file_to_save = None

    try:
        response = urllib.request.urlopen(url_to_download)
        file_to_save = open(file_path, 'wb')
        file_to_save.write(response.read())

    except urllib.error.HTTPError as e:
        print('Failed to download contents of URL')
    print('Status code: {}'.format(e.code))
    print()

    finally:
        if file_to_save != None:
            file_to_save.close()

        if response != None:
        response.close()

if __name__ == '__main__':
    run_user_interface()

Executing the program on my friend's computer works fine. However, when I execute it on my computer, I receive the following error.

Traceback (most recent call last):
File "C:\Users\garci\Desktop\ICS_32_Winter_2020\new_download_file.py", line 63, in <module>
run_user_interface()

  File "C:\Users\garci\Desktop\ICS_32_Winter_2020\new_download_file.py", line 20, in run_user_interface
_download_url(url, save_path)

  File "C:\Users\garci\Desktop\ICS_32_Winter_2020\new_download_file.py", line 40, in _download_url
file_to_save = open(file_path, 'wb')

PermissionError: [Errno 13] Permission denied: 'C:\\Users\\garci\\Desktop\\ICS_32_Winter_2020'

How could I fix this permission error? Thank you.


问:
Parse JSON array APEX_JSON in PL SQL
I have the following JSON object -

```<code>{
  "items": [
    {
      "tableName": "contacts",
      "count": 1,
      "columnNames": [
        "id"
      ],
      "rows": [
        [
          "45"
        ]
      ]
    }
  ],
  "links": [
    {
      "rel": "self",

    },
    {
      "rel": "describedby",

    }
  ]
}
</code>```

I am trying to extract the value from rows- I need the value 45.

I tried to extract using -

```<code>row_id := apex_json.get_number ('rows[%d]', 1);
</code>```

How I can extract it?
Thanks in advance.

答:
Here's an example:

```<code>declare

  l_json_val apex_json.t_values;
  l_clob     clob;
  l_row_val  varchar2(255);

begin

  l_clob := q'-
    {
      "items": [
        {
          "tableName": "contacts",
          "count": 1,
          "columnNames": [
            "id"
          ],
          "rows": [
            [
              "45"
            ]
          ]
        }
      ],
      "links": [
        {
          "rel": "self",

        },
        {
          "rel": "describedby",

        }
      ]
    }
  -';

  apex_json.parse(p_values => l_json_val, p_source => l_clob, p_strict => false);

  l_row_val := apex_json.get_varchar2(p_path => 'items[1].rows[1][1]', p_values => l_json_val);

  dbms_output.put_line(l_row_val);

end;
</code>```

Note that the path expressions with apex_json use a 1 base array index, not 0.

Title: Parse JSON array APEX_JSON in PL SQL

Body:
I have the following JSON object -

{
  "items": [
    {
      "tableName": "contacts",
      "count": 1,
      "columnNames": [
        "id"
      ],
      "rows": [
        [
          "45"
        ]
      ]
    }
  ],
  "links": [
    {
      "rel": "self",

    },
    {
      "rel": "describedby",

    }
  ]
}

I am trying to extract the value from rows- I need the value 45.

I tried to extract using -

row_id := apex_json.get_number ('rows[%d]', 1);

How I can extract it?
Thanks in advance.

Body:
Here's an example:

declare

  l_json_val apex_json.t_values;
  l_clob     clob;
  l_row_val  varchar2(255);

begin

  l_clob := q'-
    {
      "items": [
        {
          "tableName": "contacts",
          "count": 1,
          "columnNames": [
            "id"
          ],
          "rows": [
            [
              "45"
            ]
          ]
        }
      ],
      "links": [
        {
          "rel": "self",

        },
        {
          "rel": "describedby",

        }
      ]
    }
  -';

  apex_json.parse(p_values => l_json_val, p_source => l_clob, p_strict => false);

  l_row_val := apex_json.get_varchar2(p_path => 'items[1].rows[1][1]', p_values => l_json_val);

  dbms_output.put_line(l_row_val);

end;

Note that the path expressions with apex_json use a 1 base array index, not 0.


问:
Adding input to a string with a max of 10 words C#
I am creating for my studies a program a simple one. In this program I need to make a sentence of 10 words. After the last input however I want to make it stop. So what I tried is this:
Create an empty string called textt, use a while loop since I make it always true it will proceed, create a string with the assignement that shows up in the program to the user aSentence its called, take an int named count and give it the value of 0, then I start my for loop I use the for loop cause I can add a condition and iterator so it stops and of course the initializer.

In the for loop I: print out the aSentence ( the user will read this ), I put a string called input and let the user put in a word ( I'm a beginner I do not know if how to make an error if the user put two words but thats not the assignment now ), I put the string textt since they are immutable but not in here and I add " " for create empty space and of course the input. Then I print out the textt what the user wrote down and I increment ( if I say this correctly ) with i++.

Then I start an if statement which says that if i ( see my for loop ) is equal == to 9 cause I increment this in my for loop it should print out End of the sentence, show the whole textt and then break.

However for some reason the loop is infinite everytime you input something. And the line End of the sentence will show up now and then and now when the loop should be finished at 9.
My question how do I fix this to make sure the sentencenends when 10 words have been inputted by the user and the End of the sentence pops up at exactly 10 input words.

```<code>using System;

namespace Opgave_10_woorden_invoegen_in_1_string_plakken
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a program that stops after input of 10 words
            string textt = "";
            while (true)
            {
                string aSentence = new string("We are making a sentence of 10 words.");
                int count = 0;
                for (int i = 0; i < 9; i++)
                {
                    Console.WriteLine(aSentence);
                    string input = Console.ReadLine();
                    textt = textt + " " + input;
                    Console.WriteLine(textt, i++);
                    if (i == 9)
                    {
                        Console.WriteLine("End of the sentence", textt);
                        break;
                    }
                }
            }
        }
    }
}
</code>```

答:
Combining my comments into an answer:

while(true) will run forever (unless some code calls break). Your inner for loop should work fine - why not just remove the while loop?

And your for loop condition should be < 10, since you want 10 items and the count is starting at 0. And you don't need a break statement inside a for loop, since the condition is built-in at the for statement.

There's also a problem in that you're incrementing i twice: once in the for statement iterator and again in the body of the for loop, so i will become 9 in only 5 iterations. Remove the inner increment. See the for statement documentation here.

Also, you don't need to do call a string constructor for the string assignment (does that even compile?). Just assign the string directly: string aSentance = "We are making a sentence of 10 words.";

Finally, you might look at the documentation for Console.WriteLine. The second variable you're passing to it isn't likely what you think it should be.

To put this all into a sample:

```<code>static void Main()
{
    //Create a program that stops after input of 10 words
    string textt = "";
    string aSentence = "We are making a sentence of 10 words.";

    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine(aSentence);
        textt = textt + " " + Console.ReadLine();
        Console.WriteLine(textt);
    }

    Console.WriteLine("End of the sentence");
    Console.ReadKey();
}
</code>```

Body:
I am creating for my studies a program a simple one. In this program I need to make a sentence of 10 words. After the last input however I want to make it stop. So what I tried is this:
Create an empty string called textt, use a while loop since I make it always true it will proceed, create a string with the assignement that shows up in the program to the user aSentence its called, take an int named count and give it the value of 0, then I start my for loop I use the for loop cause I can add a condition and iterator so it stops and of course the initializer.

In the for loop I: print out the aSentence ( the user will read this ), I put a string called input and let the user put in a word ( I'm a beginner I do not know if how to make an error if the user put two words but thats not the assignment now ), I put the string textt since they are immutable but not in here and I add " " for create empty space and of course the input. Then I print out the textt what the user wrote down and I increment ( if I say this correctly ) with i++.

Then I start an if statement which says that if i ( see my for loop ) is equal == to 9 cause I increment this in my for loop it should print out End of the sentence, show the whole textt and then break.

However for some reason the loop is infinite everytime you input something. And the line End of the sentence will show up now and then and now when the loop should be finished at 9.
My question how do I fix this to make sure the sentencenends when 10 words have been inputted by the user and the End of the sentence pops up at exactly 10 input words.

using System;

namespace Opgave_10_woorden_invoegen_in_1_string_plakken
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a program that stops after input of 10 words
            string textt = "";
            while (true)
            {
                string aSentence = new string("We are making a sentence of 10 words.");
                int count = 0;
                for (int i = 0; i < 9; i++)
                {
                    Console.WriteLine(aSentence);
                    string input = Console.ReadLine();
                    textt = textt + " " + input;
                    Console.WriteLine(textt, i++);
                    if (i == 9)
                    {
                        Console.WriteLine("End of the sentence", textt);
                        break;
                    }
                }
            }
        }
    }
}

Body:
Combining my comments into an answer:

while(true) will run forever (unless some code calls break). Your inner for loop should work fine - why not just remove the while loop?

And your for loop condition should be < 10, since you want 10 items and the count is starting at 0. And you don't need a break statement inside a for loop, since the condition is built-in at the for statement.

There's also a problem in that you're incrementing i twice: once in the for statement iterator and again in the body of the for loop, so i will become 9 in only 5 iterations. Remove the inner increment. See the for statement documentation here.

Also, you don't need to do call a string constructor for the string assignment (does that even compile?). Just assign the string directly: string aSentance = "We are making a sentence of 10 words.";

Finally, you might look at the documentation for Console.WriteLine. The second variable you're passing to it isn't likely what you think it should be.

To put this all into a sample:

static void Main()
{
    //Create a program that stops after input of 10 words
    string textt = "";
    string aSentence = "We are making a sentence of 10 words.";

    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine(aSentence);
        textt = textt + " " + Console.ReadLine();
        Console.WriteLine(textt);
    }

    Console.WriteLine("End of the sentence");
    Console.ReadKey();
}


问:
Convert for loop into numpy array

for timeprojection in range(100):
   for term in range(8):
       zerocouponbondprice[timeprojection,term] = zerocouponbondprice[timeprojection-1,term-1]*cashflow[timeprojection,term]
```

How can I convert something like this into numpy array form, so that I can reduce two for loop to increase the speed? (If timeprojection and term are dynamic numbers.)

Title: Convert for loop into numpy array

Body:
for timeprojection in range(100):
   for term in range(8):
       zerocouponbondprice[timeprojection,term] = zerocouponbondprice[timeprojection-1,term-1]*cashflow[timeprojection,term]

How can I convert something like this into numpy array form, so that I can reduce two for loop to increase the speed? (If timeprojection and term are dynamic numbers.)

Body:
If I get the question right, you can replace the two loops / ranges by using appropriate indexing. A simplified example:

import numpy as np

# these would be your input arrays zerocouponbondprice and cashflow:
arr0, arr1 = np.ones((10,10)), np.ones((10,10))

# these would be your ranges:
idx0, idx1 = 3, 9

# now you can do the calculation as simple as
arr0[idx0:idx1, idx0:idx1] = arr0[idx0-1:idx1-1, idx0-1:idx1-1] + arr1[idx0:idx1, idx0:idx1]

print(arr0)
[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
  [1. 1. 1. 2. 2. 2. 2. 2. 2. 1.]
  [1. 1. 1. 2. 2. 2. 2. 2. 2. 1.]
  [1. 1. 1. 2. 2. 2. 2. 2. 2. 1.]
  [1. 1. 1. 2. 2. 2. 2. 2. 2. 1.]
  [1. 1. 1. 2. 2. 2. 2. 2. 2. 1.]
  [1. 1. 1. 2. 2. 2. 2. 2. 2. 1.]
  [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]


问:
Get an Item of a Custom View
Hellow guys,
I have an android resource layout file view_notification_badge.xml as below

```<code>`<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/badge"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_gravity="top|center_horizontal"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:padding="3dp"
        android:visibility="gone"
        app:srcCompat="@drawable/ic_notify_50" />

    <com.adalipa.smartcard.api.payment.font.RobotoTextView
        android:id="@+id/badgecount"
        style="@style/ButtonStyle.RaisedEmpty"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top|center_horizontal"
        android:layout_margin="0dp"
        android:minWidth="112dp"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:padding="3dp"
        android:textStyle="bold"
        android:text="0"
        android:textColor="#FF3D00"
        android:textSize="16dp"
        android:visibility="visible"
        tools:ignore="PrivateResource" />
</FrameLayout>`
</code>```

and i have my MainActivity.java method that sets the badge on the BottomNavigationView as below

```<code>BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationView.getChildAt(0);
                BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(2);
                notificationBadge = LayoutInflater.from(this).inflate(R.layout.view_notification_badge, menuView, false);

                itemView.addView(notificationBadge);
</code>```

My issue is how can i get the RobotoTextView item badgecount in XML fileso that  so that i can set text to it using my my Java code?. Thank you in advance

答:
Since you know the id of the TextView, you can use View.findViewById() on the inflated View:

```<code>TextView tvCount = notificationBadge.findViewById(R.id.badgecount);
</code>```

Title: Get an Item of a Custom View

Body:
Hellow guys,
I have an android resource layout file view_notification_badge.xml as below

`<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/badge"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_gravity="top|center_horizontal"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:padding="3dp"
        android:visibility="gone"
        app:srcCompat="@drawable/ic_notify_50" />

    <com.adalipa.smartcard.api.payment.font.RobotoTextView
        android:id="@+id/badgecount"
        style="@style/ButtonStyle.RaisedEmpty"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top|center_horizontal"
        android:layout_margin="0dp"
        android:minWidth="112dp"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:padding="3dp"
        android:textStyle="bold"
        android:text="0"
        android:textColor="#FF3D00"
        android:textSize="16dp"
        android:visibility="visible"
        tools:ignore="PrivateResource" />
</FrameLayout>`

and i have my MainActivity.java method that sets the badge on the BottomNavigationView as below

BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationView.getChildAt(0);
                BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(2);
                notificationBadge = LayoutInflater.from(this).inflate(R.layout.view_notification_badge, menuView, false);

                itemView.addView(notificationBadge);

My issue is how can i get the RobotoTextView item badgecount in XML fileso that  so that i can set text to it using my my Java code?. Thank you in advance

Body:
Since you know the id of the TextView, you can use View.findViewById() on the inflated View:

TextView tvCount = notificationBadge.findViewById(R.id.badgecount);


问:
How can I preserve both matching and non-matching parts using immutable collection in O(n) time
I have to operate on tmp list based on some condition.
false does a bulk db insert and true does an update

```<code>val tmp = List(1,2,3, 15)
val bool = List(true, true, true, false)
</code>```

I am using the below approach to create 2 lists , one matching and one non-matching.

```<code>val result = tmp.zip(bool).partition {
case tuple if tuple._2 => true
case tuple if !tuple._2 => false
}
</code>```

I get 2 lists , so I can run insertAll(result._2) and updateAll(result._1)

Since partition uses scala.collection.mutable.Builder, I was trying to find an approach that solves the problem using immutable collections.

答:
This is a recursive partition function using immutable data

```<code>def part[T](list: List[T])(f: T => Boolean): (List[T], List[T]) = {
  @annotation.tailrec
  def loop(rem: List[T], res1: List[T], res2: List[T]): (List[T], List[T]) =
    rem match {
      case Nil =>
        (res1.reverse, res2.reverse)
      case hd :: tail =>
        if (f(hd)) {
          loop(tail, hd +: res1, res2)
        } else {
          loop(tail, res1, hd +: res2)
        }
    }

  loop(list, Nil, Nil)
}
</code>```

This solution is built in reverse to keep the algorithm O(n)

Body:
I have to operate on tmp list based on some condition.
false does a bulk db insert and true does an update

val tmp = List(1,2,3, 15)
val bool = List(true, true, true, false)

I am using the below approach to create 2 lists , one matching and one non-matching.

val result = tmp.zip(bool).partition {
case tuple if tuple._2 => true
case tuple if !tuple._2 => false
}

I get 2 lists , so I can run insertAll(result._2) and updateAll(result._1)

Since partition uses scala.collection.mutable.Builder, I was trying to find an approach that solves the problem using immutable collections.

Body:
This is a recursive partition function using immutable data

def part[T](list: List[T])(f: T => Boolean): (List[T], List[T]) = {
  @annotation.tailrec
  def loop(rem: List[T], res1: List[T], res2: List[T]): (List[T], List[T]) =
    rem match {
      case Nil =>
        (res1.reverse, res2.reverse)
      case hd :: tail =>
        if (f(hd)) {
          loop(tail, hd +: res1, res2)
        } else {
          loop(tail, res1, hd +: res2)
        }
    }

  loop(list, Nil, Nil)
}

This solution is built in reverse to keep the algorithm O(n)


问:
How to define a path with two optional parameters in OpenAPI 3.0?
I registered at SwaggerHub and created a new API using OpenAPI 3.0. In my API, the /tasks path has 2 non-required parameters, but I can not set them as not required - the editor shows the "Not allowed Values" error.

Here's my API definition:

openapi: 3.0.0
info:
  description: A Simple IP Address API
  title: VTasks
  version: v1
servers:
# Added by API Auto Mocking Plugin
  - description: SwaggerHub API Auto Mocking
    url: https://virtserver.swaggerhub.com/petrogromovo/Vtasks/1.0.0
  - description: SwaggerHub API Auto Mocking
    url: http://hosting.tk

paths:

  /tasks:
    get:
      tags:
        - tasks
      summary: Get paginated / filtered tasks listing
      operationId: tasks
      parameters:
        - name: page
          in: path
          description: The page number to be fetched. If missed default 1.
          required: true
          schema:
            type: integer
        - name: order_by
          in: path
          description: The order_by  be fetched.
          required: false  // ERROR : should be equal to one of the allowed values allowedValues: true
          schema:
            type: string
        - name: filter
          in: path
          description: The filter for title field.
          required: false // ERROR : should be equal to one of the allowed values allowedValues: true
          schema:
            type: string
      responses:
        '200':
          description: successful operation
        '400':
          description: Invalid tasks supplied
        '404':
          description: tasks were not found
```

But if I remove the required attributes, I get 2 errors:

should have required property 'required'

  missingProperty: required

What is the valid syntax?

答:
Are these parameters supposed to be path parameters or query parameters?

Path parameters (in: path) are part of the endpoint path, and as such must be indicated by {...} in the path template:

```<code>paths:
  /tasks/{page}/{order_by}/{filter}:
</code>```

Path parameters are always required, i.e. they must have required: true.

Query parameters are send in the query string, e.g. /tasks?page=...&order_by=.... To use query parameters, change the parameter location to in: query.

More information: Describing Parameters

Body:
I registered at SwaggerHub and created a new API using OpenAPI 3.0. In my API, the /tasks path has 2 non-required parameters, but I can not set them as not required - the editor shows the "Not allowed Values" error.

Here's my API definition:

openapi: 3.0.0
info:
  description: A Simple IP Address API
  title: VTasks
  version: v1
servers:
# Added by API Auto Mocking Plugin
  - description: SwaggerHub API Auto Mocking
    url: https://virtserver.swaggerhub.com/petrogromovo/Vtasks/1.0.0
  - description: SwaggerHub API Auto Mocking
    url: http://hosting.tk

paths:

  /tasks:
    get:
      tags:
        - tasks
      summary: Get paginated / filtered tasks listing
      operationId: tasks
      parameters:
        - name: page
          in: path
          description: The page number to be fetched. If missed default 1.
          required: true
          schema:
            type: integer
        - name: order_by
          in: path
          description: The order_by  be fetched.
          required: false  // ERROR : should be equal to one of the allowed values allowedValues: true
          schema:
            type: string
        - name: filter
          in: path
          description: The filter for title field.
          required: false // ERROR : should be equal to one of the allowed values allowedValues: true
          schema:
            type: string
      responses:
        '200':
          description: successful operation
        '400':
          description: Invalid tasks supplied
        '404':
          description: tasks were not found

But if I remove the required attributes, I get 2 errors:

should have required property 'required'

  missingProperty: required

What is the valid syntax?

Body:
Are these parameters supposed to be path parameters or query parameters?

Path parameters (in: path) are part of the endpoint path, and as such must be indicated by {...} in the path template:

paths:
  /tasks/{page}/{order_by}/{filter}:

Path parameters are always required, i.e. they must have required: true.

Query parameters are send in the query string, e.g. /tasks?page=...&order_by=.... To use query parameters, change the parameter location to in: query.

More information: Describing Parameters


答:
You can do it as follows:

```<code>public class Main {
    public static void main(String[] args) {
        String[] ids = { "123456789_sample_code_xyz", "91343486_code_zxy" };
        String[] codeTypes = { "sample_code", "code", "formal_code" };
        String max;
        for (String id : ids) {
            max = "";
            for (String codeType : codeTypes) {
                if (id.contains(codeType)) {
                    if (max.length() < codeType.length()) {
                        max = codeType;
                    }
                }
            }
            System.out.println(id + " : " + max);
        }
    }
}
</code>```

Output:

```<code>123456789_sample_code_xyz : sample_code
91343486_code_zxy : code
</code>```

Title: JAVA return longest value if a string contains any of the items from a List

Body:
I have the following array of code types:

["sample_code","code","formal_code"]

and the following ids:

String id="123456789_sample_code_xyz";
String id2="91343486_code_zxy";

I want to extract the code type from the ids

this is my code snippet:

    String codeTypes[] = {"sample_code","code","formal_code"};
    String id= "123456789_sample_code_xyz";
    String codeType = Arrays.stream(codeTypes).parallel().filter(id::contains).findAny().get();
    System.out.println(codeType);

it doesnt work with the 1st id, because it returns "code" instead of "sample_code", I want to get the longest code type.

for the 1st id the code type should be "sample_code"
for the 2nd id the code type should be "code"

Body:
You can do it as follows:

public class Main {
    public static void main(String[] args) {
        String[] ids = { "123456789_sample_code_xyz", "91343486_code_zxy" };
        String[] codeTypes = { "sample_code", "code", "formal_code" };
        String max;
        for (String id : ids) {
            max = "";
            for (String codeType : codeTypes) {
                if (id.contains(codeType)) {
                    if (max.length() < codeType.length()) {
                        max = codeType;
                    }
                }
            }
            System.out.println(id + " : " + max);
        }
    }
}

Output:

123456789_sample_code_xyz : sample_code
91343486_code_zxy : code


问:
Cannot query field \"addWorkout\" on type \"Mutation\
I am fairly new to GraphQL, my previous question was regarding some reference error I was getting which I eventually resolved, however, now I am getting this error. It seems that I cannot add a workout as it doesn't recognize that it is a mutation field within the schema.

I keep getting the error of

```<code>Cannot query field \"addWorkout\" on type \"Mutation\
</code>```

Anyway, on app.js, this is my code

```<code>const express = require("express")
const app = express();
const userSchema = require("./graph-schema/userQueries")
const workoutSchema = require("./graph-schema/workoutQueries")
const mealSchema = require("./graph-schema/mealQueries")
const mongoose = require("mongoose")
const {mergeSchemas} = require("graphql-tools")

//connect to mongoDB atlase database
mongoose.connect("mongodb+srv://Zubair97:superman2008@cluster0-epauj.mongodb.net/test?retryWrites=true&w=majority")
mongoose.connection.once("open", () => {
    console.log("Connected to database")
})

const combinedSchemas = mergeSchemas({
    schemas: [
        userSchema,
        mealSchema,
        workoutSchema
    ],
})

//this module allows express to communicate with graphql ;
//we use it as a single endpoint
const graphqlHTTP = require("express-graphql")

app.use("/graphql" , graphqlHTTP({
    schema: combinedSchemas,
    graphiql: true

}))

app.listen(4000, () => {
    console.log(`Listening on port 4000`)
})
</code>```

The workout queries and mutations are defined in a file called workoutQueries.js, which I have exported, you can see that I have addWorkout defined in the resolvers

```<code>const graphql = require("graphql")
const {WorkoutType} = require("./schema")
const Workout = require("../models/Workout.js")
const {GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLInt, GraphQLList} = graphql;

const WorkoutQuery = new GraphQLObjectType({
    name: "WorkoutQuery",
    fields: () => ({
        workout: {
            type: WorkoutType,
            args: {id: {type: GraphQLID}},
            resolve(parent, args){
                //returns the workout instance from the database
                return Workout.findById(args.id)
            }

        },

        workouts: {
            type: new GraphQLList(WorkoutType),
            resolve(parent, args){
                //returns all workouts from the databse
                return Workout.find({})
            }
        }
    })

})

const WorkoutMutation = new GraphQLObjectType({
    name: "WorkoutMutation",
    addWorkout: {
        type: WorkoutType,
        args: {
            name: {type: GraphQLString},
            reps: {type: GraphQLInt},
            sets: {type: GraphQLInt},
            burnedCalories: {type: GraphQLInt},
            userId: {type: GraphQLID},

        },
        resolve(parent, args){
            let workout = new Workout({
                name: args.name,
                reps: args.reps,
                sets: args.sets,
                burnedCalories: args.burnedCalories,
                userId: args.userId
            })

            return workout.save();
        }
    },

})

module.exports = new GraphQLSchema({
    query: WorkoutQuery,
    mutation: WorkoutMutation
})
</code>```

Also, this issue is occurring even if I try to add a meal, the queries and mutations are defined at a file called mealQueries.js, which I have exported

```<code>const graphql = require("graphql")
const {MealType, NutritionType} = require("./schema")
const Meal = require("../models/Meal.js")
const {GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLInt, GraphQLList} = graphql;

const MealQuery = new GraphQLObjectType({
    name: "MealQueries",
    fields: () => ({
        meal: {
            type: MealType,
            args: {id: {type: GraphQLID}},
            resolve(parent, args){
                return Meal.findById(args.id)
            }
        },

        meals: {
            type: new GraphQLList(MealType),
            resolve(parent, args){
                return Meal.find({})
            }
        }

    })

})

const MealMutation = new GraphQLObjectType({
    name: "MealMutation",
    addMeal: {
        type: MealType,
        args: {
            name: {type: GraphQLString},
            servings: {type: GraphQLInt},
            calories: {type: GraphQLInt},
            nutrition: {type: NutritionType},
            userId: {type: GraphQLID}
        },
        resolve(parent, args){

            let meal = new Meal({
                userId: args.userId,
                name: args.name,
                servings: args.servings,
                calories: args.calories,
                nutrition: {
                    carbohydrates: args.nutrition.carbohydrates,
                    fats: args.nutrition.fats,
                    proteins: args.nutrition.proteins
                }
            })

            return meal.save();
        }
    }

})

module.exports = new GraphQLSchema({
    query: MealQuery,
    mutation: MealMutation
})
</code>```

I have no issue in creating a user and authenticating a user, the queries and mutation for that are defined in userQueries.js

```<code>const graphql = require("graphql")
const User = require("../models/User.js")
const bcrypt = require("bcrypt")
const jwt = require("jsonwebtoken")
const {AuthType, UserType} = require("./schema")
const {GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLInt, GraphQLList} = graphql;

const UserQuery = new GraphQLObjectType({
    name: "UserQuery",
    fields: () => ({
        user: {
            type: UserType,
            args: {id: {type: GraphQLID}},
            resolve(parent, args){
                //returns the user from the database
                return User.findById(args.id)
            }
        },
        login: {
            type: AuthType,
            args: {email: {type: GraphQLString}, password: {type: GraphQLString}},
            resolve(parent, {email, password}){
                return User.findOne({email: email}).then((user) => {
                    const isEqual = bcrypt.compare(password, user.password)
                    if (!isEqual) {
                        throw new Error('Password is incorrect!');
                    }

                    const token = jwt.sign({
                        userId: user.id,
                        email: user.email},
                        "a_super_secret",
                        {expiresIn: "1h"}
                    )

                    return {token: token, userId: user.id}

                })

            }
        }

    })

})

const UserMutation = new GraphQLObjectType({
    name: "Mutation",
    fields: {
        addUser: {
            type: UserType,
            args: {
                name: {type: GraphQLString},
                email: {type: GraphQLString},
                password: {type: GraphQLString}
            },
            async resolve(parent, args){
                const existingUser =  await User.findOne({email: args.email})
                if (!existingUser){
                    const error = new Error("User already exists");
                }

                const encryptedPassword =  await bcrypt.hash(args.password, 12)

                let user = new User({
                    name: args.name,
                    email: args.email,
                    password: encryptedPassword
                })

                const createdUser =  user.save();
                return createdUser
            }
        }

    }
})

module.exports = new GraphQLSchema({
    query: UserQuery,
    mutation: UserMutation,
})
</code>```

I have also defined the UserType, AuthType, MealType, NutritionType and WorkoutType in a file called schema.js

```<code>const graphql = require("graphql")
const Workout = require("../models/Workout.js")
const User = require("../models/User.js")
const Meal = require("../models/Meal")

const {GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLInt, GraphQLList} = graphql;

//describes what attributes and its types, a User has in each query
const UserType = new GraphQLObjectType({
    name: "User",
    fields: () => ({
        id: {type: GraphQLID},
        name: {type: GraphQLString},
        email: {type: GraphQLString},
        password: {type: GraphQLString},
        workouts: {
            type: new GraphQLList(WorkoutType),
            resolve(parent, args){
                //returns all the workouts created by a user
                return Workout.findById({userId: parent.id})
            }
        },
        meals: {
            type: new GraphQLList(MealType),
            resolve(parent, args){
                //returns all the meals created by a user
                return Meal.findById({userId: parent.id})
            }
        }

    })
})

const NutritionType = new GraphQLObjectType({
    name: "Nutrition",
    fields: () => ({
        carbohydrates: {type: GraphQLInt},
        fats: {type: GraphQLInt},
        proteins: {type: GraphQLInt}
    })
})

const WorkoutType = new GraphQLObjectType({
    name: "Workout",
    fields: () => ({
        id: {type: GraphQLID},
        name: {type: GraphQLString},
        reps: {type: GraphQLInt},
        burnedCalories: {type: GraphQLInt},
        sets: {type: GraphQLInt},
        user: {
            type: UserType,
            resolve(parent, args){
                //returns the user from the database that created the workout instance
                return User.findById(parent.userId)

            }
        }

    })
})

const AuthType = new GraphQLObjectType({
    name: "Authentication",
    fields: () => ({
        token: {type: GraphQLString},
        userId: {type: GraphQLString}
    })
})

const MealType = new GraphQLObjectType({
    name: "Meal",
    fields: () => ({
        id: {type: GraphQLID},
        calories: {type: GraphQLInt},
        servings: {type: GraphQLInt},
        nutrition: {type: NutritionType},
        user: {
            type: UserType,
            resolve(parent, args){
                //returns the user from the database that created the meal instance
                return User.findById(parent.userId)
            }
        }

    })
})

module.exports = {
    AuthType,
    WorkoutType,
    UserType,
    MealType,
    NutritionType
}
</code>```

I suspect the error I am getting is due to mergeSchema object from graphql-tools, maybe it cannot merge the GraphQLSchema types properly? I am not sure. Any help is appreciated!

答:
mergeSchemas is intended to be used with schema stitching. It should not be used just to modularize your single schema, which is what you're trying to do here.

You should only create a single GraphQLSchema object, a single GraphQLObjectType for your query root type and a single GraphQLObjectType for your mutation root type. If you want the fields for a specific type, like your Mutation type, to be spread across multiple modules, then you should export just those fields, not an entire type or schema.

```<code>module.exports = {
  queries: {
    workout: { ... },
    workouts: { ... },
  },
  mutations: {
    addWorkout: { ... },
  },
}
</code>```

Whatever file you create your schema in can then import these fields from multiple  modules and combine them into an individual schema.

```<code>const query = new GraphQLObjectType({
  name: 'Query',
  fields: () => ({
    ...require('moduleA').queries,
    ...require('moduleB').queries,
    ...require('moduleC').queries,
  }),
})
const mutation = new GraphQLObjectType({ ... })
const schema = new GraphQLSchema({ query, mutation })
</code>```

Body:
I am fairly new to GraphQL, my previous question was regarding some reference error I was getting which I eventually resolved, however, now I am getting this error. It seems that I cannot add a workout as it doesn't recognize that it is a mutation field within the schema.

I keep getting the error of

Cannot query field \"addWorkout\" on type \"Mutation\

Anyway, on app.js, this is my code

const express = require("express")
const app = express();
const userSchema = require("./graph-schema/userQueries")
const workoutSchema = require("./graph-schema/workoutQueries")
const mealSchema = require("./graph-schema/mealQueries")
const mongoose = require("mongoose")
const {mergeSchemas} = require("graphql-tools")

//connect to mongoDB atlase database
mongoose.connect("mongodb+srv://Zubair97:superman2008@cluster0-epauj.mongodb.net/test?retryWrites=true&w=majority")
mongoose.connection.once("open", () => {
    console.log("Connected to database")
})

const combinedSchemas = mergeSchemas({
    schemas: [
        userSchema,
        mealSchema,
        workoutSchema
    ],
})

//this module allows express to communicate with graphql ;
//we use it as a single endpoint
const graphqlHTTP = require("express-graphql")

app.use("/graphql" , graphqlHTTP({
    schema: combinedSchemas,
    graphiql: true

}))

app.listen(4000, () => {
    console.log(`Listening on port 4000`)
})

The workout queries and mutations are defined in a file called workoutQueries.js, which I have exported, you can see that I have addWorkout defined in the resolvers

const graphql = require("graphql")
const {WorkoutType} = require("./schema")
const Workout = require("../models/Workout.js")
const {GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLInt, GraphQLList} = graphql;

const WorkoutQuery = new GraphQLObjectType({
    name: "WorkoutQuery",
    fields: () => ({
        workout: {
            type: WorkoutType,
            args: {id: {type: GraphQLID}},
            resolve(parent, args){
                //returns the workout instance from the database
                return Workout.findById(args.id)
            }

        },

        workouts: {
            type: new GraphQLList(WorkoutType),
            resolve(parent, args){
                //returns all workouts from the databse
                return Workout.find({})
            }
        }
    })

})

const WorkoutMutation = new GraphQLObjectType({
    name: "WorkoutMutation",
    addWorkout: {
        type: WorkoutType,
        args: {
            name: {type: GraphQLString},
            reps: {type: GraphQLInt},
            sets: {type: GraphQLInt},
            burnedCalories: {type: GraphQLInt},
            userId: {type: GraphQLID},

        },
        resolve(parent, args){
            let workout = new Workout({
                name: args.name,
                reps: args.reps,
                sets: args.sets,
                burnedCalories: args.burnedCalories,
                userId: args.userId
            })

            return workout.save();
        }
    },

})

module.exports = new GraphQLSchema({
    query: WorkoutQuery,
    mutation: WorkoutMutation
})

Also, this issue is occurring even if I try to add a meal, the queries and mutations are defined at a file called mealQueries.js, which I have exported

const graphql = require("graphql")
const {MealType, NutritionType} = require("./schema")
const Meal = require("../models/Meal.js")
const {GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLInt, GraphQLList} = graphql;

const MealQuery = new GraphQLObjectType({
    name: "MealQueries",
    fields: () => ({
        meal: {
            type: MealType,
            args: {id: {type: GraphQLID}},
            resolve(parent, args){
                return Meal.findById(args.id)
            }
        },

        meals: {
            type: new GraphQLList(MealType),
            resolve(parent, args){
                return Meal.find({})
            }
        }

    })

})

const MealMutation = new GraphQLObjectType({
    name: "MealMutation",
    addMeal: {
        type: MealType,
        args: {
            name: {type: GraphQLString},
            servings: {type: GraphQLInt},
            calories: {type: GraphQLInt},
            nutrition: {type: NutritionType},
            userId: {type: GraphQLID}
        },
        resolve(parent, args){

            let meal = new Meal({
                userId: args.userId,
                name: args.name,
                servings: args.servings,
                calories: args.calories,
                nutrition: {
                    carbohydrates: args.nutrition.carbohydrates,
                    fats: args.nutrition.fats,
                    proteins: args.nutrition.proteins
                }
            })

            return meal.save();
        }
    }

})

module.exports = new GraphQLSchema({
    query: MealQuery,
    mutation: MealMutation
})

I have no issue in creating a user and authenticating a user, the queries and mutation for that are defined in userQueries.js

const graphql = require("graphql")
const User = require("../models/User.js")
const bcrypt = require("bcrypt")
const jwt = require("jsonwebtoken")
const {AuthType, UserType} = require("./schema")
const {GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLInt, GraphQLList} = graphql;

const UserQuery = new GraphQLObjectType({
    name: "UserQuery",
    fields: () => ({
        user: {
            type: UserType,
            args: {id: {type: GraphQLID}},
            resolve(parent, args){
                //returns the user from the database
                return User.findById(args.id)
            }
        },
        login: {
            type: AuthType,
            args: {email: {type: GraphQLString}, password: {type: GraphQLString}},
            resolve(parent, {email, password}){
                return User.findOne({email: email}).then((user) => {
                    const isEqual = bcrypt.compare(password, user.password)
                    if (!isEqual) {
                        throw new Error('Password is incorrect!');
                    }

                    const token = jwt.sign({
                        userId: user.id,
                        email: user.email},
                        "a_super_secret",
                        {expiresIn: "1h"}
                    )

                    return {token: token, userId: user.id}

                })

            }
        }

    })

})

const UserMutation = new GraphQLObjectType({
    name: "Mutation",
    fields: {
        addUser: {
            type: UserType,
            args: {
                name: {type: GraphQLString},
                email: {type: GraphQLString},
                password: {type: GraphQLString}
            },
            async resolve(parent, args){
                const existingUser =  await User.findOne({email: args.email})
                if (!existingUser){
                    const error = new Error("User already exists");
                }

                const encryptedPassword =  await bcrypt.hash(args.password, 12)

                let user = new User({
                    name: args.name,
                    email: args.email,
                    password: encryptedPassword
                })

                const createdUser =  user.save();
                return createdUser
            }
        }

    }
})

module.exports = new GraphQLSchema({
    query: UserQuery,
    mutation: UserMutation,
})

I have also defined the UserType, AuthType, MealType, NutritionType and WorkoutType in a file called schema.js

const graphql = require("graphql")
const Workout = require("../models/Workout.js")
const User = require("../models/User.js")
const Meal = require("../models/Meal")

const {GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLInt, GraphQLList} = graphql;

//describes what attributes and its types, a User has in each query
const UserType = new GraphQLObjectType({
    name: "User",
    fields: () => ({
        id: {type: GraphQLID},
        name: {type: GraphQLString},
        email: {type: GraphQLString},
        password: {type: GraphQLString},
        workouts: {
            type: new GraphQLList(WorkoutType),
            resolve(parent, args){
                //returns all the workouts created by a user
                return Workout.findById({userId: parent.id})
            }
        },
        meals: {
            type: new GraphQLList(MealType),
            resolve(parent, args){
                //returns all the meals created by a user
                return Meal.findById({userId: parent.id})
            }
        }

    })
})

const NutritionType = new GraphQLObjectType({
    name: "Nutrition",
    fields: () => ({
        carbohydrates: {type: GraphQLInt},
        fats: {type: GraphQLInt},
        proteins: {type: GraphQLInt}
    })
})

const WorkoutType = new GraphQLObjectType({
    name: "Workout",
    fields: () => ({
        id: {type: GraphQLID},
        name: {type: GraphQLString},
        reps: {type: GraphQLInt},
        burnedCalories: {type: GraphQLInt},
        sets: {type: GraphQLInt},
        user: {
            type: UserType,
            resolve(parent, args){
                //returns the user from the database that created the workout instance
                return User.findById(parent.userId)

            }
        }

    })
})

const AuthType = new GraphQLObjectType({
    name: "Authentication",
    fields: () => ({
        token: {type: GraphQLString},
        userId: {type: GraphQLString}
    })
})

const MealType = new GraphQLObjectType({
    name: "Meal",
    fields: () => ({
        id: {type: GraphQLID},
        calories: {type: GraphQLInt},
        servings: {type: GraphQLInt},
        nutrition: {type: NutritionType},
        user: {
            type: UserType,
            resolve(parent, args){
                //returns the user from the database that created the meal instance
                return User.findById(parent.userId)
            }
        }

    })
})

module.exports = {
    AuthType,
    WorkoutType,
    UserType,
    MealType,
    NutritionType
}

I suspect the error I am getting is due to mergeSchema object from graphql-tools, maybe it cannot merge the GraphQLSchema types properly? I am not sure. Any help is appreciated!

Body:
mergeSchemas is intended to be used with schema stitching. It should not be used just to modularize your single schema, which is what you're trying to do here.

You should only create a single GraphQLSchema object, a single GraphQLObjectType for your query root type and a single GraphQLObjectType for your mutation root type. If you want the fields for a specific type, like your Mutation type, to be spread across multiple modules, then you should export just those fields, not an entire type or schema.

module.exports = {
  queries: {
    workout: { ... },
    workouts: { ... },
  },
  mutations: {
    addWorkout: { ... },
  },
}

Whatever file you create your schema in can then import these fields from multiple  modules and combine them into an individual schema.

const query = new GraphQLObjectType({
  name: 'Query',
  fields: () => ({
    ...require('moduleA').queries,
    ...require('moduleB').queries,
    ...require('moduleC').queries,
  }),
})
const mutation = new GraphQLObjectType({ ... })
const schema = new GraphQLSchema({ query, mutation })