问:
Coefficient of the features in the decision function. random forest
How can i do to get coefficient of the features in RandomForest() like model.coef_ in logistic regression.?

```<code>model = GridSearchCV(estimator=classifier,  param_grid=grid_param,
                     scoring='roc_auc',
                     cv=5,
                     n_jobs=-1)
best_model= model.fit(X_train, y_train)
best_model.feature_importances_
</code>```

答:
It's unclear which framework you're using, or even if you are using a framework...

But, if you are using sklearn, then you can access the feature importance with model.feature_importances_.

Body:
How can i do to get coefficient of the features in RandomForest() like model.coef_ in logistic regression.?

model = GridSearchCV(estimator=classifier,  param_grid=grid_param,
                     scoring='roc_auc',
                     cv=5,
                     n_jobs=-1)
best_model= model.fit(X_train, y_train)
best_model.feature_importances_


来源: stackexchange

问:
Visual Studio std::stringstream pubsetbuf does not work
pubsetbuf member of std::stringbuf is not working at all in Visual Studio 2010!

The code:

```<code>char *FileData = ... ;
unsigned long long FileDataLen = ... ;
std::stringstream *SS = new std::stringstream(std::stringstream::in | std::stringstream::out);
SS->rdbuf()->pubsetbuf( FileData, (std::streamsize)FileDataLen );
</code>```

pubsetbuf does nothing in Visual Studio!!!

Workaround #1:

```<code>std::stringstream *SS = new std::stringstream( std::string(FileData, (size_type)FileDataLen ) ),std::stringstream::in | std::stringstream::out);
</code>```

Workaround #2:

```<code>SS->rdbuf()->sputn(FileData, (streamsize)FileDataLen);
</code>```

But both of these workarounds produce unnecessary memory copying.
I definitely need a working pubsetbuf member of std::stringbuf.

答:
I recently encountered the same issue of setbuf not being implemented in Visual Studio 2017.

After some searching on Stack Overflow, I found a solution for an output stream that doesn't use copying of the buffer which I modified for an input stream. Here they are for reference.

Output Stream

Source: Setting the internal buffer used by a standard stream (pubsetbuf)

```
#include <streambuf>

template <typename char_type>
struct ostreambuf : public std::basic_streambuf<char_type, std::char_traits<char_type> >
{
    ostreambuf(char_type* buffer, std::streamsize bufferLength)
    {
        // set the "put" pointer the start of the buffer and record it's length.
        setp(buffer, buffer + bufferLength);
    }
};
```

Input Stream

Source: Internal buffer used by standard input stream (pubsetbuf)

```
#include <streambuf>

template <typename char_type>
struct istreambuf : public basic_streambuf<char_type, char_traits<char_type>>
{
    istreambuf(char_type* buffer, streamsize buffer_length)
    {
        // Set the "get" pointer to the start of the buffer, the next item, and record its length.
        this->setg(buffer, buffer, buffer + buffer_length);
    }
};

int main()
{
    ifstream infile(FILENAME, ifstream::binary);

    // Read entire file into buffer.
    infile.seekg(0, ios::end);
    streampos length = infile.tellg();
    infile.seekg(0, ios::beg);
    vector<char> buffer(length);
    //char* buffer = new char[length];
    infile.read(&buffer[0], length);
    infile.close();

    // Create buffer and point local_stream to it.
    istreambuf<char> istream_buffer(&buffer[0], length);
    istream local_stream(&istream_buffer);

    string str1;

    while (local_stream >> str1)
    {
        . . .
    }
}```

ContentLicense: CC BY-SA 3.0

Body:
pubsetbuf member of std::stringbuf is not working at all in Visual Studio 2010!

The code:

char *FileData = ... ;
unsigned long long FileDataLen = ... ;
std::stringstream *SS = new std::stringstream(std::stringstream::in | std::stringstream::out);
SS->rdbuf()->pubsetbuf( FileData, (std::streamsize)FileDataLen );

pubsetbuf does nothing in Visual Studio!!!

Workaround #1:

std::stringstream *SS = new std::stringstream( std::string(FileData, (size_type)FileDataLen ) ),std::stringstream::in | std::stringstream::out);

Workaround #2:

SS->rdbuf()->sputn(FileData, (streamsize)FileDataLen);

But both of these workarounds produce unnecessary memory copying.
I definitely need a working pubsetbuf member of std::stringbuf.

Body:
I recently encountered the same issue of setbuf not being implemented in Visual Studio 2017.

After some searching on Stack Overflow, I found a solution for an output stream that doesn't use copying of the buffer which I modified for an input stream. Here they are for reference.

Output Stream

Source: Setting the internal buffer used by a standard stream (pubsetbuf)

#include <streambuf>

template <typename char_type>
struct ostreambuf : public std::basic_streambuf<char_type, std::char_traits<char_type> >
{
    ostreambuf(char_type* buffer, std::streamsize bufferLength)
    {
        // set the "put" pointer the start of the buffer and record it's length.
        setp(buffer, buffer + bufferLength);
    }
};

Input Stream

Source: Internal buffer used by standard input stream (pubsetbuf)

#include <streambuf>

template <typename char_type>
struct istreambuf : public basic_streambuf<char_type, char_traits<char_type>>
{
    istreambuf(char_type* buffer, streamsize buffer_length)
    {
        // Set the "get" pointer to the start of the buffer, the next item, and record its length.
        this->setg(buffer, buffer, buffer + buffer_length);
    }
};

int main()
{
    ifstream infile(FILENAME, ifstream::binary);

    // Read entire file into buffer.
    infile.seekg(0, ios::end);
    streampos length = infile.tellg();
    infile.seekg(0, ios::beg);
    vector<char> buffer(length);
    //char* buffer = new char[length];
    infile.read(&buffer[0], length);
    infile.close();

    // Create buffer and point local_stream to it.
    istreambuf<char> istream_buffer(&buffer[0], length);
    istream local_stream(&istream_buffer);

    string str1;

    while (local_stream >> str1)
    {
        . . .
    }
}

ContentLicense: CC BY-SA 4.0


问:
display only fixed no of items in Recycler view and remaining items in new page(using Show all)
i have 100 items which is parsed from a JSON file.
i want to display 20 items in a recycler(horizontal scroll) and on reaching the 20th item i want to add a footer that shows a "Show ALL"(imagebutton) which when clicked goes to a new page where you can view all the 100 items in a grid view//
,my doubt is how can i just display only 20 items out of the 100 items in the first page.</p>

答: Just set the size of the adapter 20.when you click show more then move to next page and show all data.</p>


答:
Random forest is an ensemble of decision trees, it is not a linear model. Sklearn provides importance of individual features which were used to train a random forest classifier or regressor. It can be accessed as follows, and returns an array of decimals which sum to 1.

```<code>model.feature_importances_
</code>```

If you want to see this in combination of feature names, then you can use zip(<feature names>, model.feature_importances_), and cast it to list.

Title: Coefficient of the features in the decision function. random forest

Body:
Random forest is an ensemble of decision trees, it is not a linear model. Sklearn provides importance of individual features which were used to train a random forest classifier or regressor. It can be accessed as follows, and returns an array of decimals which sum to 1.

model.feature_importances_

If you want to see this in combination of feature names, then you can use zip(<feature names>, model.feature_importances_), and cast it to list.


问:
Catchable Fatal Error: Argument 1 passed to "...\FormType::__construct() must implement interface
I am trying to call entityManager in formType. I don't get why this is not working.

FormType :

```<code>private $manager;

public function __construct(ObjectManager $manager)
{
    $this->manager = $manager;
}
</code>```

Controller:

```<code>$form = $this->createForm(ProductsType::class, $products);
</code>```

Services:

```<code>apx.form.type.product:
    class: ApxDev\UsersBundle\Form\ProductType
    arguments: ["@doctrine.orm.entity_manager"]
    tags:
        - { name: form.type }
</code>```

Error:

Catchable Fatal Error: Argument 1 passed to MyBundle\Form\FormType::__construct() must implement interface Doctrine\Common\Persistence\ObjectManager, none given, called in vendor/symfony/symfony/src/Symfony/Component/Form/FormRegistry.php on line 90 and defined

答:
Try in services.yml:

```apx.form.type.product:
    class: ApxDev\UsersBundle\Form\ProductType
    arguments:
        - '@doctrine.orm.entity_manager'
    tags:
        - { name: form.type }```

Symfony 3.4

Body:
I am trying to call entityManager in formType. I don't get why this is not working.

FormType :

private $manager;

public function __construct(ObjectManager $manager)
{
    $this->manager = $manager;
}

Controller:

$form = $this->createForm(ProductsType::class, $products);

Services:

apx.form.type.product:
    class: ApxDev\UsersBundle\Form\ProductType
    arguments: ["@doctrine.orm.entity_manager"]
    tags:
        - { name: form.type }

Error:

Catchable Fatal Error: Argument 1 passed to MyBundle\Form\FormType::__construct() must implement interface Doctrine\Common\Persistence\ObjectManager, none given, called in vendor/symfony/symfony/src/Symfony/Component/Form/FormRegistry.php on line 90 and defined

Body:
Try in services.yml:

apx.form.type.product:
    class: ApxDev\UsersBundle\Form\ProductType
    arguments:
        - '@doctrine.orm.entity_manager'
    tags:
        - { name: form.type }

Symfony 3.4


问:
How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?
This is running on Windows Server 2008 and used to work several months ago.  I am just now using this server again for some dev work with VS.

This is live web server used to serve up a few test sites as well.

This came up when running Visual Studio, then launching my projects for debugging.

