问:
phantomjs npm install fails behind proxy
Trying to install PhantomJS via an npm wrapper while behind the corporate proxy. I had already set the http_proxy and https_proxy environment variables so that npm itself would be able to communicate with the registry:

```<code>export http_proxy=my-company-proxy.com:80
export https_proxy=my-company-proxy.com:80
</code>```

But when it came to the node install.js stage of phantomjs, I got a Protocol not supported error:

```<code>http.js:1711
    throw new Error('Protocol:' + options.protocol + ' not supported.');
      ^
Error: Protocol:my-company-proxy.com: not supported.
</code>```

答:
This is what worked for me.

Open the terminal as an administrator

Navigate to your project folder and enter the following commands

sudo npm config set proxy http://proxy_host:port -g then

sudo npm config set https-proxy http://proxy_host:port -g

Hope this works for you. Good luck.

Body:
Trying to install PhantomJS via an npm wrapper while behind the corporate proxy. I had already set the http_proxy and https_proxy environment variables so that npm itself would be able to communicate with the registry:

export http_proxy=my-company-proxy.com:80
export https_proxy=my-company-proxy.com:80

But when it came to the node install.js stage of phantomjs, I got a Protocol not supported error:

http.js:1711
    throw new Error('Protocol:' + options.protocol + ' not supported.');
      ^
Error: Protocol:my-company-proxy.com: not supported.


来源: stackexchange

问:
How to set a random color for each group of elements looping through an array?
I am trying to set a different colors using jquery on each .elements, their children (.element) should have the same color but the attribution of color should be random for each .elements. How can I do it ?

Here's an example : https://jsfiddle.net/auscpzy6/6/

Html

```<code><div class="elements"> <!-- children share the same color -->
  <div class="element">1</div> <!-- exmaple : red -->
  <div class="element">2</div> <!-- exmaple : red -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">3</div> <!-- exmaple : blue -->
  <div class="element">4</div> <!-- exmaple : blue -->
  <div class="element">5</div> <!-- exmaple : blue -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">6</div> <!-- exmaple : yellow -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">7</div> <!-- exmaple : blue -->
  <div class="element">8</div> <!-- exmaple : blue -->
</div>
</code>```

Javascript : This is what I tried but everything stay on the same color.

```<code>function eachEl(el){
    var items = ["blue", "red", "yellow"];
    var item = items[Math.floor(Math.random()*items.length)];
    $(el).css({
        "color": item,
    });
}

$(".elements").each(function() {
    eachEl('.element');
});
</code>```

Any solution ?

答:
Instead of eachEl('.element'); you need to use eachEl($(this).find('.element'));. Your code was taking elements that have class as element but you need only child element of the current elements.

function eachEl(el) {
  var items = ["blue", "red", "yellow"];
  var item = items[Math.floor(Math.random() * items.length)];
  $(el).css({
    "color": item,
  });
}

