问:
SMLNJ Insertion Sort Operator and Operand dont agree error
Im making an insertion sort code in SML, here it is

```<code>fun compare(x:real, y:real, F) = F(x, y);
fun isEqual(x:real, y:real) = ((x <= y) andalso (x >= y));

fun rinsert(x: real, [], F) = [x]
    |rinsert(x, (y::ys), F) =
    if isEqual(x, y) then rinsert (x, ys, F)
    else if compare(x, y, F) then x::y::ys
            else y::(rinsert (x, ys, F));

fun rinsort([], F) = []
    |rinsort(x::xs, F) = rinsert(x, (rinsort(xs, F), F));
</code>```

However, on running it i get this error

```<code>val isEqual = fn : real * real -> bool
val rinsert = fn : real * real list * (real * real -> bool) -> real list
stdIn:12.27-12.58 Error: operator and operand don't agree [tycon mismatch]
  operator domain: real * real list * (real * real -> bool)
  operand:         'Z * ('Y list * 'X)
  in expression:
    rinsert (x,(rinsort (<exp>,<exp>),F))
</code>```

I understand that rinsort is calling rinsert incorrectly, but I'm not sure how to fix it.

答:
If it can be useful, This is an example of how your code should work with areal list:

```<code>fun compare(x:real, y:real, F) = F x y;
fun isEqual(x:real, y:real) = ((x <= y) andalso (x >= y));

fun rinsert(x: real, [], F) = [x]
    |rinsert(x, (y::ys), F) =
    if isEqual(x, y) then rinsert (x, ys, F)
    else if compare(x, y, F) then x::y::ys
            else y::(rinsert (x, ys, F));

fun rinsort([], F) = []
    |rinsort(x::xs, F) = rinsert(x, rinsort(xs, F), F);

val funcComp = fn r1 : real => fn r2 : real => if r1 < r2 then true else false;
val l : real list = [1.0, 3.8, 5.6, 3.8, 4.4, 5.6, 6.3, 5.5, 4.6, 8.1];
val b = rinsort(l, funcComp);
</code>```

Body:
Im making an insertion sort code in SML, here it is

fun compare(x:real, y:real, F) = F(x, y);
fun isEqual(x:real, y:real) = ((x <= y) andalso (x >= y));

fun rinsert(x: real, [], F) = [x]
    |rinsert(x, (y::ys), F) =
    if isEqual(x, y) then rinsert (x, ys, F)
    else if compare(x, y, F) then x::y::ys
            else y::(rinsert (x, ys, F));

fun rinsort([], F) = []
    |rinsort(x::xs, F) = rinsert(x, (rinsort(xs, F), F));

However, on running it i get this error

val isEqual = fn : real * real -> bool
val rinsert = fn : real * real list * (real * real -> bool) -> real list
stdIn:12.27-12.58 Error: operator and operand don't agree [tycon mismatch]
  operator domain: real * real list * (real * real -> bool)
  operand:         'Z * ('Y list * 'X)
  in expression:
    rinsert (x,(rinsort (<exp>,<exp>),F))

I understand that rinsort is calling rinsert incorrectly, but I'm not sure how to fix it.

Body:
If it can be useful, This is an example of how your code should work with areal list:

fun compare(x:real, y:real, F) = F x y;
fun isEqual(x:real, y:real) = ((x <= y) andalso (x >= y));

fun rinsert(x: real, [], F) = [x]
    |rinsert(x, (y::ys), F) =
    if isEqual(x, y) then rinsert (x, ys, F)
    else if compare(x, y, F) then x::y::ys
            else y::(rinsert (x, ys, F));

fun rinsort([], F) = []
    |rinsort(x::xs, F) = rinsert(x, rinsort(xs, F), F);

val funcComp = fn r1 : real => fn r2 : real => if r1 < r2 then true else false;
val l : real list = [1.0, 3.8, 5.6, 3.8, 4.4, 5.6, 6.3, 5.5, 4.6, 8.1];
val b = rinsort(l, funcComp);


来源: stackexchange

问:
Visual Studio 2010: very slow web applications debugging!
I recently installed Visual Studio 2010 (Ultimate edition, final version released in April), and found that debugging a web application became very slow (2-3 times slower than in Visual Studio 2008)!

I took the same web application and checked the speed of loading of one of its pages in VS 2008 and VS 2010, and compared the time it takes to load the page.

I tested it using 2 approaches: 1) debugging under ASP.NET Development Server (by pressing the "Start" button) and 2) using ASP.NET Development Server without debugging (by using the "View in Browser" menu command).

And I got the following results for Visual Studio 2008 and 2010.

1) ASP.NET Development Server withoud debugging ("View in Browser"): the speed of page loading is the same in VS 2008 and 2010.

2) Debugging under ASP.NET Development Server ("Start" button): in VS 2010 the page takes more time to load than in VS 2008 - VS 2010 debugging is 2-3 times slower than in VS 2008!

3) At the same time, when debugging a web application in VS 2008, it takes the same time to load the page compared to when using only the "View in Browser" command. That is, VS 2008 debugging does not introduce any overhead to page loading in the web browser!

I wanted to make sure that other people have the same problem with slow debugging of web applications in VS 2010. Can this issue be solved by any means?

BTW, I am using Windows XP SP3.

Thank you.

答: I tried a lot of things and the only way to solve it was the swax solution 'Delete all breakpoints'</p>

ContentLicense: CC BY-SA 2.5


问:
Testing asyn calls throws Unhandled promise rejection in Node JS
I´m unit testing an Express function like this:

```<code>function(request,response,someDependency){
  ...
  someDependency.doStuff(arg1,arg2)
  .then(function(someResponse){
      response.status(200).send({body: someResponse});
  })
  .catch(function(error){
      response.status(500).send({someResponse: 'error');
  });
}
</code>```

In my unit tests (using Mocha), I have decided to mock my response, using assertions inside it, and also to mock my dependency:

An abstraction of my mockedResponse:

```<code>...
exports.expectedStatus = function(status){
  this.expectedCode = status;
}
exports.status = function(realStatus){
  this.expectdCode = realStatus;
  return this;
}
exports.send = function(body){
  assert.strictEqual(this.realStatus,this.expectedCode);
}
</code>```

and an abstraction of my dependency would be:

```<code>exports.setPromiseError(error){
  this.error = error;
};
exports.doStuff(arg1,arg2){
   return new Promise(function (resolve, reject){
      if (!error)
         resolve({this: 'is', a: 'response'});
      else
         reject(error);
     }});
</code>```

In my unit tests I have a test like this:

```<code>mockedResponse = require('./fake/assertiveResponse.js');
mockedDependency       = require('./fake/dependency.js');

it('should throw error',function(){
   mockedDependency.setPromiseError(new Error('sorry, not today');
   myLibUnderTest.myFunctionUnderTest(someFakeRequest,
                                       mockedResponse.get()
                                        .expectedStatus(200), <--I´m forcing a failing test here!
                                      mockedDependency);
});
</code>```

But...my assert appears to be swalled by the promise and I get a passing test with this console output:

```<code>(node:1512) UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 2): AssertionError: 500 === 200
</code>```

Right now I´m not even sure I´m using Promises the right way...any help is appreciated.

答:
Not super familiar with Express, but looking at your code, is there just a typo?

I see this.expectedCode vs this.expectdCode

```<code>exports.expectedStatus = function(status){
  this.expectedCode = status;
}
exports.status = function(realStatus){
  this.expectdCode = realStatus;
  return this;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I´m unit testing an Express function like this:

function(request,response,someDependency){
  ...
  someDependency.doStuff(arg1,arg2)
  .then(function(someResponse){
      response.status(200).send({body: someResponse});
  })
  .catch(function(error){
      response.status(500).send({someResponse: 'error');
  });
}

In my unit tests (using Mocha), I have decided to mock my response, using assertions inside it, and also to mock my dependency:

An abstraction of my mockedResponse:

...
exports.expectedStatus = function(status){
  this.expectedCode = status;
}
exports.status = function(realStatus){
  this.expectdCode = realStatus;
  return this;
}
exports.send = function(body){
  assert.strictEqual(this.realStatus,this.expectedCode);
}

and an abstraction of my dependency would be:

exports.setPromiseError(error){
  this.error = error;
};
exports.doStuff(arg1,arg2){
   return new Promise(function (resolve, reject){
      if (!error)
         resolve({this: 'is', a: 'response'});
      else
         reject(error);
     }});

In my unit tests I have a test like this:

mockedResponse = require('./fake/assertiveResponse.js');
mockedDependency       = require('./fake/dependency.js');

it('should throw error',function(){
   mockedDependency.setPromiseError(new Error('sorry, not today');
   myLibUnderTest.myFunctionUnderTest(someFakeRequest,
                                       mockedResponse.get()
                                        .expectedStatus(200), <--I´m forcing a failing test here!
                                      mockedDependency);
});

But...my assert appears to be swalled by the promise and I get a passing test with this console output:

(node:1512) UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 2): AssertionError: 500 === 200

Right now I´m not even sure I´m using Promises the right way...any help is appreciated.

Body:
Not super familiar with Express, but looking at your code, is there just a typo?

I see this.expectedCode vs this.expectdCode

exports.expectedStatus = function(status){
  this.expectedCode = status;
}
exports.status = function(realStatus){
  this.expectdCode = realStatus;
  return this;


问:
Read last line from website without saving file on disk
I have a website with many large CSV files (up to 100,000 lines each). From each CSV file, I need to read the last line in the file. I know how to solve the problem when I save the file on disk before reading its content:

```<code>                var url = "http://data.cocorahs.org/cocorahs/export/exportreports.aspx?ReportType=Daily&Format=csv&Date=1/1/2000&Station=UT-UT-24"
            var client = new System.Net.WebClient();
            var tempFile = System.IO.Path.GetTempFileName();
            client.DownloadFile(url, tempFile);
            var lastLine = System.IO.File.ReadLines(tempFile).Last();