Trying to launch any site through localhost:xxxx when IISExpress has been launched (using actual port #'s in the config to access different sites):

```<code>This webpage is not available

ERR_CONNECTION_REFUSED
</code>```

I have been at this for a few days already, as I have read others have had similar issues, tried most things I have read including changing the managedruntimeversion from "v4.0" to "v4.0.30319" for .net 4.5 (I have never had to do this before) and disabling the logging module (all suggestions found here).

There are only two entries in my hosts file that point to internal server IP addresses.  No localhost related IP's or references.

I have gone as far as re-installing IIS Express, and Visual Studio 2013. I also created a brand new WebApplication site to try to resolve this (simple and no other complicated bindings).

When I spin up Fiddler, I see the following on the page:

```<code>[Fiddler] The socket connection to localhost failed.
ErrorCode: 10061.
No connection could be made because the target machine actively refused it 127.0.0.1:23162
</code>```

I have removed all proxy settings from IE's LAN connection section, where before I was getting a red-x popup in VS indicating something like IISExpress could not launch.

This is not a matter of SSL vs non SSL.

I had TFS Server installed - uninstalled that in case there were some odd bindings that were interfering.

I tried deleting the IISExpress config/settings folder several times.

Current applicationhost.config contains:

```<code><site name="WebApplication1" id="4">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="C:\TFS-WorkRepository\Sandbox\WebApplication1\WebApplication1" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:23162:localhost" />
                </bindings>
            </site>
            <siteDefaults>
                <logFile logFormat="W3C" directory="%IIS_USER_HOME%\Logs" />
                <traceFailedRequestsLogging directory="%IIS_USER_HOME%\TraceLogFiles" enabled="true" maxLogFileSizeKB="1024" />
            </siteDefaults>
            <applicationDefaults applicationPool="Clr4IntegratedAppPool" />
</code>```

I wish there was a tag for really-stuck.

Please suggest away, as I don't want to go as far as spinning up a new server.

-- UPDATE --

In the URL bar, when I enter the computer name or IP address :xxxx I get the ERR_CONNECTION_TIMED_OUT rather than ERR_CONNECTION_REFUSED.

答:
While probably not related to your problem, I had the same issue today. As it turns out, I had enabled an URL Rewrite module to force my site to use HTTPS instead of HTTP and on my production environment, this worked just fine. But on my development system, where it runs as an application within my default site, it failed...

As it turns out, my default site had no binding for HTTPS so the rewrite module would send me from HTTP to HTTPS, yet nothing was listening to the HTTPS port...

There's a chance that you have this issue for a similar reason. This error seems to occur if there's no proper binding for the site you're trying to access...

Body:
This is running on Windows Server 2008 and used to work several months ago.  I am just now using this server again for some dev work with VS.

This is live web server used to serve up a few test sites as well.

This came up when running Visual Studio, then launching my projects for debugging.

Trying to launch any site through localhost:xxxx when IISExpress has been launched (using actual port #'s in the config to access different sites):

This webpage is not available

ERR_CONNECTION_REFUSED

I have been at this for a few days already, as I have read others have had similar issues, tried most things I have read including changing the managedruntimeversion from "v4.0" to "v4.0.30319" for .net 4.5 (I have never had to do this before) and disabling the logging module (all suggestions found here).

There are only two entries in my hosts file that point to internal server IP addresses.  No localhost related IP's or references.

I have gone as far as re-installing IIS Express, and Visual Studio 2013. I also created a brand new WebApplication site to try to resolve this (simple and no other complicated bindings).

When I spin up Fiddler, I see the following on the page:

[Fiddler] The socket connection to localhost failed.
ErrorCode: 10061.
No connection could be made because the target machine actively refused it 127.0.0.1:23162

I have removed all proxy settings from IE's LAN connection section, where before I was getting a red-x popup in VS indicating something like IISExpress could not launch.

This is not a matter of SSL vs non SSL.

I had TFS Server installed - uninstalled that in case there were some odd bindings that were interfering.

I tried deleting the IISExpress config/settings folder several times.

Current applicationhost.config contains:

<site name="WebApplication1" id="4">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="C:\TFS-WorkRepository\Sandbox\WebApplication1\WebApplication1" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:23162:localhost" />
                </bindings>
            </site>
            <siteDefaults>
                <logFile logFormat="W3C" directory="%IIS_USER_HOME%\Logs" />
                <traceFailedRequestsLogging directory="%IIS_USER_HOME%\TraceLogFiles" enabled="true" maxLogFileSizeKB="1024" />
            </siteDefaults>
            <applicationDefaults applicationPool="Clr4IntegratedAppPool" />

I wish there was a tag for really-stuck.

Please suggest away, as I don't want to go as far as spinning up a new server.

-- UPDATE --

In the URL bar, when I enter the computer name or IP address :xxxx I get the ERR_CONNECTION_TIMED_OUT rather than ERR_CONNECTION_REFUSED.


问:
Help creating exam grading program in Python
I am trying to create a program that reads multiple choice answers from a txt file and compares them to a set answer key.  This is what I have so far but the problem is that that when I run it, the answer key gets stuck on a single letter throughout the life of the program.  I have put a print statement right after the for answerKey line and it prints out correctly, but when it compares the "exam" answers to the answer key it gets stuck and always thinks "A" should be the correct answer. Which is weird because it is the 3rd entry in my sample answer key.

Here's the code:

```<code>answerKey = open("answerkey.txt" , 'r')
studentExam = open("studentexam.txt" , 'r')
index = 0
numCorrect = 0
for line in answerKey:
    answer = line.split()
for line in studentExam:
    studentAnswer = line.split()
    if studentAnswer != answer:
        print("You got question number", index + 1, "wrong\nThe correct answer was" ,answer , "but you answered", studentAnswer)
        index += 1
    else:
        numCorrect += 1
        index += 1
grade = int((numCorrect / 20) * 100)
print("The number of correctly answered questions:" , numCorrect)
print("The number of incorrectly answered questions:" , 20 - numCorrect)
print("Your grade is" ,grade ,"%")
if grade <= 75:
    print("You have not passed")
else:
    print("Congrats! You passed!")
</code>```

Thanks for any help you can give me!

答: You are overwriting your answer in every iteration of the for line loop. A is most likely the last entry in your answer key. Try combining the two for loops into just one!</p>

Body:
I am trying to create a program that reads multiple choice answers from a txt file and compares them to a set answer key.  This is what I have so far but the problem is that that when I run it, the answer key gets stuck on a single letter throughout the life of the program.  I have put a print statement right after the for answerKey line and it prints out correctly, but when it compares the "exam" answers to the answer key it gets stuck and always thinks "A" should be the correct answer. Which is weird because it is the 3rd entry in my sample answer key.

Here's the code:

answerKey = open("answerkey.txt" , 'r')
studentExam = open("studentexam.txt" , 'r')
index = 0
numCorrect = 0
for line in answerKey:
    answer = line.split()
for line in studentExam:
    studentAnswer = line.split()
    if studentAnswer != answer:
        print("You got question number", index + 1, "wrong\nThe correct answer was" ,answer , "but you answered", studentAnswer)
        index += 1
    else:
        numCorrect += 1
        index += 1
grade = int((numCorrect / 20) * 100)
print("The number of correctly answered questions:" , numCorrect)
print("The number of incorrectly answered questions:" , 20 - numCorrect)
print("Your grade is" ,grade ,"%")
if grade <= 75:
    print("You have not passed")
else:
    print("Congrats! You passed!")

Thanks for any help you can give me!


问:
How can i initialize a linked list node with a single init call?
I am trying to create a linked list in Python. My question is in the init function of the below code

```<code>class Node(object):

    def __init__(self, data=None, next_node=None):
        self.data = data
        self.next_node = next_node

    def get_data(self):
        return self.data

    def get_next(self):
        return self.next_node

    def set_next(self, new_next):
        self.next_node = new_next

firstNode = Node(15)

secondNode = Node(20)

thirdNode = Node(25)

firstNode.next_node = secondNode

</code>```

I want to ask if we can initialize a node (along with its data and the next node link) in a single init call?

In the above code, I am first passing the data attribute of the node in the init call, and then i am setting the link with the help of the next_node attribute. Is there a way to do both the things in a single init call?

答:
I'll add a functional version using reduce, build is reversed, being 4 the the root node data (you could reverse the data):

```<code>from functools import reduce
ll =  reduce(lambda x, y: Node(y, x), (1, 2, 3, 4), Node(0))
</code>```

Here you have the live example

Body:
I am trying to create a linked list in Python. My question is in the init function of the below code

class Node(object):

    def __init__(self, data=None, next_node=None):
        self.data = data
        self.next_node = next_node

    def get_data(self):
        return self.data

    def get_next(self):
        return self.next_node

    def set_next(self, new_next):
        self.next_node = new_next

firstNode = Node(15)

secondNode = Node(20)

thirdNode = Node(25)

firstNode.next_node = secondNode

I want to ask if we can initialize a node (along with its data and the next node link) in a single init call?

In the above code, I am first passing the data attribute of the node in the init call, and then i am setting the link with the help of the next_node attribute. Is there a way to do both the things in a single init call?

Body:
I'll add a functional version using reduce, build is reversed, being 4 the the root node data (you could reverse the data):

from functools import reduce
ll =  reduce(lambda x, y: Node(y, x), (1, 2, 3, 4), Node(0))

Here you have the live example


问:
timeout when testing promise rejection with sinon and chai-as-promise
I have a function which wraps a third party child-process-promise, which itself wraps spawn in promise.

```<code>let spawn = require('child-process-promise').spawn;

run(cmd, args = []) {
    return new Promise(async (resolve, reject) => {
      let command = spawn(cmd, args);
      let childProcess = command.childProcess;
      let result = '';

      childProcess.stdout.on('data', (data) => {
        result += data.toString();
      });

      try {
        const res = await command;
        resolve(result);
      } catch (err) {
        if (err.code && err.code === 'ENOENT') {
          reject(`Command "${cmd}" not found`);
        } else {
          reject('Exec err' + err);
        }
      }
    });
  }
</code>```

Testing the resolve was quite straightforward and I manage to get my stdout data passed to result then detected by chai-as-promised using await expect(shellRun).to.eventually.become('hello world');

Our problem is when we try to test the catch part of our method.

```<code>const ERROR = 'someError';

beforeEach(() => {
    sandbox = sinon.createSandbox();

    spawnEvent = new events.EventEmitter();
    spawnEvent.stdout = new events.EventEmitter();

    spawnStub = sandbox.stub();
    spawnStub.returns({ childProcess: spawnEvent });

    spawnStub.withArgs(ERRORED, ARGUMENTS).throws(ERROR));

    shell = proxyquireStrict('../../lib/utils/spawnWrapper', {
      'child-process-promise': {
        spawn: spawnStub
      }
    }
    );
  });

  afterEach(() => {
    sandbox.restore();
  });

  describe('when a generic error occurs', () => {
    it('should reject the promise', async () => {
      const shellRun = run(ERRORED, ARGUMENTS);

      await expect(shellRun).to.eventually.be.rejectedWith('Exec err' + ERROR);
    });
  });
</code>```

We manage to get childProcessPromiseSpawn to throw an error conditionally by playing with ou spawnStub.withArgs. But a timeout is encountered:

```<code>(node:15425) UnhandledPromiseRejectionWarning: Error: someError
(node:15425) 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(). (rejection id: 838)

1 failing

  1) run method
       when a generic error occurs
         should reject the promise:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
</code>```

We tried spawnStub.withArgs(ERRORED, ARGUMENTS).rejects instead of throws without more success. Changing someError for new Error('someError') doesn't work either.

We also tried to catch at test level

```<code>try {
  await run(ERRORED, ARGUMENTS);
} catch (e) {
  expect(e).to.equal('Exec err' + ERROR);
}
</code>```

But the timeout still occurs.

答:
This depend of which testing library you are using. Each library has a dedicated timeout.

For mocha you can define it in the test suite or for a unique test

https://mochajs.org/#timeouts

Body:
I have a function which wraps a third party child-process-promise, which itself wraps spawn in promise.

let spawn = require('child-process-promise').spawn;

run(cmd, args = []) {
    return new Promise(async (resolve, reject) => {
      let command = spawn(cmd, args);
      let childProcess = command.childProcess;
      let result = '';

      childProcess.stdout.on('data', (data) => {
        result += data.toString();
      });

      try {
        const res = await command;
        resolve(result);
      } catch (err) {
        if (err.code && err.code === 'ENOENT') {
          reject(`Command "${cmd}" not found`);
        } else {
          reject('Exec err' + err);
        }
      }
    });
  }

Testing the resolve was quite straightforward and I manage to get my stdout data passed to result then detected by chai-as-promised using await expect(shellRun).to.eventually.become('hello world');

Our problem is when we try to test the catch part of our method.

const ERROR = 'someError';

beforeEach(() => {
    sandbox = sinon.createSandbox();

    spawnEvent = new events.EventEmitter();
    spawnEvent.stdout = new events.EventEmitter();

    spawnStub = sandbox.stub();
    spawnStub.returns({ childProcess: spawnEvent });

    spawnStub.withArgs(ERRORED, ARGUMENTS).throws(ERROR));

    shell = proxyquireStrict('../../lib/utils/spawnWrapper', {
      'child-process-promise': {
        spawn: spawnStub
      }
    }
    );
  });

  afterEach(() => {
    sandbox.restore();
  });

  describe('when a generic error occurs', () => {
    it('should reject the promise', async () => {
      const shellRun = run(ERRORED, ARGUMENTS);

      await expect(shellRun).to.eventually.be.rejectedWith('Exec err' + ERROR);
    });
  });

We manage to get childProcessPromiseSpawn to throw an error conditionally by playing with ou spawnStub.withArgs. But a timeout is encountered:

(node:15425) UnhandledPromiseRejectionWarning: Error: someError
(node:15425) 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(). (rejection id: 838)

1 failing

  1) run method
       when a generic error occurs
         should reject the promise:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