$(".elements").each(function() {
  eachEl($(this).find('.element'));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="elements">
  <!-- children share the same color -->
  <div class="element">1</div>
  <!-- exmaple : red -->
  <div class="element">2</div>
  <!-- exmaple : red -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">3</div>
  <!-- exmaple : blue -->
  <div class="element">4</div>
  <!-- exmaple : blue -->
  <div class="element">5</div>
  <!-- exmaple : blue -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">6</div>
  <!-- exmaple : yellow -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">7</div>
  <!-- exmaple : blue -->
  <div class="element">8</div>
  <!-- exmaple : blue -->
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to set a different colors using jquery on each .elements, their children (.element) should have the same color but the attribution of color should be random for each .elements. How can I do it ?

Here's an example : https://jsfiddle.net/auscpzy6/6/

Html

1

2

3

4

5

6

7

8

Javascript : This is what I tried but everything stay on the same color.

function eachEl(el){
    var items = ["blue", "red", "yellow"];
    var item = items[Math.floor(Math.random()*items.length)];
    $(el).css({
        "color": item,
    });
}

$(".elements").each(function() {
    eachEl('.element');
});

Any solution ?

Body:
Instead of eachEl('.element'); you need to use eachEl($(this).find('.element'));. Your code was taking elements that have class as element but you need only child element of the current elements.

function eachEl(el) {
  var items = ["blue", "red", "yellow"];
  var item = items[Math.floor(Math.random() * items.length)];
  $(el).css({
    "color": item,
  });
}

$(".elements").each(function() {
  eachEl($(this).find('.element'));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="elements">
  <!-- children share the same color -->
  <div class="element">1</div>
  <!-- exmaple : red -->
  <div class="element">2</div>
  <!-- exmaple : red -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">3</div>
  <!-- exmaple : blue -->
  <div class="element">4</div>
  <!-- exmaple : blue -->
  <div class="element">5</div>
  <!-- exmaple : blue -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">6</div>
  <!-- exmaple : yellow -->
</div>

<div class="elements">
  <!-- children share the same color -->
  <div class="element">7</div>
  <!-- exmaple : blue -->
  <div class="element">8</div>
  <!-- exmaple : blue -->
</div>


问:
split div into 2 columns doesn't work
Can you please help me, it took me so much time trying to fixe this problem.
i have 2 slider and i need to split each slide into 2 colums. The problem is that the second column which is float: right doesn't show in both sliders .
Here is a code pen that shows the problem codepen
thank you

Here is my structure:

    .Dash_map_wrapSlider {
 position: absolute;
 overflow: hidden;
 height: 100%;
 width: calc(100% - 3rem);
 bottom: calc(-80% + 10rem);
 left: 3rem;
 background: #fff;
 border: 1px solid;
 transition: 0.5s;
 z-index: 1;}

    .Dash_map_wrapSlider:hover{
 bottom: 0rem;
 transition: 0.5s;}

    .Dash_map_wrapSlider:hover{
 bottom: 0rem;
 transition: 0.5s;}

    .Dash_map_wrapSliderchoise {
 background: #3E474F;
 box-shadow: 0 .5em 1em #111;
 position: absolute;
 left: 0;
 bottom: 0;
 z-index: 900;
 width: 100%;
 height: 2rem;
 line-height: 2rem;
 text-align: center;
 vertical-align: middle;}

    .Dash_map_sumSlide {
 height: 100%;
 width: 100%;
 position: absolute;
 top: 0;
 left: 100%;
 z-index: 10;
 background-color: #fff;
 transition: left 0s .75s;}

    .clsDashMap_sumSlideInput {
 display: none;
 height: 11rem;}

    .clsDashMap_sumSlideTitle {
 position : absolute;
 top:0;
 width: 100%;
 height: 2rem;
 left: inherit;
 color: #fff;
 background-color: #73b9ff;
 text-align: center;
 font-weight: bold;
 font-size: 1.20rem;}

    .clsDashMap_sumSlideContentBoxTitle {
 font-weight: bold;
 color: #666;}

    .clsDashMap_sumSlideSiteContentSummary {
 position : absolute;
 top: 2rem;
 width: 100%;
 height: 16rem;
 color: #000000;
 background-color: aliceblue;
 text-align: center;}

    .clsDashMap_sumSlideContent {
 position: absolute;
 top: 20rem;
 margin: auto;
 width: 100%;
 color: #000000;}

    [id^="Dash"]:checked + .Dash_map_sumSlide {
 left: 0;
 z-index: 100;
 transition: left .65s ease-out;}

    .Dash_map_wrapSliderchoise label {
 color: #fff;
 cursor: pointer;
 display: inline-block;
 line-height: 2rem;
 font-size: 0.75rem;
 font-weight: bold;
 padding: 0 1em;}

    .clsDashMap_sumSlideContentBox {
 margin: auto;
 float: left;
    padding: 10px;
    text-align: center;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Dash_map_wrapSlider">
    <div style="border: 1px solid red;width: 100%;">
     <input id="Dash_map_sumSlideSite" class="clsDashMap_sumSlideInput" type="radio" name="slides" checked>
     <div class="Dash_map_sumSlide slide_Site " style="float: left;width: 50%;border: 2px solid yellow;">
      <div class="clsDashMap_sumSlideTitle">SITE</div>
      <div class="clsDashMap_sumSlideSiteContentSummary">
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">Etat</div>
        <div class="green led">OK</div>
        <div class="red led">KO</div>
       </div>
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">AlarmesSite</div>
        <canvas id="pieChartAlm" ></canvas>
       </div>
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">TicketsSite</div>
        <canvas id="pieChartTkt" ></canvas>
       </div>
      </div>
      <div class="clsDashMap_sumSlideContent">put here content</div>
     </div>

     <div class="Dash_map_sumSlide slide_Alarme" style="float: right;width: 50%; border: 2px solid green;">
      <div class="clsDashMap_sumSlideTitle" >ALARME</div>
      <div class="clsDashMap_sumSlideSiteContentSummary">
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">Etat</div>
        <div class="green led">OK</div>
        <div class="red led">KO</div>
       </div>
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">ALARME1Alm</div>
        <canvas id="pieChartAlm" ></canvas>
       </div>
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">Tickets1Alm</div>
        <canvas id="pieChartTkt" ></canvas>
       </div>
      </div>
      <div class="clsDashMap_sumSlideContent">put here content</div>
     </div>
    </div>

    <div style="border: 1px solid red;">
     <input id="Dash_map_sumSlideAlarme" class="clsDashMap_sumSlideInput" type="radio" name="slides" checked>
     <div class="Dash_map_sumSlide slide_Site " style="width: 50%;border: 2px solid black;">
      <div class="clsDashMap_sumSlideTitle">TECHNICIEN</div>
      <div class="clsDashMap_sumSlideSiteContentSummary">
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">Etat</div>
        <div class="green led">OK</div>
        <div class="red led">KO</div>
       </div>
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">Alarmes2Tech</div>
       </div>
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">Tickets2Tech</div>
       </div>
      </div>
      <div class="clsDashMap_sumSlideContent">put here content</div>
     </div>
      <div class="Dash_map_sumSlide slide_Alarme" style="width: 50%; float: right;border: 2px solid darkturquoise;">
      <div class="clsDashMap_sumSlideTitle" style="position: initial;">ACTION</div>
      <div class="clsDashMap_sumSlideSiteContentSummary">
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">Etat</div>
        <div class="green led">OK</div>
        <div class="red led">KO</div>
       </div>
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">alarme3Act</div>
       </div>
       <div class="clsDashMap_sumSlideContentBox">
        <div class="clsDashMap_sumSlideContentBoxTitle">Tickets3Act</div>
       </div>
      </div>
      <div class="clsDashMap_sumSlideContent">put here content</div>
     </div>
    </div></code>```

答: Instead of float: right; give left: 50%; to the second column

Title: split div into 2 columns doesn't work

Body:
Can you please help me, it took me so much time trying to fixe this problem.
i have 2 slider and i need to split each slide into 2 colums. The problem is that the second column which is float: right doesn't show in both sliders .
Here is a code pen that shows the problem codepen
thank you

Here is my structure:

    .Dash_map_wrapSlider {
 position: absolute;
 overflow: hidden;
 height: 100%;
 width: calc(100% - 3rem);
 bottom: calc(-80% + 10rem);
 left: 3rem;
 background: #fff;
 border: 1px solid;
 transition: 0.5s;
 z-index: 1;}

    .Dash_map_wrapSlider:hover{
 bottom: 0rem;
 transition: 0.5s;}

    .Dash_map_wrapSlider:hover{
 bottom: 0rem;
 transition: 0.5s;}

    .Dash_map_wrapSliderchoise {
 background: #3E474F;
 box-shadow: 0 .5em 1em #111;
 position: absolute;
 left: 0;
 bottom: 0;
 z-index: 900;
 width: 100%;
 height: 2rem;
 line-height: 2rem;
 text-align: center;
 vertical-align: middle;}

    .Dash_map_sumSlide {
 height: 100%;
 width: 100%;
 position: absolute;
 top: 0;
 left: 100%;
 z-index: 10;
 background-color: #fff;
 transition: left 0s .75s;}

    .clsDashMap_sumSlideInput {
 display: none;
 height: 11rem;}

    .clsDashMap_sumSlideTitle {
 position : absolute;
 top:0;
 width: 100%;
 height: 2rem;
 left: inherit;
 color: #fff;
 background-color: #73b9ff;
 text-align: center;
 font-weight: bold;
 font-size: 1.20rem;}

    .clsDashMap_sumSlideContentBoxTitle {
 font-weight: bold;
 color: #666;}

    .clsDashMap_sumSlideSiteContentSummary {
 position : absolute;
 top: 2rem;
 width: 100%;
 height: 16rem;
 color: #000000;
 background-color: aliceblue;
 text-align: center;}

    .clsDashMap_sumSlideContent {
 position: absolute;
 top: 20rem;
 margin: auto;
 width: 100%;
 color: #000000;}

    [id^="Dash"]:checked + .Dash_map_sumSlide {
 left: 0;
 z-index: 100;
 transition: left .65s ease-out;}

    .Dash_map_wrapSliderchoise label {
 color: #fff;
 cursor: pointer;
 display: inline-block;
 line-height: 2rem;
 font-size: 0.75rem;
 font-weight: bold;
 padding: 0 1em;}

    .clsDashMap_sumSlideContentBox {
 margin: auto;
 float: left;
    padding: 10px;
    text-align: center;}

     <input id="Dash_map_sumSlideSite" class="clsDashMap_sumSlideInput" type="radio" name="slides" checked>

SITE

Etat

OK

KO

AlarmesSite

        <canvas id="pieChartAlm" ></canvas>

TicketsSite

        <canvas id="pieChartTkt" ></canvas>

put here content

ALARME

Etat

OK

KO

ALARME1Alm

        <canvas id="pieChartAlm" ></canvas>

Tickets1Alm

        <canvas id="pieChartTkt" ></canvas>

put here content

     <input id="Dash_map_sumSlideAlarme" class="clsDashMap_sumSlideInput" type="radio" name="slides" checked>

TECHNICIEN

Etat

OK

KO

Alarmes2Tech

Tickets2Tech

put here content

ACTION

Etat

OK

KO

alarme3Act

Tickets3Act

put here content


问:
Can I loop on a method?
I am using a method to retrieve an enumerable and was wandering a silly thing : is it ok to loop on the method call? say I have a method getDocuments in a Document class that returns an IEnumerable, then can I do:

```<code>Document doc=new Document();
foreach(var item in doc.getDocuments())
{//Code here
}
</code>```

Or is it better to assign a variable to that result and loop on the variable?

答: It's ok to loop for a method result, it will be evaluated only once. So, it's not necessary to use a temporary variable.</p>

Title: Can I loop on a method?

Body:
I am using a method to retrieve an enumerable and was wandering a silly thing : is it ok to loop on the method call? say I have a method getDocuments in a Document class that returns an IEnumerable, then can I do:

Document doc=new Document();
foreach(var item in doc.getDocuments())
{//Code here
}

Or is it better to assign a variable to that result and loop on the variable?


问:
Certificate key usage inadequate for attempted operation. Error code: SEC_ERROR_INADEQUATE_KEY_USAGE
I am provided CA Signed Server certificate, chain certificate and private key. From those, I created keystore using open SSL and secured the web application (HTTPS configuration in server.xml). However, when I tried to access web application via browser(Firefox), it gives out below error.

Secure Connection Failed

Certificate key usage inadequate for attempted operation. Error code: SEC_ERROR_INADEQUATE_KEY_USAGE

Certificates were initially in ".crt" and I tried after converting them to ".cer" as well. Still, the error complains something about "Key Usage". I ran following command to check certificate key usage and screenshot is attached.

```<code>openssl x509 -in ServerCertificate.cer -text -noout
</code>```

Below is from Chain certificate;

Your help in resolving this issue is highly appreciated.
[PS: Before configuring CA signed certificates, I created self signed certs and that configuration worked with no issue]

答:
The issue with the key store was, I have imported intermediate CA certificates under different aliases. What I did was put all certificates of the chain in one certificate and executed below commands. This fixed my problem.</p>

```<code>openssl pkcs12 -export -name ALIAS -in "path to certificate bundle" -inkey "path to privkey" -out "keystore.p12"

keytool -importkeystore -srckeystore "keystore.p12" -srcstoretype pkcs12 -destkeystore "keystore.jks"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am provided CA Signed Server certificate, chain certificate and private key. From those, I created keystore using open SSL and secured the web application (HTTPS configuration in server.xml). However, when I tried to access web application via browser(Firefox), it gives out below error.

Secure Connection Failed

Certificate key usage inadequate for attempted operation. Error code: SEC_ERROR_INADEQUATE_KEY_USAGE

Certificates were initially in ".crt" and I tried after converting them to ".cer" as well. Still, the error complains something about "Key Usage". I ran following command to check certificate key usage and screenshot is attached.

openssl x509 -in ServerCertificate.cer -text -noout

Below is from Chain certificate;

Your help in resolving this issue is highly appreciated.
[PS: Before configuring CA signed certificates, I created self signed certs and that configuration worked with no issue]

Body:
The issue with the key store was, I have imported intermediate CA certificates under different aliases. What I did was put all certificates of the chain in one certificate and executed below commands. This fixed my problem.

openssl pkcs12 -export -name ALIAS -in "path to certificate bundle" -inkey "path to privkey" -out "keystore.p12"

keytool -importkeystore -srckeystore "keystore.p12" -srcstoretype pkcs12 -destkeystore "keystore.jks"


问:
TestComplete Out of memory issue
The problem we face when we try to run our automation script on for long hours is in between the execution we face with “Out of Memory” issue.This issue is bcoz GDI Object” leak happening due to which the RAM is becoming full and the tool is throwing the error.Is it possible to release these GDI objects through test complete script?</p>

答: Maybe you are having a lot of performance counters on your project and the memory consumption for long executions are weird. Try removing all of them and reexecuting your project. I hope this solves your problem.</p>

Title: TestComplete Out of memory issue


答:
The problem is that you are passing '.element' instead of $(this), this should works:

```<code>function eachEl(el) {
  var items = ["blue", "red", "yellow"];
  var item = items[Math.floor(Math.random() * items.length)];
  $(el).css({
    "color": item,
  });
}

$(".elements").each(function() {
  eachEl($(this));
});
</code>```

Title: How to set a random color for each group of elements looping through an array?

Body:
The problem is that you are passing '.element' instead of $(this), this should works:

function eachEl(el) {
  var items = ["blue", "red", "yellow"];
  var item = items[Math.floor(Math.random() * items.length)];
  $(el).css({
    "color": item,
  });
}

$(".elements").each(function() {
  eachEl($(this));
});


问:
pass a php variable in an anchor tag inside a php loop
I have a list of records on a table which look like this..

PHP/HTML CODE:

```<code><script src="js/jquery-3.2.1.js"></script>
<?php
while($resrecord=mysqli_fetch_array($resdata))
{  ?>
  <tr>
        <td> <?php echo $resrecord[0];?>  </td>
        <td> <?php echo $resrecord[2];?>  </td>
        <td> <?php echo $resrecord[3];?>   </td>
        <td> <a onclick="window.open('test.php?id='+'<?php echo $resrecord[0]; ?>','popup','width=600,height=600');">Tesing</a>  </td>
          //also checked with href of anchor tag
  </tr>
 <?php }   ?>
</code>```

Which means I can't access a php variable in javascript. I also tried these methods

```<code><script type="text/javascript">
  var x= '<?php echo $resrecord[0]; ?>';
  //OR
  var x= '<?php echo json_encode($resrecord[0]); ?>';
    //here x won't populate with above php variables
</script>
</code>```

I've also tested the above javascript methods on a simple PHP variable which didn't belong to any loop and still didn't work.

答:
[UPDATED] You can pass the value using attribute in a class, Try this one.

```<code><script src="js/jquery-3.2.1.js"></script>
<?php while($resrecord=mysqli_fetch_array($resdata))  {  ?>
    <tr>
         <td> <?php echo $resrecord[0];?>  </td>
         <td> <?php echo $resrecord[2];?>  </td>
         <td> <?php echo $resrecord[3];?>   </td>
         <td> <a class="getAllData" data-id="<?php echo $resrecord[0];?>">Tesing</a> </td>
         //also checked with href of anchor tag
    </tr>
<?php }   ?>
</code>```

Then use jquery function:

you do this.

```<code><script>
    $(window).ready(function(){
        $(".getAllData").on("click", function(){
            var id = $(this).data('id'); //get the current data-id you the row
            window.open('test.php?id='+id,'popup','width=600,height=600');
        });
    });
</script>
</code>```

This should do it.

Body:
I have a list of records on a table which look like this..

PHP/HTML CODE:

<?php
while($resrecord=mysqli_fetch_array($resdata))
{  ?>

         <?php echo $resrecord[0];?>
         <?php echo $resrecord[2];?>
         <?php echo $resrecord[3];?>
         <a onclick="window.open('test.php?id='+'<?php echo $resrecord[0]; ?>','popup','width=600,height=600');">Tesing
          //also checked with href of anchor tag

 <?php }   ?>

Which means I can't access a php variable in javascript. I also tried these methods

I've also tested the above javascript methods on a simple PHP variable which didn't belong to any loop and still didn't work.

Body:
[UPDATED] You can pass the value using attribute in a class, Try this one.

<script src="js/jquery-3.2.1.js"></script>
<?php while($resrecord=mysqli_fetch_array($resdata))  {  ?>
    <tr>
         <td> <?php echo $resrecord[0];?>  </td>
         <td> <?php echo $resrecord[2];?>  </td>
         <td> <?php echo $resrecord[3];?>   </td>
         <td> <a class="getAllData" data-id="<?php echo $resrecord[0];?>">Tesing</a> </td>
         //also checked with href of anchor tag
    </tr>
<?php }   ?>

Then use jquery function:

you do this.

<script>
    $(window).ready(function(){
        $(".getAllData").on("click", function(){
            var id = $(this).data('id'); //get the current data-id you the row
            window.open('test.php?id='+id,'popup','width=600,height=600');
        });
    });
</script>

This should do it.


问:
How to format rspec to show passing on default
How do I format rspec permanently to show passing test text.
Currently I have to type in : $ rspec spec --format documentation every time I run it.

I see that the documentation says to run the following for
 "You can also specify an output target (STDOUT by default) by appending a
filename to the argument:"

```<code>documentation:rspec.output.txt
</code>```

However, I do not know what it means by 'specify an output target (STDOUT by default)

I just want to see text on passing tests instead of green dots without having to type --format documentation every time...

答:
You need to create a .rspec file in the root of your project

```<code>* YOUR_PROJECT
** A_SPEC_FOLDER
** ANOTHER_SPEC_FOLDER
** Gemfile
** .rspec
** spec_helper.rb
</code>```

Then, you just have to add to your .rspec file

```<code>--format documentation
</code>```

and run your spec.

Body:
How do I format rspec permanently to show passing test text.
Currently I have to type in : $ rspec spec --format documentation every time I run it.

I see that the documentation says to run the following for
 "You can also specify an output target (STDOUT by default) by appending a
filename to the argument:"

documentation:rspec.output.txt

However, I do not know what it means by 'specify an output target (STDOUT by default)

I just want to see text on passing tests instead of green dots without having to type --format documentation every time...

Body:
You need to create a .rspec file in the root of your project

* YOUR_PROJECT
** A_SPEC_FOLDER
** ANOTHER_SPEC_FOLDER
** Gemfile
** .rspec
** spec_helper.rb

Then, you just have to add to your .rspec file

--format documentation

and run your spec.


问:
Castle-Windsor Fluent Interface: How to register all implementations of all interfaces?
I have two assemblies EDC2.DAL and EDC2 where EDC2.DaoInterfaces defines a bunch of interfaces for data access objects to objects in the EDC2.Domain namespace.  These are all implemented by classes in EDC2.DAL.

So to give an example:

```<code>Assembly EDC2
  Namespace EDC2.DaoInterfaces
    ICustomerDao
    IProductDao
Assembly EDC2.DAL
  Namespace EDC2.DAL
    CustomerDao : ICustomerDao
    ProductDao : IProductDao
</code>```

I would like to use Windsor's fluent interface to register all interfaces in EDC2.DaoInterfaces as being implemented by their corresponding implementors in EDC2.DAL.

Can anyone tell me how to do this?

答:
Found the solution here:</p>

```<code>AllTypes.Pick().FromAssemblyNamed("EDC2.DAL").If(x => !x.IsGenericType).WithService.FirstInterface()
</code>```

OwnerDisplayName: George Mauer

ContentLicense: CC BY-SA 2.5

Body:
I have two assemblies EDC2.DAL and EDC2 where EDC2.DaoInterfaces defines a bunch of interfaces for data access objects to objects in the EDC2.Domain namespace.  These are all implemented by classes in EDC2.DAL.

So to give an example:

Assembly EDC2
  Namespace EDC2.DaoInterfaces
    ICustomerDao
    IProductDao
Assembly EDC2.DAL
  Namespace EDC2.DAL
    CustomerDao : ICustomerDao
    ProductDao : IProductDao

I would like to use Windsor's fluent interface to register all interfaces in EDC2.DaoInterfaces as being implemented by their corresponding implementors in EDC2.DAL.

Can anyone tell me how to do this?

Body:
Found the solution here:

AllTypes.Pick().FromAssemblyNamed("EDC2.DAL").If(x => !x.IsGenericType).WithService.FirstInterface()


答:
The method call is evaluated once and the returned IEnumerable is then used by the loop.

In short, what you are doing is fine.

There is the potential for a small gotcha though. If an expression tree is returned as an IEnumerable, and while the foreach is executing, the underlying datastructure is edited, it will throw an exception

Title: Can I loop on a method?


问:
Draw LineChart separately using MPAndroidChart?
I am using MPAndroidChart Library to Display the LineChart .I am not Able to Distinctly Display the LineChart Seperately with TermWise.I have Used Same ArrayList i.e called allMarks to Store the information for all the Term.When i Clear the ArrayList then only the Specific Term Marks are plotted in the Chart, if ArrayList.Clear(); is not used then all the Marks are Displayed. How can each term marks be Seperately Displayed?

Dashboard

```<code>public class Dashboard extends Fragment {

    ListView listViewNotice, listviewpendingbills;
    String Navigation_URL = "http://192.168.100.5:84/api/academics/getNotices";
    String Navigation_URL_BIlls = "http://192.168.100.5:84/Api/financeApi/getAllFees";
    String Navigation_URL_CHART = "http://192.168.100.5:84/api/academics/getSingleStudentsMarks";
    String Navigation_URL_getExam = "http://192.168.100.5:84/api/academics/getExams";
    String Navigation_URL_getExamData = "http://192.168.100.5:84/api/academics/getStdMarksByTermStd";

    String access_token;
    String Notice, BillNumber, Status, AmountPaid, ReceiptIssueDate;
    String master_id;
    TextView pendingbills, NoNotice;
    LineChart chart;

    private static final String TAG = "Test";
    ArrayList<Entry> entries, entry;
    ArrayList<String> labels = new ArrayList<String>();
    LineDataSet set, set1;
    LineData data, data2;

    // ArrayList<LineData> xVals = new ArrayList<String>();

    ArrayList allExams;
    ArrayList getCourses;
    ArrayList getMarks;
    ArrayList getCourseID;
    ArrayList getExamDesc;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
        // getActivity().setTitle("St. Xavier's High School");
        setHasOptionsMenu(true);

        listViewNotice = (ListView) view.findViewById(R.id.list_student_notice_dashboard);
        listviewpendingbills = (ListView) view.findViewById(R.id.student_dashboard_pendingbills);
        pendingbills = (TextView) view.findViewById(R.id.textpendingbills);
        NoNotice = (TextView) view.findViewById(R.id.textnoticedashboard);
        //  lineChart = (BarChart) view.findViewById(R.id.chart1);
        chart = (LineChart) view.findViewById(R.id.chart1);

        SessionManagement session = new SessionManagement(getContext());
        session.checkLogin();
        access_token = session.getAccesstToken();
        master_id = session.getMasterId();
        makeJsonObjectRequestNotices();
        makeJsonObjectRequestBills();
        //  makeJsonObjectRequestGraph();

        makeJsonObjectMarksWithGraph();

        allExams = new ArrayList();
        getCourses = new ArrayList();
        getMarks = new ArrayList();
        getCourseID = new ArrayList();
        getExamDesc = new ArrayList();
        labels.add("Math");
        chart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(labels));
        chart.invalidate();

        return view;
    }

  String examDescription;
    private void makeJsonObjectMarksWithGraph() {

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        String URL1 = Navigation_URL_getExam;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL1,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {

                            JSONArray jArray = new JSONArray(response);
                            for (int i = 0; i < jArray.length(); i++) {
                                JSONObject jsonObject = jArray.getJSONObject(i);
                                String TermID = jsonObject.getString("TermID");
                                examDescription = jsonObject.getString("examDescription");
                                getTermID(TermID, examDescription);
                                allExams.add(TermID);
                                Log.d("Term ID", getTermID(TermID, examDescription));
                            }
                            Log.d("All Exam", String.valueOf(allExams.size()));
                            int j;
                            for (j = 0; j < allExams.size(); j++) {
                                String termID = (String) allExams.get(j);
                                getExamData(termID);
                            }

                            //Collections.sort(entries, new EntryXComparator());

                        } catch (JSONException e) {
                            Toast.makeText(getContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }
                    }
                }

                , new Response.ErrorListener()

        {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), error.toString(), LENGTH_LONG).show();
            }
        }
        )

        {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", "Bearer " + access_token);
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                return headers;
            }

      /*      @Override
            protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();

                map.put("id", master_id);
                //map.put("accessID", accessID);
                map.put("currentUser", master_id);
                return map;

            }   */
        };

        requestQueue.add(stringRequest);
    }

 public String TermID;
    public String Description;

    private String getTermID(String TermID, String Description) {
        this.TermID = TermID;
        this.Description = Description;
        return TermID;
    }

    private void getExamData(String TermID) {

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        String URL1 = Navigation_URL_getExamData + "?StdID=" + master_id + "&TermID=" + TermID;
        //String URL1 = Navigation_URL_CHART + "?StdID=" + master_id;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL1,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {

                            JSONArray jArray = new JSONArray(response);
                            if (jArray.length() != 0) {
                                for (int i = 0; i < jArray.length(); i++) {
                                    JSONObject jsonObject = jArray.getJSONObject(i);

                                    Log.d("JSON Object", String.valueOf(jsonObject));
                                    String CourseId = jsonObject.getString("CourseID");
                                    String CourseName = jsonObject.getString("CourseName");
                                    String examDescription = jsonObject.getString("examDescription");
                                    Float Marks = Float.valueOf(jsonObject.getString("Marks"));

                                    getMarks.add(Marks);
                                    getCourses.add(CourseName);
                                    getCourseID.add(CourseId);
                                    getExamDesc.add(examDescription);
                                    System.out.println("the Courses are" + getCourses);

                                }
                                Log.d("JSON Object", String.valueOf(getMarks));
                                plotGraph(getMarks);
                                //getMarks.clear();

                            }

                        } catch (JSONException e) {
                            Toast.makeText(getContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), error.toString(), LENGTH_LONG).show();
            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", "Bearer " + access_token);
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                return headers;
            }
        };

        requestQueue.add(stringRequest);
    }
  ArrayList<Entry> allMarks = new ArrayList<Entry>();

    private void plotGraph(ArrayList getMarks) {
        ArrayList<Entry> allMarks = new ArrayList<Entry>();
        System.out.println("GetMARKS" + getMarks.size());
        ArrayList<ILineDataSet> testDataSet = new ArrayList<>();
        // HashMap<ILineDataSet> map = new HashMap<String, String>();

        for (int k = 0; k < getMarks.size(); k++) {
          /*  allMarks.add(new Entry(k, (Float) getMarks.get(k)));
            set = new LineDataSet(allMarks, examDescription);
            data = new LineData(set);
            lines.add(data);

            chart.setData(data);

            set.setColor(Color.GREEN);
            set.setDrawFilled(true);
            set.setDrawValues(true);
            chart.notifyDataSetChanged();
            chart.invalidate();

            */

            allMarks.add(new Entry(k, (Float) getMarks.get(k)));
            LineDataSet set = new LineDataSet(allMarks, examDescription);
            // set different color for each set as your requirement
            testDataSet.add(set);
            chart.notifyDataSetChanged();
            chart.invalidate();
            //  allMarks.clear();

        }

        chart.setData(new LineData(testDataSet));
    }
}
</code>```

http://192.168.100.5:84/api/academics/getSingleStudentsMarks?StdID=0095

```<code>[
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 4027,
    "Marks": 45,
    "Sno": 2107,
    "StdID": 95,
    "TermID": 6022,
    "CourseName": "Arts",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "First Term",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 5034,
    "Marks": 90,
    "Sno": 2108,
    "StdID": 95,
    "TermID": 6022,
    "CourseName": "Math",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "First Term",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 5035,
    "Marks": 52,
    "Sno": 2109,
    "StdID": 95,
    "TermID": 6022,
    "CourseName": "English",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "First Term",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 6034,
    "Marks": 70,
    "Sno": 2110,
    "StdID": 95,
    "TermID": 6022,
    "CourseName": "hi",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "First Term",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 4027,
    "Marks": 50,
    "Sno": 4119,
    "StdID": 95,
    "TermID": 7024,
    "CourseName": "Arts",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "Second",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 5034,
    "Marks": 60,
    "Sno": 4120,
    "StdID": 95,
    "TermID": 7024,
    "CourseName": "Math",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "Second",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 5035,
    "Marks": 70,
    "Sno": 4121,
    "StdID": 95,
    "TermID": 7024,
    "CourseName": "English",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "Second",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 6034,
    "Marks": 80,
    "Sno": 4122,
    "StdID": 95,
    "TermID": 7024,
    "CourseName": "hi",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "Second",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 4027,
    "Marks": 10,
    "Sno": 4123,
    "StdID": 95,
    "TermID": 7025,
    "CourseName": "Arts",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "Third",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 5034,
    "Marks": 20,
    "Sno": 4124,
    "StdID": 95,
    "TermID": 7025,
    "CourseName": "Math",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "Third",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 5035,
    "Marks": 30,
    "Sno": 4125,
    "StdID": 95,
    "TermID": 7025,
    "CourseName": "English",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "Third",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 6034,
    "Marks": 90,
    "Sno": 4126,
    "StdID": 95,
    "TermID": 7025,
    "CourseName": "hi",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "Third",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 4027,
    "Marks": 80,
    "Sno": 4127,
    "StdID": 95,
    "TermID": 7026,
    "CourseName": "Arts",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "fourth term",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 5034,
    "Marks": 10,
    "Sno": 4128,
    "StdID": 95,
    "TermID": 7026,
    "CourseName": "Math",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "fourth term",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 5035,
    "Marks": 76,
    "Sno": 4129,
    "StdID": 95,
    "TermID": 7026,
    "CourseName": "English",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "fourth term",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 6034,
    "Marks": 93,
    "Sno": 4130,
    "StdID": 95,
    "TermID": 7026,
    "CourseName": "hi",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "fourth term",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  }
]
</code>```

I am currently getting all the term marks in the OneArray Called as AllMarks. Can't I plot the marks with Different Term with Different Color in Same Chart?

答:
Try this one. It will show your chart as a cubic shape not straight line.

```<code>dataset.setDrawFilled(true);
dataset.setDrawCubic(true);
dataset.setDrawValues(false);
</code>```

dataset is the object of LineDataSet.

Above code works with version compile 'com.github.PhilJay:MPAndroidChart:v2.1.6'

Body:
I am using MPAndroidChart Library to Display the LineChart .I am not Able to Distinctly Display the LineChart Seperately with TermWise.I have Used Same ArrayList i.e called allMarks to Store the information for all the Term.When i Clear the ArrayList then only the Specific Term Marks are plotted in the Chart, if ArrayList.Clear(); is not used then all the Marks are Displayed. How can each term marks be Seperately Displayed?

Dashboard

public class Dashboard extends Fragment {

    ListView listViewNotice, listviewpendingbills;
    String Navigation_URL = "http://192.168.100.5:84/api/academics/getNotices";
    String Navigation_URL_BIlls = "http://192.168.100.5:84/Api/financeApi/getAllFees";
    String Navigation_URL_CHART = "http://192.168.100.5:84/api/academics/getSingleStudentsMarks";
    String Navigation_URL_getExam = "http://192.168.100.5:84/api/academics/getExams";
    String Navigation_URL_getExamData = "http://192.168.100.5:84/api/academics/getStdMarksByTermStd";

    String access_token;
    String Notice, BillNumber, Status, AmountPaid, ReceiptIssueDate;
    String master_id;
    TextView pendingbills, NoNotice;
    LineChart chart;

    private static final String TAG = "Test";
    ArrayList<Entry> entries, entry;
    ArrayList<String> labels = new ArrayList<String>();
    LineDataSet set, set1;
    LineData data, data2;

    // ArrayList<LineData> xVals = new ArrayList<String>();

    ArrayList allExams;
    ArrayList getCourses;
    ArrayList getMarks;
    ArrayList getCourseID;
    ArrayList getExamDesc;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
        // getActivity().setTitle("St. Xavier's High School");
        setHasOptionsMenu(true);

        listViewNotice = (ListView) view.findViewById(R.id.list_student_notice_dashboard);
        listviewpendingbills = (ListView) view.findViewById(R.id.student_dashboard_pendingbills);
        pendingbills = (TextView) view.findViewById(R.id.textpendingbills);
        NoNotice = (TextView) view.findViewById(R.id.textnoticedashboard);
        //  lineChart = (BarChart) view.findViewById(R.id.chart1);
        chart = (LineChart) view.findViewById(R.id.chart1);

        SessionManagement session = new SessionManagement(getContext());
        session.checkLogin();
        access_token = session.getAccesstToken();
        master_id = session.getMasterId();
        makeJsonObjectRequestNotices();
        makeJsonObjectRequestBills();
        //  makeJsonObjectRequestGraph();

        makeJsonObjectMarksWithGraph();

        allExams = new ArrayList();
        getCourses = new ArrayList();
        getMarks = new ArrayList();
        getCourseID = new ArrayList();
        getExamDesc = new ArrayList();
        labels.add("Math");
        chart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(labels));
        chart.invalidate();

        return view;
    }

  String examDescription;
    private void makeJsonObjectMarksWithGraph() {

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        String URL1 = Navigation_URL_getExam;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL1,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {

                            JSONArray jArray = new JSONArray(response);
                            for (int i = 0; i < jArray.length(); i++) {
                                JSONObject jsonObject = jArray.getJSONObject(i);
                                String TermID = jsonObject.getString("TermID");
                                examDescription = jsonObject.getString("examDescription");
                                getTermID(TermID, examDescription);
                                allExams.add(TermID);
                                Log.d("Term ID", getTermID(TermID, examDescription));
                            }
                            Log.d("All Exam", String.valueOf(allExams.size()));
                            int j;
                            for (j = 0; j < allExams.size(); j++) {
                                String termID = (String) allExams.get(j);
                                getExamData(termID);
                            }

                            //Collections.sort(entries, new EntryXComparator());

                        } catch (JSONException e) {
                            Toast.makeText(getContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }
                    }
                }

                , new Response.ErrorListener()

        {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), error.toString(), LENGTH_LONG).show();
            }
        }
        )

        {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", "Bearer " + access_token);
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                return headers;
            }

      /*      @Override
            protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();

                map.put("id", master_id);
                //map.put("accessID", accessID);
                map.put("currentUser", master_id);
                return map;

            }   */
        };

        requestQueue.add(stringRequest);
    }

 public String TermID;
    public String Description;

    private String getTermID(String TermID, String Description) {
        this.TermID = TermID;
        this.Description = Description;
        return TermID;
    }

    private void getExamData(String TermID) {

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        String URL1 = Navigation_URL_getExamData + "?StdID=" + master_id + "&TermID=" + TermID;
        //String URL1 = Navigation_URL_CHART + "?StdID=" + master_id;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL1,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {

                            JSONArray jArray = new JSONArray(response);
                            if (jArray.length() != 0) {
                                for (int i = 0; i < jArray.length(); i++) {
                                    JSONObject jsonObject = jArray.getJSONObject(i);

                                    Log.d("JSON Object", String.valueOf(jsonObject));
                                    String CourseId = jsonObject.getString("CourseID");
                                    String CourseName = jsonObject.getString("CourseName");
                                    String examDescription = jsonObject.getString("examDescription");
                                    Float Marks = Float.valueOf(jsonObject.getString("Marks"));

                                    getMarks.add(Marks);
                                    getCourses.add(CourseName);
                                    getCourseID.add(CourseId);
                                    getExamDesc.add(examDescription);
                                    System.out.println("the Courses are" + getCourses);

                                }
                                Log.d("JSON Object", String.valueOf(getMarks));
                                plotGraph(getMarks);
                                //getMarks.clear();

                            }

                        } catch (JSONException e) {
                            Toast.makeText(getContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), error.toString(), LENGTH_LONG).show();
            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", "Bearer " + access_token);
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                return headers;
            }
        };

        requestQueue.add(stringRequest);
    }
  ArrayList<Entry> allMarks = new ArrayList<Entry>();

    private void plotGraph(ArrayList getMarks) {
        ArrayList<Entry> allMarks = new ArrayList<Entry>();
        System.out.println("GetMARKS" + getMarks.size());
        ArrayList<ILineDataSet> testDataSet = new ArrayList<>();
        // HashMap<ILineDataSet> map = new HashMap<String, String>();

        for (int k = 0; k < getMarks.size(); k++) {
          /*  allMarks.add(new Entry(k, (Float) getMarks.get(k)));
            set = new LineDataSet(allMarks, examDescription);
            data = new LineData(set);
            lines.add(data);

            chart.setData(data);

            set.setColor(Color.GREEN);
            set.setDrawFilled(true);
            set.setDrawValues(true);
            chart.notifyDataSetChanged();
            chart.invalidate();

            */

            allMarks.add(new Entry(k, (Float) getMarks.get(k)));
            LineDataSet set = new LineDataSet(allMarks, examDescription);
            // set different color for each set as your requirement
            testDataSet.add(set);
            chart.notifyDataSetChanged();
            chart.invalidate();
            //  allMarks.clear();

        }

        chart.setData(new LineData(testDataSet));
    }
}

