问:
JS script - Value Dependent (multiple dropdown)
Right now I have two dropdowns and the goal is to have the User select "OFF" on the first option, the second dropdown automatically selects "ON" and vice versa.

The code currently below with the JavaScript works, but works for only one pair of the dropdown. I was wondering what I need to change to make it work for both pairs or even four pairs in the future.

Code:

<!DOCTYPE html>

Currently:
     <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
      <option value="">Select Option</option>
      <option value="'S microphone is currently on. Please remind them to turn it ">OFF</option>
      <option value="'S microphone is currently off. Please remind them to turn it ">ON</option>
     </select>

Microphone:
     <select id="microphone" class="microphone select2" name = "microphone">
      <option value=" "  selected="selected">Select Option</option>
      <option value="ON. Thank you.">ON</option>
      <option value="OFF. Thank you.">OFF</option>
     </select>

Currently:
     <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
      <option value="">Select Option</option>
      <option value="'S microphone is currently on. Please remind them to turn it ">OFF</option>
      <option value="'S microphone is currently off. Please remind them to turn it ">ON</option>
     </select>

Microphone:
     <select id="microphone" class="microphone select2" name = "microphone">
      <option value=" "  selected="selected">Select Option</option>
      <option value="ON. Thank you.">ON</option>
      <option value="OFF. Thank you.">OFF</option>
     </select>

   </form>

```

答:
I would suggest using document.getElementById() instead of querySelectorAll().  The problem is that you're always accessing the first one, element 0.  You also need to ensure you have unique values for each 'id' property; in the code above you have duplicate values for microphone and cmicrophone.

You will need to add a loop for dynamic number of selects by fetching all of them and iterating over them to map each of the event handlers:

```<code>const cmicrophones = document.querySelectorAll('.select1');
const microphones = document.querySelectorAll('.select2');
for (var i = 0; i < cmicrophones.length; i++) {
  const cmicrophone = cmicrophones[i];
  const microphone = microphones[i];

  ....
}
</code>```

Body:
I would suggest using document.getElementById() instead of querySelectorAll().  The problem is that you're always accessing the first one, element 0.  You also need to ensure you have unique values for each 'id' property; in the code above you have duplicate values for microphone and cmicrophone.

You will need to add a loop for dynamic number of selects by fetching all of them and iterating over them to map each of the event handlers:

const cmicrophones = document.querySelectorAll('.select1');
const microphones = document.querySelectorAll('.select2');
for (var i = 0; i < cmicrophones.length; i++) {
  const cmicrophone = cmicrophones[i];
  const microphone = microphones[i];

  ....
}


来源: stackexchange

问:
I am looking for a way to call multiple shell scripts in a serialized manner from a base shell script
I am looking for a way to call multiple shell scripts in a serialized manner from a base shell script. Scenario:

A shell script- Base_script.sh , which will internally call:

script_1.sh ,

script_2.sh ,
script_3.sh ,

Once "script_1.sh" will finish, THEN ONLY it should call "script_2.sh" and so on.

What all methods i have tried, are somehow executing all the scripts at once.
OS: RHEL using Shell/Bash

Edit: In response to some comments, I agree, i can use (which i already did):

script1.sh && script2.sh

calling each script one by one (sh script1.sh; sh script2.sh ..so on)

even tried using an array to declare the scripts and then execute each in a loop

Problem & the Solution i got:

Each script eg-"script_1.sh" was a complex one. Its all doing some kind of database benchmarking.
The scripts were having some function that was going in background (someFunction &) while execution. So even though the scripts were actually getting called one by one, yet the processing of the previous scripts kept on going in the background.

Had to redesign the entire thing to get every module & functions in the "Base_script.sh" itself.

Thanks everyone for the answers though. Appreciate it !!

答:
As stated you can use && or if you wanted to make it more complete you can use

```<code>wait $!
</code>```

which will wait for the pid of the last run command to exit. This way you can add some if statements in for validity.

ContentLicense: CC BY-SA 3.0

Body:
As stated you can use && or if you wanted to make it more complete you can use

wait $!

which will wait for the pid of the last run command to exit. This way you can add some if statements in for validity.


问:
Nginx doesn't recognize my Rails 3 application
I have set up nginx + REE + passenger on my Linode VPS, which has been running great for past six month, both for Rails 2.3.x and Sinatra applications.

However this week I tried to add Rails 3 application to the stack, and I keep on getting 404 Not Found. Logs show that nginx doesn't recognize Rails application and is trying to serve it as static.

```<code>2010/11/29 23:44:44 [error] 12464#0: *29 "/var/app/modelky/public/index.html"
is not found (2: No such file or directory), client: 90.177.23.122, server:
reedink.com, request: "GET / HTTP/1.1", host: "reedink.com"

2010/11/29 23:44:44 [error] 12464#0: *30 open() "/var/app/modelky/public/favicon.ico"
failed (2: No such file or directory), client: 90.177.23.122,
server: reedink.com, request: "GET /favicon.ico HTTP/1.1", host: "reedink.com"
</code>```

However, I'm using the same configuration as I use for all my other Rails 2.3.5 and Sinatra applications that works without any problems

```<code>server {
    listen 80;
    server_name www.reedink.com;
    rewrite ^(.*) http://reedink.com$1 permanent;
}

server {
    listen 80;
    server_name reedink.com;
    root /var/app/modelky/public;
    passenger_enabled on;
}
</code>```

From what I understand, Rails 3 should be rack compatible, so from the server's point of view, it's no different than any Sinatra application right?

答:
I just built out a rail 3 box on linode this weekend.  I started w/ this stackscript

http://www.linode.com/stackscripts/view/?StackScriptID=1288

and then went from there.

here's a copy of my server conf from the nginx.conf

```<code>server {
  listen 80;
  server_name localhost;
  root /home/deploy/foo.bar.com/current/public;
  passenger_enabled on;
}
</code>```

i'd also try adding a static index.html file, get nginx working properly and then try and bootstrap the rails app.

ContentLicense: CC BY-SA 2.5

Body:
I have set up nginx + REE + passenger on my Linode VPS, which has been running great for past six month, both for Rails 2.3.x and Sinatra applications.

However this week I tried to add Rails 3 application to the stack, and I keep on getting 404 Not Found. Logs show that nginx doesn't recognize Rails application and is trying to serve it as static.

2010/11/29 23:44:44 [error] 12464#0: *29 "/var/app/modelky/public/index.html"
is not found (2: No such file or directory), client: 90.177.23.122, server:
reedink.com, request: "GET / HTTP/1.1", host: "reedink.com"

2010/11/29 23:44:44 [error] 12464#0: *30 open() "/var/app/modelky/public/favicon.ico"
failed (2: No such file or directory), client: 90.177.23.122,
server: reedink.com, request: "GET /favicon.ico HTTP/1.1", host: "reedink.com"

However, I'm using the same configuration as I use for all my other Rails 2.3.5 and Sinatra applications that works without any problems

server {
    listen 80;
    server_name www.reedink.com;
    rewrite ^(.*) http://reedink.com$1 permanent;
}

server {
    listen 80;
    server_name reedink.com;
    root /var/app/modelky/public;
    passenger_enabled on;
}

From what I understand, Rails 3 should be rack compatible, so from the server's point of view, it's no different than any Sinatra application right?

Body:
I just built out a rail 3 box on linode this weekend.  I started w/ this stackscript

http://www.linode.com/stackscripts/view/?StackScriptID=1288

and then went from there.

here's a copy of my server conf from the nginx.conf

server {
  listen 80;
  server_name localhost;
  root /home/deploy/foo.bar.com/current/public;
  passenger_enabled on;
}

i'd also try adding a static index.html file, get nginx working properly and then try and bootstrap the rails app.


问:
Converting 17 to "2017", SQL
BACKGROUND

I currently have two tables:

ActualSale.Year = "2017"

Note the text format

BudgetSale.Year = 17

Note the number format

I am looking to combine data from the ActualSale table and the BudgetSales table and join them on the year field.

APPROACH/PSEUDO CODE

```<code>SELECT
ActualSale.Year,
BudgetSales.Year

FROM
BudgetSale,
ActualSale

WHERE
ActualSales.year="2017"
</code>```

NOTE: Budget Sales tables are only inputted year-by-year, therefore the BudgetSale table only has data where year=17 (therefore, I do not necessarily have to filter for BudgetSales.Year=17.

QUESTIONS

Within SQL, how can I consistently convert "2017" (text) to 17 (number). I was thinking of removing the first two numbers in ActualSales.year to just leave "17" and then convert to a value using val(), but was wondering if there was a better way.

答:
I was wondering whether to answer - as Jon Skeet has given a comment I suspect that SQL has rewritten itself to conform.

https://meta.stackexchange.com/questions/9134/jon-skeet-facts/9182#9182

The first problem is that Year is a reserved word (has a specific meaning to Access).

One way to solve the problem is to add 2000 to the BudgetSale year.

This will be a problem if you're dealing with dates pre-2000.

```<code>FROM ActualSale ASa INNER JOIN BudgetSale BSa ON CLNG(ASa.sYear)=BSa.lYear+2000
</code>```

Another way as you suggest is to remove the first two numbers from the string:

```<code>FROM ActualSale ASa INNER JOIN BudgetSale BSa ON VAL(right(ASa.sYear,2))=BSa.lYear
</code>```

Another way is to convert the Years into dates:

```<code>FROM ActualSale ASa INNER JOIN BudgetSale BSa ON Year(DateSerial(ASa.syear,1,1))=Year(DateSerial(BSa.lyear,1,1))
</code>```

I think the best way is to convert the values to dates before they're added to the database.

Title: Converting 17 to "2017", SQL

Body:
BACKGROUND

I currently have two tables:

ActualSale.Year = "2017"

Note the text format

BudgetSale.Year = 17

Note the number format

I am looking to combine data from the ActualSale table and the BudgetSales table and join them on the year field.

APPROACH/PSEUDO CODE

SELECT
ActualSale.Year,
BudgetSales.Year

FROM
BudgetSale,
ActualSale

WHERE
ActualSales.year="2017"

NOTE: Budget Sales tables are only inputted year-by-year, therefore the BudgetSale table only has data where year=17 (therefore, I do not necessarily have to filter for BudgetSales.Year=17.

QUESTIONS

Within SQL, how can I consistently convert "2017" (text) to 17 (number). I was thinking of removing the first two numbers in ActualSales.year to just leave "17" and then convert to a value using val(), but was wondering if there was a better way.

Body:
I was wondering whether to answer - as Jon Skeet has given a comment I suspect that SQL has rewritten itself to conform.

https://meta.stackexchange.com/questions/9134/jon-skeet-facts/9182#9182

The first problem is that Year is a reserved word (has a specific meaning to Access).

One way to solve the problem is to add 2000 to the BudgetSale year.

This will be a problem if you're dealing with dates pre-2000.

FROM ActualSale ASa INNER JOIN BudgetSale BSa ON CLNG(ASa.sYear)=BSa.lYear+2000

Another way as you suggest is to remove the first two numbers from the string:

FROM ActualSale ASa INNER JOIN BudgetSale BSa ON VAL(right(ASa.sYear,2))=BSa.lYear

Another way is to convert the Years into dates:

FROM ActualSale ASa INNER JOIN BudgetSale BSa ON Year(DateSerial(ASa.syear,1,1))=Year(DateSerial(BSa.lyear,1,1))

I think the best way is to convert the values to dates before they're added to the database.


问:
Conditional dateadd in procedure
I have a procedure that receives 3 parameters:

```<code>@startdate  = '2017-01-01'
@interval   = 'DD'
@duration   = 5
</code>```

What I need to do is output a new date, based on the above. A dateadd does not work, courtesy of that @interval not being correct.

```<code>select dateadd(@interval, @duration, @startdate)
</code>```

Invalid parameter 1 specified for dateadd.

Can anyone steer me right?

答:
You are going to need a CASE as the arguments cannot be provided dynamically:

```<code>select case @interval
  when 'dd' then DATEADD(dd, @duration, @startdate)
  when 'mm' then DATEADD(mm, @duration, @startdate)
  ...