We tried spawnStub.withArgs(ERRORED, ARGUMENTS).rejects instead of throws without more success. Changing someError for new Error('someError') doesn't work either.

We also tried to catch at test level

try {
  await run(ERRORED, ARGUMENTS);
} catch (e) {
  expect(e).to.equal('Exec err' + ERROR);
}

But the timeout still occurs.


问:
How many wiki instances to install?
I've been asked to install Mediawiki to house documentation for a company intranet. Furthermore, I've been asked to install several instances - one per contributing group: non-technical users get one, developers one, management one, etc. The idea is to provide separate web spaces for each group. Is there a way to achieve separation within one instance?

答:
I think you've already got a strong argument: maintaining multiple instances will be a pain.  Plus, if all users can read/write to all of them, it'll be a pain in the ass to coordinate a sign-on system between them all.

You might be able to convince your supervisor that what you really need is one wiki using multiple categories, as it sounds like that is more what he actually wants.  Categories can keep the entries organized.  You could even write a separate portal page for each category (it'd sure be a lot less work than maintaining a new instance for each group!).

Though I don't suggest it, you could setup your server to have multiple entry points that point towards the same site...  (i.e., wiki/dev,  wiki/qa both point to the same site).

ContentLicense: CC BY-SA 2.5

Title: How many wiki instances to install?

LastEditorDisplayName: nzpcmad

OwnerDisplayName: Daniel Lew


问:
How to store an array with two indices in the variable name?
I have an array inside 2 for loops running over the indices i,j. I would like to store the array as a variable such that the variable carries an index [i,j]. How can I do this

import numpy as np
n = 5
cond = [[[],[]] for _ in range(n)]
for i in range(n):
    for j in range(n):
        H=np.array([[1,i],[3,j]])
        eig_values, eig_vectors = np.linalg.eig(H)
        eig_vectors[:,0][np.newaxis]
        cond[i,j] = eig_vectors[:,0][np.newaxis]

```

I get an error saying that 'list indices must be integers or slices, not tuple'

答:
Yes, you could declare cond as a numpy array, as an array of zeros for instance.
If I understood correctly, you want to store eig_vectors[:,0] for each i, j, which is what the code below does.

```<code>import numpy as np
n = 5
cond = np.zeros((n, n, 2)) # declare a numpy array of zeros of shape (n, n, 2)
for i in range(n):
    for j in range(n):
        H=np.array([[1,i],[3,j]])
        eig_values, eig_vectors = np.linalg.eig(H)
        cond[i,j] = eig_vectors[:,0]
</code>```

Body:
I have an array inside 2 for loops running over the indices i,j. I would like to store the array as a variable such that the variable carries an index [i,j]. How can I do this

import numpy as np
n = 5
cond = [[[],[]] for _ in range(n)]
for i in range(n):
    for j in range(n):
        H=np.array([[1,i],[3,j]])
        eig_values, eig_vectors = np.linalg.eig(H)
        eig_vectors[:,0][np.newaxis]
        cond[i,j] = eig_vectors[:,0][np.newaxis]

I get an error saying that 'list indices must be integers or slices, not tuple'

Body:
Yes, you could declare cond as a numpy array, as an array of zeros for instance.
If I understood correctly, you want to store eig_vectors[:,0] for each i, j, which is what the code below does.

import numpy as np
n = 5
cond = np.zeros((n, n, 2)) # declare a numpy array of zeros of shape (n, n, 2)
for i in range(n):
    for j in range(n):
        H=np.array([[1,i],[3,j]])
        eig_values, eig_vectors = np.linalg.eig(H)
        cond[i,j] = eig_vectors[:,0]


问:
Create one object instance per class in hierarchy
I was asked this question in an interview.

There are 3 classes A, B extends A & C extends B. We have to design these classes conforming to these constraints

Client can instantiate only one instance of A, one instance of B & one instance of C using their default constructor with new keyword.

Trying to create another instance of any of these class will result in an exception.

The designer of the class have to enforce the above 2 rules, so that client will experience the above rules implicitly (i.e. it should not be the responsibility of client to conform to above rules).

I suggested an approach using an static Map<Class, Object>. So for e.g. when somebody called new B() it would check if map.contains(B.class). If yes then throw exception & if not then save instance in map & let the object be created.

But the next question was how would I enforce this approach on each class? As per my approach each constructor would have to carefully populate the map otherwise it will break the constraint.

How would I solve this problem?

答:
how would I enforce this approach on each class?

Since A is extended by B and C , you could add the check inside the A constructor , so everytime A, or B, or C is created it will check if it's already present, otherwise it will throws exception, something like:

```<code>public static class A{
    static List<Class<? extends A>> createdClasses = new ArrayList<>();
    public A() {
        if (createdClasses.contains(getClass())) {
            throw new InvalidParameterException("Class already present!");
        }else{
            createdClasses.add(getClass());
        }
    }
}
</code>```

In this way you will get an exception if you will create a second C instance

```<code> A testA = new A();
 B testB = new B();
 C testC = new C();
 C testC2 = new C(); //Exception here
</code>```

Body:
how would I enforce this approach on each class?

Since A is extended by B and C , you could add the check inside the A constructor , so everytime A, or B, or C is created it will check if it's already present, otherwise it will throws exception, something like:

public static class A{
    static List<Class<? extends A>> createdClasses = new ArrayList<>();
    public A() {
        if (createdClasses.contains(getClass())) {
            throw new InvalidParameterException("Class already present!");
        }else{
            createdClasses.add(getClass());
        }
    }
}

In this way you will get an exception if you will create a second C instance

 A testA = new A();
 B testB = new B();
 C testC = new C();
 C testC2 = new C(); //Exception here


问:
Dart 2.3 ignores breakpoints
I am developing a web app in Dart using Webstorm as IDE. After upgrading from Dart SDK 2.2 to Dart SDK 2.3 I noticed that all breakpoints I set in Webstorm are ignored (although the app seems to run properly in Chrome) That breakpoints are correctly marked as a "red circle" but unlike the previous SDK they miss the "tick" inside (which I think means they are not recognized by Chrome).

I tried to "repair cache" and "upgrade dependencies" but breakpoints still don't work.

That's the pubspec.yaml dev_dependencies:

```<code>dev_dependencies:
  build_runner: ^1.4.0
  build_test: ^0.10.7+3
  build_web_compilers: ^2.1.0

</code>```

Here is the "webdev serve" command:

```<code>/dart/2.3.1/dart-sdk/bin/pub global run webdev serve web:53321
</code>```

Here is the "webdev serve" command result:

```<code>[INFO] Serving `web` on http://localhost:53321
[INFO] Running build completed, took 351ms
[INFO] Caching finalized dependency graph completed, took 177ms
[INFO] Succeeded after 536ms with 0 outputs (0 actions)
</code>```

Here the versions of envolved softwares:

```<code>- O.S.: macOS High Sierra 10.13.6
- Chrome: 74.0.3729.169
- Webstorm: 2019.1 - Build 191.7141.49
- Dart SDK: 2.3.1
- Dart webdev: 2.0.5
</code>```

I'm trying to figure out if the issue is related to Webstorm, Dart SDK or Chrome. I don't exclude that I miss some new configuration due to the Dart SDK upgrade. Downgrading back to Dart SDK 2.2 everything works fine. Thank you for your hints.

答: Reproduced, logged as WEB-39095. Please follow it for updates</p>

Title: Dart 2.3 ignores breakpoints

Body:
I am developing a web app in Dart using Webstorm as IDE. After upgrading from Dart SDK 2.2 to Dart SDK 2.3 I noticed that all breakpoints I set in Webstorm are ignored (although the app seems to run properly in Chrome) That breakpoints are correctly marked as a "red circle" but unlike the previous SDK they miss the "tick" inside (which I think means they are not recognized by Chrome).

I tried to "repair cache" and "upgrade dependencies" but breakpoints still don't work.

That's the pubspec.yaml dev_dependencies:

dev_dependencies:
  build_runner: ^1.4.0
  build_test: ^0.10.7+3
  build_web_compilers: ^2.1.0

Here is the "webdev serve" command:

/dart/2.3.1/dart-sdk/bin/pub global run webdev serve web:53321

Here is the "webdev serve" command result:

[INFO] Serving `web` on http://localhost:53321
[INFO] Running build completed, took 351ms
[INFO] Caching finalized dependency graph completed, took 177ms
[INFO] Succeeded after 536ms with 0 outputs (0 actions)

Here the versions of envolved softwares:

- O.S.: macOS High Sierra 10.13.6
- Chrome: 74.0.3729.169
- Webstorm: 2019.1 - Build 191.7141.49
- Dart SDK: 2.3.1
- Dart webdev: 2.0.5

I'm trying to figure out if the issue is related to Webstorm, Dart SDK or Chrome. I don't exclude that I miss some new configuration due to the Dart SDK upgrade. Downgrading back to Dart SDK 2.2 everything works fine. Thank you for your hints.


问:
Java8 lambda for checking two conditions
I have the following code snippet which I would try to change to the lambda function.

```<code>if(catList != null && catList.size() > 0) {
    animalType = AnimalType.CAT;
    HttpEntity<List<?>> request = new HttpEntity<>(catList, headers);
    response = restTemplate.postForObject(apiUrl, request, String.class);
} else if(dogList != null && dogList.size() > 0) {
    animalType = AnimalType.DOG;
} else {
    return;
}
</code>```

Somehow I have written like as shown below, but don't know to incorporate the dogList checking the condition

```<code>Optional.of(catList)
    .map(catList -> {
        ....
    })
    .orElse(return); //<------ THIS IS NOT POSSIBLE
</code>```

Can anyone please help me with this

答:
You can have an other Optional inside of the first Optional

```<code>Optional o = Optional.of(catList)
                     .map(catList -> ...)
                     .orElse(Optional.of(dogList)
                                     .map(dogList -> ...));
</code>```

Or other method using Stream if you can make the call to the service generic enough

Or other method using Stream#of

It will basically go through both lists, find the first that is not null (but you can add other conditions to your filter if you want) and apply the generic call to service.

```<code>Optional o = Stream.of(catList, dogList)
                   .filter(Objects::nonNull /*or other condition if you want*/)
                   .findFirst()
                   .map(list -> /*generic call to service*/);
</code>```

And invoke it this way

```<code>if (!o.isPresent()) return;
</code>```

Body:
I have the following code snippet which I would try to change to the lambda function.

if(catList != null && catList.size() > 0) {
    animalType = AnimalType.CAT;
    HttpEntity<List<?>> request = new HttpEntity<>(catList, headers);
    response = restTemplate.postForObject(apiUrl, request, String.class);
} else if(dogList != null && dogList.size() > 0) {
    animalType = AnimalType.DOG;
} else {
    return;
}

Somehow I have written like as shown below, but don't know to incorporate the dogList checking the condition

Optional.of(catList)
    .map(catList -> {
        ....
    })
    .orElse(return); //<------ THIS IS NOT POSSIBLE

Can anyone please help me with this

Body:
You can have an other Optional inside of the first Optional

Optional o = Optional.of(catList)
                     .map(catList -> ...)
                     .orElse(Optional.of(dogList)
                                     .map(dogList -> ...));

Or other method using Stream if you can make the call to the service generic enough

Or other method using Stream#of

It will basically go through both lists, find the first that is not null (but you can add other conditions to your filter if you want) and apply the generic call to service.

Optional o = Stream.of(catList, dogList)
                   .filter(Objects::nonNull /*or other condition if you want*/)
                   .findFirst()
                   .map(list -> /*generic call to service*/);

And invoke it this way

if (!o.isPresent()) return;


问:
How to monitor cpu usage and ram usage for each request in Django
I am running a Django Rest Framework server on Google Cloud Platform. Most of my requests are post request. I want to analyse which request is using how much memory and how much CPU on average. Is there a way to analyze it?

My API code looks like as follow:

```<code>class GetAudioDialogue(APIView):

    def post(self, request):
        ...
</code>```

答:
I have no experience analyzing this but I found some possible options.

Custom middleware using psutil

It is possible to write your own middleware that tracks memory usage per process request and repsponse. An example of this can be found in this StackOverflow - Question

Pympler

As their Github repo states:

Development tool to measure, monitor and analyze the memory behavior of Python objects in a running Python application.

It offers ways to track memory in Django, tracking class instances, individual objects and more. More information can be found in the corresponding docs

Valgrind

As the official website states:

Valgrind is an instrumentation framework for building dynamic analysis tools. There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. You can also use Valgrind to build new tools.

It requires some setting up. Info about how to set it up for Python can be found in this StackOverflow - Question

Body:
I am running a Django Rest Framework server on Google Cloud Platform. Most of my requests are post request. I want to analyse which request is using how much memory and how much CPU on average. Is there a way to analyze it?

My API code looks like as follow:

class GetAudioDialogue(APIView):

    def post(self, request):
        ...


问:
Metricbeat System process permissions needed on windows
We are using metricbeat system process module to monitor all processes running on windows platforms. Metricbeat is only able to get himself process information. We want to get all processes information.
What permissions do it need to get all the processes in windows operative system?
Thanks</p>

答: There's a bug in metricbeat that fail when executing metricbeat with non-admin user. Oppened on https://github.com/elastic/gosigar/pull/121</p>


问:
Inserting contact to Samsung I9000 Galaxy S returns an exception
I have this code for inserting contacts tested on all HTC devices and it seems to be working fine until I tried it on a Samsung I9000 Galaxy S which gives me a java.lang.NullPointerException on this particular line of code

```<code>String strDisplayName = "First Name" + " " + "LastName";
values.put(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, strDisplayName);
Uri rawContactUri = context.getContentResolver().insert(RawContacts.CONTENT_URI, values); //java.lang.NullPointerException here
</code>```

It seems like this URI doesn't exist or maybe samsung has a different way on inserting contacts. Has anyone experience this on samsung galaxy device? Please share your thoughts.

Thanks

答:
When debugging, you are able to "watch" your variables or you could test null variables.

Also, there's code missing: Where's the act (= activity?) coming from, that's probably the one which is NULL.

Body:
I have this code for inserting contacts tested on all HTC devices and it seems to be working fine until I tried it on a Samsung I9000 Galaxy S which gives me a java.lang.NullPointerException on this particular line of code

String strDisplayName = "First Name" + " " + "LastName";
values.put(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, strDisplayName);
Uri rawContactUri = context.getContentResolver().insert(RawContacts.CONTENT_URI, values); //java.lang.NullPointerException here

It seems like this URI doesn't exist or maybe samsung has a different way on inserting contacts. Has anyone experience this on samsung galaxy device? Please share your thoughts.

Thanks


问:
Remove Arabic Diacritic
I want php to convert this...

```<code>Text : الْحَمْدُ لِلَّهِ رَبِّ الْعَالَمِينَ
converted to : الحمد لله رب العالمين
</code>```

I am not sure where to start and how to do it. Absolutely no idea. I have done some research, found this link http://www.suhailkaleem.com/2009/08/26/remove-diacritics-from-arabic-text-quran/ but it is not using php. I would like to use php and covert the above text to converted text. I want to remove any diacritic from user input arabic text

答:
Try this code, it's works fine:

```<code><?php
$str = 'الْحَمْدُ لِلَّهِ رَبِّ الْعَالَمِينَ';

$unicode = [
            "~[\x{0600}-\x{061F}]~u",
            "~[\x{063B}-\x{063F}]~u",
            "~[\x{064B}-\x{065E}]~u",
            "~[\x{066A}-\x{06FF}]~u",
        ];

$str = preg_replace($unicode, "", $str);
echo $str;
?>
</code>```

See: Arabic unicode

Thank's for: Hosein Shahrestani

Title: Remove Arabic Diacritic

Body:
I want php to convert this...

Text : الْحَمْدُ لِلَّهِ رَبِّ الْعَالَمِينَ
converted to : الحمد لله رب العالمين

I am not sure where to start and how to do it. Absolutely no idea. I have done some research, found this link http://www.suhailkaleem.com/2009/08/26/remove-diacritics-from-arabic-text-quran/ but it is not using php. I would like to use php and covert the above text to converted text. I want to remove any diacritic from user input arabic text

Body:
Try this code, it's works fine:

<?php
$str = 'الْحَمْدُ لِلَّهِ رَبِّ الْعَالَمِينَ';

$unicode = [
            "~[\x{0600}-\x{061F}]~u",
            "~[\x{063B}-\x{063F}]~u",
            "~[\x{064B}-\x{065E}]~u",
            "~[\x{066A}-\x{06FF}]~u",
        ];

$str = preg_replace($unicode, "", $str);
echo $str;
?>

See: Arabic unicode

Thank's for: Hosein Shahrestani


问:
sp-analysis failed in IDA pro
I am using IDA pro to analysis software binary. Sometime, some function with end up with sp-analysis failed.
I am writing program with IDAPython. Is there any API to detect this case, so I can ignore those failure cases for now.</p>

答:
ALT+K the negative stack pointer and change the previous to -.

@Train answer didn't really help unfortunately.

Title: sp-analysis failed in IDA pro


问:
A repository, according to the Repository pattern, should provide queries or actual entities?
I am currently refactoring my code for a web application developed using ASP.NET MVC3 with C# and Razor. One of the pattern I am using in order to better structure my application is the Repository pattern, which, besides being a really useful pattern, is also a frequent matter of discussion  within the developers' community.

In this context I found an article by Fredrik Normen which states that, according to the definition of Repository,a repository class must provide actual entities (for instance List in .NET) and not queriable objects (IQueriable in .NET). Instead in the NerdDinner tutorial from ASP.NET MVC official website they use IQueriable when the Repository has to provide multiple instances of the same object and the actual entity when the repository has to provide a single instance of the object.

What is the most correct approach to use when modeling a repository class/interface according to the Repository pattern?

Thanks

Francesco

答:
In my opinion this sort of thing is detrimental to the use of your time. ;-)

In theory, your repository should return objects or traditional collections of them, yes. However, even the definition of the repository pattern you link to uses the term "collection-like interface". Certainly, an IQueryable<Entity> is a 'collection-like' interface, yes?

In practice, I almost never think about the distinction... but I always try to put all of the querying code in the repository. I'd say 90% of my collection-based repository methods return traditional collections, while the other 10% return something based on IQueryable<>. The exceptions usually have to do with paging; so I can get the totals from the query down the line if needed, and not have to get that info early if I don't need it. It's a little lazy, but it works for me.

But I do think it's a good idea to always try to return traditional collections, because that will mean you are encapsulating all of your querying in the repository, which is where it should be. I would recommend just not to get too caught up in the extreme levels of adhering to someone's idea of what the requirement is for pattern-X


答:
This pattern doesn't make much sense, but you can use the implicit super() invocation in default constructors to your advantage here.

Given:

```<code>class A{
        static final Set<Class<?>> classes = new HashSet<>();
        public A() {
            if (!classes.add(getClass()))
               throw new IllegalStateException(
                  "One instance of " + getClass() + " already created."
               );
        }
    }
class B extends A{}
class C extends B{}
</code>```

And somewhere...

```<code>new A();
new B();
new C();
new C();
</code>```

The last invocation will throw the exception because the implicit C constructor invokes super().

Making this thread-safe would be the next step, which you can do in a number of ways.

Title: Create one object instance per class in hierarchy

Body:
I was asked this question in an interview.

There are 3 classes A, B extends A & C extends B. We have to design these classes conforming to these constraints

Client can instantiate only one instance of A, one instance of B & one instance of C using their default constructor with new keyword.

Trying to create another instance of any of these class will result in an exception.

The designer of the class have to enforce the above 2 rules, so that client will experience the above rules implicitly (i.e. it should not be the responsibility of client to conform to above rules).

I suggested an approach using an static Map<Class, Object>. So for e.g. when somebody called new B() it would check if map.contains(B.class). If yes then throw exception & if not then save instance in map & let the object be created.

But the next question was how would I enforce this approach on each class? As per my approach each constructor would have to carefully populate the map otherwise it will break the constraint.

How would I solve this problem?

Body:
This pattern doesn't make much sense, but you can use the implicit super() invocation in default constructors to your advantage here.

Given:

class A{
        static final Set<Class<?>> classes = new HashSet<>();
        public A() {
            if (!classes.add(getClass()))
               throw new IllegalStateException(
                  "One instance of " + getClass() + " already created."
               );
        }
    }
class B extends A{}
class C extends B{}

And somewhere...

new A();
new B();
new C();
new C();

The last invocation will throw the exception because the implicit C constructor invokes super().

Making this thread-safe would be the next step, which you can do in a number of ways.


问:
Plotly dash template similar to shinydashboard
For R Shiny, there are multiple very useful templates to start building your dashboard. Best known is the shinydashboard package, which makes use of a Bootstrap 3 template. I'm looking for a similar template or example as a starting point for creating a Dash Dashboard. There are lots of examples on Dash webpage, but none of these have navigation on the left pane.

Question:

Is there a template for a Python Dash dashboard, which has navigation on the left pane and plots/filters in the right pane of the web page?

答:
GitHub issue 44 has some good discussions about this topic, including:

https://github.com/masdeseiscaracteres/dash-html-template

Also, this tutorial looks interesting, but it's not free:

https://www.ftuforums.com/interactive-python-dashboards-with-plotly-and-dash-udemy-course-free-download/


答:
Assuming Windows, set it to Danish, perform the operations and then set it back.</p>

```<code>Sys.setlocale("LC_TIME", "Danish")

date <- c("08. Maj 2012", "09. Okt 2012")
fmt <- "%d. %b %Y"
as.Date(date, fmt)
## [1] "2012-05-08" "2012-10-09"

Sys.setlocale("LC_TIME")
</code>```

Title: How to transform character to Date if the date is in a foreign language? #Danish

Body:
I have scraped data from a Danish newspaper and the dates are like this:

"08. Maj 2012"

This is in character class and I wanna as data class.

I tried as.Date(dates, "%d. %b %Y")

and I got:

Error in as.Date.default(allarticles.dr, "%d. %b %Y") :    do not know
  how to convert 'allarticles.dr' to class “Date”

How can I do? I need to transform character to date but it is not recognizing in the normal way.

I also tried

Sys.setlocale("LC_TIME", "da_DK.UTF-8")
as.Date(dates, "%d. %b %Y)

and I am getting a lot of NAs

When applying dputthese are a sample of NAs that appear:

"10. Feb. 2018", "13. Feb. 2018", "18. Feb. 2018", "21. Feb. 2018",
"27. Feb. 2018", "01. Mar. 2018", "01. Mar. 2018", "09. Mar. 2018",
"14. Mar. 2018", "24. Mar. 2018", "26. Mar. 2018", "07. Apr. 2018",
"12. Apr. 2018", "15. Apr. 2018", "28. Apr. 2018", "04. Jun. 2018",
"05. Jun. 2018", "05. Jun. 2018", "12. Jun. 2018", "14. Jun. 2018",
"16. Jun. 2018", "17. Jun. 2018", "19. Jun. 2018", "21. Jun. 2018",
"29. Jun. 2018", "12. Jul. 2018", "13. Jul. 2018", "15. Jul. 2018",
"22. Jul. 2018", "07. Aug. 2018", "08. Aug. 2018", "20. Aug. 2018",
"21. Aug. 2018", "25. Aug. 2018", "28. Aug. 2018", "31. Aug. 2018",
"31. Aug. 2018", "02. Sep. 2018", "02. Sep. 2018", "06. Sep. 2018",
"20. Sep. 2018", "27. Sep. 2018", "01. Okt. 2018", "06. Okt. 2018",
"09. Okt. 2018", "11. Okt. 2018", "13. Okt. 2018", "13. Okt. 2018",
"13. Okt. 2018", "13. Okt. 2018", "15. Okt. 2018", "17. Okt. 2018",
"18. Okt. 2018", "18. Okt. 2018", "18. Okt. 2018", "20. Okt. 2018",
"22. Okt. 2018", "23. Okt. 2018", "24. Okt. 2018", "27. Okt. 2018",
"27. Okt. 2018", "27. Okt. 2018", "27. Okt. 2018", "29. Okt. 2018",
"08. Nov. 2018", "08. Nov. 2018", "08. Nov. 2018", "08. Nov. 2018",
"13. Nov. 2018", "15. Nov. 2018", "16. Nov. 2018", "27. Nov. 2018",
"27. Nov. 2018", "28. Nov. 2018", "29. Nov. 2018", "02. Dec. 2018",
"05. Dec. 2018", "05. Dec. 2018", "05. Dec. 2018", "06. Dec. 2018",
"07. Dec. 2018", "08. Dec. 2018", "12. Dec. 2018", "13. Dec. 2018",
"19. Dec. 2018", "20. Dec. 2018", "01. Jan. 2019", "06. Jan. 2019",
"04. Feb. 2019", "06. Feb. 2019", "07. Feb. 2019", "18. Feb. 2019",
"21. Feb. 2019", "07. Mar. 2019", "21. Mar. 2019", "27. Mar. 2019",
"28. Mar. 2019"

Body:
Assuming Windows, set it to Danish, perform the operations and then set it back.

Sys.setlocale("LC_TIME", "Danish")

date <- c("08. Maj 2012", "09. Okt 2012")
fmt <- "%d. %b %Y"
as.Date(date, fmt)
## [1] "2012-05-08" "2012-10-09"

Sys.setlocale("LC_TIME")


问:
InvalidKeyException: Only SecretKey is supported
I have recently started seeing this error in devices.

```<code>java.security.InvalidKeyException: Only SecretKey is supported
        at com.android.org.conscrypt.OpenSSLCipher.checkAndSetEncodedKey(OpenSSLCipher.java:436)
        at com.android.org.conscrypt.OpenSSLCipher.engineInit(OpenSSLCipher.java:273)
        at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:2664)
        at javax.crypto.Cipher.tryCombinations(Cipher.java:2575)
        at javax.crypto.Cipher$SpiAndProviderUpdater.updateAndGetSpiAndProvider(Cipher.java:2480)
        at javax.crypto.Cipher.chooseProvider(Cipher.java:567)
        at javax.crypto.Cipher.init(Cipher.java:975)
        at javax.crypto.Cipher.init(Cipher.java:910)