http://192.168.100.5:84/api/academics/getSingleStudentsMarks?StdID=0095

[
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 4027,
    "Marks": 45,
    "Sno": 2107,
    "StdID": 95,
    "TermID": 6022,
    "CourseName": "Arts",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "First Term",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 5034,
    "Marks": 90,
    "Sno": 2108,
    "StdID": 95,
    "TermID": 6022,
    "CourseName": "Math",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "First Term",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 5035,
    "Marks": 52,
    "Sno": 2109,
    "StdID": 95,
    "TermID": 6022,
    "CourseName": "English",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "First Term",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 6034,
    "Marks": 70,
    "Sno": 2110,
    "StdID": 95,
    "TermID": 6022,
    "CourseName": "hi",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "First Term",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 4027,
    "Marks": 50,
    "Sno": 4119,
    "StdID": 95,
    "TermID": 7024,
    "CourseName": "Arts",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "Second",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 5034,
    "Marks": 60,
    "Sno": 4120,
    "StdID": 95,
    "TermID": 7024,
    "CourseName": "Math",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "Second",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 5035,
    "Marks": 70,
    "Sno": 4121,
    "StdID": 95,
    "TermID": 7024,
    "CourseName": "English",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "Second",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 6034,
    "Marks": 80,
    "Sno": 4122,
    "StdID": 95,
    "TermID": 7024,
    "CourseName": "hi",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "Second",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 4027,
    "Marks": 10,
    "Sno": 4123,
    "StdID": 95,
    "TermID": 7025,
    "CourseName": "Arts",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "Third",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 5034,
    "Marks": 20,
    "Sno": 4124,
    "StdID": 95,
    "TermID": 7025,
    "CourseName": "Math",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "Third",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 5035,
    "Marks": 30,
    "Sno": 4125,
    "StdID": 95,
    "TermID": 7025,
    "CourseName": "English",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "Third",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 6034,
    "Marks": 90,
    "Sno": 4126,
    "StdID": 95,
    "TermID": 7025,
    "CourseName": "hi",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "Third",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 4027,
    "Marks": 80,
    "Sno": 4127,
    "StdID": 95,
    "TermID": 7026,
    "CourseName": "Arts",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "fourth term",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 5034,
    "Marks": 10,
    "Sno": 4128,
    "StdID": 95,
    "TermID": 7026,
    "CourseName": "Math",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "fourth term",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 5035,
    "Marks": 76,
    "Sno": 4129,
    "StdID": 95,
    "TermID": 7026,
    "CourseName": "English",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "fourth term",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  },
  {
    "CLASSNO": "1",
    "CLASS_ID": 2021,
    "CourseID": 6034,
    "Marks": 93,
    "Sno": 4130,
    "StdID": 95,
    "TermID": 7026,
    "CourseName": "hi",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "fourth term",
    "type": "Terminal",
    "NAME": "Calvin Patterson"
  }
]