</code>```

Is there any way to get the last line without saving a temporary file on disk?
I tried:

```<code>using (var stream = client.OpenRead(seriesUrl))
{
    using (var reader = new StreamReader(stream))
    {
        var lastLine = reader.ReadLines("file.txt").Last();
    }
}
</code>```

but the StreamReader class does not have a ReadLines method ...

答:
StreamReader does not have a ReadLines method, but it does have a ReadLine method to read the next line from the stream.  You can use it to read the last line from the remote resource like this:

```<code>using (var stream = client.OpenRead(seriesUrl))
{
    using (var reader = new StreamReader(stream))
    {
        string lastLine;

        while ((lastLine = reader.ReadLine()) != null)
        {
            // Do nothing...
        }

        // lastLine now contains the very last line from reader
    }
}
</code>```

Reading one line at a time with ReadLine will use less memory compared to StreamReader.ReadToEnd, which will read the entire stream into memory as a string.  For CSV files with 100,000 lines this could be a significant amount of memory.

Body:
I have a website with many large CSV files (up to 100,000 lines each). From each CSV file, I need to read the last line in the file. I know how to solve the problem when I save the file on disk before reading its content:

                var url = "http://data.cocorahs.org/cocorahs/export/exportreports.aspx?ReportType=Daily&Format=csv&Date=1/1/2000&Station=UT-UT-24"
            var client = new System.Net.WebClient();
            var tempFile = System.IO.Path.GetTempFileName();
            client.DownloadFile(url, tempFile);
            var lastLine = System.IO.File.ReadLines(tempFile).Last();

Is there any way to get the last line without saving a temporary file on disk?
I tried:

using (var stream = client.OpenRead(seriesUrl))
{
    using (var reader = new StreamReader(stream))
    {
        var lastLine = reader.ReadLines("file.txt").Last();
    }
}

but the StreamReader class does not have a ReadLines method ...

Body:
StreamReader does not have a ReadLines method, but it does have a ReadLine method to read the next line from the stream.  You can use it to read the last line from the remote resource like this:

using (var stream = client.OpenRead(seriesUrl))
{
    using (var reader = new StreamReader(stream))
    {
        string lastLine;

        while ((lastLine = reader.ReadLine()) != null)
        {
            // Do nothing...
        }

        // lastLine now contains the very last line from reader
    }
}

Reading one line at a time with ReadLine will use less memory compared to StreamReader.ReadToEnd, which will read the entire stream into memory as a string.  For CSV files with 100,000 lines this could be a significant amount of memory.


问:
How do I configure Undertow handlers to support proper rewriting for SPA bookmarking?
I am trying to configure JBoss EAP 7 (via Undertow) to properly rewrite any SPA URLS back to the SPA's index.html using Undertow handlers. Unfortunately, my API is located at /api, so I need to let any requests pass through which start with /api.

Here is my current configuration (lifted from another SO answer):

```<code>not equals(%R, '/my-app') and
not equals(%R, '/my-app/') and
not equals(%R, '/my-app/index.html') and
not path-prefix('/my-app/api') and
not regex('/my-app/.*\.js') and
regex('/my-app/.+') -> rewrite('/my-app/index.html')
</code>```

Unfortunately, this doesn't seem to be rewriting anything. How can I update this configuration to property rewrite URLs?

答:
As a start, try this configuration in WEB-INF/undertow-handlers.conf:

```<code>path-prefix('/api') -> done
path-suffix('.js') -> done
path-prefix('/') -> rewrite('/')
</code>```

You shouldn't need the /my-app prefix on any rules as they are already running in the context of your app.

However, you may need to add other predicates to prevent rewriting other resources like stylesheets, favicons, sourcemaps, etc. The full list of predicates and handlers can be helpful to produce more specific, targeted rules.

Please note, path-suffix still accounts for a path like /app?thing.js. Though you may never use a query parameter like that, it's good to keep in mind that it'll be rewritten.

Body:
I am trying to configure JBoss EAP 7 (via Undertow) to properly rewrite any SPA URLS back to the SPA's index.html using Undertow handlers. Unfortunately, my API is located at /api, so I need to let any requests pass through which start with /api.

Here is my current configuration (lifted from another SO answer):

not equals(%R, '/my-app') and
not equals(%R, '/my-app/') and
not equals(%R, '/my-app/index.html') and
not path-prefix('/my-app/api') and
not regex('/my-app/.*\.js') and
regex('/my-app/.+') -> rewrite('/my-app/index.html')

Unfortunately, this doesn't seem to be rewriting anything. How can I update this configuration to property rewrite URLs?

Body:
As a start, try this configuration in WEB-INF/undertow-handlers.conf:

path-prefix('/api') -> done
path-suffix('.js') -> done
path-prefix('/') -> rewrite('/')

You shouldn't need the /my-app prefix on any rules as they are already running in the context of your app.

However, you may need to add other predicates to prevent rewriting other resources like stylesheets, favicons, sourcemaps, etc. The full list of predicates and handlers can be helpful to produce more specific, targeted rules.

Please note, path-suffix still accounts for a path like /app?thing.js. Though you may never use a query parameter like that, it's good to keep in mind that it'll be rewritten.


问:
Changing axis titles for autoplot
Using autoplot from ggfortify to create diagnostic plots:

```<code>library(ggplot2)
library(ggfortify)

mod <- lm(Petal.Width ~ Petal.Length, data = iris)
autoplot(mod, label.size = 3)
</code>```

Is it possible to change the axis and plot titles (easily)? I'd like to translate them.

答:
```<code>library(ggplot2)
library(ggfortify)

mod <- lm(Petal.Width ~ Petal.Length, data = iris)
autoplot(mod,which=c(1:6), ncols=2)    #total 6 plots in two columns
#change axes label & title of plot 1. similarly by changing 'which' parameters count you can label other plots.
autoplot(mod,which=1) +
  labs(x="x-axis label of fig1", y="y-axis label of fig1", title="Fig1 plot")
</code>```

Kindly don't forget to let us know if it helped :)

Title: Changing axis titles for autoplot

Body:
Using autoplot from ggfortify to create diagnostic plots:

library(ggplot2)
library(ggfortify)

mod <- lm(Petal.Width ~ Petal.Length, data = iris)
autoplot(mod, label.size = 3)

Is it possible to change the axis and plot titles (easily)? I'd like to translate them.

Body:
library(ggplot2)
library(ggfortify)

mod <- lm(Petal.Width ~ Petal.Length, data = iris)
autoplot(mod,which=c(1:6), ncols=2)    #total 6 plots in two columns
#change axes label & title of plot 1. similarly by changing 'which' parameters count you can label other plots.
autoplot(mod,which=1) +
  labs(x="x-axis label of fig1", y="y-axis label of fig1", title="Fig1 plot")

Kindly don't forget to let us know if it helped :)


问:
Angular4 Material sidenav not working
I am trying to test out the sidenav functionality in angular4 material. From whatever information I could gather from google. I made this plunker.
https://plnkr.co/edit/4VfijY?p=preview

```<code><md-sidenav-container>
  <md-sidenav #sidenav mode="side" opened="true">
    <md-nav-list>
      <a md-list-item>
        Home
      </a>
      <a md-list-item>
        Channels
      </a>
    </md-nav-list>
  </md-sidenav>