</code>```

From https://github.com/justinsb/android-libcore/blob/master/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLCipher.java#L232
exception is thrown when:

```<code>if (!(key instanceof SecretKey)) {
   throw new InvalidKeyException("Only SecretKey is supported");
}
</code>```

I always get my SecretKey from store like this:

```<code>SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
</code>```

Any idea what is going on?

答:
Generate Secret Key with Key_Generator Object.

For example:

Initialize SecretKeyObject as Global

```<code>SecretKey secretKeyObject;
</code>```

Initialize the Key Generator Object by:

```<code>KeyGenerator keyGeneratorObject = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,"AndroidKeyStore");
            keyStoreObject.load(null);
            keyGeneratorObject.init(new KeyGenParameterSpec.Builder(key_name,KeyProperties.PURPOSE_ENCRYPT|KeyProperties.PURPOSE_DECRYPT).setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build());
           secretKeyObject = keyGeneratorObject.generateKey();
</code>```

And then

```<code>cipherObject.init(Cipher.ENCRYPT_MODE, secretKeyObject);
</code>```

This Worked For me.

Body:
I have recently started seeing this error in devices.

java.security.InvalidKeyException: Only SecretKey is supported
        at com.android.org.conscrypt.OpenSSLCipher.checkAndSetEncodedKey(OpenSSLCipher.java:436)
        at com.android.org.conscrypt.OpenSSLCipher.engineInit(OpenSSLCipher.java:273)
        at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:2664)
        at javax.crypto.Cipher.tryCombinations(Cipher.java:2575)
        at javax.crypto.Cipher$SpiAndProviderUpdater.updateAndGetSpiAndProvider(Cipher.java:2480)
        at javax.crypto.Cipher.chooseProvider(Cipher.java:567)
        at javax.crypto.Cipher.init(Cipher.java:975)
        at javax.crypto.Cipher.init(Cipher.java:910)

From https://github.com/justinsb/android-libcore/blob/master/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLCipher.java#L232
exception is thrown when:

if (!(key instanceof SecretKey)) {
   throw new InvalidKeyException("Only SecretKey is supported");
}

I always get my SecretKey from store like this:

SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);

Any idea what is going on?

Body:
Generate Secret Key with Key_Generator Object.

For example:

Initialize SecretKeyObject as Global

SecretKey secretKeyObject;

Initialize the Key Generator Object by:

KeyGenerator keyGeneratorObject = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,"AndroidKeyStore");
            keyStoreObject.load(null);
            keyGeneratorObject.init(new KeyGenParameterSpec.Builder(key_name,KeyProperties.PURPOSE_ENCRYPT|KeyProperties.PURPOSE_DECRYPT).setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build());
           secretKeyObject = keyGeneratorObject.generateKey();

And then

cipherObject.init(Cipher.ENCRYPT_MODE, secretKeyObject);

This Worked For me.


答: Wouldn't the problem be that you iterate over all the lines in answerkey.txt and then end up comparing its last line only to all studentexam.txt lines?</p>

Title: Help creating exam grading program in Python

Body:
I am trying to create a program that reads multiple choice answers from a txt file and compares them to a set answer key.  This is what I have so far but the problem is that that when I run it, the answer key gets stuck on a single letter throughout the life of the program.  I have put a print statement right after the for answerKey line and it prints out correctly, but when it compares the "exam" answers to the answer key it gets stuck and always thinks "A" should be the correct answer. Which is weird because it is the 3rd entry in my sample answer key.

Here's the code:

answerKey = open("answerkey.txt" , 'r')
studentExam = open("studentexam.txt" , 'r')
index = 0
numCorrect = 0
for line in answerKey:
    answer = line.split()
for line in studentExam:
    studentAnswer = line.split()
    if studentAnswer != answer:
        print("You got question number", index + 1, "wrong\nThe correct answer was" ,answer , "but you answered", studentAnswer)
        index += 1
    else:
        numCorrect += 1
        index += 1
grade = int((numCorrect / 20) * 100)
print("The number of correctly answered questions:" , numCorrect)
print("The number of incorrectly answered questions:" , 20 - numCorrect)
print("Your grade is" ,grade ,"%")
if grade <= 75:
    print("You have not passed")
else:
    print("Congrats! You passed!")

Thanks for any help you can give me!


问:
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@292fbfb is not valid
Android Studio 3.4

```<code>public class SubscribesFragment extends SubscribesBaseFragment {

 @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof Activity) {
            mActivity = (Activity) context;
        }
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, final Intent intent) {
            // Get extra data included in the Intent
            String action = intent.getAction();
            if (action.equals(ExistSubscribeWidget.ACTION_REFUSE_PAPER_INVOICE)) {
                String providerGUID = intent.getStringExtra(ProviderWidget.EXTRA_PROVIDER_TAG);
                String notificationSubscribeOwnerKey = intent.getStringExtra(ExistSubscribeWidget.NOTIFICATION_SUBSCRIBE_OWNERkEY);
                showConfirmDialogRefusePaperInvoice(context, providerGUID, notificationSubscribeOwnerKey);
            }
        }
    };

    private void showConfirmDialogRefusePaperInvoice(Context context, final String providerGUID, final String notificationSubscribeOwnerKey) {
        final Activity actitivity = mActivity;
        AlertDialog.Builder builder = new AlertDialog.Builder(actitivity);
        builder.setTitle(R.string.refuse_paper_dialog_title);
        View customView = AndroidUtil.getLinearLayout(actitivity, R.layout.refuse_paper_dialog);
        builder.setView(customView);
        builder.setPositiveButton(R.string.ok, new android.content.DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
              //some code
            }
        });
        builder.setNegativeButton(R.string.cancel, new android.content.DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show(); // crash here
    }

}
</code>```

but app crash :

```<code>FATAL EXCEPTION: main
 Process: com.myproject.app, PID: 6376
 android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@292fbfb is not valid; is your activity running?
    at android.view.ViewRootImpl.setView(ViewRootImpl.java:567)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
    at android.app.Dialog.show(Dialog.java:319)
    at com.myproject.app.fragment.SubscribesFragment.showConfirmDialogRefusePaperInvoice(SubscribesFragment.java:108)
    at com.myproject.app.fragment.SubscribesFragment.access$000(SubscribesFragment.java:38)
    at com.myproject.app.fragment.SubscribesFragment$1.onReceive(SubscribesFragment.java:60)
    at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:313)
    at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:121)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答: You are using brodcast recover context to show dialog. Use activity context for that.</p>