I am currently getting all the term marks in the OneArray Called as AllMarks. Can't I plot the marks with Different Term with Different Color in Same Chart?

Body:
Try this one. It will show your chart as a cubic shape not straight line.

dataset.setDrawFilled(true);
dataset.setDrawCubic(true);
dataset.setDrawValues(false);

dataset is the object of LineDataSet.

Above code works with version compile 'com.github.PhilJay:MPAndroidChart:v2.1.6'


问:
UserControl Invalidate() method. How to properly invalidate the child controls in a UserControl
I have created my UserControl class and everything works as it should. Just wondering what method Invalidate does. It actually does not invalidate controls in my class, and I have not found any effects when it is called. Could anyone explain what this method does in the UserControl classes.

答:
To make a UserControl Invalidate all nested controls you need to call a special overload of Invalidate(invalidateChildren):

```<code>yourUserControl.Invalidate(true);
</code>```

Invalidates a specific region of the control and causes a paint
  message to be sent to the control. Optionally, invalidates the child
  controls assigned to the control.

Note the remarks:

Remarks

Calling the Invalidate method does not force a synchronous paint; to
  force a synchronous paint, call the Update method after calling the
  Invalidate method. When this method is called with no parameters, the
  entire client area is added to the update region.

Update

If you want to call this from a thread other than the UI thread you need to use Invoke, maybe like this:

```<code>public delegate void InvalidateUC();
public InvalidateUC myInvalidateDelegate;

public void InvalidateMethod()
{
    yourUserControl1.Invalidate(true);
}
</code>```

Now, after doing

```<code>myInvalidateDelegate = new InvalidateUC(InvalidateMethod);
</code>```

You can call this from the other thread

```<code>yourForm.yourUserControl1.Invoke(myInvalidateDelegate);
</code>```

note that if you are not quite sure whether the call actually  comes from a non-ui thread you can (and should) add the condition

```<code>if (yourForm.yourUserControl1.InvokeRequired)..
</code>```

Body:
To make a UserControl Invalidate all nested controls you need to call a special overload of Invalidate(invalidateChildren):

yourUserControl.Invalidate(true);

Invalidates a specific region of the control and causes a paint
  message to be sent to the control. Optionally, invalidates the child
  controls assigned to the control.

Note the remarks:

Remarks

Calling the Invalidate method does not force a synchronous paint; to
  force a synchronous paint, call the Update method after calling the
  Invalidate method. When this method is called with no parameters, the
  entire client area is added to the update region.

Update

If you want to call this from a thread other than the UI thread you need to use Invoke, maybe like this:

public delegate void InvalidateUC();
public InvalidateUC myInvalidateDelegate;

public void InvalidateMethod()
{
    yourUserControl1.Invalidate(true);
}

Now, after doing

myInvalidateDelegate = new InvalidateUC(InvalidateMethod);

You can call this from the other thread

yourForm.yourUserControl1.Invoke(myInvalidateDelegate);

note that if you are not quite sure whether the call actually  comes from a non-ui thread you can (and should) add the condition

if (yourForm.yourUserControl1.InvokeRequired)..


问:
Mock Ajax (Reactjs + Mobx)
I want to make some fake my ajax calls so when on localhost I can bring back dummy data from a fake method instead of doing real calls to my server(where the structure might not exist).

What is the best way to do this in reactjs + mobx?

I was thinking of making a fake store as this is where all my actions are with my ajax calls but that would involve always making the entire store with all functions.

I then though of maybe extracting out the ajax calls from the store and then mockup those calls but I am not sure the best way to do that.

答:
Use json-server for faking api calls and redux for state management, I have used this in one of my projects. It is quite simple and requires very less boilerplate code. Redux updates a global store through actions and components can subscribe to store for changes.