end
</code>```

Title: Conditional dateadd in procedure

Body:
I have a procedure that receives 3 parameters:

@startdate  = '2017-01-01'
@interval   = 'DD'
@duration   = 5

What I need to do is output a new date, based on the above. A dateadd does not work, courtesy of that @interval not being correct.

select dateadd(@interval, @duration, @startdate)

Invalid parameter 1 specified for dateadd.

Can anyone steer me right?

Body:
You are going to need a CASE as the arguments cannot be provided dynamically:

select case @interval
  when 'dd' then DATEADD(dd, @duration, @startdate)
  when 'mm' then DATEADD(mm, @duration, @startdate)
  ...
end


问:
Site search and return results in separate web page
Hello and thanks for your help in advance.

I want to make an internal search capability on my web site.

A user enters a keyword in the search field and after they press enter, the result are shown on a separate web page. So if someone enters the word cat, all the web pages on my web site will be populated in a list with hyperlinks to the pages. I want this to only search my site, no google search engines.

I want to make this in the simplest way possible to php no python, just javascript.

I attempted to make it happen but this code just takes me to a page that has the word i searched for on it.

```<code><div id="widget-user">

    <form id="siteSearch" method="get" action="http://www.example.com/first">
        <input type="text" id="searchInput" name="q" maxlength="20">
        <input type="submit" value="Search">
    </form>

    <script>

        var a = document.getElementById("siteSearch");
        a.addEventListener("submit", function(event) {

            event.preventDefault();
            var b = document.getElementById("searchInput").value;
            window.location.href = "http://www.example.com/first" + b;

        });

    </script>
</code>```

答: try change this and let us know window.location="etzy.html"</p>

Body:
Hello and thanks for your help in advance.

I want to make an internal search capability on my web site.

A user enters a keyword in the search field and after they press enter, the result are shown on a separate web page. So if someone enters the word cat, all the web pages on my web site will be populated in a list with hyperlinks to the pages. I want this to only search my site, no google search engines.

I want to make this in the simplest way possible to php no python, just javascript.

I attempted to make it happen but this code just takes me to a page that has the word i searched for on it.

    <form id="siteSearch" method="get" action="http://www.example.com/first">
        <input type="text" id="searchInput" name="q" maxlength="20">
        <input type="submit" value="Search">
    </form>


答:
In mySQL you will need to setup a join between the two tables, IOW, how are they related.

```<code>SELECT
    ActualSale.Year,
    BudgetSales.Year
FROM BudgetSale
JOIN ActualSale
    ON ActualSales.year = CONCAT("20",BudgetSales.Year)
WHERE ActualSales.year="2017"
</code>```

You will need to specify a bit more in the ON clause, since all of the year values are the same, every record in the ActualSale. will match with every record in the BudgetSale table.

Title: Converting 17 to "2017", SQL

Body:
In mySQL you will need to setup a join between the two tables, IOW, how are they related.

SELECT
    ActualSale.Year,
    BudgetSales.Year
FROM BudgetSale
JOIN ActualSale
    ON ActualSales.year = CONCAT("20",BudgetSales.Year)
WHERE ActualSales.year="2017"

You will need to specify a bit more in the ON clause, since all of the year values are the same, every record in the ActualSale. will match with every record in the BudgetSale table.


问:
How to get sampleRate for microphone?
I need get sampleRate for microphone in JS.
I tried those ways:

```<code>//Example 1
var context = new window.AudioContext();
var sampleRate = context.sampleRate;