Body:
Android Studio 3.4

public class SubscribesFragment extends SubscribesBaseFragment {

 @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof Activity) {
            mActivity = (Activity) context;
        }
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, final Intent intent) {
            // Get extra data included in the Intent
            String action = intent.getAction();
            if (action.equals(ExistSubscribeWidget.ACTION_REFUSE_PAPER_INVOICE)) {
                String providerGUID = intent.getStringExtra(ProviderWidget.EXTRA_PROVIDER_TAG);
                String notificationSubscribeOwnerKey = intent.getStringExtra(ExistSubscribeWidget.NOTIFICATION_SUBSCRIBE_OWNERkEY);
                showConfirmDialogRefusePaperInvoice(context, providerGUID, notificationSubscribeOwnerKey);
            }
        }
    };

    private void showConfirmDialogRefusePaperInvoice(Context context, final String providerGUID, final String notificationSubscribeOwnerKey) {
        final Activity actitivity = mActivity;
        AlertDialog.Builder builder = new AlertDialog.Builder(actitivity);
        builder.setTitle(R.string.refuse_paper_dialog_title);
        View customView = AndroidUtil.getLinearLayout(actitivity, R.layout.refuse_paper_dialog);
        builder.setView(customView);
        builder.setPositiveButton(R.string.ok, new android.content.DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
              //some code
            }
        });
        builder.setNegativeButton(R.string.cancel, new android.content.DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show(); // crash here
    }

}