See documentation here-

https://github.com/typicode/json-server

http://redux.js.org/

Example from my app-
You can make a fake store by creating a db.json and then you can use either default routes provided by json-sever or create your own.

This can be your db.json

```<code>{
    "questions": [
        {
            "id": 2,
            "question": "A train running at the speed of 60 km/hr crosses a pole in 9 seconds. What is the length of the train?",
            "options": [
                "120 metres",
                "180 metres",
                "324 metres",
                "150 metres"
            ],
            "answer": 4
        },
        {
            "id": 3,
            "question": "The length of the bridge, which a train 130 metres long and travelling at 45 km/hr can cross in 30 seconds, is",
            "options": [
                "200 m",
                "225 m",
                "245 m",
                "250 m"
            ],
            "answer": 3
        }
    ]
}
</code>```

start this mock api by running this json-server --watch db.json in your folder with db.json file.

Then use http://localhost:3000/questions

Comment if you want more detailed information on any of stuff mentioned above. I can provide you sample code as I have implemented this full flow.

Title: Mock Ajax (Reactjs + Mobx)

Body:
Use json-server for faking api calls and redux for state management, I have used this in one of my projects. It is quite simple and requires very less boilerplate code. Redux updates a global store through actions and components can subscribe to store for changes.

See documentation here-

https://github.com/typicode/json-server

http://redux.js.org/

Example from my app-
You can make a fake store by creating a db.json and then you can use either default routes provided by json-sever or create your own.

This can be your db.json

{
    "questions": [
        {
            "id": 2,
            "question": "A train running at the speed of 60 km/hr crosses a pole in 9 seconds. What is the length of the train?",
            "options": [
                "120 metres",
                "180 metres",
                "324 metres",
                "150 metres"
            ],
            "answer": 4
        },
        {
            "id": 3,
            "question": "The length of the bridge, which a train 130 metres long and travelling at 45 km/hr can cross in 30 seconds, is",
            "options": [
                "200 m",
                "225 m",
                "245 m",
                "250 m"
            ],
            "answer": 3
        }
    ]
}

start this mock api by running this json-server --watch db.json in your folder with db.json file.

Then use http://localhost:3000/questions

Comment if you want more detailed information on any of stuff mentioned above. I can provide you sample code as I have implemented this full flow.


问:
Copy selected data from one worksheet to another with Excel VBA
I am trying to copy selected data from one worksheet to another with Excel VBA. As you can see in my pictures when the value is a 0, the value of the test_Point should be written in another worksheet. So I want to copy the test_Point value of each cell where the value is 0.

Source data on Sheet1:

Expected result to be put on Sheet2:

答:
Try this:</p>

```<code>Sub Demo()
    Dim srcWS As Worksheet, destWS As Worksheet
    Dim lastRow As Long, i As Long, rowIndex As Long
    Dim rng As Range

    'change sheet names as required
    Set srcWS = ThisWorkbook.Worksheets("Sheet1")
    Set destWS = ThisWorkbook.Worksheets("Sheet2")
    lastRow = srcWS.Cells(Rows.Count, "A").End(xlUp).Row
    rowIndex = 1

    With srcWS
        For Each rng In .Range("B2:B" & lastRow)
            If rng.Value = 0 Then
                destWS.Range("A" & rowIndex).Value = rng.Offset(0, -1).Value
                rowIndex = rowIndex + 1
            End If
        Next rng
    End With
End Sub
</code>```

Body:
Try this:

Sub Demo()
    Dim srcWS As Worksheet, destWS As Worksheet
    Dim lastRow As Long, i As Long, rowIndex As Long
    Dim rng As Range

    'change sheet names as required
    Set srcWS = ThisWorkbook.Worksheets("Sheet1")
    Set destWS = ThisWorkbook.Worksheets("Sheet2")
    lastRow = srcWS.Cells(Rows.Count, "A").End(xlUp).Row
    rowIndex = 1

    With srcWS
        For Each rng In .Range("B2:B" & lastRow)
            If rng.Value = 0 Then
                destWS.Range("A" & rowIndex).Value = rng.Offset(0, -1).Value
                rowIndex = rowIndex + 1
            End If
        Next rng
    End With
End Sub


问:
Expected condition failed: waiting for visibility of element located by By.xpath
I am trying to click on Sign in link on site alibaba.com

This is my test case:

```<code>public class TestCase {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        String URL = "http://www.alibaba.com/";
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver",
                "D:\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get(URL);
        Thread.sleep(2000);
        SignIn.SignIn_click(driver).click();
    }

}
</code>```

This is object class where in am locating the web element

```<code>package PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SignIn {

    private static WebElement element = null;

    public static WebElement SignIn_click(WebDriver driver) {
        element = (new WebDriverWait(driver, 10)).until(ExpectedConditions
                .visibilityOfElementLocated(By
                        .xpath("//a[@data-val='ma_signin']")));
        element = driver.findElement(By
                .xpath("//a[@data-val='ma_signin']"));
        return element;

    }

}
</code>```

But when I run this code , I'm always getting this exception:

```<code>Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.xpath: //a[@data-val='ma_signin'] (tried for 10 second(s) with 500 MILLISECONDS interval)
    Build info: version: 'unknown', revision: '86a5d70', time: '2017-02-16 07:47:51 -0800'
    System info: host: 'ANUM-PC', ip: '172.16.11.162', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_121'
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41), userDataDir=C:\Users\Anum\AppData\Local\Temp\scoped_dir1716_14873}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=59.0.3071.115, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
    Session ID: d0c1083c113270bd4ded08846544878e
        at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:80)
        at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:257)
        at PageObjects.SignIn.SignIn_click(SignIn.java:15)
        at AutomationFramework.TestCase.main(TestCase.java:24)
</code>```

Please help me on this.

答:
Please try this following:</p>

```<code>package PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SignIn {

    private static WebElement element = null;
    public static WebElement SignIn_click(WebDriver driver) throws InterruptedException {
    element = driver.findElement(By.xpath("id('J_SC_header')/header/div[2]//span[1]/a[@data-val='ma_signin']"));

    while (!isDisplayed(element))
    {
        Thread.sleep(3000);
        System.out.println("Element is not visible yet");
    }
    return element;

    }
    public static boolean isDisplayed(WebElement element) {
        try {
            if(element.isDisplayed())
                return element.isDisplayed();
            }catch (NoSuchElementException ex) {
            return false;
        }
        return false;
    }
}
</code>```

Body:
I am trying to click on Sign in link on site alibaba.com

This is my test case:

public class TestCase {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        String URL = "http://www.alibaba.com/";
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver",
                "D:\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get(URL);
        Thread.sleep(2000);
        SignIn.SignIn_click(driver).click();
    }

}

This is object class where in am locating the web element

package PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SignIn {

    private static WebElement element = null;

    public static WebElement SignIn_click(WebDriver driver) {
        element = (new WebDriverWait(driver, 10)).until(ExpectedConditions
                .visibilityOfElementLocated(By
                        .xpath("//a[@data-val='ma_signin']")));
        element = driver.findElement(By
                .xpath("//a[@data-val='ma_signin']"));
        return element;

    }

}

But when I run this code , I'm always getting this exception:

Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.xpath: //a[@data-val='ma_signin'] (tried for 10 second(s) with 500 MILLISECONDS interval)
    Build info: version: 'unknown', revision: '86a5d70', time: '2017-02-16 07:47:51 -0800'
    System info: host: 'ANUM-PC', ip: '172.16.11.162', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_121'
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41), userDataDir=C:\Users\Anum\AppData\Local\Temp\scoped_dir1716_14873}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=59.0.3071.115, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
    Session ID: d0c1083c113270bd4ded08846544878e
        at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:80)
        at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:257)
        at PageObjects.SignIn.SignIn_click(SignIn.java:15)
        at AutomationFramework.TestCase.main(TestCase.java:24)

Please help me on this.

Body:
Please try this following:

package PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SignIn {

    private static WebElement element = null;
    public static WebElement SignIn_click(WebDriver driver) throws InterruptedException {
    element = driver.findElement(By.xpath("id('J_SC_header')/header/div[2]//span[1]/a[@data-val='ma_signin']"));

    while (!isDisplayed(element))
    {
        Thread.sleep(3000);
        System.out.println("Element is not visible yet");
    }
    return element;

    }
    public static boolean isDisplayed(WebElement element) {
        try {
            if(element.isDisplayed())
                return element.isDisplayed();
            }catch (NoSuchElementException ex) {
            return false;
        }
        return false;
    }
}


问:
angularjs ng-pattern for 2 languages
I want to use ng-pattern for 2 sets of languages, for example english and hebrew, all my tries just don't work:

```<code>vm.uNamePattern = "/^[a-zA-Z\s]|[א-ת]*$/";
vm.uNamePattern = "/^[a-zA-Zא-ת\s]*$/";
</code>```

Here is a ref to only hebrew question - hebrew-only.

Thanks.

答:
```<code>vm.uNamePattern = "/^[a-zA-Zא-ת\s]*$/";
</code>```

should be

```<code>vm.uNamePattern = /^[a-zA-Zא-ת\s]*$/;
</code>```

You want a Regexp, not a string.

Demo

Title: angularjs ng-pattern for 2 languages

Body:
I want to use ng-pattern for 2 sets of languages, for example english and hebrew, all my tries just don't work:

vm.uNamePattern = "/^[a-zA-Z\s]|[א-ת]*$/";
vm.uNamePattern = "/^[a-zA-Zא-ת\s]*$/";

Here is a ref to only hebrew question - hebrew-only.

Thanks.

Body:
vm.uNamePattern = "/^[a-zA-Zא-ת\s]*$/";

should be

vm.uNamePattern = /^[a-zA-Zא-ת\s]*$/;

You want a Regexp, not a string.

Demo