</md-sidenav-container>
</code>```

Could someone point out what am I doing wrong ?. I could use another pair of eyes.

Also if someone has successfully made a working sidenav or has a good tutorial could you please share here ?

Thanks a lot.

答:
Did you install Angular2 material package? use npm command like:

npm i --save @angular/material

Title: Angular4 Material sidenav not working

Body:
I am trying to test out the sidenav functionality in angular4 material. From whatever information I could gather from google. I made this plunker.
https://plnkr.co/edit/4VfijY?p=preview

<md-sidenav-container>
  <md-sidenav #sidenav mode="side" opened="true">
    <md-nav-list>

        Home

        Channels

    </md-nav-list>
  </md-sidenav>
</md-sidenav-container>

Could someone point out what am I doing wrong ?. I could use another pair of eyes.

Also if someone has successfully made a working sidenav or has a good tutorial could you please share here ?

Thanks a lot.


问:
Firebase functions FCM
I'm building an app with Firebase and as they added functions I wanted to try this out but ran into a few errors as I am unfamiliar with this language... I'm trying to send an FCM to every user of a group (when a new one is added to the database) and I used the example I found online but still ran into some trouble.

```<code>exports.sendPush = functions.database.ref('/groups/{groupId}').onWrite(event => {

const groupId = event.params.groupId;

... // defining constants like msg

const participators = admin.database().ref('/groups/' + groupId + '/users').once('value');
let getDeviceTokensPromise = []
for (let part in participators) {

    getDeviceTokensPromise.push(admin.database().ref('/users/' + part + '/notificationtoken')).once('value');

}

return Promise.all([getDeviceTokensPromise, participators]).then(results => {

    const tokensSnapshot = results[0];
    const follower = results[1];

    // Check if there are any device tokens.
    if (!tokensSnapshot.hasChildren()) {

        return console.log('There are no notification tokens to send to.');

    }

    console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
    console.log('Fetched follower profile', follower);

// Notification details.
    const payload = {
        notification: {
            title: 'New meeting!',
            body: msg
        }
    };

// Listing all tokens.
const tokens = Object.keys(tokensSnapshot.val());

// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
  // For each message check if there was an error.
  ...
</code>```

So I guess my mistake must be in the first few lines as all the rest follows this code (I left out the unimportant bits)... Here is my firebase architecture:

The groups branch of the firebase database

One user under the branch users

Regards

答:
Your code is fine. Just change the following

```<code>const participators = admin.database().ref('/groups/' + groupId + '/users').once('value');
</code>```

and

```<code>getDeviceTokensPromise.push(admin.database().ref('/users/' + part + '/notificationtoken')).once('value');
</code>```

to these :-

```<code>const participators = admin.database().ref(`/groups/${groupId}/users`).once('value');
</code>```

and

```<code>getDeviceTokensPromise.push(admin.database().ref(`/users/${part}/notificationtoken`)).once('value');
</code>```

Also, make sure that you use `` and not  ' ' inside the ref part.

Title: Firebase functions FCM

Body:
I'm building an app with Firebase and as they added functions I wanted to try this out but ran into a few errors as I am unfamiliar with this language... I'm trying to send an FCM to every user of a group (when a new one is added to the database) and I used the example I found online but still ran into some trouble.

exports.sendPush = functions.database.ref('/groups/{groupId}').onWrite(event => {

const groupId = event.params.groupId;

... // defining constants like msg

const participators = admin.database().ref('/groups/' + groupId + '/users').once('value');
let getDeviceTokensPromise = []
for (let part in participators) {

    getDeviceTokensPromise.push(admin.database().ref('/users/' + part + '/notificationtoken')).once('value');

}

return Promise.all([getDeviceTokensPromise, participators]).then(results => {

    const tokensSnapshot = results[0];
    const follower = results[1];

    // Check if there are any device tokens.
    if (!tokensSnapshot.hasChildren()) {

        return console.log('There are no notification tokens to send to.');

    }

    console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
    console.log('Fetched follower profile', follower);

// Notification details.
    const payload = {
        notification: {
            title: 'New meeting!',
            body: msg
        }
    };

// Listing all tokens.
const tokens = Object.keys(tokensSnapshot.val());

// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
  // For each message check if there was an error.
  ...

So I guess my mistake must be in the first few lines as all the rest follows this code (I left out the unimportant bits)... Here is my firebase architecture:

The groups branch of the firebase database

One user under the branch users

Regards

Body:
Your code is fine. Just change the following

const participators = admin.database().ref('/groups/' + groupId + '/users').once('value');

and

getDeviceTokensPromise.push(admin.database().ref('/users/' + part + '/notificationtoken')).once('value');

to these :-

const participators = admin.database().ref(`/groups/${groupId}/users`).once('value');

and

getDeviceTokensPromise.push(admin.database().ref(`/users/${part}/notificationtoken`)).once('value');

Also, make sure that you use `` and not  ' ' inside the ref part.


问:
How do I retrieve the value of a specific XML node by path?
I am looking for a Javascript solution to this problem:

I have an XML document which is loaded by way of a typical AJAX method:

var xml = http.responseXML;

Consider the following example xml snippet:

```<code><main>
    <primary>
         <enabled>true</enabled>
     </primary>
     <secondary>
         <enabled>true</enabled>
     </secondary>
 </main>
</code>```

I would like to get the value of a node by specifying the path as follows:

```<code>var second_enabled = getNodeValueByPath('main/secondary/enabled', xml);
</code>```

I cannot find any concise way of doing something like this. I seem to be forced to iterate through node collections after using getElementsByTagName and the like.

How would I construct the method getNodeValueByPath or is there some construct in Javascript that allows for this?

I am not well versed in Javascript.

EDIT: Here is an example that shows my attempt at using XPath and how it is failing:

XML:

```<code><?xml version="1.0" ?>
<main xmlns="example.com">
  <primary>
    <enabled>true</enabled>
  </primary>
  <secondary>
    <enabled>false</enabled>
  </secondary>
</main>
</code>```

JavaScript: (these are the relevant functions only)

```<code>function useHttpResponse()
{
    if (http.readyState == 4)
    {
        if(http.status == 200)
        {
            var xml = http.responseXML;
            var evalue = getXMLValueByPath('/main/secondary/enabled', xml);
            alert(evalue);
        }
    }
}

function getXMLValueByPath(nodepath, xml)
{
    var result = xml.evaluate(nodepath, xml, null, XPathResult.STRING_TYPE, null).stringValue;
    return result;
}
</code>```

I am using the above JavaScript without any additional libraries. I am using Mozilla Firefox 3.6.13 which uses the document.evaluate method to select nodes (according to this information from w3schools). This application is for internal use and does not have to work on multiple browsers.

Given these examples, the alert dialog will appear, but contain no text. If I remove the string xmlns="example.com" from the XML document, the alert dialog appears with the text "false" as desired.

Debugging using Firebug shows that resultNode is an empty string as long as the namespace is declared.

答:
```<code>XmlDocument xDoc = new XmlDocument();
xDoc.Load("d:\\one.xml");
XmlNode xNode = xDoc.SelectSingleNode(@"//main/secondary/enabled");
string result = ((XmlElement)xNode).FirstChild.Value;
</code>```

Body:
I am looking for a Javascript solution to this problem:

I have an XML document which is loaded by way of a typical AJAX method:

var xml = http.responseXML;

Consider the following example xml snippet:

    <primary>
         <enabled>true</enabled>
     </primary>
     <secondary>
         <enabled>true</enabled>
     </secondary>

I would like to get the value of a node by specifying the path as follows:

var second_enabled = getNodeValueByPath('main/secondary/enabled', xml);

I cannot find any concise way of doing something like this. I seem to be forced to iterate through node collections after using getElementsByTagName and the like.

How would I construct the method getNodeValueByPath or is there some construct in Javascript that allows for this?

I am not well versed in Javascript.

EDIT: Here is an example that shows my attempt at using XPath and how it is failing:

XML:

<?xml version="1.0" ?>

  <primary>
    <enabled>true</enabled>
  </primary>
  <secondary>
    <enabled>false</enabled>
  </secondary>

JavaScript: (these are the relevant functions only)

function useHttpResponse()
{
    if (http.readyState == 4)
    {
        if(http.status == 200)
        {
            var xml = http.responseXML;
            var evalue = getXMLValueByPath('/main/secondary/enabled', xml);
            alert(evalue);
        }
    }
}

function getXMLValueByPath(nodepath, xml)
{
    var result = xml.evaluate(nodepath, xml, null, XPathResult.STRING_TYPE, null).stringValue;
    return result;
}

I am using the above JavaScript without any additional libraries. I am using Mozilla Firefox 3.6.13 which uses the document.evaluate method to select nodes (according to this information from w3schools). This application is for internal use and does not have to work on multiple browsers.

Given these examples, the alert dialog will appear, but contain no text. If I remove the string xmlns="example.com" from the XML document, the alert dialog appears with the text "false" as desired.

Debugging using Firebug shows that resultNode is an empty string as long as the namespace is declared.


问:
File loading by getClass().getResource() fails, File() works
I'm trying to incorporate a css file to my JavaFX appllication, by the following snippet:

```<code>public void loadExternalCSS() {
      System.out.println("CLASSPATH: "+System.getProperty("java.class.path"));
      try{
        skinCSS = getClass().getResource("css/default_skin.css").toExternalForm();
      }
      catch(Exception e){
          System.err.println("Exception: " + e);
          e.printStackTrace(System.err);
      }
}
</code>```

Which yields, at runtime:

```<code>java.lang.NullPointerException
    at
robotikosanomologitos.RobotikosAnomologitos.loadExternalCSS(RobotikosAnomologitos.java:529)
    at robotikosanomologitos.RobotikosAnomologitos.start(RobotikosAnomologitos.java:491)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)
</code>```

The weird thing is that a few lines above this function, I have a small function that reads from a properties file.

```<code>public void readPropertiesFile() {
        Properties props = new Properties();
        InputStream is;
        try {
            File f = new File("properties");
            is = new FileInputStream(f);
        }
        /* etcetera */
}
</code>```

This works like a charm. The properties file is located at the root of the project directory, C:\~my_projects_folder~\RobotikosAnomologitos

After searching around for a solution, I saw that getClass().getResource() attempts to find a resource in the classpath. I tried printing the classpath at every run, and I get:
RobotikosAnomologitos\dist\run125323585\RobotikosAnomologitos.jar which is logical enough.

After looking inside this temporary folder while running the program, though, I can find no css folder nor css file.

But the file is indeed located in my working project directory, under RobotikosAnomologitos\css\default_skin.css. For some reason it doesn't make it in the classpath at runtime, causing getResource() to return null when looking for it.

Any ideas on how to include it?

EDIT: I forgot to mention that I have also placed css/default_skin.css under the src package, and shows up in Netbeans' package tree (src/css/default_skin.css).

In the same way, I have some graphics that are located under src/graphics/ which get loaded fine by getClass().getResourceAsStream(). Which also bafflesss me as to why the css file can't be found. Maybe it doesn't get compiled in the jar?

答: Check if you are not using binary encode of CSS files (see Project Properties>Packaging). If you are using, the mentioned file extension should be ".bss".</p>

Body:
I'm trying to incorporate a css file to my JavaFX appllication, by the following snippet:

public void loadExternalCSS() {
      System.out.println("CLASSPATH: "+System.getProperty("java.class.path"));
      try{
        skinCSS = getClass().getResource("css/default_skin.css").toExternalForm();
      }
      catch(Exception e){
          System.err.println("Exception: " + e);
          e.printStackTrace(System.err);
      }
}

Which yields, at runtime:

java.lang.NullPointerException
    at
robotikosanomologitos.RobotikosAnomologitos.loadExternalCSS(RobotikosAnomologitos.java:529)
    at robotikosanomologitos.RobotikosAnomologitos.start(RobotikosAnomologitos.java:491)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)

The weird thing is that a few lines above this function, I have a small function that reads from a properties file.

public void readPropertiesFile() {
        Properties props = new Properties();
        InputStream is;
        try {
            File f = new File("properties");
            is = new FileInputStream(f);
        }
        /* etcetera */
}

This works like a charm. The properties file is located at the root of the project directory, C:\~my_projects_folder~\RobotikosAnomologitos

After searching around for a solution, I saw that getClass().getResource() attempts to find a resource in the classpath. I tried printing the classpath at every run, and I get:
RobotikosAnomologitos\dist\run125323585\RobotikosAnomologitos.jar which is logical enough.

After looking inside this temporary folder while running the program, though, I can find no css folder nor css file.

But the file is indeed located in my working project directory, under RobotikosAnomologitos\css\default_skin.css. For some reason it doesn't make it in the classpath at runtime, causing getResource() to return null when looking for it.

Any ideas on how to include it?

EDIT: I forgot to mention that I have also placed css/default_skin.css under the src package, and shows up in Netbeans' package tree (src/css/default_skin.css).

In the same way, I have some graphics that are located under src/graphics/ which get loaded fine by getClass().getResourceAsStream(). Which also bafflesss me as to why the css file can't be found. Maybe it doesn't get compiled in the jar?


问:
How are random numbers generated in R when random seed is fixed?
I am running some stochastic simulation experiments and in one step I want to estimate the correlation between random numbers when the underlying source of randomness is the same, i.e., common U(0,1) random numbers.

I thought the following two code segments should produce the same result.

```<code>set.seed(1000)
a_1 = rgamma(100, 3, 4)
set.seed(1000)
b_1 = rgamma(100, 4, 5)
cor(a_1,b_1)

set.seed(1000)
u = runif(100)
a_2 = qgamma(u, 3, 4)
b_2 = qgamma(u, 4, 5)
cor(a_2,b_2)
</code>```

But the results are different

```<code>> cor(a_1,b_1)
[1] -0.04139218
> cor(a_2,b_2)
[1] 0.9993478
</code>```

Which a fixed random seed, I expect the correlations to be close to 1 (as it is the case in the second code segment). However, the outputs in the first code segment is surprising

For this specific seed (1000), the correlation in the first segment has a negative sign and a very small magnitude. Neither the sign nor the magnitude makes sense...

When playing around with different seeds (e.g., 1, 10, 100, 1000), the correlation in the first segment changes significantly while the correlation in the second segment is quite stable.

Can anyone give some insights about how R samples random numbers from the same seed?

Thanks in advance!

答:
```<code>set.seed(1)
u = runif(1000)
</code>```

Seems to be a typo for

```<code>set.seed(1000)
u = runif(100)
</code>```

If so, the only reason that I see for you thinking that the two experiments should be equivalent is that you are hypothesizing that rgamma(100, 3, 4) is generated by inverse transform sampling: start with runif(100) and then run those 100 numbers through the inverse of the cdf for a gamma random variable with parameters 3 and 4. However, the Wikipedia article on gamma random variables suggest that more sophisticated methods are used in generating gamma random variables (methods which involve multiple calls to the underlying PRNG).

?rgamma shows that R uses the Ahrens-Dieter algorithm that the Wikipedia article discusses. Thus there is no reason to expect that your two computations will yield the same result.

If what I took to be a typo at the beginning of my answer is what you actually intended then I have absolutely no idea why you would think that they should be equivalent, since they would then lack the "same seed" that you mention and furthermore correspond to different sample sizes.

Body:
I am running some stochastic simulation experiments and in one step I want to estimate the correlation between random numbers when the underlying source of randomness is the same, i.e., common U(0,1) random numbers.

I thought the following two code segments should produce the same result.

set.seed(1000)
a_1 = rgamma(100, 3, 4)
set.seed(1000)
b_1 = rgamma(100, 4, 5)
cor(a_1,b_1)

set.seed(1000)
u = runif(100)
a_2 = qgamma(u, 3, 4)
b_2 = qgamma(u, 4, 5)
cor(a_2,b_2)

But the results are different

> cor(a_1,b_1)
[1] -0.04139218
> cor(a_2,b_2)
[1] 0.9993478

Which a fixed random seed, I expect the correlations to be close to 1 (as it is the case in the second code segment). However, the outputs in the first code segment is surprising

For this specific seed (1000), the correlation in the first segment has a negative sign and a very small magnitude. Neither the sign nor the magnitude makes sense...

When playing around with different seeds (e.g., 1, 10, 100, 1000), the correlation in the first segment changes significantly while the correlation in the second segment is quite stable.

Can anyone give some insights about how R samples random numbers from the same seed?

Thanks in advance!

Body:
set.seed(1)
u = runif(1000)

Seems to be a typo for

set.seed(1000)
u = runif(100)

If so, the only reason that I see for you thinking that the two experiments should be equivalent is that you are hypothesizing that rgamma(100, 3, 4) is generated by inverse transform sampling: start with runif(100) and then run those 100 numbers through the inverse of the cdf for a gamma random variable with parameters 3 and 4. However, the Wikipedia article on gamma random variables suggest that more sophisticated methods are used in generating gamma random variables (methods which involve multiple calls to the underlying PRNG).

?rgamma shows that R uses the Ahrens-Dieter algorithm that the Wikipedia article discusses. Thus there is no reason to expect that your two computations will yield the same result.

If what I took to be a typo at the beginning of my answer is what you actually intended then I have absolutely no idea why you would think that they should be equivalent, since they would then lack the "same seed" that you mention and furthermore correspond to different sample sizes.


问:
Job for docker.service failed because the control process exited with error code
So I installed docker engine on RHEL 7

Now when I do a

```<code>service docker start
</code>```

I get the following error:

```<code>Job for docker.service failed because the control process exited with error code. See "systemctl status docker.service" and "journalctl -xe" for details.
</code>```

and when I go to "systemctl status docker.service" and "journalctl -xe"
I get:

```<code>docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/docker.service.d
           └─docker.conf
   Active: failed (Result: exit-code) since Thu 2016-09-08 22:15:53 EDT; 10s ago
     Docs: https://docs.docker.com
  Process: 13504 ExecStart=/usr/bin/docker daemon -H fd:// --mtu 1400 --exec-opt native.cgroupdriver=systemd (code=exited, status=1/FAILURE)
 Main PID: 13504 (code=exited, status=1/FAILURE)

Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Starting Docker Application Container Engine...
Sep 08 22:15:53 app-linux2.app-netapp.lab.com docker[13504]: time="2016-09-08T22:15:53.227074798-04:00" level=fatal msg="no sockets found via socket activation: make sure the service ...by systemd"
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service: main process exited, code=exited, status=1/FAILURE
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Failed to start Docker Application Container Engine.
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Unit docker.service entered failed state.
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service failed.
</code>```

And

--

```<code>-- The start-up result is done.
Sep 08 22:10:01 app-linux2.app-netapp.lab.com CROND[12753]: (root) CMD (/usr/lib64/sa/sa1 1 1)
Sep 08 22:10:01 app-linux2.app-netapp.lab.com systemd[1]: Starting Session 58 of user root.
-- Subject: Unit session-58.scope has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit session-58.scope has begun starting up.
Sep 08 22:10:53 app-linux2.app-netapp.lab.com polkitd[766]: Registered Authentication Agent for unix-process:12878:2674931 (system bus name :1.173 [/usr/bin/pkttyagent --notify-fd 5 --fallback], ob
Sep 08 22:10:53 app-linux2.app-netapp.lab.com systemd[1]: Starting Docker Application Container Engine...
-- Subject: Unit docker.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit docker.service has begun starting up.
Sep 08 22:10:53 app-linux2.app-netapp.lab.com docker[12895]: time="2016-09-08T22:10:53.413304246-04:00" level=fatal msg="no sockets found via socket activation: make sure the service was started by
Sep 08 22:10:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service: main process exited, code=exited, status=1/FAILURE
Sep 08 22:10:53 app-linux2.app-netapp.lab.com systemd[1]: Failed to start Docker Application Container Engine.
-- Subject: Unit docker.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit docker.service has failed.
--
-- The result is failed.
Sep 08 22:10:53 app-linux2.app-netapp.lab.com systemd[1]: Unit docker.service entered failed state.
Sep 08 22:10:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service failed.
Sep 08 22:10:53 app-linux2.app-netapp.lab.com polkitd[766]: Unregistered Authentication Agent for unix-process:12878:2674931 (system bus name :1.173, object path /org/freedesktop/PolicyKit1/Authent
Sep 08 22:13:36 app-linux2.app-netapp.lab.com polkitd[766]: Registered Authentication Agent for unix-process:13214:2691210 (system bus name :1.174 [/usr/bin/pkttyagent --notify-fd 5 --fallback], ob
Sep 08 22:13:36 app-linux2.app-netapp.lab.com polkitd[766]: Unregistered Authentication Agent for unix-process:13214:2691210 (system bus name :1.174, object path /org/freedesktop/PolicyKit1/Authent
Sep 08 22:15:53 app-linux2.app-netapp.lab.com polkitd[766]: Registered Authentication Agent for unix-process:13489:2704913 (system bus name :1.175 [/usr/bin/pkttyagent --notify-fd 5 --fallback], ob
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Starting Docker Application Container Engine...
-- Subject: Unit docker.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit docker.service has begun starting up.
Sep 08 22:15:53 app-linux2.app-netapp.lab.com docker[13504]: time="2016-09-08T22:15:53.227074798-04:00" level=fatal msg="no sockets found via socket activation: make sure the service was started by
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service: main process exited, code=exited, status=1/FAILURE
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Failed to start Docker Application Container Engine.
-- Subject: Unit docker.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit docker.service has failed.
--
-- The result is failed.
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Unit docker.service entered failed state.
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service failed.
Sep 08 22:15:53 app-linux2.app-netapp.lab.com polkitd[766]: Unregistered Authentication Agent for unix-process:13489:2704913 (system bus name :1.175, object path /org/freedesktop/PolicyKit1/Authent
lines 3473-3523/3523 (END)
</code>```

I tried to search solution for this
but could not find any.

答:
Fixing the Job for docker.service failed because the control process exited with error code. See "systemctl status docker.service" and "journalctl -xe" for details. problem, for me this worked:

create daemon.json in /etc/docker/

put this in it:

{

  "exec-root": "/path/to/docker/run",

 "storage-driver": "overlay",

  "graph": "/path/to/docker/lib"

}

then try: docker daemon

reboot

docker run hello-world should succeed now

Body:
So I installed docker engine on RHEL 7

Now when I do a

service docker start

I get the following error:

Job for docker.service failed because the control process exited with error code. See "systemctl status docker.service" and "journalctl -xe" for details.

and when I go to "systemctl status docker.service" and "journalctl -xe"
I get:

docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/docker.service.d
           └─docker.conf
   Active: failed (Result: exit-code) since Thu 2016-09-08 22:15:53 EDT; 10s ago
     Docs: https://docs.docker.com
  Process: 13504 ExecStart=/usr/bin/docker daemon -H fd:// --mtu 1400 --exec-opt native.cgroupdriver=systemd (code=exited, status=1/FAILURE)
 Main PID: 13504 (code=exited, status=1/FAILURE)

Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Starting Docker Application Container Engine...
Sep 08 22:15:53 app-linux2.app-netapp.lab.com docker[13504]: time="2016-09-08T22:15:53.227074798-04:00" level=fatal msg="no sockets found via socket activation: make sure the service ...by systemd"
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service: main process exited, code=exited, status=1/FAILURE
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Failed to start Docker Application Container Engine.
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Unit docker.service entered failed state.
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service failed.

And

--

-- The start-up result is done.
Sep 08 22:10:01 app-linux2.app-netapp.lab.com CROND[12753]: (root) CMD (/usr/lib64/sa/sa1 1 1)
Sep 08 22:10:01 app-linux2.app-netapp.lab.com systemd[1]: Starting Session 58 of user root.
-- Subject: Unit session-58.scope has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit session-58.scope has begun starting up.
Sep 08 22:10:53 app-linux2.app-netapp.lab.com polkitd[766]: Registered Authentication Agent for unix-process:12878:2674931 (system bus name :1.173 [/usr/bin/pkttyagent --notify-fd 5 --fallback], ob
Sep 08 22:10:53 app-linux2.app-netapp.lab.com systemd[1]: Starting Docker Application Container Engine...
-- Subject: Unit docker.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit docker.service has begun starting up.
Sep 08 22:10:53 app-linux2.app-netapp.lab.com docker[12895]: time="2016-09-08T22:10:53.413304246-04:00" level=fatal msg="no sockets found via socket activation: make sure the service was started by
Sep 08 22:10:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service: main process exited, code=exited, status=1/FAILURE
Sep 08 22:10:53 app-linux2.app-netapp.lab.com systemd[1]: Failed to start Docker Application Container Engine.
-- Subject: Unit docker.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit docker.service has failed.
--
-- The result is failed.
Sep 08 22:10:53 app-linux2.app-netapp.lab.com systemd[1]: Unit docker.service entered failed state.
Sep 08 22:10:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service failed.
Sep 08 22:10:53 app-linux2.app-netapp.lab.com polkitd[766]: Unregistered Authentication Agent for unix-process:12878:2674931 (system bus name :1.173, object path /org/freedesktop/PolicyKit1/Authent
Sep 08 22:13:36 app-linux2.app-netapp.lab.com polkitd[766]: Registered Authentication Agent for unix-process:13214:2691210 (system bus name :1.174 [/usr/bin/pkttyagent --notify-fd 5 --fallback], ob
Sep 08 22:13:36 app-linux2.app-netapp.lab.com polkitd[766]: Unregistered Authentication Agent for unix-process:13214:2691210 (system bus name :1.174, object path /org/freedesktop/PolicyKit1/Authent
Sep 08 22:15:53 app-linux2.app-netapp.lab.com polkitd[766]: Registered Authentication Agent for unix-process:13489:2704913 (system bus name :1.175 [/usr/bin/pkttyagent --notify-fd 5 --fallback], ob
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Starting Docker Application Container Engine...
-- Subject: Unit docker.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit docker.service has begun starting up.
Sep 08 22:15:53 app-linux2.app-netapp.lab.com docker[13504]: time="2016-09-08T22:15:53.227074798-04:00" level=fatal msg="no sockets found via socket activation: make sure the service was started by
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service: main process exited, code=exited, status=1/FAILURE
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Failed to start Docker Application Container Engine.
-- Subject: Unit docker.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit docker.service has failed.
--
-- The result is failed.
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: Unit docker.service entered failed state.
Sep 08 22:15:53 app-linux2.app-netapp.lab.com systemd[1]: docker.service failed.
Sep 08 22:15:53 app-linux2.app-netapp.lab.com polkitd[766]: Unregistered Authentication Agent for unix-process:13489:2704913 (system bus name :1.175, object path /org/freedesktop/PolicyKit1/Authent
lines 3473-3523/3523 (END)

I tried to search solution for this
but could not find any.


问:
Pass Record variable to .NET library
Is there a way to pass variable of Record (or RecordRef) type as a parameter to method of .NET object?</p>

答:
In theory it is not possible pass like datatable or something else. What you can do is to create a public class in .NET that is visible in NAV, complete the data of that class and pass the .NET class as a parameter with the data in the NAV table.

For example table 18 (Customer) you can create a .NET class with the same structure, call this class in NAV code, complete the data in NAV and then pass this class with the same fields data as table 18 to .NET

If you need pass a parameter multiples registers of the same table create a Array of this .NET class perform a loop, assing the values and pass one by one to .NET

I made a code similar to the one I told you about and it works correctly.

Title: Pass Record variable to .NET library


问:
How to implement multiple screens within an App
I am currently working on an Android App which has different service dimensions, such as " service order", "route planning", "photo gallery" and a central login.
so far i implemented each "screen" (and by screen i mean actually the layout of a screen) as a seperate class, which loads a specific layout and handles all listeners and core functionalities such as calling webservices in a thread, receiving answers etc.
I am not quite sure if this is the best way to implemnt mulitiple layout-screens.

The Android dev guideline proposes to use single activities for each "screen layout". However I doubt that this is the most effective way of doing things. Since i need information for each "layout" which are retrieved by the central login (here: a  user object). Since an activity (as far as i understand) is a seperate thread, the passing and retrieving of information seems not very practical.

I would like to get your oppinions/feedback on that and thanks for any hint or tip.

So far my structure looks like :

Activity

loads login layout (res/layout/login.xml with setlContentView)

depending on buttonclick other resources are loaded and initialized (means listeners are added etc.)

Greets
 Peter

答: The dev guidelines recommend that for a reason. It IS the most effective way of doing things. You may complain about having to store your data so it can be passed along from activity to activity, but guess what? You're developing an app for a phone! At any point in time, the phone could ring, forcing the user to switch away from your app. Or the user could just choose to temporarily look at a different app. If your app goes back to square one after switching back and lost all data, the user will be understandably angry.</p>


问:
how to resolve "cannot read property appendChild of null" in the following code?
```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title> speech synthesizer</title>
  </head>
  <body>
    <div class="voiceinator">
      <h1> My Speech Synthesizer </h1>

      <select id="voices" name="voice">
        <option value="">Select a voice</option>
      </select>

    <label for="rate">Rate:</label>
    <input type="range" name="rate" value="1" min="0" max="3" step="0.1">

    <label for="pitch">Pitch:</label>
    <input type="range" name="pitch" min="0" max="2" step="0.1">

    <textarea name="text"> Hello there! </textarea>
    <button type="button" id="stop"> Stop! </button>
    <button type="button" id="speak"> Speak </button>
    </div>
 <script type="text/javascript">

  const msg = new SpeechSynthesisUtterance();
  let voices = [];
  var voicesDropdown = document.querySelector('[name="voices"]');
  const options = document.querySelector('[name="range"], [name="text"]'); // this selects the rate control bar, pitch bar and text area
  const speakButton = document.querySelector('#speak');
  const stopButton = document.querySelector('#stop');
  msg.text = document.querySelector('[name="text"]').value;

  function populateVoices()
  {
    voices = this.getVoices();

    for( var i=0 ; i<voices.length ; i++ ){
      var opt = voices[i];
      var el = document.createElement("option");
      el.textContent = opt;
      el.value = opt;
      voicesDropdown.appendChild(el);
    }

  }
  //when speechSynthesis loads , voiceschanged event occurs and populateVoices function is fired
  speechSynthesis.addEventListener('voiceschanged', populateVoices);
 </script>
  </body>
</html>
</code>```

THIS IS THE ERROR I AM GETTING --- HOW TO RESOLVE IT?

SPEECH SYNTHESIZER.html:45 Uncaught TypeError: Cannot read property 'appendChild' of null
      at SpeechSynthesis.populateVoices (SPEECH SYNTHESIZER.html:45)

Also please tell me how do I append two values to el.textContent? For eg. I want it to display voices[i].name and voices[i].lang

答:
THIS IS THE ERROR I AM GETTING --- HOW TO RESOLVE IT?

One way is to update the name attribute of the <select> tag:

```<code><select id="voices" name="voices">
</code>```

Or the javascript could be updated:

```<code>var voicesDropdown = document.querySelector('[name="voices"]');
</code>```

how do I append two values to el.textContent? For eg. I want it to display voices[i].name and voices[i].lang

The options properties can be referenced with setting the textContent property and appended using the addition operator (i.e. +) or String.concatenate().

```<code>el.textContent = opt.name + ' - ' + opt.lang;
</code>```

See this demonstrated in the snippet below.

const msg = new SpeechSynthesisUtterance();
let voices = [];
var voicesDropdown = document.querySelector('[name="voices"]');
const options = document.querySelector('[name="range"], [name="text"]'); // this selects the rate control bar, pitch bar and text area
const speakButton = document.querySelector('#speak');
const stopButton = document.querySelector('#stop');
msg.text = document.querySelector('[name="text"]').value;

function populateVoices() {
  voices = this.getVoices();

  for (var i = 0; i < voices.length; i++) {
    var opt = voices[i];
    var el = document.createElement("option");
    el.textContent = opt.name + ' - ' + opt.lang;
    el.value = opt;
    voicesDropdown.appendChild(el);
  }

}
//when speechSynthesis loads , voiceschanged event occurs and populateVoices function is fired
speechSynthesis.addEventListener('voiceschanged', populateVoices);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="voiceinator">
  <h1> My Speech Synthesizer </h1>

  <select id="voices" name="voices">
        <option value="">Select a voice</option>
      </select>

  <label for="rate">Rate:</label>
  <input type="range" name="rate" value="1" min="0" max="3" step="0.1">

  <label for="pitch">Pitch:</label>
  <input type="range" name="pitch" min="0" max="2" step="0.1">

  <textarea name="text"> Hello there! </textarea>
  <button type="button" id="stop"> Stop! </button>
  <button type="button" id="speak"> Speak </button>
</div></code>```

Body:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title> speech synthesizer</title>

 My Speech Synthesizer

      <select id="voices" name="voice">
        <option value="">Select a voice</option>
      </select>

    Rate:
    <input type="range" name="rate" value="1" min="0" max="3" step="0.1">

    Pitch:
    <input type="range" name="pitch" min="0" max="2" step="0.1">

    <textarea name="text"> Hello there! </textarea>
    <button type="button" id="stop"> Stop! </button>
    <button type="button" id="speak"> Speak </button>

THIS IS THE ERROR I AM GETTING --- HOW TO RESOLVE IT?

SPEECH SYNTHESIZER.html:45 Uncaught TypeError: Cannot read property 'appendChild' of null
      at SpeechSynthesis.populateVoices (SPEECH SYNTHESIZER.html:45)

Also please tell me how do I append two values to el.textContent? For eg. I want it to display voices[i].name and voices[i].lang

Body:
THIS IS THE ERROR I AM GETTING --- HOW TO RESOLVE IT?

One way is to update the name attribute of the <select> tag:

<select id="voices" name="voices">

Or the javascript could be updated:

var voicesDropdown = document.querySelector('[name="voices"]');

how do I append two values to el.textContent? For eg. I want it to display voices[i].name and voices[i].lang

The options properties can be referenced with setting the textContent property and appended using the addition operator (i.e. +) or String.concatenate().

el.textContent = opt.name + ' - ' + opt.lang;

See this demonstrated in the snippet below.

const msg = new SpeechSynthesisUtterance();
let voices = [];
var voicesDropdown = document.querySelector('[name="voices"]');
const options = document.querySelector('[name="range"], [name="text"]'); // this selects the rate control bar, pitch bar and text area
const speakButton = document.querySelector('#speak');
const stopButton = document.querySelector('#stop');
msg.text = document.querySelector('[name="text"]').value;

function populateVoices() {
  voices = this.getVoices();

  for (var i = 0; i < voices.length; i++) {
    var opt = voices[i];
    var el = document.createElement("option");
    el.textContent = opt.name + ' - ' + opt.lang;
    el.value = opt;
    voicesDropdown.appendChild(el);
  }

}
//when speechSynthesis loads , voiceschanged event occurs and populateVoices function is fired
speechSynthesis.addEventListener('voiceschanged', populateVoices);

<div class="voiceinator">
  <h1> My Speech Synthesizer </h1>

  <select id="voices" name="voices">
        <option value="">Select a voice</option>
      </select>

  <label for="rate">Rate:</label>
  <input type="range" name="rate" value="1" min="0" max="3" step="0.1">

  <label for="pitch">Pitch:</label>
  <input type="range" name="pitch" min="0" max="2" step="0.1">

  <textarea name="text"> Hello there! </textarea>
  <button type="button" id="stop"> Stop! </button>
  <button type="button" id="speak"> Speak </button>
</div>


问:
HTTP port exposed but not responding properly
Running Docker 1.9.1 on OpenSuse 42.1 (can't upgrade at this time but also the same problem on Docker 1.12).

I have a Docker images that exposes a web application on port 8080. I can ssh into the container and access the application correctly from inside the container on http://localhost:8080/.

I run the container using

```<code>docker run -p 10000:8080 ...
</code>```

and I would expect the web application being accessible on either

```<code>http://localhost:10000 or http://public-ip:10000
</code>```

The port is open but the connection is being closed immediately.

```<code>sudo netstat -nap|grep LISTEN|grep -v LISTENING|grep 1000
root's password:
tcp        0      0 :::10000                :::*                    LISTEN      17375/docker-proxy
</code>```

I can telnet to port 10000 but as said the connection is being closed immediately

```<code>docker --version
Docker version 1.9.1, build a34a1d5
docker version
Client:
Version: 1.9.1
API version: 1.21
Go version: go1.4.2
Git commit: a34a1d5
Built:
OS/Arch: linux/amd64
Server:
 Version:      1.9.1
 API version:  1.21
 Go version:   go1.4.2
 Git commit:   a34a1d5
 Built:
 OS/Arch:      linux/amd64

docker info (1.9)
Containers: 23
 Running: 1
 Paused: 0
 Stopped: 22
Images: 198
Server Version: 1.12.6
Storage Driver: devicemapper
 Pool Name: docker-8:2-1074640197-pool
 Pool Blocksize: 65.54 kB
 Base Device Size: 10.74 GB
 Backing Filesystem: xfs
 Data file: /dev/loop0
 Metadata file: /dev/loop1
 Data Space Used: 13.22 GB
 Data Space Total: 107.4 GB
 Data Space Available: 94.16 GB
 Metadata Space Used: 20.58 MB
 Metadata Space Total: 2.147 GB
 Metadata Space Available: 2.127 GB
 Thin Pool Minimum Free Space: 10.74 GB
 Udev Sync Supported: true
 Deferred Removal Enabled: false
 Deferred Deletion Enabled: false
 Deferred Deleted Device Count: 0
 Data loop file: /var/lib/docker/devicemapper/devicemapper/data
 WARNING: Usage of loopback devices is strongly discouraged for production use. Use `--storage-opt dm.thinpooldev` to specify a custom block storage device.
 Metadata loop file: /var/lib/docker/devicemapper/devicemapper/metadata
 Library Version: 1.02.136 (2016-11-05)
Logging Driver: journald
Cgroup Driver: systemd
Plugins:
 Volume: local
 Network: null bridge host overlay
Swarm: inactive
Runtimes: oci runc
Default Runtime: oci
Security Options: seccomp
Kernel Version: 4.11.8-200.fc25.x86_64
Operating System: Fedora 25 (Server Edition)
OSType: linux
Architecture: x86_64
Number of Docker Hooks: 2
CPUs: 6
Total Memory: 29.45 GiB
Name: dev2.zopyx.com
ID: DE7T:KEX4:UCRB:KOED:2DHE:3437:MYDS:LPQT:BBYO:SOQH:2EZL:VTYR
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Insecure Registries:
 127.0.0.0/8
Registries: docker.io (secure)

docker info (1.12)
Containers: 23
 Running: 1
 Paused: 0
 Stopped: 22
Images: 198
Server Version: 1.12.6
Storage Driver: devicemapper
 Pool Name: docker-8:2-1074640197-pool
 Pool Blocksize: 65.54 kB
 Base Device Size: 10.74 GB
 Backing Filesystem: xfs
 Data file: /dev/loop0
 Metadata file: /dev/loop1
 Data Space Used: 13.22 GB
 Data Space Total: 107.4 GB
 Data Space Available: 94.16 GB
 Metadata Space Used: 20.58 MB
 Metadata Space Total: 2.147 GB
 Metadata Space Available: 2.127 GB
 Thin Pool Minimum Free Space: 10.74 GB
 Udev Sync Supported: true
 Deferred Removal Enabled: false
 Deferred Deletion Enabled: false
 Deferred Deleted Device Count: 0
 Data loop file: /var/lib/docker/devicemapper/devicemapper/data
 WARNING: Usage of loopback devices is strongly discouraged for production use. Use `--storage-opt dm.thinpooldev` to specify a custom block storage device.
 Metadata loop file: /var/lib/docker/devicemapper/devicemapper/metadata
 Library Version: 1.02.136 (2016-11-05)
Logging Driver: journald
Cgroup Driver: systemd
Plugins:
 Volume: local
 Network: bridge host overlay null
Swarm: inactive
Runtimes: runc oci
Default Runtime: oci
Security Options: seccomp
Kernel Version: 4.11.8-200.fc25.x86_64
Operating System: Fedora 25 (Server Edition)
OSType: linux
Architecture: x86_64
Number of Docker Hooks: 2
CPUs: 6
Total Memory: 29.45 GiB
Name: dev2.zopyx.com
ID: DE7T:KEX4:UCRB:KOED:2DHE:3437:MYDS:LPQT:BBYO:SOQH:2EZL:VTYR
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Insecure Registries:
 127.0.0.0/8
Registries: docker.io (secure)
</code>```

What could be the problem here?

答: Solution: the webservice internally was only binding to 127.0.0.1 instead to 0.0.0.0</p>

Body:
Running Docker 1.9.1 on OpenSuse 42.1 (can't upgrade at this time but also the same problem on Docker 1.12).

I have a Docker images that exposes a web application on port 8080. I can ssh into the container and access the application correctly from inside the container on http://localhost:8080/.

I run the container using

docker run -p 10000:8080 ...

and I would expect the web application being accessible on either

http://localhost:10000 or http://public-ip:10000

The port is open but the connection is being closed immediately.

sudo netstat -nap|grep LISTEN|grep -v LISTENING|grep 1000
root's password:
tcp        0      0 :::10000                :::*                    LISTEN      17375/docker-proxy

I can telnet to port 10000 but as said the connection is being closed immediately

docker --version
Docker version 1.9.1, build a34a1d5
docker version
Client:
Version: 1.9.1
API version: 1.21
Go version: go1.4.2
Git commit: a34a1d5
Built:
OS/Arch: linux/amd64
Server:
 Version:      1.9.1
 API version:  1.21
 Go version:   go1.4.2
 Git commit:   a34a1d5
 Built:
 OS/Arch:      linux/amd64

docker info (1.9)
Containers: 23
 Running: 1
 Paused: 0
 Stopped: 22
Images: 198
Server Version: 1.12.6
Storage Driver: devicemapper
 Pool Name: docker-8:2-1074640197-pool
 Pool Blocksize: 65.54 kB
 Base Device Size: 10.74 GB
 Backing Filesystem: xfs
 Data file: /dev/loop0
 Metadata file: /dev/loop1
 Data Space Used: 13.22 GB
 Data Space Total: 107.4 GB
 Data Space Available: 94.16 GB
 Metadata Space Used: 20.58 MB
 Metadata Space Total: 2.147 GB
 Metadata Space Available: 2.127 GB
 Thin Pool Minimum Free Space: 10.74 GB
 Udev Sync Supported: true
 Deferred Removal Enabled: false
 Deferred Deletion Enabled: false
 Deferred Deleted Device Count: 0
 Data loop file: /var/lib/docker/devicemapper/devicemapper/data
 WARNING: Usage of loopback devices is strongly discouraged for production use. Use `--storage-opt dm.thinpooldev` to specify a custom block storage device.
 Metadata loop file: /var/lib/docker/devicemapper/devicemapper/metadata
 Library Version: 1.02.136 (2016-11-05)
Logging Driver: journald
Cgroup Driver: systemd
Plugins:
 Volume: local
 Network: null bridge host overlay
Swarm: inactive
Runtimes: oci runc
Default Runtime: oci
Security Options: seccomp
Kernel Version: 4.11.8-200.fc25.x86_64
Operating System: Fedora 25 (Server Edition)
OSType: linux
Architecture: x86_64
Number of Docker Hooks: 2
CPUs: 6
Total Memory: 29.45 GiB
Name: dev2.zopyx.com
ID: DE7T:KEX4:UCRB:KOED:2DHE:3437:MYDS:LPQT:BBYO:SOQH:2EZL:VTYR
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Insecure Registries:
 127.0.0.0/8
Registries: docker.io (secure)

docker info (1.12)
Containers: 23
 Running: 1
 Paused: 0
 Stopped: 22
Images: 198
Server Version: 1.12.6
Storage Driver: devicemapper
 Pool Name: docker-8:2-1074640197-pool
 Pool Blocksize: 65.54 kB
 Base Device Size: 10.74 GB
 Backing Filesystem: xfs
 Data file: /dev/loop0
 Metadata file: /dev/loop1
 Data Space Used: 13.22 GB
 Data Space Total: 107.4 GB
 Data Space Available: 94.16 GB
 Metadata Space Used: 20.58 MB
 Metadata Space Total: 2.147 GB
 Metadata Space Available: 2.127 GB
 Thin Pool Minimum Free Space: 10.74 GB
 Udev Sync Supported: true
 Deferred Removal Enabled: false
 Deferred Deletion Enabled: false
 Deferred Deleted Device Count: 0
 Data loop file: /var/lib/docker/devicemapper/devicemapper/data
 WARNING: Usage of loopback devices is strongly discouraged for production use. Use `--storage-opt dm.thinpooldev` to specify a custom block storage device.
 Metadata loop file: /var/lib/docker/devicemapper/devicemapper/metadata
 Library Version: 1.02.136 (2016-11-05)
Logging Driver: journald
Cgroup Driver: systemd
Plugins:
 Volume: local
 Network: bridge host overlay null
Swarm: inactive
Runtimes: runc oci
Default Runtime: oci
Security Options: seccomp
Kernel Version: 4.11.8-200.fc25.x86_64
Operating System: Fedora 25 (Server Edition)
OSType: linux
Architecture: x86_64
Number of Docker Hooks: 2
CPUs: 6
Total Memory: 29.45 GiB
Name: dev2.zopyx.com
ID: DE7T:KEX4:UCRB:KOED:2DHE:3437:MYDS:LPQT:BBYO:SOQH:2EZL:VTYR
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Insecure Registries:
 127.0.0.0/8
Registries: docker.io (secure)

What could be the problem here?


问:
Why this setState is not a function in ComponenDidMount?
I am trying to fetch ordered data from Firebase and set it to state highscoreArray but it gives error "undefined is not a function (evaluating 'this.setState({ highscoreArray:sortedHighscores })')</p>

```<code>    componentDidMount() {
    const reference = database.ref("highscores");

    // Pushing sorted data to highscoreArray.
    reference.orderByChild("highscore").limitToLast(3).on("value", function (snapshot) {
        sortedHighscores = [];
        snapshot.forEach(function (child) {
            sortedHighscores.push({
                "username": child.val().username,
                "score": child.val().highscore
            });
        });
        sortedHighscores = sortedHighscores.reverse();
        console.log("sortedh", sortedHighscores); // fetch success
        this.setState({highscoreArray: sortedHighscores}); // gives error
    });
}
</code>```

答:
1.this not accessible within loop so use variable let that = this the use that wherever you need this in this function.

```<code>  componentDidMount() {
        const reference = database.ref("highscores");
        let that = this // here your variable declaration
        // Pushing sorted data to highscoreArray.
        reference.orderByChild("highscore").limitToLast(3).on("value", function (snapshot) {
            sortedHighscores = [];
            snapshot.forEach(function (child) {
                sortedHighscores.push({
                    "username": child.val().username,
                    "score": child.val().highscore
                });
            });
            sortedHighscores = sortedHighscores.reverse();
            console.log("sortedh", sortedHighscores); // fetch success
            that.setState({highscoreArray: sortedHighscores}); // gives error
        });
    }
</code>```

Hope this will help you :) happy coding!

Body:
I am trying to fetch ordered data from Firebase and set it to state highscoreArray but it gives error "undefined is not a function (evaluating 'this.setState({ highscoreArray:sortedHighscores })')

    componentDidMount() {
    const reference = database.ref("highscores");

    // Pushing sorted data to highscoreArray.
    reference.orderByChild("highscore").limitToLast(3).on("value", function (snapshot) {
        sortedHighscores = [];
        snapshot.forEach(function (child) {
            sortedHighscores.push({
                "username": child.val().username,
                "score": child.val().highscore
            });
        });
        sortedHighscores = sortedHighscores.reverse();
        console.log("sortedh", sortedHighscores); // fetch success
        this.setState({highscoreArray: sortedHighscores}); // gives error
    });
}

Body:
1.this not accessible within loop so use variable let that = this the use that wherever you need this in this function.

  componentDidMount() {
        const reference = database.ref("highscores");
        let that = this // here your variable declaration
        // Pushing sorted data to highscoreArray.
        reference.orderByChild("highscore").limitToLast(3).on("value", function (snapshot) {
            sortedHighscores = [];
            snapshot.forEach(function (child) {
                sortedHighscores.push({
                    "username": child.val().username,
                    "score": child.val().highscore
                });
            });
            sortedHighscores = sortedHighscores.reverse();
            console.log("sortedh", sortedHighscores); // fetch success
            that.setState({highscoreArray: sortedHighscores}); // gives error
        });
    }

Hope this will help you :) happy coding!


问:
Initialize multiple variables with different parameters
I have the following code in python 3:

```<code>x = [(''.join(random.choices(string.ascii_lowercase, k=7))) for _ in range(5)]
</code>```

Is there a better way to initialize multiple (5+) lists with different K values and in range()?

ex:

```<code>y = [(''.join(random.choices(string.ascii_lowercase, k=3))) for _ in range(5)]
z = [(''.join(random.choices(string.ascii_lowercase, k=7))) for _ in range(2)]
a = [(''.join(random.choices(string.ascii_lowercase, k=4))) for _ in range(3)]
b = [(''.join(random.choices(string.ascii_lowercase, k=3))) for _ in range(5)]
c = [(''.join(random.choices(string.ascii_lowercase, k=1))) for _ in range(3)]
</code>```

答:
Put the list comprehension in a function and use that repeatedly:

```<code>def func(k, r):
   return [(''.join(random.choices(string.ascii_lowercase, k=k))) for _ in range(r)]
</code>```

```<code>y = func(3, 5)
...
c = func(1, 3)
</code>```

If you have the values of k and r in two lists, you can do:

```<code>y,..., c =  (func(*t) for t in zip(lst_k, lst_r))
</code>```

Or better still keep the data structure as a list of lists to not worry about the number of targets on the LHS:

```<code>super_list = [func(*t) for t in zip(lst_k, lst_r)]
</code>```

Body:
I have the following code in python 3:

x = [(''.join(random.choices(string.ascii_lowercase, k=7))) for _ in range(5)]

Is there a better way to initialize multiple (5+) lists with different K values and in range()?

ex:

y = [(''.join(random.choices(string.ascii_lowercase, k=3))) for _ in range(5)]
z = [(''.join(random.choices(string.ascii_lowercase, k=7))) for _ in range(2)]
a = [(''.join(random.choices(string.ascii_lowercase, k=4))) for _ in range(3)]
b = [(''.join(random.choices(string.ascii_lowercase, k=3))) for _ in range(5)]
c = [(''.join(random.choices(string.ascii_lowercase, k=1))) for _ in range(3)]

Body:
Put the list comprehension in a function and use that repeatedly:

def func(k, r):
   return [(''.join(random.choices(string.ascii_lowercase, k=k))) for _ in range(r)]

y = func(3, 5)
...
c = func(1, 3)

If you have the values of k and r in two lists, you can do:

y,..., c =  (func(*t) for t in zip(lst_k, lst_r))

Or better still keep the data structure as a list of lists to not worry about the number of targets on the LHS:

super_list = [func(*t) for t in zip(lst_k, lst_r)]


问:
Pass Parameters in VBA HTTP Post Request
I'm trying to do a simple post request on the main search bar of http://forums.egullet.org/.  (This is one example, but I'm trying to build a tool that will work with many.)

The problem is that I can't seem to figure out the right way to structure/place the parameters such that the server processes my request.  (I do get a response, but it's just a page asking me to try the search again, rather than the result I get when I do the search in a browser.  The argument string was pulled straight out of firebug, so I'm fairly sure that it's correct.  I just get the impression that i'm not putting it in the right place/structuring it correctly/saying everything that I need to, but I don't know what to change.  It's worth noting that I previously had this working by editing the DOM of an internet explorer object, but I'm trying to switch to XMLHTTP because it's much faster/more reliable.   Thanks for your help!

```<code>Sub httpPost()
Dim XMLHTTP
Dim result As String
Dim argumentString
argumentString = "?search_term=eggs&search_app=forums"
Set XMLHTTP = CreateObject("MSXML2.XMLHTTP.6.0")
XMLHTTP.Open "POST", _
    "http://forums.egullet.org/index.php?app=core&module=search&do=search&fromMainBar=1", False
XMLHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
XMLHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
XMLHTTP.send argumentString
result = XMLHTTP.responsetext
Set XMLHTTP = Nothing
End Sub
</code>```

答:
To make it more concise and get the title of that target page:</p>

```<code>Sub httpPost()
    Dim http As New XMLHTTP60, html As New HTMLDocument
    Dim post As Object, argstr As String

    argstr = "type=all&q=eggs"

    With http
        .Open "POST", "https://forums.egullet.org/search/?", False
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
        .setRequestHeader "Content-type", "application/x-www-form-urlencoded"
        .send argstr
        html.body.innerHTML = .responseText
    End With

    For Each post In html.getElementsByClassName("ipsStreamItem_title")
        With post.getElementsByTagName("a")
            If .Length Then Row = Row + 1: Cells(Row, 1) = .Item(0).innerText
        End With
    Next post
End Sub
</code>```

Body:
I'm trying to do a simple post request on the main search bar of http://forums.egullet.org/.  (This is one example, but I'm trying to build a tool that will work with many.)

The problem is that I can't seem to figure out the right way to structure/place the parameters such that the server processes my request.  (I do get a response, but it's just a page asking me to try the search again, rather than the result I get when I do the search in a browser.  The argument string was pulled straight out of firebug, so I'm fairly sure that it's correct.  I just get the impression that i'm not putting it in the right place/structuring it correctly/saying everything that I need to, but I don't know what to change.  It's worth noting that I previously had this working by editing the DOM of an internet explorer object, but I'm trying to switch to XMLHTTP because it's much faster/more reliable.   Thanks for your help!

Sub httpPost()
Dim XMLHTTP
Dim result As String
Dim argumentString
argumentString = "?search_term=eggs&search_app=forums"
Set XMLHTTP = CreateObject("MSXML2.XMLHTTP.6.0")
XMLHTTP.Open "POST", _
    "http://forums.egullet.org/index.php?app=core&module=search&do=search&fromMainBar=1", False
XMLHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
XMLHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
XMLHTTP.send argumentString
result = XMLHTTP.responsetext
Set XMLHTTP = Nothing
End Sub

Body:
To make it more concise and get the title of that target page:

Sub httpPost()
    Dim http As New XMLHTTP60, html As New HTMLDocument
    Dim post As Object, argstr As String

    argstr = "type=all&q=eggs"

    With http
        .Open "POST", "https://forums.egullet.org/search/?", False
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
        .setRequestHeader "Content-type", "application/x-www-form-urlencoded"
        .send argstr
        html.body.innerHTML = .responseText
    End With

    For Each post In html.getElementsByClassName("ipsStreamItem_title")
        With post.getElementsByTagName("a")
            If .Length Then Row = Row + 1: Cells(Row, 1) = .Item(0).innerText
        End With
    Next post
End Sub


问:
Is there a way to use errno safely in a multi-threaded application?
If you are writing a multi-threaded application that uses system/library calls that make use of errno to indicate the error type, is there a safe way to use errno? If not, is there some other way to indicate the type of error that occurred rather than just that an error has occurred?</p>

答:
If your standard library is multithread aware, then it probably has a #define that changes errno into a function call that returns a thread-local error return value. However, to use this you generally must include <errno.h>, rather than relying on an extern declaration.

I found an article Thread-safety and POSIX.1 which addresses this very question.

OwnerDisplayName: Erik Öjebo

OwnerDisplayName: Greg Hewgill


问:
phantomjs: command not found
I followed these instructions (except for copying the executable to my PATH because I cannot seem to find it and it does not seem necessary). Then I made a file called image_render.js in my public javascripts directory with

console.log('Hello, world!');
phantom.exit();
```

<p>inside it, saved it, and ran <code>phantomjs render_image.js</code> in my terminal.
However, my terminal does not recognize the command:</p>

```-bash: phantomjs: command not found
```

What have I done wrong?

答:
Mac PATH suggested setup:

Open Terminal.

Type vi ~/.bash_profile and hit enter (this opens or creates your bash_profile where you can customize Terminal commands).

Press i to enter insert/edit mode then type alias phantomjs='~/PATH/TO/phantomjs' and be sure to replace ~/PATH/TO/phantomjs with something like ~/Documents/PhantomJS/bin/phantomsj or wherever the file exists on your machine.

Press esc to exit insert/edit mode then type :x and hit enter to save the file.

Quit and re-open Terminal.

Type phantomjs and hit enter. If you see the prompt phantomjs> then you're all set.

Type phantom.exit() to end the PhantomJS program.

Now you can navigate to any folder and run PhantomJS by simply typing phantomjs. This is helpful when saving screenshots because the images will be saved inside the folder that's active in your Terminal.

ContentLicense: CC BY-SA 4.0

Title: phantomjs: command not found

Body:
I followed these instructions (except for copying the executable to my PATH because I cannot seem to find it and it does not seem necessary). Then I made a file called image_render.js in my public javascripts directory with

console.log('Hello, world!');
phantom.exit();

inside it, saved it, and ran phantomjs render_image.js in my terminal.
However, my terminal does not recognize the command:

-bash: phantomjs: command not found

What have I done wrong?


问:
Conversion error on derivated Factory using Class<T>
The folowing miminal example resuts in an error "Collection cannot be converted to LinkedList" on Android Studio:

```<code>class Factory<F extends Factory<F>> {

   public <T extends Collection<?>> T empty(Class<T> clazz) {
       try {
           return clazz.newInstance();
       } catch (Exception e) {
           throw new Error(e);
       }
   }

}

class MyFactory extends Factory {

   // ERROR is displayed here
   LinkedList<?> list = empty(LinkedList.class);

}
</code>```

I tried to remove that error but could not figure out what is the problem. The construct T create(Class<T> clazz) should be valid and worked for me many times. So conversion should not be the problem and the error was not helpful at all.

答:
Took me a fiew hours to create a minimal exmaple (my original project is more complex and involves Android specific code). When I copied the minimal example to eclipse, I recognized I forgot to add the template parameter on MyFactory to extend Factory<MyFactory>. Eclipse gave me a warning to extend a raw-type. That raw-type does not provide generic argument on member-function empty() and returns Collection instead of T extends Collection.

Android Studio actually can create a Warning on raw-types, but it is disabled by default. See this thread for how to enable it.

I hope this helps someone who encounters the same problem.

Body:
The folowing miminal example resuts in an error "Collection cannot be converted to LinkedList" on Android Studio:

class Factory<F extends Factory<F>> {

   public <T extends Collection<?>> T empty(Class<T> clazz) {
       try {
           return clazz.newInstance();
       } catch (Exception e) {
           throw new Error(e);
       }
   }

}

class MyFactory extends Factory {

   // ERROR is displayed here
   LinkedList<?> list = empty(LinkedList.class);

}

I tried to remove that error but could not figure out what is the problem. The construct T create(Class<T> clazz) should be valid and worked for me many times. So conversion should not be the problem and the error was not helpful at all.


问:
How to make dynamic uitabbar controllers?(swift)
I make an app that has 3 tabs. I want to make my tab bar controller dynamically change the view controller of the first tab bar according to the logged in user type. The rest two tab bars are static. For example, if the user type is 1, I want to show ViewController1 for the first tab, and if the user type is 2, I want to show ViewController2 instead. Is this impossible to achieve when the tab bar is designed in the storyboard? I use storyboard in the app.

答:
You can change these by using  the function on a tabview controller setviewcontrollers (see documentation here: https://developer.apple.com/documentation/uikit/uitabbarcontroller/1621177-setviewcontrollers).

For instance I have a storyboard with 4 Viewcontrollers in a tabviewcontroller, and then in the first viewController that loads, I added the following in viewDidLoad()"

```<code>let storyboard = UIStoryboard(name: "myStoryboard", bundle: nil)
let newTab = storyboard.instantiateViewController(withIdentifier: "testControllerID") as! TestViewController
let myControllers = [newTab, tabButton2, tabButton3, self, tabButton4]
tabBarController?.setViewControllers(myControllers, animated: true)
</code>```

So I was able to rearrange my previously defined tabs as well as add "newTab", which is a VC designed on the storyboard, given an identifier, but not actually added to the tabViewController.

Hope that helps

Body:
You can change these by using  the function on a tabview controller setviewcontrollers (see documentation here: https://developer.apple.com/documentation/uikit/uitabbarcontroller/1621177-setviewcontrollers).

For instance I have a storyboard with 4 Viewcontrollers in a tabviewcontroller, and then in the first viewController that loads, I added the following in viewDidLoad()"

let storyboard = UIStoryboard(name: "myStoryboard", bundle: nil)
let newTab = storyboard.instantiateViewController(withIdentifier: "testControllerID") as! TestViewController
let myControllers = [newTab, tabButton2, tabButton3, self, tabButton4]
tabBarController?.setViewControllers(myControllers, animated: true)

So I was able to rearrange my previously defined tabs as well as add "newTab", which is a VC designed on the storyboard, given an identifier, but not actually added to the tabViewController.

Hope that helps


问:
Error in navigation after creating new Realm object
I'm using the react-native-navigation package as well as Realm in my project. My app has a realm object called Notebook that contains a list of Verse objects, which are another realm object.

The structure of the app is very simple, the first page shows a list of Notebooks and when one is selected, the app transitions to the second screen which is a list of Verses.

Here is my code to navigate from the notebook list to the verse list:

```<code>this.props.navigator.push({
  screen: 'com.beyersapps.biblebinderrn.verselist',
  title: notebook.name,
  passProps: {notebook: notebook},
  animated: true,
  animationType: 'fade',
  backButtonTitle: undefined,
  backButtonHidden: false
})
</code>```

This navigation works fine and I can move back and forth between the two screens. My problem comes when I create a new Verse and add it to the Notebook. Here is my code that lives in the second screen to create a new Verse:

```<code>realm.write(() => {
  let newVerse = realm.create('Verse', {
    reference: 'Genesis 1:1',
    favorite: false,
    memorized: false,
    scripture: 'My favorite verse'
  });

  if (this.notebook != null) {
    this.notebook.verses.push(newVerse);
  }
});
</code>```

This is where my problem starts. At this point, if I select the back button to go back to the list of Notebooks, then select a notebook again, I get this error:

Attempting to change value of a readonly property.

Exception in native call
                                                                    java.lang.RuntimeException: Error calling RCTEventEmitter.receiveTouches

at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)

  at android.os.Handler.handleCallback(Handler.java:751)

  at android.os.Handler.dispatchMessage(Handler.java:95)

  at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:31)

  at android.os.Looper.loop(Looper.java:154)

  at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:199)

  at java.lang.Thread.run(Thread.java:761)

  Caused by: com.facebook.jni.CppException: Exception calling object as function: TypeError: Attempting to change value of a readonly property.

  at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)

  at android.os.Handler.handleCallback(Handler.java:751)

  at android.os.Handler.dispatchMessage(Handler.java:95)

  at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:31)

  at android.os.Looper.loop(Looper.java:154)

  at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:199)

  at java.lang.Thread.run(Thread.java:761)

There are a couple of things I can do to make this problem go away, but both make my app useless. Since they might help in determining the issue though I can either remove {notebook: notebook} from passProps when I navigate to the new screen (but then nothing shows on the Verse list screen since it does not know which Notebook was selected). Or, I can not add the newly created Verse to the selected Notebook (but then I can't add data).

Since these two changes are in two different components (Realm and react-native-navigation), I'm not sure which component is the source of the problem.

答:
Objects passed as props (passProps) are frozen by React Native.
Try changing:

```<code>passProps: {notebook: notebook}
</code>```

to:

```<code>passProps: {notebook: _.cloneDeep(notebook)}
</code>```

If you need to reflect changes to the notebook in the previous screen, I think you should do so through the store.

Another option is to pass notebookId and get the correct notebook by id from state.

Body:
I'm using the react-native-navigation package as well as Realm in my project. My app has a realm object called Notebook that contains a list of Verse objects, which are another realm object.

The structure of the app is very simple, the first page shows a list of Notebooks and when one is selected, the app transitions to the second screen which is a list of Verses.

Here is my code to navigate from the notebook list to the verse list:

this.props.navigator.push({
  screen: 'com.beyersapps.biblebinderrn.verselist',
  title: notebook.name,
  passProps: {notebook: notebook},
  animated: true,
  animationType: 'fade',
  backButtonTitle: undefined,
  backButtonHidden: false
})

This navigation works fine and I can move back and forth between the two screens. My problem comes when I create a new Verse and add it to the Notebook. Here is my code that lives in the second screen to create a new Verse:

realm.write(() => {
  let newVerse = realm.create('Verse', {
    reference: 'Genesis 1:1',
    favorite: false,
    memorized: false,
    scripture: 'My favorite verse'
  });

  if (this.notebook != null) {
    this.notebook.verses.push(newVerse);
  }
});

This is where my problem starts. At this point, if I select the back button to go back to the list of Notebooks, then select a notebook again, I get this error:

Attempting to change value of a readonly property.

Exception in native call
                                                                    java.lang.RuntimeException: Error calling RCTEventEmitter.receiveTouches

at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)

  at android.os.Handler.handleCallback(Handler.java:751)

  at android.os.Handler.dispatchMessage(Handler.java:95)

  at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:31)

  at android.os.Looper.loop(Looper.java:154)

  at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:199)

  at java.lang.Thread.run(Thread.java:761)

  Caused by: com.facebook.jni.CppException: Exception calling object as function: TypeError: Attempting to change value of a readonly property.

  at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)

  at android.os.Handler.handleCallback(Handler.java:751)

  at android.os.Handler.dispatchMessage(Handler.java:95)

  at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:31)

  at android.os.Looper.loop(Looper.java:154)

  at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:199)

  at java.lang.Thread.run(Thread.java:761)

There are a couple of things I can do to make this problem go away, but both make my app useless. Since they might help in determining the issue though I can either remove {notebook: notebook} from passProps when I navigate to the new screen (but then nothing shows on the Verse list screen since it does not know which Notebook was selected). Or, I can not add the newly created Verse to the selected Notebook (but then I can't add data).

Since these two changes are in two different components (Realm and react-native-navigation), I'm not sure which component is the source of the problem.

Body:
Objects passed as props (passProps) are frozen by React Native.
Try changing:

passProps: {notebook: notebook}

to:

passProps: {notebook: _.cloneDeep(notebook)}

If you need to reflect changes to the notebook in the previous screen, I think you should do so through the store.

Another option is to pass notebookId and get the correct notebook by id from state.


问:
Trying to merge data values from two columns into one column for analysis
```<code>Sex         cat dog horse
Male    YES NO  NO
Female  YES YES NO
Male    YES YES NO
Female  NO  NO  NO
Male    NO  NO  NO
Male    NO  YES YES
Female  YES YES YES
Female  YES NO  YES
Male    NO  NO  NO
Male    YES NO  YES
Male    NA  NO  NO
Female  NA  NO  YES
Female  NO  YES NO
Female  NA  NA  YES
Female  YES NA  NO
Male    YES NA  YES
Male    NO  NA  NO
Male    NO  NA  YES
Male    NA  NA  NA

data$animals <- paste(c(data$cat, data$dog, data$horse), collapse = "")
</code>```

CrossTable(data$animals,data$sex, prop.chisq = FALSE, prop.t=FALSE, chisq = T)

I currently have my data set up like so and what I'm trying to do is to merge all the YES, NO, and NA from the "Owns a ____" to make a new column that would tell me "Owns an animal" and have the same inputs of (YES, NO, or NA).
I've tried "paste" but it doesn't seem to provide what I want

Thank you for any help you can provide!

My end goal would be something like this

```<code>sex owns animals
Male    YES
Female  YES
Male    YES
Female  NA
Male    NA
Male    NO
Female  NO
Female  YES
Male    YES
Male    YES
Male    NA
Female  NO
Female  NO
Female  NA
Female  YES
Male    NO
Male    YES
Male    NA
Male    NA
</code>```

答:
```<code>df <- read.table(text="Male    YES NO  NO
Female  YES YES NO
                 Male    YES YES NO
                 Female  NO  NO  NO
                 Male    NO  NO  NO
                 Male    NO  YES YES
                 Female  YES YES YES
                 Female  YES NO  YES
                 Male    NO  NO  NO
                 Male    YES NO  YES
                 Male    NA  NO  NO
                 Female  NA  NO  YES
                 Female  NO  YES NO
                 Female  NA  NA  YES
                 Female  YES NA  NO
                 Male    YES NA  YES
                 Male    NO  NA  NO
                 Male    NO  NA  YES
                 Male    NA  NA  NA", header=F)

df$animal <- apply(df[, 2:4], 1, function(x) any(x=="YES"))
df$animal <- ifelse(df$animal, "YES","NO")
df

#        V1   V2   V3   V4 animal
# 1    Male  YES   NO   NO    YES
# 2  Female  YES  YES   NO    YES
# 3    Male  YES  YES   NO    YES
# 4  Female   NO   NO   NO     NO
# 5    Male   NO   NO   NO     NO
# 6    Male   NO  YES  YES    YES
# 7  Female  YES  YES  YES    YES
# 8  Female  YES   NO  YES    YES
# 9    Male   NO   NO   NO     NO
# 10   Male  YES   NO  YES    YES
# 11   Male <NA>   NO   NO   <NA>
# 12 Female <NA>   NO  YES    YES
# 13 Female   NO  YES   NO    YES
# 14 Female <NA> <NA>  YES    YES
# 15 Female  YES <NA>   NO    YES
# 16   Male  YES <NA>  YES    YES
# 17   Male   NO <NA>   NO   <NA>
# 18   Male   NO <NA>  YES    YES
# 19   Male <NA> <NA> <NA>   <NA>
</code>```

Body:
Sex         cat dog horse
Male    YES NO  NO
Female  YES YES NO
Male    YES YES NO
Female  NO  NO  NO
Male    NO  NO  NO
Male    NO  YES YES
Female  YES YES YES
Female  YES NO  YES
Male    NO  NO  NO
Male    YES NO  YES
Male    NA  NO  NO
Female  NA  NO  YES
Female  NO  YES NO
Female  NA  NA  YES
Female  YES NA  NO
Male    YES NA  YES
Male    NO  NA  NO
Male    NO  NA  YES
Male    NA  NA  NA

data$animals <- paste(c(data$cat, data$dog, data$horse), collapse = "")

CrossTable(data$animals,data$sex, prop.chisq = FALSE, prop.t=FALSE, chisq = T)

I currently have my data set up like so and what I'm trying to do is to merge all the YES, NO, and NA from the "Owns a ____" to make a new column that would tell me "Owns an animal" and have the same inputs of (YES, NO, or NA).
I've tried "paste" but it doesn't seem to provide what I want

Thank you for any help you can provide!

My end goal would be something like this

sex owns animals
Male    YES
Female  YES
Male    YES
Female  NA
Male    NA
Male    NO
Female  NO
Female  YES
Male    YES
Male    YES
Male    NA
Female  NO
Female  NO
Female  NA
Female  YES
Male    NO
Male    YES
Male    NA
Male    NA