but app crash :

FATAL EXCEPTION: main
 Process: com.myproject.app, PID: 6376
 android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@292fbfb is not valid; is your activity running?
    at android.view.ViewRootImpl.setView(ViewRootImpl.java:567)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
    at android.app.Dialog.show(Dialog.java:319)
    at com.myproject.app.fragment.SubscribesFragment.showConfirmDialogRefusePaperInvoice(SubscribesFragment.java:108)
    at com.myproject.app.fragment.SubscribesFragment.access$000(SubscribesFragment.java:38)
    at com.myproject.app.fragment.SubscribesFragment$1.onReceive(SubscribesFragment.java:60)
    at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:313)
    at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:121)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)


问:
Basic C question on copying char arrays to char pointers
I have some doubts in basic C programming.

I have a char array and I have to copy it to a char pointer. So I did the following:

```<code>char a[] = {0x3f, 0x4d};
char *p = a;
printf("a = %s\n",a);
printf("p = %s\n",p);
unsigned char str[] = {0x3b, 0x4b};
unsigned char *pstr =str;
memcpy(pstr, str, sizeof str);
printf("str = %s\n",str);
printf("pstr = %s\n",pstr);
</code>```

My printf statements for pstr and str get appended with the data "a".
If I remove memcpy I get junk. Can some C Guru enlighten me?

答:
Add a null terminator, cause that's what you printf expects:</p>

```<code>char a[] = {0x3f, 0x4d, '\0'};
</code>```

Body:
I have some doubts in basic C programming.

I have a char array and I have to copy it to a char pointer. So I did the following:

char a[] = {0x3f, 0x4d};
char *p = a;
printf("a = %s\n",a);
printf("p = %s\n",p);
unsigned char str[] = {0x3b, 0x4b};
unsigned char *pstr =str;
memcpy(pstr, str, sizeof str);
printf("str = %s\n",str);
printf("pstr = %s\n",pstr);

My printf statements for pstr and str get appended with the data "a".
If I remove memcpy I get junk. Can some C Guru enlighten me?

Body:
Add a null terminator, cause that's what you printf expects:

char a[] = {0x3f, 0x4d, '\0'};


问:
Node/Express Unhandled promise rejections are deprecated
I have been trying to resolve these unhandled Promise rejections that I continue to get in my code.

The current one I get is as follows:

[nodemon] starting mocha --recursive -R min   (node:35286)
  UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: The
  expression evaluated to a falsy value:

assert(count + 1 === newCount)

```<code>at Driver.count.then.newCount (/Users/danale/Projects/muber/test/controllers/drivers_controller.test.js:16:13)
at processTicksAndRejections (internal/process/next_tick.js:81:5) (node:35286) UnhandledPromiseRejectionWarning: Unhandled promise
</code>```

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(). (rejection id: 1) (node:35286) [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 test that should be passing is this one:

```<code>const assert = require("assert");
const request = require("supertest");
const mongoose = require("mongoose");
const app = require("../../app");

const Driver = mongoose.model("driver");

describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", done => {
    Driver.count().then(count => {
      request(app)
        .post("api/drivers")
        .send({ email: "test@test.com" })
        .end(() => {
          Driver.count().then(newCount => {
            assert(count + 1 === newCount);
            done();
          });
        });
    });
  });
});
</code>```

To deal with the Promise rejections that I was getting earlier I did this:

```<code>const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const routes = require("./routes/routes");
const app = express();

mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/muber", { useMongoClient: true });

app.use(bodyParser.json());
routes(app);

module.exports = app;
</code>```

The controller I am trying to test is:

```<code>const Driver = require("../models/driver");

module.exports = {
  greeting(req, res) {
    res.send({ hi: "there" });
  },

  create(req, res) {
    console.log(req.body);
    const driverProps = req.body;

    Driver.create(driverProps).then(driver => res.send(driver));
  }
};
</code>```

I did try to add the catch() to the test like so:

```<code>describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", done => {
    Driver.count()
      .then(count => {
        request(app)
          .post("api/drivers")
          .send({ email: "test@test.com" })
          .end((err, res) => {
            Driver.count().then(newCount => {
              assert(count + 1 === newCount);
              done();
            });
          });
      })
      .catch(error => console.log(error));
  });
});
</code>```

but it did not resolve the error.

This is my route handler:

```<code>const DriversController = require("../controllers/drivers_controller");

module.exports = app => {
  // Watch for incoming requests of method GET to the route http://localhost:3050/api
  app.get("/api", DriversController.greeting);

  app.post("/api/drivers", DriversController.create);
};
</code>```

答:
I might be wrong, but you're doing an comparison and a calculation without doing the count + 1 first. What might fix it is:

```<code>assert((count + 1) === newCount)
</code>```

So in the example above you split the calculation from comparing the values.

See the comment on this below

Body:
I have been trying to resolve these unhandled Promise rejections that I continue to get in my code.

The current one I get is as follows:

[nodemon] starting mocha --recursive -R min   (node:35286)
  UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: The
  expression evaluated to a falsy value:

assert(count + 1 === newCount)

at Driver.count.then.newCount (/Users/danale/Projects/muber/test/controllers/drivers_controller.test.js:16:13)
at processTicksAndRejections (internal/process/next_tick.js:81:5) (node:35286) 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(). (rejection id: 1) (node:35286) [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 test that should be passing is this one:

const assert = require("assert");
const request = require("supertest");
const mongoose = require("mongoose");
const app = require("../../app");

const Driver = mongoose.model("driver");

describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", done => {
    Driver.count().then(count => {
      request(app)
        .post("api/drivers")
        .send({ email: "test@test.com" })
        .end(() => {
          Driver.count().then(newCount => {
            assert(count + 1 === newCount);
            done();
          });
        });
    });
  });
});