问:
Angular 4 - how to trigger an animation when a div comes into the viewport?
I've been building a new site using Angular 4 and i'm trying to re-create a effect where when a div becomes visible (when you scroll down the screen) then that can then trigger a angular animation to slide the div in form the sides.

I've been able to do this in the past using jQuery outside of Angular 4 but i want to try and create the same effect using native Angular 4 animations.

Can anyone offer me advice on how to trigger an animation when a div comes into view (i.e. scrolled down to lower part of the page as it enters the viewport?). I have written the slide animations already but i don't know how to trigger that with a scroll when a div becomes visible at a later date to the view port.

Thanks everyone!

答:
I've created a base component that provides a flag appearedOnce, which turns true once if the component is either completely within view or it's upper edge has reached view's upper edge.

```<code>@Injectable()
export class AppearOnce implements AfterViewInit, OnDestroy {
  appearedOnce: boolean;

  elementPos: number;
  elementHeight: number;

  scrollPos: number;
  windowHeight: number;

  subscriptionScroll: Subscription;
  subscriptionResize: Subscription;

  constructor(private element: ElementRef, private cdRef: ChangeDetectorRef){}
  onResize() {
    this.elementPos = this.getOffsetTop(this.element.nativeElement);
    this.elementHeight = this.element.nativeElement.clientHeight;
    this.checkVisibility();
  }
  onScroll() {
    this.scrollPos = window.scrollY;
    this.windowHeight = window.innerHeight;
    this.checkVisibility();
  }
  getOffsetTop(element: any){
    let offsetTop = element.offsetTop || 0;
    if(element.offsetParent){
      offsetTop += this.getOffsetTop(element.offsetParent);
    }
    return offsetTop;
  }

  checkVisibility(){
    if(!this.appearedOnce){
      if(this.scrollPos >= this.elementPos || (this.scrollPos + this.windowHeight) >= (this.elementPos + this.elementHeight)){
        this.appearedOnce = true;
        this.unsubscribe();
        this.cdRef.detectChanges();
      }
    }
  }

  subscribe(){
    this.subscriptionScroll = Observable.fromEvent(window, 'scroll').startWith(null)
      .subscribe(() => this.onScroll());
    this.subscriptionResize = Observable.fromEvent(window, 'resize').startWith(null)
      .subscribe(() => this.onResize());
  }
  unsubscribe(){
    if(this.subscriptionScroll){
      this.subscriptionScroll.unsubscribe();
    }
    if(this.subscriptionResize){
      this.subscriptionResize.unsubscribe();
    }
  }

  ngAfterViewInit(){
    this.subscribe();
  }
  ngOnDestroy(){
    this.unsubscribe();
  }
}
</code>```

You can simply extend this component and make use of the appearedOnce property by inheritance

```<code>@Component({
  template: `
    <div>
      <div *ngIf="appearedOnce">...</div>
      ...
    </div>
  `
})
class MyComponent extends AppearOnceComponent {
    ...
}
</code>```

Keep in mind to call super() if you need to overwrite constructor or lifecyclehooks.

(edit) plunker:
https://embed.plnkr.co/yIpA1mI1b9kVoEXGy6Hh/

(edit) i've turned this into a directive in another answer below.

Body:
I've created a base component that provides a flag appearedOnce, which turns true once if the component is either completely within view or it's upper edge has reached view's upper edge.

@Injectable()
export class AppearOnce implements AfterViewInit, OnDestroy {
  appearedOnce: boolean;

  elementPos: number;
  elementHeight: number;

  scrollPos: number;
  windowHeight: number;

  subscriptionScroll: Subscription;
  subscriptionResize: Subscription;

  constructor(private element: ElementRef, private cdRef: ChangeDetectorRef){}
  onResize() {
    this.elementPos = this.getOffsetTop(this.element.nativeElement);
    this.elementHeight = this.element.nativeElement.clientHeight;
    this.checkVisibility();
  }
  onScroll() {
    this.scrollPos = window.scrollY;
    this.windowHeight = window.innerHeight;
    this.checkVisibility();
  }
  getOffsetTop(element: any){
    let offsetTop = element.offsetTop || 0;
    if(element.offsetParent){
      offsetTop += this.getOffsetTop(element.offsetParent);
    }
    return offsetTop;
  }

  checkVisibility(){
    if(!this.appearedOnce){
      if(this.scrollPos >= this.elementPos || (this.scrollPos + this.windowHeight) >= (this.elementPos + this.elementHeight)){
        this.appearedOnce = true;
        this.unsubscribe();
        this.cdRef.detectChanges();
      }
    }
  }

  subscribe(){
    this.subscriptionScroll = Observable.fromEvent(window, 'scroll').startWith(null)
      .subscribe(() => this.onScroll());
    this.subscriptionResize = Observable.fromEvent(window, 'resize').startWith(null)
      .subscribe(() => this.onResize());
  }
  unsubscribe(){
    if(this.subscriptionScroll){
      this.subscriptionScroll.unsubscribe();
    }
    if(this.subscriptionResize){
      this.subscriptionResize.unsubscribe();
    }
  }

  ngAfterViewInit(){
    this.subscribe();
  }
  ngOnDestroy(){
    this.unsubscribe();
  }
}

You can simply extend this component and make use of the appearedOnce property by inheritance

@Component({
  template: `
    <div>
      <div *ngIf="appearedOnce">...</div>
      ...
    </div>
  `
})
class MyComponent extends AppearOnceComponent {
    ...
}

Keep in mind to call super() if you need to overwrite constructor or lifecyclehooks.

(edit) plunker:
https://embed.plnkr.co/yIpA1mI1b9kVoEXGy6Hh/

(edit) i've turned this into a directive in another answer below.


问:
Groovy-JSONSlurper: Transform JSON map into a key=value pair
I have a JSON object, which we assume to be flat (no nesting) and a map. How can I transform this into a single string of key=value pairs, delimited by tab using JSONSlurper in Groovy?</p>

答:
<pre class="lang-js prettyprint-override"><code>//parse json-string to map
def json = new groovy.json.JsonSlurper().parseText('{"a":"1","B":"22"}')
//convert map to array of `key=value` strings
//and then join into one with new line delimiter
String txt = json.collect{"${it.key}=${it.value}"}.join('\n')
</code>```


问:
How to get a query error from prepare() in PDO PHP?
```<code>    $st = $db->prepare("SELECT * FROM c6ode");
</code>```

How can I check the intentional mysql error for the query in above case?

答:
/* Provoke an error -- the BONES table does not exist */

```<code>$sth = $dbh->prepare('SELECT skull FROM bones');
$sth->execute();