//Example 2
var audioTimer = 0;
var sampleRate = 0;
recorder.onaudioprocess = function() {
    var time = new Date().getTime();
    if (audioTimer) {
        sampleRate = (1000 * 2048) / (time - audioTimer);  //2048 - buffer size
    }
    audioTimer = time;
}
</code>```

But I got sampleRate value for speakers only, not for microphone

答:
You want to use the MediaDevices API to enumerate devices and examine the audio input.  (https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices)

However, I'd point out this won't help in Web Audio - Web Audio will always resample the input to the output device sample rate (and clock) when you use attach a stream to the audio graph.  In the future, you should be able to create a context at a different sample rate, and then it will (mostly) work; there's no provision for locking to the actual input clock, though.

Title: How to get sampleRate for microphone?

Body:
I need get sampleRate for microphone in JS.
I tried those ways:

//Example 1
var context = new window.AudioContext();
var sampleRate = context.sampleRate;

//Example 2
var audioTimer = 0;
var sampleRate = 0;
recorder.onaudioprocess = function() {
    var time = new Date().getTime();
    if (audioTimer) {
        sampleRate = (1000 * 2048) / (time - audioTimer);  //2048 - buffer size
    }
    audioTimer = time;
}

But I got sampleRate value for speakers only, not for microphone


问:
Simplemodal for JQuery: close currently visible modal and show another
I realize this question has been asked several times in several different forms, but I cannot get it to work properly for the life of me.

I have two DIVs on my page used for modals, ids signup-popup and login-popup. They each have their own close buttons with class simplemodal-close and showing/closing each one on its own works fine.

I want to add a button to the signup modal that closes it and opens the login modal. I followed the instructions Eric gave in the first link above, which I've included below:

```<code>$('a#ask').click(function(){
    $('#modal-contact').modal({onShow: function (dialog) {
        // handle the close yourself.
        // Don't use the closeClass on this element
        // call $.modal.close(); when you are done
        // call a function to open a new modal
    });
    return false;
});
</code>```

However, this doesn't work; the signup modal closes but the login modal doesn't. Here is my code (using noConflict, hence the use of jQuery() rather than $()):

```<code>jQuery(function (jQuery) {
    jQuery('#btn-signup-open').click(function () {
        jQuery('#signup-popup').modal({onShow: function (dialog) {
            jQuery('#login-from-signup').click(function () {
                jQuery.modal.close();
                jQuery('#login-popup').modal();
            })
        }});
        return false;
    });
});
</code>```

And I also tried the following instead, figuring it was simpler and more straightforward, however the result was the same (signup modal closes, login modal doesn't close, regular close button & form submit works fine):

```<code>jQuery(function (jQuery) {
    jQuery('#login-from-signup').click(function () {
        jQuery.modal.close();
        jQuery('#login-popup').modal();
        return false;
    });
});
</code>```

I did try Eric's other suggestion which was to just replace the content of the modal. This works, but seems hack-y because I have to manually bind the close button (not a big deal) and the modal doesn't auto-resize for the smaller login form. While this works, it seems like there should be a better way to do it (specifically the code I have right above, or some minor tweak to it).

```<code>jQuery(function (jQuery) {
    jQuery('#login-from-signup').click(function () {
        jQuery('.simplemodal-wrap').html('<div class="popup simplemodal-data" id="login-popup" style="display: block;">'+jQuery("#login-popup").html()+'</div>');
        jQuery('.simplemodal-close').click(function() {jQuery.modal.close(); return false;});
          return false;
    });
});
</code>```

答:
Thanks to Andrey for answering this in another post!

The current onClose event acts like onBeforeClose and no onAfterClose for $.modal.close() is designed. The only workaround is to wait:

```<code>$.modal.close(); window.setTimeout(showSecondModal, 500);
</code>```

Here's my working code:

```<code>jQuery(function (jQuery) {
  jQuery('#login-from-signup').click(function () {
    jQuery.modal.close();
    window.setTimeout(function() {jQuery('#login-popup').modal()}, 250);
    return false;
  });
});
</code>```

Body:
I realize this question has been asked several times in several different forms, but I cannot get it to work properly for the life of me.

I have two DIVs on my page used for modals, ids signup-popup and login-popup. They each have their own close buttons with class simplemodal-close and showing/closing each one on its own works fine.

I want to add a button to the signup modal that closes it and opens the login modal. I followed the instructions Eric gave in the first link above, which I've included below:

$('a#ask').click(function(){
    $('#modal-contact').modal({onShow: function (dialog) {
        // handle the close yourself.
        // Don't use the closeClass on this element
        // call $.modal.close(); when you are done
        // call a function to open a new modal
    });
    return false;
});

However, this doesn't work; the signup modal closes but the login modal doesn't. Here is my code (using noConflict, hence the use of jQuery() rather than $()):

jQuery(function (jQuery) {
    jQuery('#btn-signup-open').click(function () {
        jQuery('#signup-popup').modal({onShow: function (dialog) {
            jQuery('#login-from-signup').click(function () {
                jQuery.modal.close();
                jQuery('#login-popup').modal();
            })
        }});
        return false;
    });
});

And I also tried the following instead, figuring it was simpler and more straightforward, however the result was the same (signup modal closes, login modal doesn't close, regular close button & form submit works fine):

jQuery(function (jQuery) {
    jQuery('#login-from-signup').click(function () {
        jQuery.modal.close();
        jQuery('#login-popup').modal();
        return false;
    });
});

I did try Eric's other suggestion which was to just replace the content of the modal. This works, but seems hack-y because I have to manually bind the close button (not a big deal) and the modal doesn't auto-resize for the smaller login form. While this works, it seems like there should be a better way to do it (specifically the code I have right above, or some minor tweak to it).

jQuery(function (jQuery) {
    jQuery('#login-from-signup').click(function () {
        jQuery('.simplemodal-wrap').html('
'+jQuery("#login-popup").html()+'
');
        jQuery('.simplemodal-close').click(function() {jQuery.modal.close(); return false;});
          return false;
    });
});

Body:
Thanks to Andrey for answering this in another post!

The current onClose event acts like onBeforeClose and no onAfterClose for $.modal.close() is designed. The only workaround is to wait:

$.modal.close(); window.setTimeout(showSecondModal, 500);

Here's my working code:

jQuery(function (jQuery) {
  jQuery('#login-from-signup').click(function () {
    jQuery.modal.close();
    window.setTimeout(function() {jQuery('#login-popup').modal()}, 250);
    return false;
  });
});


问:
What exactly is the Link-edit step
Question

What exactly does the link-edit step in my COBOL complier do?

After the code is compiled, there is a link edit step performed. I am not really sure what this step does.

Background Information

Right out of school (3 years ago) I got a job as a mainframe application developer. Having learned nothing about mainframes in school, my knowledge has many gaps. Around my shop, we kind of have a "black box" attitude of we don't need to know how a lot of this stuff works, it just does. I am trying to understand why we need this link-edit step if the program as already compiled successfully.

答:
The linkedit/binderer step makes an executable program out of the output from the compiler (or the Assembler).

If you look at the output data set on SYSLIN from your COBOL compile step (if it is a temporary dataset, you can override it to an FB, LRECL 80 sequential dataset to be able to look at it) you'll see "card images", which contain (amongst some other stuff) the machine-code generated by the compiler.

These card-images are not executable. The code is not even contiguous, and many things like necessary runtime modules are missing.

The Program Binder/Binder (PGM=HEWL) takes the object code (card-images) from the compiler/assembler and does everything necessary (according to the options it was installed with, and further options you provide, and other libraries which many contain object-code or loadmodules or Program Objects) to create an executable program.

There used to be a thing called the Linkage Editor which accomplished this task. Hence linkedit, linkedited. Unfortunately, in English, bind does not conjugate in the same way as edit. There's no good word, so I use Binderer, and Bindered, partly to rail against the establishment which decided to call it the Program Binder (not to be so confused with Binding for DB2, either).

So, today, by linkedit people mean "use of the Program Binder". It is a process to make the output from your compile/assemble into an executable program, which can be a loadmodule, or a Program Object (Enterprise COBOL V5+ can only be bindered into Program Objects, not loadmodules), or a DLL (not to be confused with .dll).

It is worth looking at the output of SYSLIN, the SYSPRINT output from the binder step, and consulting manuals/presentations of the Program Binder which will give you an idea of what goes in, what happens (look up any IEW messages, especially for non-zero-RC executions of the step) by sticking the message in a browser search box. From the documentary material you'll start to get an idea of the breadth of the subject also. The Binder is able to do many useful things.

Here's a link to a useful diagram, some more detailed explanation, and the name of the main reference document for the binder for application programmes: z/OS MVS Program Management: User's Guide and Reference

The program management binder

As an end-note, the reason they are "card images" is because... back in olden times, the object deck from compiler/assembler would be punched onto physical cards. Which would then be used as input cards to the linkage editor. I'm not sorry that I missed out on having to do that ever...

Title: What exactly is the Link-edit step


问:
Query, sort and replace DOM elements
I am trying to sort the order of a nodeList that I queried for and replace them onto the DOM but using the solution below I am getting undefined in the HTML. Does anybody know whats going on?

```<code>const container = elem[0].childNodes[1];
let graphs = container.querySelectorAll('visualization-container[data-graph]');

const sorted = [].slice.call(graphs).sort((a, b) => {
    const first = a.getAttribute('data-graph');
    const second = b.getAttribute('data-graph');

    return scope.visualizationsOrder[first] > scope.visualizationsOrder[second] ? 1 : -1;
});

console.log(sorted); // Sorted is correct
container.replaceWith(sorted); // error here
</code>```

Here is a jsfiddle that illustrates the issue https://jsfiddle.net/ejdq1xyz/

答:
The "problem" here is, that sorted is an array of Nodes.

I'm not quite sure why you want to replace the container with its sorted children...

If the container should not be removed than you have to use .appendChild(), .append() or .insertAdjacentElement() instead of .replaceWith().

And because sorted is an array you have to add the nodes one by one with a for loop or .forEach():

```<code>sorted.forEach(n => container.appendChild(n));
sorted.forEach(n => container.append(n));
sorted.forEach(n => container.insertAdjacentElement("beforeEnd", n));
</code>```

In case of .append() you could also use .apply() (ES5 version) or the ES6 spread operator/syntax ... as it will also accept a set of Nodes/DOMStrings:

```<code>container.append.apply(container, sorted);
container.append(...sorted);
</code>```

const order = {
  identifierOne: 4,
  identifierTwo: 3,
  identifierThree: 1,
  identifierFour: 2
};

const container = document.querySelector('.container');
const graphs = container.querySelectorAll('.graph[data-graph]');

const sorted = [].slice.call(graphs).sort((a, b) => {
    const first = a.getAttribute('data-graph');
    const second = b.getAttribute('data-graph');

    return order[first] > order[second] ? 1 : -1;
});

sorted.forEach(n => container.appendChild(n));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
<div class='graph' data-graph='identifierOne'>4</div>
<div class='graph' data-graph='identifierTwo'>3</div>
<div class='graph' data-graph='identifierThree'>1</div>
<div class='graph' data-graph='identifierFour'>2</div>
</div></code>```

If the container should be replaced than you can use .replaceWith() with .apply()  or the spread operator/syntax ...

```<code>container.replaceWith.apply(container, sorted);
container.replaceWith(...sorted);
</code>```

const order = {
  identifierOne: 4,
  identifierTwo: 3,
  identifierThree: 1,
  identifierFour: 2
};

const container = document.querySelector('.container');
const graphs = container.querySelectorAll('.graph[data-graph]');

const sorted = [].slice.call(graphs).sort((a, b) => {
    const first = a.getAttribute('data-graph');
    const second = b.getAttribute('data-graph');

    return order[first] > order[second] ? 1 : -1;
});

container.replaceWith.apply(container, sorted);
//container.replaceWith(...sorted);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
<div class='graph' data-graph='identifierOne'>4</div>
<div class='graph' data-graph='identifierTwo'>3</div>
<div class='graph' data-graph='identifierThree'>1</div>
<div class='graph' data-graph='identifierFour'>2</div>
</div></code>```

Title: Query, sort and replace DOM elements

Body:
I am trying to sort the order of a nodeList that I queried for and replace them onto the DOM but using the solution below I am getting undefined in the HTML. Does anybody know whats going on?

const container = elem[0].childNodes[1];
let graphs = container.querySelectorAll('visualization-container[data-graph]');

const sorted = [].slice.call(graphs).sort((a, b) => {
    const first = a.getAttribute('data-graph');
    const second = b.getAttribute('data-graph');

    return scope.visualizationsOrder[first] > scope.visualizationsOrder[second] ? 1 : -1;
});

console.log(sorted); // Sorted is correct
container.replaceWith(sorted); // error here

Here is a jsfiddle that illustrates the issue https://jsfiddle.net/ejdq1xyz/

Body:
The "problem" here is, that sorted is an array of Nodes.

I'm not quite sure why you want to replace the container with its sorted children...

If the container should not be removed than you have to use .appendChild(), .append() or .insertAdjacentElement() instead of .replaceWith().

And because sorted is an array you have to add the nodes one by one with a for loop or .forEach():

sorted.forEach(n => container.appendChild(n));
sorted.forEach(n => container.append(n));
sorted.forEach(n => container.insertAdjacentElement("beforeEnd", n));

In case of .append() you could also use .apply() (ES5 version) or the ES6 spread operator/syntax ... as it will also accept a set of Nodes/DOMStrings:

container.append.apply(container, sorted);
container.append(...sorted);

const order = {
  identifierOne: 4,
  identifierTwo: 3,
  identifierThree: 1,
  identifierFour: 2
};

const container = document.querySelector('.container');
const graphs = container.querySelectorAll('.graph[data-graph]');

const sorted = [].slice.call(graphs).sort((a, b) => {
    const first = a.getAttribute('data-graph');
    const second = b.getAttribute('data-graph');

    return order[first] > order[second] ? 1 : -1;
});

sorted.forEach(n => container.appendChild(n));

<div class='container'>
<div class='graph' data-graph='identifierOne'>4</div>
<div class='graph' data-graph='identifierTwo'>3</div>
<div class='graph' data-graph='identifierThree'>1</div>
<div class='graph' data-graph='identifierFour'>2</div>
</div>

If the container should be replaced than you can use .replaceWith() with .apply()  or the spread operator/syntax ...

container.replaceWith.apply(container, sorted);
container.replaceWith(...sorted);

const order = {
  identifierOne: 4,
  identifierTwo: 3,
  identifierThree: 1,
  identifierFour: 2
};

const container = document.querySelector('.container');
const graphs = container.querySelectorAll('.graph[data-graph]');

const sorted = [].slice.call(graphs).sort((a, b) => {
    const first = a.getAttribute('data-graph');
    const second = b.getAttribute('data-graph');

    return order[first] > order[second] ? 1 : -1;
});

container.replaceWith.apply(container, sorted);
//container.replaceWith(...sorted);

<div class='container'>
<div class='graph' data-graph='identifierOne'>4</div>
<div class='graph' data-graph='identifierTwo'>3</div>
<div class='graph' data-graph='identifierThree'>1</div>
<div class='graph' data-graph='identifierFour'>2</div>
</div>


问:
How to find a substring from a string using regular expression in php?
I have a string like "I love my country". If i search for 'country' my program will show "exist". But if I search 'count' my program will show "Not exist".</p>

答:
Is this what you're looking for?

I'm not a master of Regex so someone may have a more optimal solution but simply searching for country with word boundaries should get you what you're after.

/\b(country)\b/g

So in PHP something like the following:

```<code>$string = 'I love my country';
$matchExists = preg_match('/\b(country)\b/', $string);

echo ($matchExists) ? 'Match Found' : 'No Match Found'; // Output: Match Found
</code>```

And one that fails:

```<code>$string = 'I love mycountry';
$matchExists = preg_match('/\b(country)\b/', $string);

echo ($matchExists) ? 'Match Found' : 'No Match Found'; // Output: No Match Found
</code>```

And reminder you can see a bunch of different outputs here as well as test any others you may have.

Body:
Is this what you're looking for?

I'm not a master of Regex so someone may have a more optimal solution but simply searching for country with word boundaries should get you what you're after.

/\b(country)\b/g

So in PHP something like the following:

$string = 'I love my country';
$matchExists = preg_match('/\b(country)\b/', $string);

echo ($matchExists) ? 'Match Found' : 'No Match Found'; // Output: Match Found

And one that fails:

$string = 'I love mycountry';
$matchExists = preg_match('/\b(country)\b/', $string);

echo ($matchExists) ? 'Match Found' : 'No Match Found'; // Output: No Match Found

And reminder you can see a bunch of different outputs here as well as test any others you may have.


问:
React-Native view was rendered with explicitly set width/height but with a 0 flexBasis
In React-native 0.39,

I often get this error but I don't really understand why (appart the fact that I didn't set flexGrow...).

Here is the error from the console

```<code>View was rendered with explicitly set width/height but with a 0 flexBasis. (This might be fixed by changing flex: to flexGrow:) View: <RCTShadowView: 0x6080005a02a0; viewName: RCTView; reactTag: 2608; frame: {{0, 0}, {nan, nan}}>
</code>```

Can someone explain to me why this error is triggered ?

EDIT: The error comes from this bit of boilerplate code I added in on the main View :

```<code>flex: 1,
// remove width and height to override fixed static size
width: null,
height: null,
</code>```

But If someone could shed a light on react-native styling or lead me to good resources, I'll be grateful :)

答:
As the error states - change the 'flex' to 'flexGrow' and the issue is solved.

The difficult part about this is how to locate which 'flex' needs to be changed from the whole project. What I did was (using Atom Editor, so 'Find in Project' ...) changing each 'flex:' with 'flexGrow:' (with the ':' at the end you make sure that you change a style) and then simply search the whole project again for a 'flexGrow' and change every 'flexGrow' from each file with 'flex' until you locate the corrupted 'flex'.

I prefer using flex instead of flexGrow, that's why I revert to flex. This is why: Layout Props

Hope this solves the issues.

Body:
In React-native 0.39,

I often get this error but I don't really understand why (appart the fact that I didn't set flexGrow...).

Here is the error from the console

View was rendered with explicitly set width/height but with a 0 flexBasis. (This might be fixed by changing flex: to flexGrow:) View: <RCTShadowView: 0x6080005a02a0; viewName: RCTView; reactTag: 2608; frame: {{0, 0}, {nan, nan}}>

Can someone explain to me why this error is triggered ?

EDIT: The error comes from this bit of boilerplate code I added in on the main View :

flex: 1,
// remove width and height to override fixed static size
width: null,
height: null,

But If someone could shed a light on react-native styling or lead me to good resources, I'll be grateful :)


问:
Correct use of subprocess in python 2.7
I have 2 pdf files to convert into text everyday via terminal, pdftotext module, and from there sort the data with a python script. To save time typing in,for file in *.pdf; do pdftotext -layout "$file"; done into the terminal, I thought I could add it to the top of the following .py script.

I believe subprocess is the answer, but for the life of me I am unable to get it to save a .txt file beside the .pdf the same as pdftotext does via the terminal.

I have tried "Quotes", [Lists] and "Quotes" in [Lists], even tried "usr/lib/pdftotext".

Why does this not work for a pdf in home folder,

```<code>import subprocess

process = subprocess.Popen(['pdftotext', '-layout', 'ALL.pdf', 'ALL.txt'])
</code>```

Thanks

答:
Not the answer but how to get to the answer. When programs don't behave, start testing your assumptions and printing information as you go. This example should reduce the possible problems. You should see some prints from this program. If not, it may have to do with how you run the program. I am assuming that you run from the command line where you can see standard and error prints from python and pdftotext. If not, this will need updates.

```<code>#!/usr/bin/env python

import subprocess
import os
import sys
import time

# just in case we are double clicking from a windows manager and the
# window doesn't stay up very long
print "Starting in..."
for i in range(3, 0, -1):
    print i
    time.sleep(1)

# if you don't see these, it may be how you are running the program.
print "Platform", sys.platform
print "Running in directory", os.getcwd()

if not os.path.isfile('ALL.pdf'):
    print >> sys.stderr, "ALL.pdf does not exist"
    exit(2)

if os.path.isfile("ALL.txt"):
    print "Found old ALL.txt, deleting"
    os.remove("ALL.txt")

print "Running pdftotext..."

subprocess.check_output(['pdftotext', '-layout', 'ALL.pdf', 'ALL.txt'])
if not os.path.isfile('ALL.txt'):
    print "Program did not create ALL.txt"
    exit(2)
print "Success! ALL.txt was written."

# note: if you don't see "Success!" something bad happened
</code>```

I created a test file and ran it

```<code>td@mintyfresh ~/tmp $ python test.py
Starting in...
3
2
1
Platform linux2
Running in directory /home/td/tmp
Found old ALL.txt, deleting
Running pdftotext...
Success! ALL.txt was written.
</code>```

I then injected a file-not-found error and ran again

```<code>td@mintyfresh ~/tmp $ mv ALL.pdf ALL.pdf-tmp
td@mintyfresh ~/tmp $ python test.py
Starting in...
3
2
1
Platform linux2
Running in directory /home/td/tmp
ALL.pdf does not exist
</code>```

It detected one obvious problem easily.

Title: Correct use of subprocess in python 2.7

Body:
I have 2 pdf files to convert into text everyday via terminal, pdftotext module, and from there sort the data with a python script. To save time typing in,for file in *.pdf; do pdftotext -layout "$file"; done into the terminal, I thought I could add it to the top of the following .py script.

I believe subprocess is the answer, but for the life of me I am unable to get it to save a .txt file beside the .pdf the same as pdftotext does via the terminal.

I have tried "Quotes", [Lists] and "Quotes" in [Lists], even tried "usr/lib/pdftotext".

Why does this not work for a pdf in home folder,

import subprocess

process = subprocess.Popen(['pdftotext', '-layout', 'ALL.pdf', 'ALL.txt'])

Thanks

Body:
Not the answer but how to get to the answer. When programs don't behave, start testing your assumptions and printing information as you go. This example should reduce the possible problems. You should see some prints from this program. If not, it may have to do with how you run the program. I am assuming that you run from the command line where you can see standard and error prints from python and pdftotext. If not, this will need updates.

#!/usr/bin/env python

import subprocess
import os
import sys
import time

# just in case we are double clicking from a windows manager and the
# window doesn't stay up very long
print "Starting in..."
for i in range(3, 0, -1):
    print i
    time.sleep(1)

# if you don't see these, it may be how you are running the program.
print "Platform", sys.platform
print "Running in directory", os.getcwd()

if not os.path.isfile('ALL.pdf'):
    print >> sys.stderr, "ALL.pdf does not exist"
    exit(2)

if os.path.isfile("ALL.txt"):
    print "Found old ALL.txt, deleting"
    os.remove("ALL.txt")

print "Running pdftotext..."

subprocess.check_output(['pdftotext', '-layout', 'ALL.pdf', 'ALL.txt'])
if not os.path.isfile('ALL.txt'):
    print "Program did not create ALL.txt"
    exit(2)
print "Success! ALL.txt was written."

# note: if you don't see "Success!" something bad happened

I created a test file and ran it

td@mintyfresh ~/tmp $ python test.py
Starting in...
3
2
1
Platform linux2
Running in directory /home/td/tmp
Found old ALL.txt, deleting
Running pdftotext...
Success! ALL.txt was written.

I then injected a file-not-found error and ran again

td@mintyfresh ~/tmp $ mv ALL.pdf ALL.pdf-tmp
td@mintyfresh ~/tmp $ python test.py
Starting in...
3
2
1
Platform linux2
Running in directory /home/td/tmp
ALL.pdf does not exist

It detected one obvious problem easily.


问:
Pause execution in method until SelectionChanged event from ListView is raised
I have a windows 10 uwp app in C#. In one method, I check a list of strings. If I only have one item in my list, we are good. However, if I have more than one item, I want to popup a ListView so the user can select the one string from the multiples. When they select one, the ListView_SelectionChanged event is raised and I can get the selected string. However, that is in a different method/event from the caller obviously.

The issue is, I want the calling method to pause execution and wait until the user selects a string from the ListView. After, they select one, I need to continue execution in the caller. I know this was done with a while loop and a flag in the past but this is blocking. I don't necessarily care if it blocks but with async/await and other new framework features, I am sure there is a better way?

Thanks!

答:
I guess I accidentally asked this same question, in a different way twice. For that I apologize. I think I was still searching around for a solution to this problem with no answer that was working and I posted again.

That said, I was able to finally come up with a solution that works for me and I wanted to share it. I already answered it on my other question so here is the link to it.

My answer on the other post

Hope this helps!


问:
Stacked bar chart from JSON file - seems to be ignoring a value
Pretty new to this stuff, so any help is greatly appreciated. To start off with, here is my JSON file's contents:

```<code>[
  {
    "drg": "NONSPECIFIC CEREBROVASCULAR DISORDERS W MCC",
    "approved": 124,
    "denied": 38
  },
  {
    "drg": "SEIZURES WO MCC",
    "approved": 138,
    "denied": 26
  },
  {
    "drg": "CHRONIC OBSTRUCTIVE PULMONARY DISEASE W CC",
    "approved": 352,
    "denied": 61
  },
  {
    "drg": "CHEST PAIN",
    "approved": 246,
    "denied": 44
  },
  {
    "drg": "TRANSIENT ISCHEMIA",
    "approved": 205,
    "denied": 37
  },
  {
    "drg": "OTHER DISORDERS OF NERVOUS SYSTEM W CC",
    "approved": 133,
    "denied": 23
  },
  {
    "drg": "DIABETES W MCC",
    "approved": 151,
    "denied": 27
  },
  {
    "drg": "CARDIAC ARRHYTHMIA CONDUCTION DISORDERS W CC",
    "approved": 336,
    "denied": 55
  },
  {
    "drg": "HYPERTENSION WO MCC",
    "approved": 177,
    "denied": 29
  },
  {
    "drg": "POISONING TOXIC EFFECTS OF DRUGS WO MCC",
    "approved": 144,
    "denied": 24
  }
]
</code>```

My stacked bar chart, which worked fine with a CSV file, keeps ignoring the "denied" value. I suspect the issue has something to do with my formatting of the "processed_json.push()" portion of my code. It renders the approved value stacked on top of itself. Here is the script file:

```<code><script>
    $(document).ready(function() {
        var processed_json = new Array();
        $.getJSON('/dashboard-test-data/denied-percentage-2015-chart.json', function(data) {
            for (i = 0; i < data.length; i++) {
                processed_json.push([data[i].drg, data[i].approved, data[i].denied]);
            }
            $('#denied-percentage-2015-chart').highcharts({
                chart: {
                    type: 'bar'
                },
                credits: {
                    text: 'Vortext Analytics',
                    href: 'http://www.vortextanalytics.com'
                },
                title: {
                    text: 'Top 10 DRG by Denial Percentage 2015'
                },
                xAxis: {
                    type: 'category',
                },
                navigation: {
                    menuStyle: {
                        border: '1px solid #ddd',
                        boxShadow: 'none',
                    },
                    menuItemStyle: {
                        padding: '5px 1.5rem',
                    },
                    menuItemHoverStyle: {
                        backgroundColor: '#f7f7f9',
                        color: '#666'
                    },
                    buttonOptions: {
                        height: 40,
                        width: 46,
                        symbolX: 23,
                        symbolY: 22,
                        x: 10,
                        y: -15,
                        symbolSize: 13,
                    }
                },
                yAxis: {
                    min: 0,
                    title: {
                        text: 'Total Records'
                    },
                    stackLabels: {
                        enabled: true,
                        style: {
                            fontWeight: 'bold',
                            color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
                        },
                        formatter: function() {
                            return (this.axis.series[1].yData[this.x] / this.total * 100).toPrecision(2) + '%';
                        }
                    }
                },
                legend: {
                    align: 'left',
                    x: 0,
                    verticalAlign: 'bottom',
                    y: 22,
                    floating: true,
                    backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
                    borderColor: '#CCC',
                    borderWidth: 1,
                    shadow: false,
                    reversed: true,
                },
                tooltip: {
                    shared: true,
                    pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: {point.y:,0f} of {point.stackTotal:,0f}  <b>({point.percentage:.1f}%)</b><br />',
                },
                plotOptions: {
                    series: {
                        stacking: 'normal',
                        dataLabels: {
                            enabled: true,
                            color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
                            style: {
                                textOutline: 'none',
                                fontWeight: 'normal',
                                fontSize: '9px'
                            }
                        },
                        pointWidth: 20,
                    }
                },
                series: [{
                    name: 'approved',
                    color: '#55B4E4',
                    data: processed_json,
                }, {
                    name: 'denied',
                    color: '#005079',
                    data: processed_json,
                }],
            });
        });
    });
</script>
</code>```

Here is what the end product should produce (screen grab from my csv version):
Correct

And here is what I'm getting from the JSON file: incorrect

Any assistance or guidance is greatly appreciated. Thanks.

答:
Have a look at highchart's stacked bar chart example. For each series, data contains the array of values for that series.

```<code>series: [{
    name: 'John',
    data: [5, 3, 4, 7, 2]
}, {
    name: 'Jane',
    data: [2, 2, 3, 2, 1]
}, {
    name: 'Joe',
    data: [3, 4, 4, 2, 5]
}]
</code>```

In your case, instead of creating the processed_json array of objects, you should create separate arrays containing each series' values.

Change the loop this way:

```<code>        var xAxis = []
            , approvedCount = []
            , deniedCount = []

        for (i = 0; i < data.length; i++) {
            xAxis.push(data[i].drg);
            approvedCount.push(data[i].approved);
            deniedCount.push(data[i].denied);
</code>```

Then adapt the chart's instantiation accordingly:

```<code>// (...)
xAxis: {
    categories: xAxis
},
// (...)
            series: [{
                name: 'approved',
                color: '#55B4E4',
                data: approvedCount,
            }, {
                name: 'denied',
                color: '#005079',
                data: deniedCount,
            }],
// (...)
</code>```

Body:
Pretty new to this stuff, so any help is greatly appreciated. To start off with, here is my JSON file's contents:

[
  {
    "drg": "NONSPECIFIC CEREBROVASCULAR DISORDERS W MCC",
    "approved": 124,
    "denied": 38
  },
  {
    "drg": "SEIZURES WO MCC",
    "approved": 138,
    "denied": 26
  },
  {
    "drg": "CHRONIC OBSTRUCTIVE PULMONARY DISEASE W CC",
    "approved": 352,
    "denied": 61
  },
  {
    "drg": "CHEST PAIN",
    "approved": 246,
    "denied": 44
  },
  {
    "drg": "TRANSIENT ISCHEMIA",
    "approved": 205,
    "denied": 37
  },
  {
    "drg": "OTHER DISORDERS OF NERVOUS SYSTEM W CC",
    "approved": 133,
    "denied": 23
  },
  {
    "drg": "DIABETES W MCC",
    "approved": 151,
    "denied": 27
  },
  {
    "drg": "CARDIAC ARRHYTHMIA CONDUCTION DISORDERS W CC",
    "approved": 336,
    "denied": 55
  },
  {
    "drg": "HYPERTENSION WO MCC",
    "approved": 177,
    "denied": 29
  },
  {
    "drg": "POISONING TOXIC EFFECTS OF DRUGS WO MCC",
    "approved": 144,
    "denied": 24
  }
]

My stacked bar chart, which worked fine with a CSV file, keeps ignoring the "denied" value. I suspect the issue has something to do with my formatting of the "processed_json.push()" portion of my code. It renders the approved value stacked on top of itself. Here is the script file:

Here is what the end product should produce (screen grab from my csv version):
Correct

And here is what I'm getting from the JSON file: incorrect

Any assistance or guidance is greatly appreciated. Thanks.

Body:
Have a look at highchart's stacked bar chart example. For each series, data contains the array of values for that series.

series: [{
    name: 'John',
    data: [5, 3, 4, 7, 2]
}, {
    name: 'Jane',
    data: [2, 2, 3, 2, 1]
}, {
    name: 'Joe',
    data: [3, 4, 4, 2, 5]
}]

In your case, instead of creating the processed_json array of objects, you should create separate arrays containing each series' values.

Change the loop this way:

        var xAxis = []
            , approvedCount = []
            , deniedCount = []

        for (i = 0; i < data.length; i++) {
            xAxis.push(data[i].drg);
            approvedCount.push(data[i].approved);
            deniedCount.push(data[i].denied);

Then adapt the chart's instantiation accordingly:

// (...)
xAxis: {
    categories: xAxis
},
// (...)
            series: [{
                name: 'approved',
                color: '#55B4E4',
                data: approvedCount,
            }, {
                name: 'denied',
                color: '#005079',
                data: deniedCount,
            }],
// (...)


问:
Calculating number of nodes in BST using recursion c++
I'm trying to find the number of nodes in a BST using recursion. Here is my code

```<code>struct Node{
    int key;
    struct Node* left;
    struct Node* right;

    Node(){
        int key = 0;
        struct Node* left = nullptr;
        struct Node* right = nullptr;
    }
};
</code>```

src_root is the address of the root node of the tree.

```<code>int BST::countNodes(Node* src_root, int sum){

        if((src_root==root && src_root==nullptr) || src_root==nullptr)
            return 0;
        else if(src_root->left==nullptr || src_root->right==nullptr)
            return sum;
        return countNodes(src_root->left, sum + 1) + countNodes(src_root->right, sum + 1) + 1;
        }
</code>```

However my code only seems to work if there are 3 nodes. Anything greater than 3 gives wrong answer. Please help me find out what's wrong with it. Thanks!

答:
You have several logical and structural problems in your implementation.  Casperah gave you the "clean" answer that I assume you already found on the web (if you haven't already done that research, you shouldn't have posted your question).  Thus, what you're looking for is not someone else's solution, but how to fix your own.

Why do you pass sum down the tree?  Lower nodes shouldn't care what the previous count is; it's the parent's job to accumulate the counts from its children.  See how that's done in Casperah's answer?  Drop the extra parameter from your code; it's merely another source for error.

Your base case has an identically false clause: src_root==root && src_root==nullptr ... if you make a meaningful call, src_root cannot be both root and nullptr.

Why are you comparing against a global value, root?  Each call simply gets its own job done and returns.  When your call tree crawls back to the original invocation, the one that was called with the root, it simply does its job and returns to the calling program.  This should not be a special case.

Your else clause is wrong: it says that if either child is null, you ignore counting the other child altogether and return only the count so far.  This guarantees that you'll give the wrong answer unless the tree is absolutely balanced and filled, a total of 2^N - 1 nodes for N levels.

Fix those items in whatever order you find instructive; the idea is to learn.  Note, however, that your final code should look a lot like the answer Casperah provided.

Body:
I'm trying to find the number of nodes in a BST using recursion. Here is my code

struct Node{
    int key;
    struct Node* left;
    struct Node* right;

    Node(){
        int key = 0;
        struct Node* left = nullptr;
        struct Node* right = nullptr;
    }
};

src_root is the address of the root node of the tree.

int BST::countNodes(Node* src_root, int sum){

        if((src_root==root && src_root==nullptr) || src_root==nullptr)
            return 0;
        else if(src_root->left==nullptr || src_root->right==nullptr)
            return sum;
        return countNodes(src_root->left, sum + 1) + countNodes(src_root->right, sum + 1) + 1;
        }

However my code only seems to work if there are 3 nodes. Anything greater than 3 gives wrong answer. Please help me find out what's wrong with it. Thanks!


问:
CRT detected that the application wrote to memory after end of heap buffer (new/delete) classes
I am receiving the "Debug error" CRT detected that the application wrote to memory after end of heap. But I don't understand why and can't find any similar examples.

The full code is...
Although I think it may just be a problem with main.

```<code>#include <iostream>
#include <cmath>
#include <array>

using namespace std;
// Declare global consts
const double pi = 3.1415926583;

// Base class Shape
class Shape{
protected:
    double *sides;
public:
    Shape(const int n){ //parameterized for n dimensional shape
    sides = new double[n];
}
// need virtual destructor
virtual ~Shape(){
    delete[] sides;
}
virtual double area() const = 0; // pure virtual function for area
virtual double volume() const = 0; // pure virtual function for volume
};

//////////////////////////////////////////////////////////
//Derived classes for 2D and 3D Shapes
class Shape2D : public Shape{ // inherit shape
protected:
    int n = 2; //n denotes the number of dimensions
public:
    // default constructor
    Shape2D() :Shape(n){}
    // param constructor
    Shape2D(const double side1, const double side2) :Shape(n){
        sides[0] = side1; sides[1] = side2;
    }
    virtual ~Shape2D(){} //virtual destructor
    double volume() const { cout << "trying to calculate volume of 2d   shape..." << endl; return 0; };
};

/////////////////////////////////////////////////////////////////////
//2D shapes
class Rectangle : public Shape2D{
public:
    // constructors
    Rectangle() :Shape2D() {}
    Rectangle(const double side1, const double side2) :Shape2D(side1, side2){}
    ~Rectangle(){}
    double area() const { return (sides[0] * sides[1]); }
};

int main(){
    Shape **ShapePointer = new Shape*[2];
    ShapePointer[0] = new Rectangle(2, 5);
    ShapePointer[1] = new Rectangle(1, 3);
    // clean up
    delete ShapePointer[0];
    delete ShapePointer[1];
    delete[] ShapePointer;
    system("pause");
    return 0;
}
</code>```

答:
the problem is the following two lines of the code:
int n = 2; //n denotes the number of dimensions
Shape2D(const double side1, const double side2) :Shape(n){ ... }

The problem is the Shape() gets executed before the n is initialized. See constructors-called-before-initializing-variables for details.

To solution to this would be to create a the following methods in the Shape class

```<code>protected:
void InitializeBuffer(const int n)
{
sides = new double[n]
}
</code>```

and instead of initialize the sides in the parent constructor, call this InitializeBuffer with in the constructor of the Shape2D class

```<code>Shape2D(const double side1, const double side2) :Shape()
{
    InitializeBuffer (n);
    sides[0] = side1; sides[1] = side2;
}
</code>```

Body:
I am receiving the "Debug error" CRT detected that the application wrote to memory after end of heap. But I don't understand why and can't find any similar examples.

The full code is...
Although I think it may just be a problem with main.

#include <iostream>
#include <cmath>
#include <array>

using namespace std;
// Declare global consts
const double pi = 3.1415926583;

// Base class Shape
class Shape{
protected:
    double *sides;
public:
    Shape(const int n){ //parameterized for n dimensional shape
    sides = new double[n];
}
// need virtual destructor
virtual ~Shape(){
    delete[] sides;
}
virtual double area() const = 0; // pure virtual function for area
virtual double volume() const = 0; // pure virtual function for volume
};

//////////////////////////////////////////////////////////
//Derived classes for 2D and 3D Shapes
class Shape2D : public Shape{ // inherit shape
protected:
    int n = 2; //n denotes the number of dimensions
public:
    // default constructor
    Shape2D() :Shape(n){}
    // param constructor
    Shape2D(const double side1, const double side2) :Shape(n){
        sides[0] = side1; sides[1] = side2;
    }
    virtual ~Shape2D(){} //virtual destructor
    double volume() const { cout << "trying to calculate volume of 2d   shape..." << endl; return 0; };
};

/////////////////////////////////////////////////////////////////////
//2D shapes
class Rectangle : public Shape2D{
public:
    // constructors
    Rectangle() :Shape2D() {}
    Rectangle(const double side1, const double side2) :Shape2D(side1, side2){}
    ~Rectangle(){}
    double area() const { return (sides[0] * sides[1]); }
};

int main(){
    Shape **ShapePointer = new Shape*[2];
    ShapePointer[0] = new Rectangle(2, 5);
    ShapePointer[1] = new Rectangle(1, 3);
    // clean up
    delete ShapePointer[0];
    delete ShapePointer[1];
    delete[] ShapePointer;
    system("pause");
    return 0;
}

Body:
the problem is the following two lines of the code:
int n = 2; //n denotes the number of dimensions
Shape2D(const double side1, const double side2) :Shape(n){ ... }

The problem is the Shape() gets executed before the n is initialized. See constructors-called-before-initializing-variables for details.

To solution to this would be to create a the following methods in the Shape class

protected:
void InitializeBuffer(const int n)
{
sides = new double[n]
}

and instead of initialize the sides in the parent constructor, call this InitializeBuffer with in the constructor of the Shape2D class

Shape2D(const double side1, const double side2) :Shape()
{
    InitializeBuffer (n);
    sides[0] = side1; sides[1] = side2;
}


问:
change movieclip instance name in runtime
I'm trying change movieclip instance name in runtime,  with name property  but I have error

```<code>Error #2078: The name property of a Timeline-placed object cannot be modified.
</code>```

I tried to create new  movieclip in runtime asign my old movie clip and change name property but I have same error...

and is any way to change instance name of movieClip in runtime?

答:
So far the only workaround I've found is to use an array:</p>

```<code>import flash.display.MovieClip;
import flash.geom.ColorTransform;

var t:Boolean; // for toggle function
var square: Array = new Array();
var changeColor: ColorTransform = new ColorTransform();

for (var i: int = 0; i < 5; ++i) {
    var rect: MovieClip = new MovieClip();
    rect.graphics.beginFill(0xaaaaaa);
    rect.graphics.drawRect(10, 10, 50, 50)
    addChild(rect);
    rect.x = 75 * (i + 1);
    rect.y = 100;

    square.push(rect)

}

// This toggles the middle square up and down, and gray to red.
square[2].addEventListener(MouseEvent.CLICK, toggle);

function toggle(event: MouseEvent): void {

    if (!t) {

        changeColor.color = 0xff00000;
        square[2].transform.colorTransform = changeColor;

        square[2].y = 50;

    } else {

        changeColor.color = 0xaaaaaa;
        square[2].transform.colorTransform = changeColor;

        square[2].y = 100;
    }

    t=!t;
}
</code>```

Body:
I'm trying change movieclip instance name in runtime,  with name property  but I have error

Error #2078: The name property of a Timeline-placed object cannot be modified.

I tried to create new  movieclip in runtime asign my old movie clip and change name property but I have same error...

and is any way to change instance name of movieClip in runtime?

Body:
So far the only workaround I've found is to use an array:

import flash.display.MovieClip;
import flash.geom.ColorTransform;

var t:Boolean; // for toggle function
var square: Array = new Array();
var changeColor: ColorTransform = new ColorTransform();

for (var i: int = 0; i < 5; ++i) {
    var rect: MovieClip = new MovieClip();
    rect.graphics.beginFill(0xaaaaaa);
    rect.graphics.drawRect(10, 10, 50, 50)
    addChild(rect);
    rect.x = 75 * (i + 1);
    rect.y = 100;

    square.push(rect)

}

// This toggles the middle square up and down, and gray to red.
square[2].addEventListener(MouseEvent.CLICK, toggle);

function toggle(event: MouseEvent): void {

    if (!t) {

        changeColor.color = 0xff00000;
        square[2].transform.colorTransform = changeColor;

        square[2].y = 50;

    } else {

        changeColor.color = 0xaaaaaa;
        square[2].transform.colorTransform = changeColor;

        square[2].y = 100;
    }

    t=!t;
}


问:
PowerShell receive vs. get verbs
I've seen quite a few discussions on which verbs to use in your own PowerShell functions, but I haven't seen a clarification on using Receive vs. Get. They mean roughly the same thing to me, but Receive is supposed to be used specifically in situations involving communications (just type Get-Verb to see this).  Get, however, is in the Common group, so I'm really not sure which one to use.

I have a function that basically wraps a RESTful API and gets data from it (I use parameter sets for the different methods of the service). Right now the function is called Get-FooData. However, I'm thinking that I should possibly rename it to Receive-FooData since it is doing some communication.

I think I'm being too literal here in wanting to use Receive. My personal feeling is that Get sounds better, but I think that's just because I'm used to using it. What are your thoughts?

答:
This is an interesting design question and I used to think on this choice a few times. According to these guidelines:

Microsoft Command Line Standard

and my feeling, too, I would use Receive-X name in cases when I also design one of the pair/satellite communication commands Send-X, Connect-X, etc. This approach improves discoverability: if I see the Receive-X then even without reading manuals I also expect additional commands to exist.

In some sense this is true for the native PowerShell command Receive-Job: we cannot just call it (unlike Get-Item, Get-Process, etc.), we have to initiate something which data can be received afterwards, namely at first we call the Start-Job. But personally, I would call it differently: Get-JobResult or something like that; to me this name would be less confusing: it's the job results that we get, not the job instances, and there are no other satellite commands like Send-Job. The name Receive-Job would be still available for something perhaps more adequate in the future.

I would go with Get in most cases. But if you actually really want a user to stop and think for a moment of why X is called Receive, not Get, and there are reasons for that then Receive might be suitable.

All in all, I have never really used the verb Receive in my cmdlet/script/function names: something always was not enough for making this choice.

ContentLicense: CC BY-SA 4.0

Title: PowerShell receive vs. get verbs


问:
Heroku Scheduler With Python Script
How do I run a python script that is in my main directory with Heroku scheduler?

Normally I run this through the command line with Heroku run python "script.py", but this syntax is clearly not correct for the Heroku Scheduler. Where it says "rake do_something" what should the correct syntax be to run a python script here? I've tried "python script.py" and this does not work either.

Thanks!

答:
The Heroku Scheduler will try to run any command you give it. For Python, if you added a mytask.py to
your app repo, you could have the Scheduler run:

```<code>python mytask.py
</code>```

Instead of waiting for the Scheduler to run to see if the command works as expected, you can also test run it like this:

```<code>heroku run python mytask.py  # or heroku run:detached ...
heroku logs --tail
</code>```

Another way to use the Scheduler would be to extend your app with a cli tool or a script runner that shares the app context. A popular one for Flask is Flask-Script.

Note: the "rake" references in the Heroku Scheduler docs example is for running tasks with ruby.

Title: Heroku Scheduler With Python Script

Body:
The Heroku Scheduler will try to run any command you give it. For Python, if you added a mytask.py to
your app repo, you could have the Scheduler run:

python mytask.py

Instead of waiting for the Scheduler to run to see if the command works as expected, you can also test run it like this:

heroku run python mytask.py  # or heroku run:detached ...
heroku logs --tail

Another way to use the Scheduler would be to extend your app with a cli tool or a script runner that shares the app context. A popular one for Flask is Flask-Script.

Note: the "rake" references in the Heroku Scheduler docs example is for running tasks with ruby.


问:
how to remove x amount of data between 2 words
how to remove some random words between 2 selected words in notepad++ using regex...
here is an example to my question

```<code>DATA100003165663180:sdhfdsdf

DATA:cuoleL

DATA0004513337081:fsdfsd

DATAjhh07016550687:csd

DATA2369343834:1dsdsdbhz
</code>```

here you can see i need to remove all the words that are between DATA and ":" in such a way that i get DATA:xxx and not DATA006554something:xxx
and as you can see on line 2 there is no extra things that needs to be removed after DATA so the regex should ignore such lines

答: Use this for search DATA([^:])* and this for replace DATA  making sure you checked the regular expression option at the left bottom corner. Click Replace All

Body:
how to remove some random words between 2 selected words in notepad++ using regex...
here is an example to my question

DATA100003165663180:sdhfdsdf

DATA:cuoleL

DATA0004513337081:fsdfsd

DATAjhh07016550687:csd

DATA2369343834:1dsdsdbhz

here you can see i need to remove all the words that are between DATA and ":" in such a way that i get DATA:xxx and not DATA006554something:xxx
and as you can see on line 2 there is no extra things that needs to be removed after DATA so the regex should ignore such lines


问:
Conditional dateadd in procedure
I have a procedure that receives 3 parameters:

```<code>@startdate  = '2017-01-01'
@interval   = 'DD'
@duration   = 5
</code>```

What I need to do is output a new date, based on the above. A dateadd does not work, courtesy of that @interval not being correct.

```<code>select dateadd(@interval, @duration, @startdate)
</code>```

Invalid parameter 1 specified for dateadd.

Can anyone steer me right?

答:
Something like this:</p>

```<code>select case @interval
  when 'yy' then DateAdd(Year, @duration, @startdate)
  when 'qq' then DateAdd(Quarter, @duration, @startdate)
  when 'mm' then DateAdd(Month, @duration, @startdate)
  when 'wk' then DateAdd(WeeK, @duration, @startdate)
  when 'dd' then DateAdd(Day, @duration, @startdate)
  when 'hh' then DateAdd(Hour, @duration, @startdate)
  when 'mi' then DateAdd(Minute, @duration, @startdate)
  when 'ss' then DateAdd(Second, @duration, @startdate)
else null
end
</code>```

Title: Conditional dateadd in procedure

Body:
I have a procedure that receives 3 parameters:

@startdate  = '2017-01-01'
@interval   = 'DD'
@duration   = 5

What I need to do is output a new date, based on the above. A dateadd does not work, courtesy of that @interval not being correct.

select dateadd(@interval, @duration, @startdate)

Invalid parameter 1 specified for dateadd.

Can anyone steer me right?

Body:
Something like this:

select case @interval
  when 'yy' then DateAdd(Year, @duration, @startdate)
  when 'qq' then DateAdd(Quarter, @duration, @startdate)
  when 'mm' then DateAdd(Month, @duration, @startdate)
  when 'wk' then DateAdd(WeeK, @duration, @startdate)
  when 'dd' then DateAdd(Day, @duration, @startdate)
  when 'hh' then DateAdd(Hour, @duration, @startdate)
  when 'mi' then DateAdd(Minute, @duration, @startdate)
  when 'ss' then DateAdd(Second, @duration, @startdate)
else null
end


问:
Clean character observation from duplicate factor levels
The situation is the following: I have a column "a" that is of class character, containing many integers. Each integer represents a category. I would like to know for each observation what unique levels they include.
Column b represents the desired result: cleaned for duplicates, yet representing each unique level.
What I would like to know is how I could clean column a, so that it looks like column b. I need to implement the solution to 60k rows.

```<code>                                                       a          b
1 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5 |   4, 5
2                            2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 |   2
3           86, 86, 86, 86, 86, 37, 37, 37, 37, 37, 37, 8, 8 |   86, 37, 8

a <- c("4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5", "2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2", "86, 86, 86, 86, 86, 37, 37, 37, 37, 37, 37, 8, 8")
b <- c("4, 5", "2", "86, 37, 8")
df <- data.frame(a, b)
</code>```

I have read a few posts about dropping duplicate factor values, but as you can try out yourself this does not yield anything useful.

```<code>droplevels(factor(df$a))
</code>```

This basically solves the issue, but it is not feasible for 60k rows.

```<code>df$a[1] <- factor(unique(as.numeric(unlist(str_extract_all(df$a[1], "[[:digit:]]+")))))
df$a[2] <- factor(unique(as.numeric(unlist(str_extract_all(df$a[2], "[[:digit:]]+")))))
df$a[3] <- factor(unique(as.numeric(unlist(str_extract_all(df$a[3], "[[:digit:]]+")))))
</code>```

答:
You missed the use of sapply here. That prevents you from having to construct element by element, eg like this:

```<code>df$a <- sapply(a,function(i){
  paste(unique(strsplit(i,", ")[[1]]),
        collapse = ", ")
})

df$a
#> [1] "4, 5"      "2"         "86, 37, 8"
</code>```

Keep in mind that strsplit() works on character vectors. So either use stringsAsFactors = FALSE when constructing the data, or convert the factor variables first to character using as.character(). In my code I just use the vector a.

On a sidenote: I love the stringr package, but in this case strsplit() will give you faster code. Using the code above, you avoid a lot of overhead created by the regular expressions you use.

Body:
The situation is the following: I have a column "a" that is of class character, containing many integers. Each integer represents a category. I would like to know for each observation what unique levels they include.
Column b represents the desired result: cleaned for duplicates, yet representing each unique level.
What I would like to know is how I could clean column a, so that it looks like column b. I need to implement the solution to 60k rows.

                                                       a          b
1 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5 |   4, 5
2                            2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 |   2
3           86, 86, 86, 86, 86, 37, 37, 37, 37, 37, 37, 8, 8 |   86, 37, 8

a <- c("4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5", "2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2", "86, 86, 86, 86, 86, 37, 37, 37, 37, 37, 37, 8, 8")
b <- c("4, 5", "2", "86, 37, 8")
df <- data.frame(a, b)

I have read a few posts about dropping duplicate factor values, but as you can try out yourself this does not yield anything useful.

droplevels(factor(df$a))

This basically solves the issue, but it is not feasible for 60k rows.

df$a[1] <- factor(unique(as.numeric(unlist(str_extract_all(df$a[1], "[[:digit:]]+")))))
df$a[2] <- factor(unique(as.numeric(unlist(str_extract_all(df$a[2], "[[:digit:]]+")))))
df$a[3] <- factor(unique(as.numeric(unlist(str_extract_all(df$a[3], "[[:digit:]]+")))))

Body:
You missed the use of sapply here. That prevents you from having to construct element by element, eg like this:

df$a <- sapply(a,function(i){
  paste(unique(strsplit(i,", ")[[1]]),
        collapse = ", ")
})

df$a
#> [1] "4, 5"      "2"         "86, 37, 8"

Keep in mind that strsplit() works on character vectors. So either use stringsAsFactors = FALSE when constructing the data, or convert the factor variables first to character using as.character(). In my code I just use the vector a.

On a sidenote: I love the stringr package, but in this case strsplit() will give you faster code. Using the code above, you avoid a lot of overhead created by the regular expressions you use.


问:
How do you plot this particular function in matlab?
I want to draw these two function in Matlab

g(x) = sin(x)/(1+x^2) and

f(x) = (x^2)/(2-x)

However I am struggling with it, here is my code

```<code>x=linspace(-5,5);
y1= sin(x)/(1+x^2);
y2= x^2/(2-x);
plot(x,y1,x,y2)
</code>```

Every time I try to run an empty figure is displayed.

答:
When you run your code, you'll realize that you are getting the following error:

Error using ^

  Inputs must be a scalar and a square matrix.

  To compute elementwise POWER, use POWER (.^) instead.

As the message very clearly states, you need to use power (.^) to perform the element-wise operation rather than mpower (^). Additionally, you'll want to use rdivide (./) rather than mrdivide (/) to perform element-wise division.

```<code>y1 = sin(x) ./ (1+x.^2);
y2 = x.^2 ./ (2-x);
</code>```

If you want each plot to be on it's own scale, you can use yyaxis

```<code>yyaxis left
plot(x, y1)
yyaxis right
plot(x, y2);
</code>```

Body:
I want to draw these two function in Matlab

g(x) = sin(x)/(1+x^2) and

f(x) = (x^2)/(2-x)

However I am struggling with it, here is my code

x=linspace(-5,5);
y1= sin(x)/(1+x^2);
y2= x^2/(2-x);
plot(x,y1,x,y2)

Every time I try to run an empty figure is displayed.

Body:
When you run your code, you'll realize that you are getting the following error:

Error using ^

  Inputs must be a scalar and a square matrix.

  To compute elementwise POWER, use POWER (.^) instead.

As the message very clearly states, you need to use power (.^) to perform the element-wise operation rather than mpower (^). Additionally, you'll want to use rdivide (./) rather than mrdivide (/) to perform element-wise division.

y1 = sin(x) ./ (1+x.^2);
y2 = x.^2 ./ (2-x);

If you want each plot to be on it's own scale, you can use yyaxis

yyaxis left
plot(x, y1)
yyaxis right
plot(x, y2);


问:
Create Balanced Binary Search Tree from Sorted linked list
What's the best way to create a balanced binary search tree from a sorted singly linked list?</p>

答:
How about creating nodes bottom-up?

This solution's time complexity is O(N). Detailed explanation in my blog post:

http://www.leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html

Two traversal of the linked list is all we need. First traversal to get the length of the list (which is then passed in as the parameter n into the function), then create nodes by the list's order.

```<code>BinaryTree* sortedListToBST(ListNode *& list, int start, int end) {
  if (start > end) return NULL;
  // same as (start+end)/2, avoids overflow
  int mid = start + (end - start) / 2;
  BinaryTree *leftChild = sortedListToBST(list, start, mid-1);
  BinaryTree *parent = new BinaryTree(list->data);
  parent->left = leftChild;
  list = list->next;
  parent->right = sortedListToBST(list, mid+1, end);
  return parent;
}

BinaryTree* sortedListToBST(ListNode *head, int n) {
  return sortedListToBST(head, 0, n-1);
}
</code>```

Body:
How about creating nodes bottom-up?

This solution's time complexity is O(N). Detailed explanation in my blog post:

http://www.leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html

Two traversal of the linked list is all we need. First traversal to get the length of the list (which is then passed in as the parameter n into the function), then create nodes by the list's order.

BinaryTree* sortedListToBST(ListNode *& list, int start, int end) {
  if (start > end) return NULL;
  // same as (start+end)/2, avoids overflow
  int mid = start + (end - start) / 2;
  BinaryTree *leftChild = sortedListToBST(list, start, mid-1);
  BinaryTree *parent = new BinaryTree(list->data);
  parent->left = leftChild;
  list = list->next;
  parent->right = sortedListToBST(list, mid+1, end);
  return parent;
}

BinaryTree* sortedListToBST(ListNode *head, int n) {
  return sortedListToBST(head, 0, n-1);
}


问:
Specifying different colour schemes for different orientations of Polarhistogram in MATLAB

Question

When using polarhistogram(theta) to plot a dataset containing azimuths from 0-360 degrees. Is it possible to specify colours for given segments?

Example

In the plot bellow for example would it be possible to specify that all bars between 0 and 90 degrees (and thus 180-270 degrees also) are red? whilst the rest remains blue?

Reference material

I think if it exists it will be within here somewhere but I am unable to figure out which part exactly:

https://www.mathworks.com/help/matlab/ref/polaraxes-properties.html

答:
If you use rose, you can extract the edges of the histogram and plot each bar one by one. It's a bit of a hack but it works, looks pretty and does not require Matlab 2016b.

```<code>theta = atan2(rand(1e3,1)-0.5,2*(rand(1e3,1)-0.5));
n = 25;
colours = hsv(n);

figure;
rose(theta,n); cla; % Use this to initialise polar axes
[theta,rho] = rose(theta,n); % Get the histogram edges
theta(end+1) = theta(1); % Wrap around for easy interation
rho(end+1) = rho(1);
hold on;
for j = 1:floor(length(theta)/4)
    k = @(j) 4*(j-1)+1; % Change of iterator
    h = polar(theta(k(j):k(j)+3),rho(k(j):k(j)+3));
    set(h,'color',colours(j,:)); % Set the color
    [x,y] = pol2cart(theta(k(j):k(j)+3),rho(k(j):k(j)+3));
    h = patch(x,y,'');
    set(h,'FaceColor',colours(j,:),'FaceAlpha',0.2);
    uistack(h,'down');
end
grid on; axis equal;
title('Coloured polar histogram')
</code>```

Result

Body:
If you use rose, you can extract the edges of the histogram and plot each bar one by one. It's a bit of a hack but it works, looks pretty and does not require Matlab 2016b.

theta = atan2(rand(1e3,1)-0.5,2*(rand(1e3,1)-0.5));
n = 25;
colours = hsv(n);

figure;
rose(theta,n); cla; % Use this to initialise polar axes
[theta,rho] = rose(theta,n); % Get the histogram edges
theta(end+1) = theta(1); % Wrap around for easy interation
rho(end+1) = rho(1);
hold on;
for j = 1:floor(length(theta)/4)
    k = @(j) 4*(j-1)+1; % Change of iterator
    h = polar(theta(k(j):k(j)+3),rho(k(j):k(j)+3));
    set(h,'color',colours(j,:)); % Set the color
    [x,y] = pol2cart(theta(k(j):k(j)+3),rho(k(j):k(j)+3));
    h = patch(x,y,'');
    set(h,'FaceColor',colours(j,:),'FaceAlpha',0.2);
    uistack(h,'down');
end
grid on; axis equal;
title('Coloured polar histogram')

Result


问:
NSNumberFormatter Currency Without Symbol?
I am using NSNumberFormatter to get a currency value from a string and it works well.

I use this code to do so:

```<code>NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
    [nf setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSString *price = [nf stringFromNumber:[NSNumber numberWithFloat:[textField.text floatValue]]];
</code>```

However, it always gives me a currency symbol at the start of the string. Rather than doing it manually form my given string, can I not somehow have the formatter not give the string any currency symbol?

答:
With Swift 5, NumberFormatter has a property called currencySymbol. currencySymbol has the following declaration:

```<code>var currencySymbol: String! { get set }
</code>```

The string used by the receiver as a local currency symbol.

Therefore, if required for your formatting style, you can set this property to an empty String.

The following Playground sample code shows how to set your currency formatting style with an empty symbol:

```<code>import Foundation

let amount = 12000

let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.currency
formatter.currencySymbol = ""
formatter.locale = Locale(identifier: "en_US") // set only if necessary

let result = formatter.string(for: amount)
print(String(describing: result)) // prints: Optional("12,000.00")
</code>```

Body:
I am using NSNumberFormatter to get a currency value from a string and it works well.

I use this code to do so:

NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
    [nf setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSString *price = [nf stringFromNumber:[NSNumber numberWithFloat:[textField.text floatValue]]];

However, it always gives me a currency symbol at the start of the string. Rather than doing it manually form my given string, can I not somehow have the formatter not give the string any currency symbol?

Body:
With Swift 5, NumberFormatter has a property called currencySymbol. currencySymbol has the following declaration:

var currencySymbol: String! { get set }

The string used by the receiver as a local currency symbol.

Therefore, if required for your formatting style, you can set this property to an empty String.

The following Playground sample code shows how to set your currency formatting style with an empty symbol:

import Foundation

let amount = 12000

let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.currency
formatter.currencySymbol = ""
formatter.locale = Locale(identifier: "en_US") // set only if necessary

let result = formatter.string(for: amount)
print(String(describing: result)) // prints: Optional("12,000.00")


问:
React-Native: Avoid Text Wrapping
I have the title of a song and its duration showing in one line. The song title needs to show an ellipsis but the duration should never wrap or show ellipsis. I've tried several combinations but fail to make this work right for long titles. The duration either goes off screen when the name shows ellipsis or the duration wraps. I can't hardcode a fixed width on the duration as it can change size.</p>

```<code><View style={{flexDirection: 'row'}}>
    <Text numberOfLines={2} style={{fontSize: 16, textAlign: 'left'}}>{title}</Text>
    <Text style={{flex: 1, fontSize: 13, textAlign: 'right', marginTop: 2}}>{duration}</Text>
</View>
</code>```

答:
The solution ended up being fairly simple. Not entirely intuitive but here's how to solve this. It appears that the text that needs ellipsis requires flex: 1.

```<code> <View style={{ flexDirection: "row" }}>
<Text numberOfLines={1} style={{ flex: 1, textAlign: "left" }}>
    {title}
</Text>
<Text style={{ textAlign: "right" }}>{duration}</Text>
</View>;
</code>```

Title: React-Native: Avoid Text Wrapping

Body:
I have the title of a song and its duration showing in one line. The song title needs to show an ellipsis but the duration should never wrap or show ellipsis. I've tried several combinations but fail to make this work right for long titles. The duration either goes off screen when the name shows ellipsis or the duration wraps. I can't hardcode a fixed width on the duration as it can change size.

<View style={{flexDirection: 'row'}}>
    <Text numberOfLines={2} style={{fontSize: 16, textAlign: 'left'}}>{title}</Text>
    <Text style={{flex: 1, fontSize: 13, textAlign: 'right', marginTop: 2}}>{duration}</Text>
</View>

Body:
The solution ended up being fairly simple. Not entirely intuitive but here's how to solve this. It appears that the text that needs ellipsis requires flex: 1.

 <View style={{ flexDirection: "row" }}>
<Text numberOfLines={1} style={{ flex: 1, textAlign: "left" }}>
    {title}
</Text>
<Text style={{ textAlign: "right" }}>{duration}</Text>
</View>;


问:
Change selection populating undesired results
I have two inputs. I am unsure what I am doing wrong, but I am simply trying to display the div associated with the input selection.

The issue I am having now is that if an input is selected, the console shows that both inputs were selected. Also, the title .pg-selection-title is not showing the correct data.

Why is my change selection now displaying the correct data?

jQuery.fn.fadeBoolToggle = function(bool) {
  return bool ? this.fadeIn(400) : this.fadeOut(400);
}

 $('.calendar-check').on('change', function () {
  if ($('#cal-2year:checked')) {
    $('#prev-2year').fadeBoolToggle($('#cal-2year:checked').length == 1);
    console.log('A selected');
    $('.pg-selection-title').html('A selected');
  };
  if ($('#cal-whiteboard:checked')) {
    $('#prev-whiteboard').fadeBoolToggle($('#cal-whiteboard:checked').length == 1);
    console.log('B selected');
    $('.pg-selection-title').html('B Selected');
  };
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cal-theme-wrap {
  display: none;
}</code>```

<input type="checkbox" class="calendar-check" id="cal-2year">
<input type="checkbox" class="calendar-check" id="cal-whiteboard">

    A

    B

```

答:
I'm assuming you also want to re-hide the divs when their respective checkboxes are unchecked? Always pass your boolean to your hide/show function, regardless of whether they are checked.

You might also reconsider changing the .pg-selection-title for both, in case both are selected.  Since the div will only be visible when that checkbox is selected, you probably don't need to dynamically change the text.

jQuery.fn.fadeBoolToggle = function(bool) {
  return bool ? this.fadeIn(400) : this.fadeOut(400);
}

$('.calendar-check').on('change', function() {
  // hide or show divs based on whether it is checked
  $('#prev-2year').fadeBoolToggle($('#cal-2year').is(':checked'));
  $('#prev-whiteboard').fadeBoolToggle($('#cal-whiteboard').is(':checked'));

  if ($('#cal-2year').is(':checked')) {
    console.log('A selected');
    // $('.pg-selection-title').html('A selected');
  };
  if ($('#cal-whiteboard').is(':checked')) {
    console.log('B selected');
    // $('.pg-selection-title').html('B Selected');
  };
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cal-theme-wrap {
  display: none;
}</code>```

<input type="checkbox" class="calendar-check" id="cal-2year">
<input type="checkbox" class="calendar-check" id="cal-whiteboard">

A Selected

    A

B Selected

    B

```

Body:
I have two inputs. I am unsure what I am doing wrong, but I am simply trying to display the div associated with the input selection.

The issue I am having now is that if an input is selected, the console shows that both inputs were selected. Also, the title .pg-selection-title is not showing the correct data.

Why is my change selection now displaying the correct data?

jQuery.fn.fadeBoolToggle = function(bool) {
  return bool ? this.fadeIn(400) : this.fadeOut(400);
}

 $('.calendar-check').on('change', function () {
  if ($('#cal-2year:checked')) {
    $('#prev-2year').fadeBoolToggle($('#cal-2year:checked').length == 1);
    console.log('A selected');
    $('.pg-selection-title').html('A selected');
  };
  if ($('#cal-whiteboard:checked')) {
    $('#prev-whiteboard').fadeBoolToggle($('#cal-whiteboard:checked').length == 1);
    console.log('B selected');
    $('.pg-selection-title').html('B Selected');
  };
});

.cal-theme-wrap {
  display: none;
}

<input type="checkbox" class="calendar-check" id="cal-2year">
<input type="checkbox" class="calendar-check" id="cal-whiteboard">

    A

    B

Body:
I'm assuming you also want to re-hide the divs when their respective checkboxes are unchecked? Always pass your boolean to your hide/show function, regardless of whether they are checked.

You might also reconsider changing the .pg-selection-title for both, in case both are selected.  Since the div will only be visible when that checkbox is selected, you probably don't need to dynamically change the text.

jQuery.fn.fadeBoolToggle = function(bool) {
  return bool ? this.fadeIn(400) : this.fadeOut(400);
}

$('.calendar-check').on('change', function() {
  // hide or show divs based on whether it is checked
  $('#prev-2year').fadeBoolToggle($('#cal-2year').is(':checked'));
  $('#prev-whiteboard').fadeBoolToggle($('#cal-whiteboard').is(':checked'));

  if ($('#cal-2year').is(':checked')) {
    console.log('A selected');
    // $('.pg-selection-title').html('A selected');
  };
  if ($('#cal-whiteboard').is(':checked')) {
    console.log('B selected');
    // $('.pg-selection-title').html('B Selected');
  };
});

.cal-theme-wrap {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="calendar-check" id="cal-2year">
<input type="checkbox" class="calendar-check" id="cal-whiteboard">

<div id="prev-2year" class="cal-theme-wrap">
  <h4 class="pg-selection-title">A Selected</h4>
  <p id="calender-preview-choice"></p>
  <div id="calendar-select">
    A
  </div>
</div>
<div id="prev-whiteboard" class="cal-theme-wrap">
  <h4 class="pg-selection-title">B Selected</h4>
  <p id="calender-preview-choice"></p>
  <div id="calendar-select">
    B
  </div>
</div>


问:
Add attribute to react native components during input text change
Is there a way to add attributes to a React component during text change ?

I've a registration page, i would like to highlight the text box by adding "error" attribute to  components.

PS: I'm using NativeBase for my project, the "Input" is equals to "Text" in react native.

Below is the code without error

```<code><Item>
  <Input placeholder='Email' onChangeText={(val) => this.validateEmail(val)}/>
  <Icon name='close-circle' />
</Item>
</code>```

Below is the code will show error

```<code>  <Item error>
    <Input placeholder='Email' onChangeText={(val) => this.validateEmail(val)}/>
    <Icon name='close-circle' />
  </Item>
</code>```

If adding extra attribute during action is not possible, could you all please suggest me a way to achieve this ?

Sorry for the question i'm still very new to react native.

答:
You can set error to true or false based on state and have validateEmail toggle that state value:</p>

```<code>this.state = {
  showError: false
}
...
<Item error={this.state.showError}>

and somewhere inside validateEmail you would do this.setState({ showError: true })
</code>```

Body:
Is there a way to add attributes to a React component during text change ?

I've a registration page, i would like to highlight the text box by adding "error" attribute to  components.

PS: I'm using NativeBase for my project, the "Input" is equals to "Text" in react native.

Below is the code without error

<Item>
  <Input placeholder='Email' onChangeText={(val) => this.validateEmail(val)}/>
  <Icon name='close-circle' />
</Item>

Below is the code will show error

  <Item error>
    <Input placeholder='Email' onChangeText={(val) => this.validateEmail(val)}/>
    <Icon name='close-circle' />
  </Item>

If adding extra attribute during action is not possible, could you all please suggest me a way to achieve this ?

Sorry for the question i'm still very new to react native.

Body:
You can set error to true or false based on state and have validateEmail toggle that state value:

this.state = {
  showError: false
}
...
<Item error={this.state.showError}>

and somewhere inside validateEmail you would do this.setState({ showError: true })