To deal with the Promise rejections that I was getting earlier I did this:

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const routes = require("./routes/routes");
const app = express();

mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/muber", { useMongoClient: true });

app.use(bodyParser.json());
routes(app);

module.exports = app;

The controller I am trying to test is:

const Driver = require("../models/driver");

module.exports = {
  greeting(req, res) {
    res.send({ hi: "there" });
  },

  create(req, res) {
    console.log(req.body);
    const driverProps = req.body;

    Driver.create(driverProps).then(driver => res.send(driver));
  }
};

I did try to add the catch() to the test like so:

describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", done => {
    Driver.count()
      .then(count => {
        request(app)
          .post("api/drivers")
          .send({ email: "test@test.com" })
          .end((err, res) => {
            Driver.count().then(newCount => {
              assert(count + 1 === newCount);
              done();
            });
          });
      })
      .catch(error => console.log(error));
  });
});

but it did not resolve the error.

This is my route handler:

const DriversController = require("../controllers/drivers_controller");

module.exports = app => {
  // Watch for incoming requests of method GET to the route http://localhost:3050/api
  app.get("/api", DriversController.greeting);

  app.post("/api/drivers", DriversController.create);
};

Body:
I might be wrong, but you're doing an comparison and a calculation without doing the count + 1 first. What might fix it is:

assert((count + 1) === newCount)

So in the example above you split the calculation from comparing the values.

See the comment on this below


问:
hyperlink to another sheet in table if checkbox is checked, but not if unchecked macro
I failed some code for an excel macro, which sends users to another sheet in an excel table once a checkbox is checked, but does nothing if it is unchecked.It is a form control checkbox and it is on the worksheet itself, not externally.

I tried this already, but no luck:

```<code>Sub CheckBox28_Click()
    If OptionButton1 = True Then
    Sheets("Sheet3!A1").Select
    ElseIf OptionButton1 = False Then
    End If

End Sub
</code>```

It compiles, but nothing happens when assigned to checkbox

Please, help :)

答:
If it is a Form Control and not an ActiveX use the following

```<code>Sub CheckBox28_Click()
    If ActiveSheet.Shapes("Option Button 1").OLEFormat.Object.Value = 1 Then
        Worksheets("Sheet3").Select
        Worksheets("Sheet3").Range("A1").Select
    Else
        'do something else
    End If
End Sub
</code>```

Further details find here:

The Complete Guide to Excel Form Control Option Button VBA

Body:
I failed some code for an excel macro, which sends users to another sheet in an excel table once a checkbox is checked, but does nothing if it is unchecked.It is a form control checkbox and it is on the worksheet itself, not externally.

I tried this already, but no luck:

Sub CheckBox28_Click()
    If OptionButton1 = True Then
    Sheets("Sheet3!A1").Select
    ElseIf OptionButton1 = False Then
    End If

End Sub

It compiles, but nothing happens when assigned to checkbox

Please, help :)

Body:
If it is a Form Control and not an ActiveX use the following

Sub CheckBox28_Click()
    If ActiveSheet.Shapes("Option Button 1").OLEFormat.Object.Value = 1 Then
        Worksheets("Sheet3").Select
        Worksheets("Sheet3").Range("A1").Select
    Else
        'do something else
    End If
End Sub

Further details find here:

The Complete Guide to Excel Form Control Option Button VBA


问:
How to properly format a WP_REST_Response in json and get arrays instead of objects?
I'm building a very small app in wordpress and need to get json data via ajax. I'm facing a strange (at least to me) problem. My original data log is like this (please pay attention to items and children > they're arrays):

```<code>object(stdClass)#6740 (2) {
  ["type"]=>
  string(5) "areas"
  ["items"]=>
  array(1) {
    [92]=>
    object(stdClass)#6742 (10) {
      ["term_id"]=>
      int(92)
      ["name"]=>
      string(6) "Italia"
      ["slug"]=>
      string(6) "italia"
      ["term_taxonomy_id"]=>
      int(92)
      ["taxonomy"]=>
      string(12) "dealer_areas"
      ["description"]=>
      string(0) ""
      ["parent"]=>
      int(82)
      ["count"]=>
      int(1)
      ["term_order"]=>
      float(0.1)
      ["children"]=>
      array(1) {
        [126]=>
        object(stdClass)#6741 (10) {
          ["term_id"]=>
          int(126)
          ["name"]=>
          string(8) "Sardegna"
          ["slug"]=>
          string(8) "sardegna"
          ["term_taxonomy_id"]=>
          int(126)
          ["taxonomy"]=>
          string(12) "dealer_areas"
          ["description"]=>
          string(0) ""
          ["parent"]=>
          int(92)
          ["count"]=>
          int(1)
          ["term_order"]=>
          float(0.10003)
          ["children"]=>
          array(0) {
          }
        }
      }
    }
  }
}
</code>```

If I pass it directly to WP_REST_Response and then to js as a json response (return new WP_REST_Response($response_obj)), I get a log like this:

As you can see, it's not exactly json... There are getter/setter methods..

OK, then I pass the value json encoded (return new WP_REST_Response(json_encode($response_obj))) and parse in javascript via JSON.parse(). I get this:

or this (another example with more than 1 obj)

As you can see, I get json, but even if original items data was an array, now I get an object. How to preserve the original array type?

答:
My own answer is:

It's not a WP_REST_Response issue.

It's not a json_decode issue

The issue is the data format and the way javascript reads arrays

In short: it's not possible to convert php non-consecutive indexed arrays to javascript arrays, since javascript wants consecutive integers keys. In all the other cases, javascript reads as associative arrays or objects (which are essentially the same). Therefore, json conversion of php non-consecutive indexed arrays will always output objects.

Body:
I'm building a very small app in wordpress and need to get json data via ajax. I'm facing a strange (at least to me) problem. My original data log is like this (please pay attention to items and children > they're arrays):

object(stdClass)#6740 (2) {
  ["type"]=>
  string(5) "areas"
  ["items"]=>
  array(1) {
    [92]=>
    object(stdClass)#6742 (10) {
      ["term_id"]=>
      int(92)
      ["name"]=>
      string(6) "Italia"
      ["slug"]=>
      string(6) "italia"
      ["term_taxonomy_id"]=>
      int(92)
      ["taxonomy"]=>
      string(12) "dealer_areas"
      ["description"]=>
      string(0) ""
      ["parent"]=>
      int(82)
      ["count"]=>
      int(1)
      ["term_order"]=>
      float(0.1)
      ["children"]=>
      array(1) {
        [126]=>
        object(stdClass)#6741 (10) {
          ["term_id"]=>
          int(126)
          ["name"]=>
          string(8) "Sardegna"
          ["slug"]=>
          string(8) "sardegna"
          ["term_taxonomy_id"]=>
          int(126)
          ["taxonomy"]=>
          string(12) "dealer_areas"
          ["description"]=>
          string(0) ""
          ["parent"]=>
          int(92)
          ["count"]=>
          int(1)
          ["term_order"]=>
          float(0.10003)
          ["children"]=>
          array(0) {
          }
        }
      }
    }
  }
}

If I pass it directly to WP_REST_Response and then to js as a json response (return new WP_REST_Response($response_obj)), I get a log like this:

As you can see, it's not exactly json... There are getter/setter methods..

OK, then I pass the value json encoded (return new WP_REST_Response(json_encode($response_obj))) and parse in javascript via JSON.parse(). I get this:

or this (another example with more than 1 obj)

As you can see, I get json, but even if original items data was an array, now I get an object. How to preserve the original array type?


问:
RegEx for extracting latitude in a string
```<code>    lrgstPlace = features[0]
    strLrgstPlace = str(lrgstPlace)
    longtide = re.match("r(lat=)([\-\d\.]*)",strLrgstPlace)
    print (longtide)
</code>```

This is how my features list looks like

Feature(place='28km S of Cliza, Bolivia', long=-65.8913, lat=-17.8571, depth=358.34, mag=6.3)
  Feature(place='12km SSE of Volcano, Hawaii', long=-155.2005, lat=19.3258333, depth=6.97, mag=5.54)

Why does the regex cant match anything?Its just gives me "None" as a result.

答:
Your original expression works fine, we might want to slightly modify it, if we wish to just extract the lat numbers:

```<code>(?:lat=)([0-9\.\-]+)(?:,)
</code>```

where ([0-9\.\-]+) would capture our desired lat, and we wrap it with two non-capturing groups:

```<code>(?:lat=)
(?:,)
</code>```

DEMO

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(?:lat=)([0-9\.\-]+)(?:,)"

test_str = "Feature(place='28km S of Cliza, Bolivia', long=-65.8913, lat=-17.8571, depth=358.34, mag=6.3) Feature(place='12km SSE of Volcano, Hawaii', long=-155.2005, lat=19.3258333, depth=6.97, mag=5.54)"

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

Body:
    lrgstPlace = features[0]
    strLrgstPlace = str(lrgstPlace)
    longtide = re.match("r(lat=)([\-\d\.]*)",strLrgstPlace)
    print (longtide)

This is how my features list looks like

Feature(place='28km S of Cliza, Bolivia', long=-65.8913, lat=-17.8571, depth=358.34, mag=6.3)
  Feature(place='12km SSE of Volcano, Hawaii', long=-155.2005, lat=19.3258333, depth=6.97, mag=5.54)

Why does the regex cant match anything?Its just gives me "None" as a result.

Body:
Your original expression works fine, we might want to slightly modify it, if we wish to just extract the lat numbers:

(?:lat=)([0-9\.\-]+)(?:,)

where ([0-9\.\-]+) would capture our desired lat, and we wrap it with two non-capturing groups:

(?:lat=)
(?:,)

DEMO

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(?:lat=)([0-9\.\-]+)(?:,)"

test_str = "Feature(place='28km S of Cliza, Bolivia', long=-65.8913, lat=-17.8571, depth=358.34, mag=6.3) Feature(place='12km SSE of Volcano, Hawaii', long=-155.2005, lat=19.3258333, depth=6.97, mag=5.54)"

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.


答: You're declaring an array "str", then pointing to it with pstr. Note that you have no null-terminating character, so after using memcpy you copy the block to itself with no null terminator, as a string requires. Thus, printf can't find the end of the string and continues printing until it finds a 0 (or '\0' in character terms)