echo "\nPDOStatement::errorInfo():\n";
$arr = $sth->errorInfo();
print_r($arr);
</code>```

output

```<code>Array
(
    [0] => 42S02
    [1] => -204
    [2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N  "DANIELS.BONES" is an undefined name.  SQLSTATE=42704
)
</code>```

Body:
    $st = $db->prepare("SELECT * FROM c6ode");

How can I check the intentional mysql error for the query in above case?

Body:
/* Provoke an error -- the BONES table does not exist */

$sth = $dbh->prepare('SELECT skull FROM bones');
$sth->execute();

echo "\nPDOStatement::errorInfo():\n";
$arr = $sth->errorInfo();
print_r($arr);

output

Array
(
    [0] => 42S02
    [1] => -204
    [2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N  "DANIELS.BONES" is an undefined name.  SQLSTATE=42704
)


问:
How to add multiple terminals in VS Code?
Can we add multiple different terminals in the VS Code? I am planning to add following three terminal and work with all of those :

Windows Command prompt

PowerShell

Git Bash

I know I need to add the following command in Preferences => Setting

```<code> // // 64-bit cmd if available, otherwise 32-bit
 "terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\cmd.exe",
// // 64-bit PowerShell if available, otherwise 32-bit
 "terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\WindowsPowerShell\\v1.0\\powershell.exe",
// // Git Bash
 "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe",
</code>```

I want to add all of the above three commands in setting.json

And when I click + different terminal should open and I want to work with those terminals without changing the preferences.
Is it possible in VS Code or not?

答:
This can be done by adding a different key at the end. By just changing your example to:

```<code>// // 64-bit cmd if available, otherwise 32-bit
 "terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\cmd.exe",
// // 64-bit PowerShell if available, otherwise 32-bit
 "terminal.integrated.shell.windows2": "C:\\Windows\\sysnative\\WindowsPowerShell\\v1.0\\powershell.exe",
// // Git Bash
 "terminal.integrated.shell.windows3": "C:\\Program Files\\Git\\bin\\bash.exe",
</code>```

Note that the key ...shell.windows is changed to ...shell.windows2 and ...shell.windows3.

Follow-up finding: I've noticed that once restart of the IDE, only the first terminal gets displayed. I had to reopen the settings and save it once to get both the terminals again. Will post if any better solution available.

Body:
Can we add multiple different terminals in the VS Code? I am planning to add following three terminal and work with all of those :

Windows Command prompt

PowerShell

Git Bash

I know I need to add the following command in Preferences => Setting

 // // 64-bit cmd if available, otherwise 32-bit
 "terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\cmd.exe",
// // 64-bit PowerShell if available, otherwise 32-bit
 "terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\WindowsPowerShell\\v1.0\\powershell.exe",
// // Git Bash
 "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe",

I want to add all of the above three commands in setting.json

And when I click + different terminal should open and I want to work with those terminals without changing the preferences.
Is it possible in VS Code or not?

Body:
This can be done by adding a different key at the end. By just changing your example to:

// // 64-bit cmd if available, otherwise 32-bit
 "terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\cmd.exe",
// // 64-bit PowerShell if available, otherwise 32-bit
 "terminal.integrated.shell.windows2": "C:\\Windows\\sysnative\\WindowsPowerShell\\v1.0\\powershell.exe",
// // Git Bash
 "terminal.integrated.shell.windows3": "C:\\Program Files\\Git\\bin\\bash.exe",

Note that the key ...shell.windows is changed to ...shell.windows2 and ...shell.windows3.

Follow-up finding: I've noticed that once restart of the IDE, only the first terminal gets displayed. I had to reopen the settings and save it once to get both the terminals again. Will post if any better solution available.


问:
Python MySQLdb script works correctly on OS X, permission denied error when copied to a linux server
I wrote a quick python script to automate setting up wordpress blogs for friends. I've tested the script with no problems on my OS X computer, but when the script is copy pasted to a linux server and ran, the script is able to create the database, but when it tries to create the user and grant privileges to it I receive

```<code>"_mysql_exceptions.OperationalError: (1044, "Access denied for user
'root'@'XXX.XXX.XXX.XXX' to database 'livetest'")"
</code>```

the script is:

```<code>db = MySQLdb.connect(host="ip",  # your host
                    user="root",       # username
                    passwd="password")
                         # password

# Create a Cursor object to execute queries.
cur = db.cursor()

# Select data from table using SQL query.

cur.execute("CREATE DATABASE IF NOT EXISTS " +blogshortstr)

cur.execute("GRANT ALL PRIVILEGES on " +blogshortstr +".*" + " " + "TO " +mysqluser+'@'+'ip'+ " " +'IDENTIFIED BY' + " " +mysqlpassword)

cur.execute("FLUSH PRIVILEGES")

db.commit()
db.close()
</code>```

答:
Eventually figured out the problem by accident thanks to another post I found thanks to a typo.

The problem turned out to be twofold.

1) When I enabled remote login it added a second root account. While the root@localhost user had the grant option, my root@ip.addr didn't. The root@ip.addr could still create and delete tables. Adding the grant option made it work.

2) At least with this code and the python module I was using (MySQLdb) nowhere is it documented in the module's documentation that the username is required to be in backticks (the key next to the 1 on QWERTY keyboard) and not regular quotes when doing GRANT ALL PRIVILEGES. I don't know why or if this is a normal thing for MySQL connectors in any language.

maybe it's obvious and I'm an idiot (this is the first thing I ever worked on in python and I've almost never used MySQL). maybe it'll help someone.

Body:
I wrote a quick python script to automate setting up wordpress blogs for friends. I've tested the script with no problems on my OS X computer, but when the script is copy pasted to a linux server and ran, the script is able to create the database, but when it tries to create the user and grant privileges to it I receive

"_mysql_exceptions.OperationalError: (1044, "Access denied for user
'root'@'XXX.XXX.XXX.XXX' to database 'livetest'")"

the script is:

db = MySQLdb.connect(host="ip",  # your host
                    user="root",       # username
                    passwd="password")
                         # password

# Create a Cursor object to execute queries.
cur = db.cursor()

# Select data from table using SQL query.

cur.execute("CREATE DATABASE IF NOT EXISTS " +blogshortstr)

cur.execute("GRANT ALL PRIVILEGES on " +blogshortstr +".*" + " " + "TO " +mysqluser+'@'+'ip'+ " " +'IDENTIFIED BY' + " " +mysqlpassword)

cur.execute("FLUSH PRIVILEGES")

db.commit()
db.close()


问:
Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable
I have a script using java to connect to display X11 in the port 10.0 at localhost

but i get always this error

```<code>java.lang.InternalError: Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable.
    at sun.awt.X11GraphicsEnvironment.initDisplay(Native Method)
    at sun.awt.X11GraphicsEnvironment.access$200(X11GraphicsEnvironment.java:62)
    at sun.awt.X11GraphicsEnvironment$1.run(X11GraphicsEnvironment.java:178)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.awt.X11GraphicsEnvironment.<clinit>(X11GraphicsEnvironment.java:142)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:186)
    at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:82)
    at sun.awt.X11.XToolkit.<clinit>(XToolkit.java:112)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:186)
    at java.awt.Toolkit$2.run(Toolkit.java:849)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.Toolkit.getDefaultToolkit(Toolkit.java:841)
    at ij.io.Opener.openJpegOrGif(Opener.java:367)
    at ij.io.Opener.openImage(Opener.java:220)
    at ij.io.Opener.openImage(Opener.java:249)
    at ij.io.Opener.open(Opener.java:116)
    at ij.IJ.open(IJ.java:1112)
    at ij.macro.Functions.open(Functions.java:2006)
    at ij.macro.Functions.doFunction(Functions.java:129)
    at ij.macro.Interpreter.doStatement(Interpreter.java:205)
    at ij.macro.Interpreter.doBlock(Interpreter.java:515)
    at ij.macro.Interpreter.runUserFunction(Interpreter.java:278)
    at ij.macro.Interpreter.getFactor(Interpreter.java:1200)
    at ij.macro.Interpreter.getTerm(Interpreter.java:1162)
    at ij.macro.Interpreter.getExpression(Interpreter.java:1145)
    at ij.macro.Interpreter.getBooleanExpression(Interpreter.java:881)
    at ij.macro.Interpreter.getLogicalExpression(Interpreter.java:857)
    at ij.macro.Interpreter.getBoolean(Interpreter.java:850)
    at ij.macro.Interpreter.doIf(Interpreter.java:829)
    at ij.macro.Interpreter.doStatement(Interpreter.java:217)
    at ij.macro.Interpreter.doBlock(Interpreter.java:515)
    at ij.macro.Interpreter.doStatement(Interpreter.java:241)
    at ij.macro.Interpreter.doIf(Interpreter.java:831)
    at ij.macro.Interpreter.doStatement(Interpreter.java:217)
    at ij.macro.Interpreter.doStatements(Interpreter.java:195)
    at ij.macro.Interpreter.run(Interpreter.java:99)
    at ij.macro.Interpreter.run(Interpreter.java:65)
    at ij.macro.Interpreter.run(Interpreter.java:75)
    at ij.plugin.Macro_Runner.runMacro(Macro_Runner.java:127)
    at ij.plugin.Macro_Runner.runMacroFile(Macro_Runner.java:112)
    at ij.IJ.runMacroFile(IJ.java:103)
    at ij.ImageJ.main(ImageJ.java:517)
</code>```

I have tried everything to solve this problem like :

```<code>export DISPLAY=:10.0
export DISPLAY=localhost:10.0
</code>```

I tried also the port 0.0 but i get always the same error

after trying xhost

```<code>xhost +local:all
xhost:  unable to open display ""
xhost:  unable to open display ":10.0"
</code>```

how can i fix this
i thought that the X Server is not runing so i tried startx its says its runing at that port

my system is Ubuntu server edition 10.04

答: I think you are working in sudo mode.Please checkout to the user mode and try again</p>

Body:
I have a script using java to connect to display X11 in the port 10.0 at localhost

but i get always this error

java.lang.InternalError: Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable.
    at sun.awt.X11GraphicsEnvironment.initDisplay(Native Method)
    at sun.awt.X11GraphicsEnvironment.access$200(X11GraphicsEnvironment.java:62)
    at sun.awt.X11GraphicsEnvironment$1.run(X11GraphicsEnvironment.java:178)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.awt.X11GraphicsEnvironment.<clinit>(X11GraphicsEnvironment.java:142)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:186)
    at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:82)
    at sun.awt.X11.XToolkit.<clinit>(XToolkit.java:112)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:186)
    at java.awt.Toolkit$2.run(Toolkit.java:849)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.Toolkit.getDefaultToolkit(Toolkit.java:841)
    at ij.io.Opener.openJpegOrGif(Opener.java:367)
    at ij.io.Opener.openImage(Opener.java:220)
    at ij.io.Opener.openImage(Opener.java:249)
    at ij.io.Opener.open(Opener.java:116)
    at ij.IJ.open(IJ.java:1112)
    at ij.macro.Functions.open(Functions.java:2006)
    at ij.macro.Functions.doFunction(Functions.java:129)
    at ij.macro.Interpreter.doStatement(Interpreter.java:205)
    at ij.macro.Interpreter.doBlock(Interpreter.java:515)
    at ij.macro.Interpreter.runUserFunction(Interpreter.java:278)
    at ij.macro.Interpreter.getFactor(Interpreter.java:1200)
    at ij.macro.Interpreter.getTerm(Interpreter.java:1162)
    at ij.macro.Interpreter.getExpression(Interpreter.java:1145)
    at ij.macro.Interpreter.getBooleanExpression(Interpreter.java:881)
    at ij.macro.Interpreter.getLogicalExpression(Interpreter.java:857)
    at ij.macro.Interpreter.getBoolean(Interpreter.java:850)
    at ij.macro.Interpreter.doIf(Interpreter.java:829)
    at ij.macro.Interpreter.doStatement(Interpreter.java:217)
    at ij.macro.Interpreter.doBlock(Interpreter.java:515)
    at ij.macro.Interpreter.doStatement(Interpreter.java:241)
    at ij.macro.Interpreter.doIf(Interpreter.java:831)
    at ij.macro.Interpreter.doStatement(Interpreter.java:217)
    at ij.macro.Interpreter.doStatements(Interpreter.java:195)
    at ij.macro.Interpreter.run(Interpreter.java:99)
    at ij.macro.Interpreter.run(Interpreter.java:65)
    at ij.macro.Interpreter.run(Interpreter.java:75)
    at ij.plugin.Macro_Runner.runMacro(Macro_Runner.java:127)
    at ij.plugin.Macro_Runner.runMacroFile(Macro_Runner.java:112)
    at ij.IJ.runMacroFile(IJ.java:103)
    at ij.ImageJ.main(ImageJ.java:517)

I have tried everything to solve this problem like :

export DISPLAY=:10.0
export DISPLAY=localhost:10.0

I tried also the port 0.0 but i get always the same error

after trying xhost

xhost +local:all
xhost:  unable to open display ""
xhost:  unable to open display ":10.0"

how can i fix this
i thought that the X Server is not runing so i tried startx its says its runing at that port

my system is Ubuntu server edition 10.04