Title: Basic C question on copying char arrays to char pointers


问:
Can I run javascript like document.getElementById() on a HTML file in Node?
I’d like to use front-end javascript functions on a HTML file -eg. reading a property from the file etc. Is this possible in node? Thanks.</p>

答:
There are plenty of libraries that handle it for you already. Probably one of the most popular may be:

JSDOM

Puppeteer

Both will allow you to use DOM features(like document.getElementByID()) from you Node JS. Get yourself familiar with the documentation and enjoy using. If you meant the opposite(using node js features in you html/js app), then you need some backend server.

Remember to search for already answered questions, I was able to find that with no ease.

Regards.


问:
Checking if an item is in an array in C
I am checking whether an item is in a an array in C using a for loop to iterate through every item in the array and comparing it one by one with a user input.

```<code>int main()
{
    char birds[] =
    {
        [0] = "a",
        [1] = "b",
        [2] = "c",
        [3] = "d",
        [4] = "e",
        [5] = "f",
        [6] = "g",
        [7] = "h"
    };
    int birdfound;
    int i;
    printf("Enter bird:");
    scanf("%c", &birdfound);
    //printf("%c", birdfound);
    for(i=0; i<8; i++)
    {
        //printf("Y");
        if(birdfound == birds[i]){
            printf("Bird in array, found at position %d\n", i);
        }
    }
    system("pause");
    return 0;
}
</code>```

I know for a fact that the issue lies within branch logic, as for some reason it fails to compare the character input with any character from the array. Therefore, the output is nothing and the program simply ends.

答:
You're assigning string literals to your chars. Try this instead:

```<code>char birds[] =
    {
        [0] = 'a',
        [1] = 'b',
        [2] = 'c',
        [3] = 'd',
        [4] = 'e',
        [5] = 'f',
        [6] = 'g',
        [7] = 'h'
    };
</code>```

Also, int birdfound must be char birdfound, otherwise scanf("%c", &birdfound); is undefined behavior because you're telling it that it's a char when it really is an int.

In all likelyhood your intention is to use strings instead when all is said and done, which you could achieve this way:

```<code>char *birds[] = // note the "*"
    {
        [0] = "foo",
        [1] = "bar",
    };
</code>```

Then you read it in like this:

```<code>char birdfound[20]; // space for 19 chars and the null terminator
scanf("%19s", &birdfound); // read up to 19 chars
</code>```

And find it like this:

```<code>if (!strcmp(birdfound, birds[i])) {
    printf("Bird in array, found at position %d\n", i);
}
</code>```

Title: Checking if an item is in an array in C

Body:
I am checking whether an item is in a an array in C using a for loop to iterate through every item in the array and comparing it one by one with a user input.

int main()
{
    char birds[] =
    {
        [0] = "a",
        [1] = "b",
        [2] = "c",
        [3] = "d",
        [4] = "e",
        [5] = "f",
        [6] = "g",
        [7] = "h"
    };
    int birdfound;
    int i;
    printf("Enter bird:");
    scanf("%c", &birdfound);
    //printf("%c", birdfound);
    for(i=0; i<8; i++)
    {
        //printf("Y");
        if(birdfound == birds[i]){
            printf("Bird in array, found at position %d\n", i);
        }
    }
    system("pause");
    return 0;
}

I know for a fact that the issue lies within branch logic, as for some reason it fails to compare the character input with any character from the array. Therefore, the output is nothing and the program simply ends.

Body:
You're assigning string literals to your chars. Try this instead:

char birds[] =
    {
        [0] = 'a',
        [1] = 'b',
        [2] = 'c',
        [3] = 'd',
        [4] = 'e',
        [5] = 'f',
        [6] = 'g',
        [7] = 'h'
    };

Also, int birdfound must be char birdfound, otherwise scanf("%c", &birdfound); is undefined behavior because you're telling it that it's a char when it really is an int.

In all likelyhood your intention is to use strings instead when all is said and done, which you could achieve this way:

char *birds[] = // note the "*"
    {
        [0] = "foo",
        [1] = "bar",
    };

Then you read it in like this:

char birdfound[20]; // space for 19 chars and the null terminator
scanf("%19s", &birdfound); // read up to 19 chars

And find it like this:

if (!strcmp(birdfound, birds[i])) {
    printf("Bird in array, found at position %d\n", i);
}


问:
import excel sheet into SAS
I'm trying to import a (.csv)excel file that I downloaded from Kaggle into SAS by using the following codes:

```<code>PROC IMPORT OUT= Sasuser.HeartDisease DATAFILE= "C:\Users\PCPCPC\Documents\StatDatas\heart"
            DBMS=excel REPLACE;
     SHEET="auto";
     GETNAMES=YES;
RUN;
</code>```

However, it gives my this error:

```<code>931  PROC IMPORT OUT= Sasuser.HeartDisease DATAFILE= "C:\Users\PCPCPC\Documents\StatDatas\heart.xlsx"
932              DBMS=excel REPLACE;
933       SHEET="auto";
934       GETNAMES=YES;
935  RUN;

ERROR: Unable to open file C:\Users\PCPCPC\Documents\StatDatas\heart.xlsx. It does not  exist or it
       is already opened exclusively by another user, or you need permission to view its data.
NOTE: The SAS System stopped processing this step because of errors.
NOTE: PROCEDURE IMPORT used (Total process time):
      real time           0.35 seconds
      cpu time            0.29 seconds
</code>```

My files in the file system looks like this:

Here is the properties of the file:

答:
First thing a CSV file is not an EXCEL file, even if your operating system has chosen to use EXCEL as the default program to open files that with that extension on their filename.  A CSV file is just a text file. You can view it with any text editor (including the SAS program editor).  So the extension on a CSV file should be .csv.

To avoid this confusion you can tell your operating system to show you the full filenames.  Here is a link to instructions for how to do this in Windows 10.  https://www.thewindowsclub.com/show-file-extensions-in-windows

You can use PROC IMPORT with CSV files.

```<code>proc import
  replace out= Sasuser.HeartDisease
  datafile= "C:\Users\PCPCPC\Documents\StatDatas\heart.csv"
  dbms=csv
;
run;
</code>```

But because they are just plain text files you can also just write your own data step to read the file.  Then you will have complete control over the variables names and how the variables are defined.

Title: import excel sheet into SAS

Body:
I'm trying to import a (.csv)excel file that I downloaded from Kaggle into SAS by using the following codes:

PROC IMPORT OUT= Sasuser.HeartDisease DATAFILE= "C:\Users\PCPCPC\Documents\StatDatas\heart"
            DBMS=excel REPLACE;
     SHEET="auto";
     GETNAMES=YES;
RUN;

However, it gives my this error:

931  PROC IMPORT OUT= Sasuser.HeartDisease DATAFILE= "C:\Users\PCPCPC\Documents\StatDatas\heart.xlsx"
932              DBMS=excel REPLACE;
933       SHEET="auto";
934       GETNAMES=YES;
935  RUN;

ERROR: Unable to open file C:\Users\PCPCPC\Documents\StatDatas\heart.xlsx. It does not  exist or it
       is already opened exclusively by another user, or you need permission to view its data.
NOTE: The SAS System stopped processing this step because of errors.
NOTE: PROCEDURE IMPORT used (Total process time):
      real time           0.35 seconds
      cpu time            0.29 seconds

My files in the file system looks like this:

Here is the properties of the file:

Body:
First thing a CSV file is not an EXCEL file, even if your operating system has chosen to use EXCEL as the default program to open files that with that extension on their filename.  A CSV file is just a text file. You can view it with any text editor (including the SAS program editor).  So the extension on a CSV file should be .csv.

To avoid this confusion you can tell your operating system to show you the full filenames.  Here is a link to instructions for how to do this in Windows 10.  https://www.thewindowsclub.com/show-file-extensions-in-windows

You can use PROC IMPORT with CSV files.

proc import
  replace out= Sasuser.HeartDisease
  datafile= "C:\Users\PCPCPC\Documents\StatDatas\heart.csv"
  dbms=csv
;
run;

But because they are just plain text files you can also just write your own data step to read the file.  Then you will have complete control over the variables names and how the variables are defined.


问:
How a basic if-statement works in Python?
I am starting with python and facing a basic issue with this nesting exercise:

```<code>bird_names="eagle", "pigeon", "colibri", "seagull"

bird_guess=input("Guess the bird: ")

if bird_guess in bird_names == False:
    print("Try again")
    bird_guess2=input("Guess the Bird: ")

    if bird_guess2 in birds == False:
        print("Try again")
        bird_guess3=input("Guess the Bird: ")

        if bird_guess3 in birds == False:
            print("Sorry out of tries")
        else:
            print("Yes 3rd try")
    else:
        print("Yes 2rd try")
else:
    print("Great, 1st try")
</code>```

When I run it and assing to bird_guess the value d for example, the code outputs direct Great, 1st try instead of going through all the other if statemnts.

Any idea where is my error?

答:
This:

```<code>if bird_guess in bird_names == False:
</code>```

is the same as:

```<code>if bird_guess in bird_names and bird_names == False:
</code>```

You should do this instead:

```<code>if bird_guess not in bird_names:
</code>```

to check if an item is not in a list.

The reason why your original expression didn't work is comparison chaining. In Python arbitrary amount of comparisons can be chained together, so for example x < y <= z is equivalent to x < y and y <= z. And thus a in b == False will become a in b and b == False.

Body:
I am starting with python and facing a basic issue with this nesting exercise:

bird_names="eagle", "pigeon", "colibri", "seagull"

bird_guess=input("Guess the bird: ")

if bird_guess in bird_names == False:
    print("Try again")
    bird_guess2=input("Guess the Bird: ")

    if bird_guess2 in birds == False:
        print("Try again")
        bird_guess3=input("Guess the Bird: ")

        if bird_guess3 in birds == False:
            print("Sorry out of tries")
        else:
            print("Yes 3rd try")
    else:
        print("Yes 2rd try")
else:
    print("Great, 1st try")

When I run it and assing to bird_guess the value d for example, the code outputs direct Great, 1st try instead of going through all the other if statemnts.

Any idea where is my error?

Body:
This:

if bird_guess in bird_names == False:

is the same as:

if bird_guess in bird_names and bird_names == False:

You should do this instead:

if bird_guess not in bird_names:

to check if an item is not in a list.

The reason why your original expression didn't work is comparison chaining. In Python arbitrary amount of comparisons can be chained together, so for example x < y <= z is equivalent to x < y and y <= z. And thus a in b == False will become a in b and b == False.