答:
Use Array.prototype.map() and some condition to handle your requirement.</p>

```<code>array.map((value) => {
  if (value.file && value.file.fileName) {
    return value.file.fileName;
  }

  return value.imgUrl;
});
</code>```

Title: how do i filter an javascript object and get the desired output as array?

Body:
Use Array.prototype.map() and some condition to handle your requirement.

array.map((value) => {
  if (value.file && value.file.fileName) {
    return value.file.fileName;
  }

  return value.imgUrl;
});


来源: stackexchange

问:
ng-change is not triggering the function
Unable to trigger the function using ng-change. If I select a same option as before initialization even after initializing it to default value through code.
I want ng-change to call my function even the option selected is same after the initialization

Thanks in advance.

答: ng-change won't work for same option selection. Use ng-click in your case.</p>

ContentLicense: CC BY-SA 3.0


问:
How to change the parameters of getElementById in a loop
I am working on a form, and I would like to reset the lines individually without using reset.
How to vary the values of the attribute passed as parameter of the method getElementById in JavaScript using a loop?
 Here is an example of my source code below:</p>

```<code><script>
         var element = document.getElementById('#re');
    element.addEventListener('click', function() {
        document.getElementById("#id1").value = "";
        document.getElementById("#id2").value = "";
        document.getElementById("#id3").value = "";
    });
</script>
</code>```

答:
Instead of using ids, you can loop through your inputs for example:</p>

```<code>var inputs = document.querySelectorAll("input");
for (var i = 0; i < inputs.length; i++) {
  inputs[i].value = "";
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Instead of using ids, you can loop through your inputs for example:

var inputs = document.querySelectorAll("input");
for (var i = 0; i < inputs.length; i++) {
  inputs[i].value = "";
}


问:
Remove namespace from XSLT output
```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <s:Header xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" />
  <soapenv:Body>
    <swiftResponseResponse xmlns="http://webservice.sbi.com">
      <swiftResponseReturn>15617TS006140|DC768736|13321.49|04-05-2017 15:13:03|SWIFTINR|NA|FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturn>
    </swiftResponseResponse>
  </soapenv:Body>
</soapenv:Envelope>
</code>```

`

my xslt code is `

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://webservice.sbi.com" exclude-result-prefixes="soapenv xsl  xsd xsi xs ">
  <!--<xsl:output method="xml" indent="yes"/>-->
  <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <!--<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>-->

  <xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="separator" />
    <xsl:choose>
        <xsl:when test="not(contains($text, $separator))">
            <swiftResponseReturnValue>
                <xsl:value-of select="$text"/>
            </swiftResponseReturnValue>
        </xsl:when>
        <xsl:otherwise>
            <swiftResponseReturnValue>
                <xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
            </swiftResponseReturnValue>
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="substring-after($text, $separator)"/>
                <xsl:with-param name="separator" select="$separator"/>
            </xsl:call-template>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
  <!--<xsl:template match="soapenv:Envelope/soapenv:Body/xs:swiftResponseResponse/xs:swiftResponseReturn">-->
    <xsl:template match="soapenv:Envelope/soapenv:Body/xs:swiftResponseResponse/xs:swiftResponseReturn">
    <!--<xsl:element name="Root">-->
      <!--<xsl:element name="swiftResponseReturn">
        <xsl:value-of select="xs:swiftResponseResponse/xs:swiftResponseReturn"/>
      </xsl:element>-->
    <xsl:copy>
        <xsl:variable name="tokenize">
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="."/>
                <xsl:with-param name="separator" select="'|'"/>
            </xsl:call-template>
        </xsl:variable>
        <xsl:copy-of select="$tokenize"/>
    </xsl:copy>
    <!--</xsl:element>-->

  </xsl:template>

</xsl:stylesheet>
</code>```

`

and my op is `

```<code><swiftResponseReturn xmlns="http://webservice.sbi.com"
                     xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <swiftResponseReturnValue xmlns="">15617TS006140</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">DC768736</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">13321.49</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">04-05-2017 15:13:03</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">SWIFTINR</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">NA</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturnValue>
</swiftResponseReturn>
</code>```

`

and expected output is
`

```<code><swiftResponseReturn>
   <swiftResponseReturnValue1>15617TS006140</swiftResponseReturnValue1>
   <swiftResponseReturnValue2>DC768736</swiftResponseReturnValue2>
   <swiftResponseReturnValue3>13321.49</swiftResponseReturnValue3>
   <swiftResponseReturnValue4>04-05-2017 15:13:03</swiftResponseReturnValue4>
   <swiftResponseReturnValue5>SWIFTINR</swiftResponseReturnValue5>
   <swiftResponseReturnValue6>NA</swiftResponseReturnValue6>
   <swiftResponseReturnValue7>FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturnValue7>
</swiftResponseReturn>
</code>```

`
i have used template to break code pipe separator format.but i don't want namespaces and also want unique identifier to distinguish each output.

答:
A more general solution: Change <xsl:copy> to <xsl:element name="{name()}">.

Of course, remember to change accordingly also the closing tag.

Edit

Here you have the XSLT script for your changed requirements:

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xs="http://webservice.sbi.com" exclude-result-prefixes="#all">
  <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="separator" />
    <xsl:choose>
      <xsl:when test="not(contains($text, $separator))">
        <token>
          <xsl:value-of select="$text"/>
        </token>
      </xsl:when>
      <xsl:otherwise>
        <token>
          <xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
        </token>
        <xsl:call-template name="tokenize">
          <xsl:with-param name="text" select="substring-after($text, $separator)"/>
          <xsl:with-param name="separator" select="$separator"/>
        </xsl:call-template>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="soapenv:Envelope/soapenv:Body/xs:swiftResponseResponse/xs:swiftResponseReturn">
    <xsl:element name="{name()}">
      <xsl:variable name="tokens">
        <xsl:call-template name="tokenize">
          <xsl:with-param name="text" select="."/>
          <xsl:with-param name="separator" select="'|'"/>
        </xsl:call-template>
      </xsl:variable>
      <xsl:for-each select="$tokens/token">
        <xsl:element name="swiftResponseReturnValue{position()}">
          <xsl:value-of select="."/>
        </xsl:element>
      </xsl:for-each>
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>
</code>```

What has changed compared to your solution:

tokenize template returns a sequence of token elements
and its result is saved in tokens variable.

Tokens from this variable are processed in a for-each loop.

Inside this loop there is created an alement. Its name is composed
from swiftResponseReturnValue (constant text) and the position number of the current tag.

The content of this source tag is printed as the content of the
just created tag.

And two additional changes at the beginning of the script:

The value of exclude-result-prefixes attribute was changed to
#all (a simpler and more general solution).

I also added <xsl:strip-space elements="*"/> to remove extra
spaces and newline chars from the output.

Title: Remove namespace from XSLT output

Body:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <s:Header xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" />
  <soapenv:Body>
    <swiftResponseResponse xmlns="http://webservice.sbi.com">
      <swiftResponseReturn>15617TS006140|DC768736|13321.49|04-05-2017 15:13:03|SWIFTINR|NA|FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturn>
    </swiftResponseResponse>
  </soapenv:Body>
</soapenv:Envelope>

`

my xslt code is `

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://webservice.sbi.com" exclude-result-prefixes="soapenv xsl  xsd xsi xs ">

  <xsl:output omit-xml-declaration="yes" indent="yes"/>

  <xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="separator" />
    <xsl:choose>
        <xsl:when test="not(contains($text, $separator))">
            <swiftResponseReturnValue>
                <xsl:value-of select="$text"/>
            </swiftResponseReturnValue>
        </xsl:when>
        <xsl:otherwise>
            <swiftResponseReturnValue>
                <xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
            </swiftResponseReturnValue>
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="substring-after($text, $separator)"/>
                <xsl:with-param name="separator" select="$separator"/>
            </xsl:call-template>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

    <xsl:template match="soapenv:Envelope/soapenv:Body/xs:swiftResponseResponse/xs:swiftResponseReturn">

    <xsl:copy>
        <xsl:variable name="tokenize">
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="."/>
                <xsl:with-param name="separator" select="'|'"/>
            </xsl:call-template>
        </xsl:variable>
        <xsl:copy-of select="$tokenize"/>
    </xsl:copy>

  </xsl:template>

</xsl:stylesheet>

`

and my op is `

<swiftResponseReturn xmlns="http://webservice.sbi.com"
                     xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <swiftResponseReturnValue xmlns="">15617TS006140</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">DC768736</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">13321.49</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">04-05-2017 15:13:03</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">SWIFTINR</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">NA</swiftResponseReturnValue>
   <swiftResponseReturnValue xmlns="">FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturnValue>
</swiftResponseReturn>

`

and expected output is
`

<swiftResponseReturn>
   <swiftResponseReturnValue1>15617TS006140</swiftResponseReturnValue1>
   <swiftResponseReturnValue2>DC768736</swiftResponseReturnValue2>
   <swiftResponseReturnValue3>13321.49</swiftResponseReturnValue3>
   <swiftResponseReturnValue4>04-05-2017 15:13:03</swiftResponseReturnValue4>
   <swiftResponseReturnValue5>SWIFTINR</swiftResponseReturnValue5>
   <swiftResponseReturnValue6>NA</swiftResponseReturnValue6>
   <swiftResponseReturnValue7>FAIL-ACCOUNT UNAVAILABLE</swiftResponseReturnValue7>
</swiftResponseReturn>

`
i have used template to break code pipe separator format.but i don't want namespaces and also want unique identifier to distinguish each output.

Body:
A more general solution: Change <xsl:copy> to <xsl:element name="{name()}">.

Of course, remember to change accordingly also the closing tag.

Edit

Here you have the XSLT script for your changed requirements:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xs="http://webservice.sbi.com" exclude-result-prefixes="#all">
  <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="separator" />
    <xsl:choose>
      <xsl:when test="not(contains($text, $separator))">
        <token>
          <xsl:value-of select="$text"/>
        </token>
      </xsl:when>
      <xsl:otherwise>
        <token>
          <xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
        </token>
        <xsl:call-template name="tokenize">
          <xsl:with-param name="text" select="substring-after($text, $separator)"/>
          <xsl:with-param name="separator" select="$separator"/>
        </xsl:call-template>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="soapenv:Envelope/soapenv:Body/xs:swiftResponseResponse/xs:swiftResponseReturn">
    <xsl:element name="{name()}">
      <xsl:variable name="tokens">
        <xsl:call-template name="tokenize">
          <xsl:with-param name="text" select="."/>
          <xsl:with-param name="separator" select="'|'"/>
        </xsl:call-template>
      </xsl:variable>
      <xsl:for-each select="$tokens/token">
        <xsl:element name="swiftResponseReturnValue{position()}">
          <xsl:value-of select="."/>
        </xsl:element>
      </xsl:for-each>
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>

What has changed compared to your solution:

tokenize template returns a sequence of token elements
and its result is saved in tokens variable.

Tokens from this variable are processed in a for-each loop.

Inside this loop there is created an alement. Its name is composed
from swiftResponseReturnValue (constant text) and the position number of the current tag.

The content of this source tag is printed as the content of the
just created tag.

And two additional changes at the beginning of the script:

The value of exclude-result-prefixes attribute was changed to
#all (a simpler and more general solution).

I also added <xsl:strip-space elements="*"/> to remove extra
spaces and newline chars from the output.


答:
For your simple example, you could loop through the values 1 - 3 (I assume the # in the ID is a typo?):

```<code>for(var i = 1; i <= 3; i++) {
   document.getElementById('id' + i).value = '';
}
</code>```

If you can identify the elements by something else, such as a class name, you might prefer to iterate over that:

```<code>var elements = document.querySelectorAll('.field');
Array.prototype.slice.call(elements).forEach(function(element) {
   element.value = '';
});
</code>```

Title: How to change the parameters of getElementById in a loop

Body:
I am working on a form, and I would like to reset the lines individually without using reset.
How to vary the values of the attribute passed as parameter of the method getElementById in JavaScript using a loop?
 Here is an example of my source code below:

Body:
For your simple example, you could loop through the values 1 - 3 (I assume the # in the ID is a typo?):

for(var i = 1; i <= 3; i++) {
   document.getElementById('id' + i).value = '';
}

If you can identify the elements by something else, such as a class name, you might prefer to iterate over that:

var elements = document.querySelectorAll('.field');
Array.prototype.slice.call(elements).forEach(function(element) {
   element.value = '';
});


问:
Showing truncated text on hover using CSS ellipsis overlaps text below it
I have a name tag in the sidebar which should display single line and truncate if long text follow by triple dots (lorem ipsum...) and should show full text on hover.

I am able to achieve this using css but my problem is when full text is displayed it overlaps the text below it. (Images attached)

HTML

```<code><p class="name">
    Lorem ipsum lorem ipsum lorem ipsum
</p>
</code>```

CSS

```<code>.name{
    color: #0079c1;
    height: 2em;
    line-height: 1em;
    font-size: 20px;
    font-weight: 400;
    text-overflow: ellipsis;
    margin-bottom: 12px;
    cursor: pointer;
    word-break: break-all;
    overflow:hidden;
    white-space: nowrap;
}

.name:hover{
    overflow: visible;
    white-space: normal;
}
</code>```

Here is a JSFiddle

Text overlapping on hover. Expected behaviour is it should push the content below it.

答:
Facing similar problem with some long email addresses in a form I created this solution where the full content is displayed on hover in a tooltip-style pseudo element.

body{
  background:#eee;
}
.box{
  background:#fff;
  box-shadow: 0 25px 30px 0 rgba(0,0,0,0.15);
  border:rgba(0,0,0,0.3);
  width:10rem;
  margin:2rem auto;
  padding:2rem;
}
.ellipsis {
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    transition: all .2s linear;
    white-space: nowrap;
    padding:.5rem 1rem;
}
.ellipsis:focus, .ellipsis:hover {
  color:transparent;
}
.ellipsis:focus:after,.ellipsis:hover:after{
    content:attr(data-text);
    overflow: visible;
    text-overflow: inherit;
    background: #fff;
    position: absolute;
    left:auto;
    top:auto;
    width: auto;
    max-width: 20rem;
    border: 1px solid #eaebec;
    padding: 0 .5rem;
    box-shadow: 0 2px 4px 0 rgba(0,0,0,.28);
    white-space: normal;
    word-wrap: break-word;
    display:block;
    color:black;
    margin-top:-1.25rem;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <p class='ellipsis' data-text='f6cd8edc-60c2-11e7-9919-ef706e78474f'>f6cd8edc-60c2-11e7-9919-ef706e78474f</p>
  <p class='ellipsis' data-text='Mauris ac eros odio. Etiam imperdiet vitae dolor eu feugiat. Pellentesque at ante dignissim, tincidunt ipsum quis, rutrum ante. Donec ac lorem nisl. Cras fringilla ex ut rutrum imperdiet. Fusce accumsan id est vel lacinia. Cras nec ligula eu velit mattis mollis. Nunc venenatis neque nibh, id dapibus orci aliquet id. Ut dictum mollis eros sed imperdiet. Phasellus quis enim nec felis sagittis varius. Ut et rutrum quam. Morbi id interdum felis. Mauris id dignissim odio.'>Mauris ac eros odio. Etiam imperdiet vitae dolor eu feugiat. Pellentesque at ante dignissim, tincidunt ipsum quis, rutrum ante. Donec ac lorem nisl. Cras fringilla ex ut rutrum imperdiet. Fusce accumsan id est vel lacinia. Cras nec ligula eu velit mattis mollis. Nunc venenatis neque nibh, id dapibus orci aliquet id. Ut dictum mollis eros sed imperdiet. Phasellus quis enim nec felis sagittis varius. Ut et rutrum quam. Morbi id interdum felis. Mauris id dignissim odio.</p>
</div></code>```

https://codepen.io/natalitique/pen/gRdmre

Requires using data attribute with the full content.

Body:
I have a name tag in the sidebar which should display single line and truncate if long text follow by triple dots (lorem ipsum...) and should show full text on hover.

I am able to achieve this using css but my problem is when full text is displayed it overlaps the text below it. (Images attached)

HTML

    Lorem ipsum lorem ipsum lorem ipsum

CSS

.name{
    color: #0079c1;
    height: 2em;
    line-height: 1em;
    font-size: 20px;
    font-weight: 400;
    text-overflow: ellipsis;
    margin-bottom: 12px;
    cursor: pointer;
    word-break: break-all;
    overflow:hidden;
    white-space: nowrap;
}

.name:hover{
    overflow: visible;
    white-space: normal;
}

Here is a JSFiddle

Text overlapping on hover. Expected behaviour is it should push the content below it.

Body:
Facing similar problem with some long email addresses in a form I created this solution where the full content is displayed on hover in a tooltip-style pseudo element.

body{
  background:#eee;
}
.box{
  background:#fff;
  box-shadow: 0 25px 30px 0 rgba(0,0,0,0.15);
  border:rgba(0,0,0,0.3);
  width:10rem;
  margin:2rem auto;
  padding:2rem;
}
.ellipsis {
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    transition: all .2s linear;
    white-space: nowrap;
    padding:.5rem 1rem;
}
.ellipsis:focus, .ellipsis:hover {
  color:transparent;
}
.ellipsis:focus:after,.ellipsis:hover:after{
    content:attr(data-text);
    overflow: visible;
    text-overflow: inherit;
    background: #fff;
    position: absolute;
    left:auto;
    top:auto;
    width: auto;
    max-width: 20rem;
    border: 1px solid #eaebec;
    padding: 0 .5rem;
    box-shadow: 0 2px 4px 0 rgba(0,0,0,.28);
    white-space: normal;
    word-wrap: break-word;
    display:block;
    color:black;
    margin-top:-1.25rem;
  }

<div class="box">
  <p class='ellipsis' data-text='f6cd8edc-60c2-11e7-9919-ef706e78474f'>f6cd8edc-60c2-11e7-9919-ef706e78474f</p>
  <p class='ellipsis' data-text='Mauris ac eros odio. Etiam imperdiet vitae dolor eu feugiat. Pellentesque at ante dignissim, tincidunt ipsum quis, rutrum ante. Donec ac lorem nisl. Cras fringilla ex ut rutrum imperdiet. Fusce accumsan id est vel lacinia. Cras nec ligula eu velit mattis mollis. Nunc venenatis neque nibh, id dapibus orci aliquet id. Ut dictum mollis eros sed imperdiet. Phasellus quis enim nec felis sagittis varius. Ut et rutrum quam. Morbi id interdum felis. Mauris id dignissim odio.'>Mauris ac eros odio. Etiam imperdiet vitae dolor eu feugiat. Pellentesque at ante dignissim, tincidunt ipsum quis, rutrum ante. Donec ac lorem nisl. Cras fringilla ex ut rutrum imperdiet. Fusce accumsan id est vel lacinia. Cras nec ligula eu velit mattis mollis. Nunc venenatis neque nibh, id dapibus orci aliquet id. Ut dictum mollis eros sed imperdiet. Phasellus quis enim nec felis sagittis varius. Ut et rutrum quam. Morbi id interdum felis. Mauris id dignissim odio.</p>
</div>

https://codepen.io/natalitique/pen/gRdmre

Requires using data attribute with the full content.


问:
How to use an input array for drawing a graph in GraphView Library?
I am developing an Android application,which can take audio input from device mic and generate a graph in real time as an output.For generating a Graph on a view I am using GraphView library.
I am trying to convert a .wav audio file into an array.But I don't know where I have to use this array for drawing a graph?  </p>

答:
i found this :
1 - create a WaveSimple (time, amplitude)
then i creat a Liste to add samples in this Liste;

```<code>Liste<WaveSample> pointListe = new ArrayListe<>();
</code>```

and when i start recording i put this :

```<code>pointList.add(new WaveSample (Time, myAudioRecord.getMaxAmplitude ());
</code>```

i want to create a lineGraph with this List but i couldn't ;
this what i write :

```<code>for(int i = 0; i<pointList.size(); i++){
    x = (double) pointList.getTime();
    y = (double) pointList.getAmplitude();
   series.appendData(new DataPoint(x, y),true,pointList.size())
   }
</code>```

but doesnt work

Body:
i found this :
1 - create a WaveSimple (time, amplitude)
then i creat a Liste to add samples in this Liste;

Liste<WaveSample> pointListe = new ArrayListe<>();

and when i start recording i put this :

pointList.add(new WaveSample (Time, myAudioRecord.getMaxAmplitude ());

i want to create a lineGraph with this List but i couldn't ;
this what i write :

for(int i = 0; i<pointList.size(); i++){
    x = (double) pointList.getTime();
    y = (double) pointList.getAmplitude();
   series.appendData(new DataPoint(x, y),true,pointList.size())
   }

but doesnt work


问:
How to handle categorical features for Decision Tree, Random Forest in spark ml?
I am trying to build decision tree and random forest classifier on the UCI bank marketing data -> https://archive.ics.uci.edu/ml/datasets/bank+marketing. There are many categorical features (having string values) in the data set.

In the spark ml document, it's mentioned that the categorical variables can be converted to numeric by indexing using either StringIndexer or VectorIndexer. I chose to use StringIndexer (vector index requires vector feature and vector assembler which convert features to vector feature accepts only numeric type ). Using this approach, each of the level of a categorical feature will be assigned numeric value based on it's frequency (0 for most frequent label of a category feature).

My question is how the algorithm of Random Forest or Decision Tree will understand that new features (derived from categorical features) are different than continuous variable. Will indexed feature be considered as continuous in the algorithm? Is it the right approach? Or should I go ahead with One-Hot-Encoding for categorical features.

I read some of the answers from this forum but i didn't get clarity on the last part.

答:
One Hot Encoding should be done for categorical variables with categories > 2.

To understand why, you should know the difference between the sub categories of categorical data: Ordinal data and Nominal data.

Ordinal Data: The values has some sort of ordering between them. example:
Customer Feedback(excellent, good, neutral, bad, very bad). As you can see there is a clear ordering between them (excellent > good > neutral > bad > very bad). In this case StringIndexer alone is sufficient for modelling purpose.

Nominal Data: The values has no defined ordering between them.
example: colours(black, blue, white, ...). In this case StringIndexer alone is NOT sufficient. and One Hot Encoding is required after String Indexing.

After String Indexing lets assume the output is:

```<code> id | colour   | categoryIndex
----|----------|---------------
 0  | black    | 0.0
 1  | white    | 1.0
 2  | yellow   | 2.0
 3  | red      | 3.0
</code>```

Then without One Hot Encoding, the machine learning algorithm will assume: red > yellow > white > black, which we know its not true.
OneHotEncoder() will help us avoid this situation.

So to answer your question,

Will indexed feature be considered as continuous in the algorithm?

It will be considered as continious variable.

Is it the right approach? Or should I go ahead with One-Hot-Encoding
  for categorical features

depends on your understanding of data.Although Random Forest and some boosting methods doesn't require OneHot Encoding, most ML algorithms need it.

Refer: https://spark.apache.org/docs/latest/ml-features.html#onehotencoder

Body:
One Hot Encoding should be done for categorical variables with categories > 2.

To understand why, you should know the difference between the sub categories of categorical data: Ordinal data and Nominal data.

Ordinal Data: The values has some sort of ordering between them. example:
Customer Feedback(excellent, good, neutral, bad, very bad). As you can see there is a clear ordering between them (excellent > good > neutral > bad > very bad). In this case StringIndexer alone is sufficient for modelling purpose.

Nominal Data: The values has no defined ordering between them.
example: colours(black, blue, white, ...). In this case StringIndexer alone is NOT sufficient. and One Hot Encoding is required after String Indexing.

After String Indexing lets assume the output is:

 id | colour   | categoryIndex
----|----------|---------------
 0  | black    | 0.0
 1  | white    | 1.0
 2  | yellow   | 2.0
 3  | red      | 3.0

Then without One Hot Encoding, the machine learning algorithm will assume: red > yellow > white > black, which we know its not true.
OneHotEncoder() will help us avoid this situation.

So to answer your question,

Will indexed feature be considered as continuous in the algorithm?

It will be considered as continious variable.

Is it the right approach? Or should I go ahead with One-Hot-Encoding
  for categorical features

depends on your understanding of data.Although Random Forest and some boosting methods doesn't require OneHot Encoding, most ML algorithms need it.

Refer: https://spark.apache.org/docs/latest/ml-features.html#onehotencoder


问:
How do I parse a website in python once I know its url?
If I know the url of a wiki site , How do I use python to parse the contents of it ?</p>

答: You might try Scrapy as well.</p>

ContentLicense: CC BY-SA 2.5

Body: You might try Scrapy as well.


问:
Node.js installation: Should it be nodejs or node.js?
After launching an ec2 Ubuntu 16.04 instance on AWS, I have both:

```<code>apt-get install nodejs
</code>```

and:

```<code>apt-get install node.js
</code>```

Both are runnable but each shows different disk usage.  Which should be the correct one to install Node.js? (Why are there two? How different are they?)

答:
I would suggest installing nvm: It removes loads of the issues relating to installing via package manager

https://github.com/creationix/nvm

you can then use the command nvm list to get the versions of node available then use command nvm install <version> to install a specific version, then nvm use <version> to use that version for what you are doing.  e.g.

nvm install 8.1.2 && nvm use 8.1.2

Body:
After launching an ec2 Ubuntu 16.04 instance on AWS, I have both:

apt-get install nodejs

and:

apt-get install node.js

Both are runnable but each shows different disk usage.  Which should be the correct one to install Node.js? (Why are there two? How different are they?)


问:
Jenkins Blue Ocean workspace Path Too Long
We are using Jenkins Blue Ocean to build .Net applications on Windows 2012 r2 Jenkins Slaves.  We use a Jenkinsfile inside the git repos to define the build pipelines.

With a couple of the projects we get a build failure due to the workspace build path being too long for Windows to handle.

This generally happens with nuget pack and npm install commands which max out the max path.

```<code>The specified path, file name, or both are too long.
The fully qualified file name must be less than 260 characters,
and the directory name must be less than 248 characters.

script returned exit code 1
</code>```

As we can't affect the length of the Visual Studio Solution nuget package paths how do we drop the workspace folder down to something Windows can handle?

Thanks to the suggestion by Mutsa here is what we ended up with in our Jenkinsfile:

```<code>pipeline {
agent {
    node {
        label 'win'
        customWorkspace "ws\\${JOB_NAME.replace("%2F", "_")}"
    }
}
</code>```

Which can be seen in context in our .net core Wakeboard UK website repo on GitHub.

答:
For declarative pipeline use customworksace option to override the default path within your node, docker or dockerfile section. See example.

```<code>agent {
node {
    customWorkspace '/some/other/path'
}
</code>```

It can be a relative path in respect to the workspace root or an absolute path.

Body:
We are using Jenkins Blue Ocean to build .Net applications on Windows 2012 r2 Jenkins Slaves.  We use a Jenkinsfile inside the git repos to define the build pipelines.

With a couple of the projects we get a build failure due to the workspace build path being too long for Windows to handle.

This generally happens with nuget pack and npm install commands which max out the max path.

The specified path, file name, or both are too long.
The fully qualified file name must be less than 260 characters,
and the directory name must be less than 248 characters.

script returned exit code 1

As we can't affect the length of the Visual Studio Solution nuget package paths how do we drop the workspace folder down to something Windows can handle?

Thanks to the suggestion by Mutsa here is what we ended up with in our Jenkinsfile:

pipeline {
agent {
    node {
        label 'win'
        customWorkspace "ws\\${JOB_NAME.replace("%2F", "_")}"
    }
}

Which can be seen in context in our .net core Wakeboard UK website repo on GitHub.

Body:
For declarative pipeline use customworksace option to override the default path within your node, docker or dockerfile section. See example.

agent {
node {
    customWorkspace '/some/other/path'
}

It can be a relative path in respect to the workspace root or an absolute path.


问:
Using GSON to parse Json into a JAVA Object where the Json Elements may vary
I am trying to parse a JSON .txt file into a JAVA object using GSON. The JSON file has the following structure:

```<code>    {
        "event0" : {
        "a" : "abc",
        "b" : "def"
        },

        "event1" : {
        "a" : "ghi",
        "b" : "jkl",
        "c" : "mno"
        }
    }
</code>```

I have read the text file into a String called dataStr. I want to use the fromJson method to capture the events into the following JAVA class:

```<code>public class Event {
    private String a;
    private String b;
    private String c;

    public Event() {}

}
</code>```

The problem is that the JSON might have one extra field "c" in some of the elements. I want to parse all the events into Event class objects, and for the cases where there is no "c" field, I want to make it null or zero in my object. It is not known beforehand which of the elements will have the "c" field.

Specifically, I was not able to figure out how to handle one extra field in some of the JSON elements. I want to do something along the lines of:

```<code>Gson gson = new Gson();
ArrayList<Event> events = gson.fromJson(dataStr, Event.class);
</code>```

But I am stuck with first, how to iterate over the events in the Json file, and secondly, how to handle some occasional missing fields into the same Event object. I would really appreciate a kick in the right direction. Thank you all.

I am fairly new to JSON parsing, and might have missed something in the following answers:

Using Gson to convert Json into Java Object

Mapping JSON into POJO using Gson

Using gson to parse json to java object

Parse JSON into a java object

How to parse a json file into a java POJO class using GSON

答:
Gson automatically do that for you.

So, if you have a class "Alpha" with 3 fields ("a", "b" and "c") and you try to work on a json object that has 2 fields with names that match with Alpha's "a" and "b", Gson will fill "a" and "b" with json file's value and "c" will automatically set as null.

So, in your case, if you write this:

```<code>ArrayList<Event> events = gson.fromJson(dataStr, Event.class);
</code>```

And in your json there are events with only 2 fields (that match with any Event's class fields) and events with all fields set, you will get a list of Events with no errors. Maybe you'll get some fields null, but the code will work.

I hope to be helpful! Ask for further informations, if you want to!

EDIT

Note that your json file has not to be .txt but .json instead!

Body:
I am trying to parse a JSON .txt file into a JAVA object using GSON. The JSON file has the following structure:

    {
        "event0" : {
        "a" : "abc",
        "b" : "def"
        },

        "event1" : {
        "a" : "ghi",
        "b" : "jkl",
        "c" : "mno"
        }
    }

I have read the text file into a String called dataStr. I want to use the fromJson method to capture the events into the following JAVA class:

public class Event {
    private String a;
    private String b;
    private String c;

    public Event() {}

}

The problem is that the JSON might have one extra field "c" in some of the elements. I want to parse all the events into Event class objects, and for the cases where there is no "c" field, I want to make it null or zero in my object. It is not known beforehand which of the elements will have the "c" field.

Specifically, I was not able to figure out how to handle one extra field in some of the JSON elements. I want to do something along the lines of:

Gson gson = new Gson();
ArrayList<Event> events = gson.fromJson(dataStr, Event.class);

But I am stuck with first, how to iterate over the events in the Json file, and secondly, how to handle some occasional missing fields into the same Event object. I would really appreciate a kick in the right direction. Thank you all.

I am fairly new to JSON parsing, and might have missed something in the following answers:

Using Gson to convert Json into Java Object

Mapping JSON into POJO using Gson

Using gson to parse json to java object

Parse JSON into a java object

How to parse a json file into a java POJO class using GSON

Body:
Gson automatically do that for you.

So, if you have a class "Alpha" with 3 fields ("a", "b" and "c") and you try to work on a json object that has 2 fields with names that match with Alpha's "a" and "b", Gson will fill "a" and "b" with json file's value and "c" will automatically set as null.

So, in your case, if you write this:

ArrayList<Event> events = gson.fromJson(dataStr, Event.class);

And in your json there are events with only 2 fields (that match with any Event's class fields) and events with all fields set, you will get a list of Events with no errors. Maybe you'll get some fields null, but the code will work.

I hope to be helpful! Ask for further informations, if you want to!

EDIT

Note that your json file has not to be .txt but .json instead!


问:
After Enabling Oracle Net Encryption Standard JDBC Connection Possible
Used Oracle Net Manager to enable network encryption.

sqlnet.ora file:

SQLNET.ENCRYPTION_CLIENT = required

SQLNET.AUTHENTICATION_SERVICES= (NTS)

SSL_VERSION = 0

SQLNET.ENCRYPTION_SERVER = required

SSL_CLIENT_AUTHENTICATION = TRUE

SQLNET.CRYPTO_SEED = '0123456789'

SQLNET.ENCRYPTION_TYPES_CLIENT= (AES256)

SQLNET.ENCRYPTION_TYPES_CLIENT= (AES256)

...

Java Code:

```<code>Properties props = new Properties();
props.put("oracle.net.encryption_client", "required");
props.put("oracle.net.encryption_types_client", "AES256");
props.put("user", "scott");
props.put("password", "tiger");
</code>```

Using other algorithm names e.g. AES128: props.put("oracle.net.encryption_types_client", "AES128"); outputs ORA-12650. This is OK. But putting only user and password to Properties connection is possible:

```<code>Properties props = new Properties();
props.put("user", "scott");
props.put("password", "tiger");
</code>```

How to disable standard connection whenever Oracle Net Encryption is required?

答:
If you don't set the "oracle.net.encryption_types_client" property in the JDBC thin driver, by default the driver will "accept" encryption and because you have made encryption "required" on the server, the encryption will be turned on. To summarize, if you "require" encryption on the server that will make all the connections use encryption. Any client that doesn't support encryption will fail to connect.

This ASO negotiation is explained in this doc, look at the table "Table 9-2 Encryption and Data Integrity Negotiations". By default the JDBC thin driver accepts encryption.

Body:
Used Oracle Net Manager to enable network encryption.

sqlnet.ora file:

SQLNET.ENCRYPTION_CLIENT = required

SQLNET.AUTHENTICATION_SERVICES= (NTS)

SSL_VERSION = 0

SQLNET.ENCRYPTION_SERVER = required

SSL_CLIENT_AUTHENTICATION = TRUE

SQLNET.CRYPTO_SEED = '0123456789'

SQLNET.ENCRYPTION_TYPES_CLIENT= (AES256)

SQLNET.ENCRYPTION_TYPES_CLIENT= (AES256)

...

Java Code:

Properties props = new Properties();
props.put("oracle.net.encryption_client", "required");
props.put("oracle.net.encryption_types_client", "AES256");
props.put("user", "scott");
props.put("password", "tiger");

Using other algorithm names e.g. AES128: props.put("oracle.net.encryption_types_client", "AES128"); outputs ORA-12650. This is OK. But putting only user and password to Properties connection is possible:

Properties props = new Properties();
props.put("user", "scott");
props.put("password", "tiger");

How to disable standard connection whenever Oracle Net Encryption is required?


答:
Using a case statement will help you here:

```<code>Select Date_Column, sum(column_A),
MAX(CASE when column_A is NULL then 'True' else 'False' end) "Includes_NULL_Value"
from table_x
group by Date_column;
</code>```

REX TESTER

Title: How to get partial sum of column and finds which rows has partial sum in mysql

Body:
+----------------------------------------+
|        Here is my sample table         |
+----------------------------------------+
| Date       Person    Column_1    Column_2 |
| 15-03-13    A       100         NULL   |
| 15-03-13    B       NULL         100   |
| 16-03-13    A       100           50   |
| 16-03-13    B       NULL         NULL  |
| 17-03-13    A       100           50   |
| 17-03-13    B       20            30   |
+----------------------------------------+

Now i wanted to do sum(column_1) by date. But i also need to which sum of row includes NULL data.
here is the output result I wanted to achieve

+---------------------------------+
| Date       SUM  includesNullval |
+---------------------------------+
| 15-03-13   100   true           |
| 16-03-13   100   true           |
| 17-03-13   120   false          |
+---------------------------------+

I don't know to achieve above output. Can anybody give me any idea or solution of this problem?

Body:
Using a case statement will help you here:

Select Date_Column, sum(column_A),
MAX(CASE when column_A is NULL then 'True' else 'False' end) "Includes_NULL_Value"
from table_x
group by Date_column;

REX TESTER


问:
collision detection using bounding boxes slowing aframe down
Hi I recently made a component for collision detection among primitive and non primitive shapes. I was using bounding box collision provided in three.js.. its working fine but when I am using it for custom objects its slowing the entire experience down... kindly look into my component and tell me whats the issue...

```<code>AFRAME.registerComponent('manual-body', {
          matchingElements: function(attribute){
            var matchingElements = [];
            var allElements = document.getElementsByTagName('*');
            for (var i = 0, n = allElements.length; i < n; i++){
              if (allElements[i].getAttribute(attribute) !== null){
                // Element exists with attribute. Add to array.
                matchingElements.push(allElements[i]);
              }
            }
            return matchingElements;
          },
          tick: function(){
            var elements=this.matchingElements('manual-body');
            for(var i=0;i<elements.length;i++){
              if(this.el.id==elements[i].id){
                continue;
              }
              firstBB = new THREE.Box3().setFromObject(elements[i].object3D);
              secondBB = new THREE.Box3().setFromObject(this.el.object3D);
              var collision = firstBB.intersectsBox(secondBB);
              if(collision){
                this.el.emit('collision', {elSource: this.el,elTarget:elements[i]});
              }
            }
          }
        });
</code>```

What do you think might be the cause of the lag? is it the collision logic inside the tick function or is it something else.....

Thanks

答:
My guess is that three.js is slowing down Your site by adjusting the box boundaries to the custom model.
 I would manually add a box entity inside Your model:

```<code><a-entity collada-model="my model">
      <a-box></a-box>
</a-entity>
</code>```

and make the collision checks with the boxes within.
If You are trying to make some kind of physics, try Don McCurdy's Cannon.js implementation, for there is no need to reinvent the wheel :P

UPDATE

If You have issues only with .obj's, and collada's are not causing issues, try converting the obj models to .dae.
 If Your issue still exists, try my boundaries override.

Body:
Hi I recently made a component for collision detection among primitive and non primitive shapes. I was using bounding box collision provided in three.js.. its working fine but when I am using it for custom objects its slowing the entire experience down... kindly look into my component and tell me whats the issue...

AFRAME.registerComponent('manual-body', {
          matchingElements: function(attribute){
            var matchingElements = [];
            var allElements = document.getElementsByTagName('*');
            for (var i = 0, n = allElements.length; i < n; i++){
              if (allElements[i].getAttribute(attribute) !== null){
                // Element exists with attribute. Add to array.
                matchingElements.push(allElements[i]);
              }
            }
            return matchingElements;
          },
          tick: function(){
            var elements=this.matchingElements('manual-body');
            for(var i=0;i<elements.length;i++){
              if(this.el.id==elements[i].id){
                continue;
              }
              firstBB = new THREE.Box3().setFromObject(elements[i].object3D);
              secondBB = new THREE.Box3().setFromObject(this.el.object3D);
              var collision = firstBB.intersectsBox(secondBB);
              if(collision){
                this.el.emit('collision', {elSource: this.el,elTarget:elements[i]});
              }
            }
          }
        });

What do you think might be the cause of the lag? is it the collision logic inside the tick function or is it something else.....

Thanks

Body:
My guess is that three.js is slowing down Your site by adjusting the box boundaries to the custom model.
 I would manually add a box entity inside Your model:

<a-entity collada-model="my model">
      <a-box></a-box>
</a-entity>

and make the collision checks with the boxes within.
If You are trying to make some kind of physics, try Don McCurdy's Cannon.js implementation, for there is no need to reinvent the wheel :P

UPDATE

If You have issues only with .obj's, and collada's are not causing issues, try converting the obj models to .dae.
 If Your issue still exists, try my boundaries override.


问:
Pyinstaller - Standalone .exe
I am trying to create an .exe file such that when run on any windows 10 pc will run without requiring any installations. What I tried using was:

```<code>pyinstaller --onefile main.py
</code>```

I ran the exe file on a friend's computer and it turns out that it required first python2.7 to be installed, then it said that modules weren't installed i.e; no module named datetime found. The executable finally ran after I installed all dependencies on my friend's computer but the whole point of creating .exe file was useless, I might as well have just typed python main.py after doing so much. Is there an appropriate way I could get an .exe file from .py which wont require anything to be installed? Like an actual standalone app. Thank you!

答:
Actually this should work. I never had problems with pyinstaller, yet. Maybe reinstall pyinstaller or make sure to use the newest version. Also try first of all an easy "helloWorld"

```<code>input("hello from Console.\nPress Enter to close it :)")
</code>```

Just tried this one on a colleague's machine that has no python installed. And it worked well.

Title: Pyinstaller - Standalone .exe

Body:
I am trying to create an .exe file such that when run on any windows 10 pc will run without requiring any installations. What I tried using was:

pyinstaller --onefile main.py

I ran the exe file on a friend's computer and it turns out that it required first python2.7 to be installed, then it said that modules weren't installed i.e; no module named datetime found. The executable finally ran after I installed all dependencies on my friend's computer but the whole point of creating .exe file was useless, I might as well have just typed python main.py after doing so much. Is there an appropriate way I could get an .exe file from .py which wont require anything to be installed? Like an actual standalone app. Thank you!

Body:
Actually this should work. I never had problems with pyinstaller, yet. Maybe reinstall pyinstaller or make sure to use the newest version. Also try first of all an easy "helloWorld"

input("hello from Console.\nPress Enter to close it :)")

Just tried this one on a colleague's machine that has no python installed. And it worked well.


问:
Singleton instance declared as static variable of GetInstance method, is it thread-safe?
I've seen implementations of Singleton patterns where instance variable was declared as static variable in GetInstance method. Like this:

```<code>SomeBaseClass &SomeClass::GetInstance()
{
   static SomeClass instance;
   return instance;
}
</code>```

I see following positive sides of this approach:

The code is simpler, because it's compiler who responsible for creating this object only when GetInstance called for the first time.

The code is safer, because there is no other way to get reference to instance, but with GetInstance method and there is no other way to change instance, but inside GetInstance method.

What are the negative sides of this approach (except that this is not very OOP-ish) ? Is this thread-safe?

答:
It is not thread safe as shown. The C++ language is silent on threads so you have no inherent guarantees from the language. You will have to use platform synchronization primitives, e.g. Win32 ::EnterCriticalSection(), to protect access.

Your particular approach would be problematic b/c the compiler will insert some (non-thread safe) code to initialize the static instance on first invocation, most likely it will be before the function body begins execution (and hence before any synchronization can be invoked.)

Using a global/static member pointer to SomeClass and then initializing within a synchronized block would prove less problematic to implement.

```<code>#include <boost/shared_ptr.hpp>

namespace
{
  //Could be implemented as private member of SomeClass instead..
  boost::shared_ptr<SomeClass> g_instance;
}

SomeBaseClass &SomeClass::GetInstance()
{
   //Synchronize me e.g. ::EnterCriticalSection()
   if(g_instance == NULL)
     g_instance = boost::shared_ptr<SomeClass>(new SomeClass());
   //Unsynchronize me e.g. :::LeaveCriticalSection();
   return *g_instance;
}
</code>```

I haven't compiled this so it's for illustrative purposes only. It also relies on the boost library to obtain the same lifetime (or there about) as your original example. You can also use std::tr1 (C++0x).

OwnerDisplayName: Dmitriy Matveev

Body:
I've seen implementations of Singleton patterns where instance variable was declared as static variable in GetInstance method. Like this:

SomeBaseClass &SomeClass::GetInstance()
{
   static SomeClass instance;
   return instance;
}

I see following positive sides of this approach:

The code is simpler, because it's compiler who responsible for creating this object only when GetInstance called for the first time.

The code is safer, because there is no other way to get reference to instance, but with GetInstance method and there is no other way to change instance, but inside GetInstance method.

What are the negative sides of this approach (except that this is not very OOP-ish) ? Is this thread-safe?

Body:
It is not thread safe as shown. The C++ language is silent on threads so you have no inherent guarantees from the language. You will have to use platform synchronization primitives, e.g. Win32 ::EnterCriticalSection(), to protect access.

Your particular approach would be problematic b/c the compiler will insert some (non-thread safe) code to initialize the static instance on first invocation, most likely it will be before the function body begins execution (and hence before any synchronization can be invoked.)

Using a global/static member pointer to SomeClass and then initializing within a synchronized block would prove less problematic to implement.

#include <boost/shared_ptr.hpp>

namespace
{
  //Could be implemented as private member of SomeClass instead..
  boost::shared_ptr<SomeClass> g_instance;
}

SomeBaseClass &SomeClass::GetInstance()
{
   //Synchronize me e.g. ::EnterCriticalSection()
   if(g_instance == NULL)
     g_instance = boost::shared_ptr<SomeClass>(new SomeClass());
   //Unsynchronize me e.g. :::LeaveCriticalSection();
   return *g_instance;
}

I haven't compiled this so it's for illustrative purposes only. It also relies on the boost library to obtain the same lifetime (or there about) as your original example. You can also use std::tr1 (C++0x).

OwnerDisplayName: Henk


问:
jQuery fade li element and cycle it when mouse hovered
I'm trying to recreate an effect in jQuery, where an element (
 ) will be cycled and has a fading effect when hovered. The '
' contains '' (image screenshots). When the mouse is on top of element it will keep cycling all that are in '
' with a fading effect. When the mouse is away it will stop cycling the list. I also want to add a pager where you can navigate to the list.

My Existing Code:
link text

My Problem: the current code has some problem with the pagination, it added all images that can be seen on the code. Instead of 1-8 only, it continued to add another 1-8 and another.
Second problem is, It also start cycling and fading when the page loads. The cycling and fading should only be working when the mouse is on top of the element.

I don't know if the 'Cycle Plugin' (Plugin Home Page) is really required on this approach, I wan't it to be minimal as much as possible. I just use 'Cycle Plugin' because it's a quick answer to my problem.

Thanks and merry xmas!

Edits

remove and added a link

答:
I could be wrong, I'm not familiar with this plugin, but it seems like you need an ID for each slideshow you have instead of using a class like you are.

I've setup a JSFiddle with your code and tweaked it. Below is how each slide should function.

starts on mouse over and stop on mouse out

changes on mouseover of the nav

changes when the nav is clicked

The link I gave you in the comments to your question should guide you to the available options for this plug-in. In case you missed it, here it is: plugin options


问:
How can i check my device is connected with internet or not in android?
Explanation:
           Hello Everyone, I am trying to check my device is connected with internet or not. I am explaining all the step what i do.

Step-1: I have created a receiver class to check when the connection status change.

Step-2: I also created a Interface in which i have method to get the connection status (true/false)

Step-3: Implement this listener on my Activity and then override the listener method.

Step-4: If my internet is connected then go ahead. If my internet is not connected i put the message your internet is not connected.

Step-5: Finally i register this receiver in AndroidManifest.xml file.

Note: All above step is working fine until SDK_VERSION Marshmallow. When i checked it with Nougt(7.0) then it's not working.

Receiver

```<code>public class ConnectivityReceiver extends BroadcastReceiver {

    public static ConnectivityReceiverListener connectivityReceiverListener;

    public ConnectivityReceiver(){
        super();
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        if (connectivityReceiverListener != null) {
            connectivityReceiverListener.onNetworkConnectionChanged(Utils.isInternetConnected(context));
        }
    }
    public static boolean isConnected(Context context) {
        if(Utils.isInternetConnected(context)){
            return true;
        }else{
            return false;
        }
    }
}
</code>```

Listener

```<code>public interface ConnectivityReceiverListener {
    void onNetworkConnectionChanged(boolean isConnected);
}
</code>```

Internet connection status method

```<code>public static boolean isInternetConnected(final Context _context) {
        ConnectivityManager cm = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null) {
            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                return true;
            } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                return true;
            }
            return true;
        } else {
            return false;
        }
    }
</code>```

Permission and register receiver in Manifest.xml

```<code><uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<receiver
            android:name="com.durian.receivers.ConnectivityReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>
</code>```

Below method is check internet connetion

```<code>private boolean checkConnection() {
    boolean isConnected = ConnectivityReceiver.isConnected(CustomerActivity.this);
    showSnack(isConnected);
    return isConnected;
}
</code>```

Below method is check isconnected or not

```<code>private void showSnack(boolean isConnected) {
    String message;
    int color;
    Snackbar snackbar;
    if (isConnected) {
        Toast.make(getActivity(),"CONNECTED",Toast.LENGTH_SHORT).show();
    } else {
        Toast.make(getActivity(),"Disconnected",Toast.LENGTH_SHORT).show();
    }
}
</code>```

Below method call the listener

```<code>@Override
protected void onResume() {
    super.onResume();
    AppController.getInstance().setConnectivityListener(this);
}
</code>```

Here is my Application class which register in android with name parameter

```<code>public class AppController extends Application{

    public static final String TAG=AppController.class.getSimpleName();

    public static Typeface fntGabriola;
    public static Typeface fntRalewayLight;
    public static Typeface fntRalewayMedium;
    public static Typeface fntRalewayRegular;
    public static Typeface fntRalewaySemiBold;
    public static Typeface fntsegoeuRegular;
    public static Typeface fntsegoeuLight;
    public static Typeface fntsegoeSemiBold;
    public static Typeface fntModerneSans;
    public static Typeface fntMordernist;
    public static Typeface fntOpenSans;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();

        mInstance = this;

        Fabric.with(this, new Crashlytics());

        fntGabriola=Typeface.createFromAsset(getAssets(),"fonts/Gabriola.ttf");
        fntRalewayLight=Typeface.createFromAsset(getAssets(),"fonts/Raleway-Light.ttf");
        fntRalewayMedium=Typeface.createFromAsset(getAssets(),"fonts/Raleway-Medium.ttf");
        fntRalewayRegular=Typeface.createFromAsset(getAssets(),"fonts/Raleway-Regular.ttf");
        fntRalewaySemiBold=Typeface.createFromAsset(getAssets(),"fonts/Raleway-SemiBold.ttf");
        fntsegoeuRegular=Typeface.createFromAsset(getAssets(),"fonts/segoeui.ttf");
        fntsegoeuLight=Typeface.createFromAsset(getAssets(),"fonts/segoeuil.ttf");
        fntsegoeSemiBold=Typeface.createFromAsset(getAssets(),"fonts/seguisb.ttf");
        fntModerneSans=Typeface.createFromAsset(getAssets(),"fonts/moderne_sans.ttf");
        fntMordernist=Typeface.createFromAsset(getAssets(),"fonts/Sk-Modernist-Regular.otf");
        fntOpenSans=Typeface.createFromAsset(getAssets(),"fonts/OpenSans-Regular.ttf");
    }
    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public void setConnectivityListener(ConnectivityReceiverListener listener) {
        ConnectivityReceiver.connectivityReceiverListener = listener;
    }
}
</code>```

Note: Everything is working fine below the nought OS Version. But the problem is when i test in nought it is not working. Please give a proper solutions which working in all the OS.

For reference you can check the snapdeal application

I want exactly as in snapdeal Android application.

答:
```<code>/**You can simply use below code Snippet**/

/**Below code Check 2 condition that Your device is connected to Wifi or Data - Connection or not. If yes then will also check that Internet is working or not..**/

/**ConnectivityReceiver Class**/

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ConnectivityReceiver
{
   private static ConnectivityReceiver.AsyncResponse asyncResponse;

/************************************************    for checking internet connection*******/
public static boolean isNetworkAvailable(Context context)
{

    ConnectivityManager connectivity = null;
    boolean isNetworkAvail = false;
    try
    {
        connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null)
        {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
            {
                for(int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }
            }
        }
        return false;
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        if (connectivity != null)
        {
            connectivity = null;
        }
    }
    return isNetworkAvail;
}

private static class ConnectionCheck extends AsyncTask<String,Void,Boolean>
{

    @Override
    protected Boolean doInBackground(String... params)
    {
        HttpURLConnection urlConnection = null;
        try
        {
            if(params[0].endsWith("") || params[0] == null)
            {
                params[0] = "http://www.google.com/";
            }

            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            if (!url.getHost().equals(urlConnection.getURL().getHost()))
            {
                // we were redirected! Kick the user out to the browser to sign on?

                return true;
            }

        }
        catch (Exception e)
        {
            e.printStackTrace();

            return false;
        }
        finally
        {
            urlConnection.disconnect();
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean)
    {
        super.onPostExecute(aBoolean);
        asyncResponse.processFinish(aBoolean);

    }
}

public interface AsyncResponse
{
    void processFinish(boolean output);
}
public static void speedTest(String url,ConnectivityReceiver.AsyncResponse asyncResponse)
{
    ConnectivityReceiver.asyncResponse = asyncResponse;
    new ConnectivityReceiver.ConnectionCheck().execute(url);
}
 }

/**Code implementation in your class**/

String ConnectionCheck_Url = "http://www.google.com/";

if(ConnectivityReceiver.isNetworkAvailable(MainActivity.this))
    {
        ConnectivityReceiver.speedTest(ConnectionCheck_Url,new ConnectivityReceiver.AsyncResponse()
        {
            @Override
            public void processFinish(boolean output)
            {
                if (output)
                {

                    /* * If The output Value --->"True" Then Only
              request will Execute
                     * NOTE: Here "True" Value Means Intenet is Working*/

                    // Implement your code here
                }
                else
                {
                   //Please_Check_Your_Internet_Connection
                }
            }
        });
    }
    else
    {
      //  Please_Connect_to_your_Wifi_or_Data_Connection
    }
}

/**Android MainifestFile.xml**/

 <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
</code>```

Body:
Explanation:
           Hello Everyone, I am trying to check my device is connected with internet or not. I am explaining all the step what i do.

Step-1: I have created a receiver class to check when the connection status change.

Step-2: I also created a Interface in which i have method to get the connection status (true/false)

Step-3: Implement this listener on my Activity and then override the listener method.

Step-4: If my internet is connected then go ahead. If my internet is not connected i put the message your internet is not connected.

Step-5: Finally i register this receiver in AndroidManifest.xml file.

Note: All above step is working fine until SDK_VERSION Marshmallow. When i checked it with Nougt(7.0) then it's not working.

Receiver

public class ConnectivityReceiver extends BroadcastReceiver {

    public static ConnectivityReceiverListener connectivityReceiverListener;

    public ConnectivityReceiver(){
        super();
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        if (connectivityReceiverListener != null) {
            connectivityReceiverListener.onNetworkConnectionChanged(Utils.isInternetConnected(context));
        }
    }
    public static boolean isConnected(Context context) {
        if(Utils.isInternetConnected(context)){
            return true;
        }else{
            return false;
        }
    }
}

Listener

public interface ConnectivityReceiverListener {
    void onNetworkConnectionChanged(boolean isConnected);
}

Internet connection status method

public static boolean isInternetConnected(final Context _context) {
        ConnectivityManager cm = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null) {
            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                return true;
            } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                return true;
            }
            return true;
        } else {
            return false;
        }
    }

Permission and register receiver in Manifest.xml

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<receiver
            android:name="com.durian.receivers.ConnectivityReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>

Below method is check internet connetion

private boolean checkConnection() {
    boolean isConnected = ConnectivityReceiver.isConnected(CustomerActivity.this);
    showSnack(isConnected);
    return isConnected;
}

Below method is check isconnected or not

private void showSnack(boolean isConnected) {
    String message;
    int color;
    Snackbar snackbar;
    if (isConnected) {
        Toast.make(getActivity(),"CONNECTED",Toast.LENGTH_SHORT).show();
    } else {
        Toast.make(getActivity(),"Disconnected",Toast.LENGTH_SHORT).show();
    }
}

Below method call the listener

@Override
protected void onResume() {
    super.onResume();
    AppController.getInstance().setConnectivityListener(this);
}

Here is my Application class which register in android with name parameter

public class AppController extends Application{

    public static final String TAG=AppController.class.getSimpleName();

    public static Typeface fntGabriola;
    public static Typeface fntRalewayLight;
    public static Typeface fntRalewayMedium;
    public static Typeface fntRalewayRegular;
    public static Typeface fntRalewaySemiBold;
    public static Typeface fntsegoeuRegular;
    public static Typeface fntsegoeuLight;
    public static Typeface fntsegoeSemiBold;
    public static Typeface fntModerneSans;
    public static Typeface fntMordernist;
    public static Typeface fntOpenSans;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();

        mInstance = this;

        Fabric.with(this, new Crashlytics());

        fntGabriola=Typeface.createFromAsset(getAssets(),"fonts/Gabriola.ttf");
        fntRalewayLight=Typeface.createFromAsset(getAssets(),"fonts/Raleway-Light.ttf");
        fntRalewayMedium=Typeface.createFromAsset(getAssets(),"fonts/Raleway-Medium.ttf");
        fntRalewayRegular=Typeface.createFromAsset(getAssets(),"fonts/Raleway-Regular.ttf");
        fntRalewaySemiBold=Typeface.createFromAsset(getAssets(),"fonts/Raleway-SemiBold.ttf");
        fntsegoeuRegular=Typeface.createFromAsset(getAssets(),"fonts/segoeui.ttf");
        fntsegoeuLight=Typeface.createFromAsset(getAssets(),"fonts/segoeuil.ttf");
        fntsegoeSemiBold=Typeface.createFromAsset(getAssets(),"fonts/seguisb.ttf");
        fntModerneSans=Typeface.createFromAsset(getAssets(),"fonts/moderne_sans.ttf");
        fntMordernist=Typeface.createFromAsset(getAssets(),"fonts/Sk-Modernist-Regular.otf");
        fntOpenSans=Typeface.createFromAsset(getAssets(),"fonts/OpenSans-Regular.ttf");
    }
    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public void setConnectivityListener(ConnectivityReceiverListener listener) {
        ConnectivityReceiver.connectivityReceiverListener = listener;
    }
}

Note: Everything is working fine below the nought OS Version. But the problem is when i test in nought it is not working. Please give a proper solutions which working in all the OS.

For reference you can check the snapdeal application

I want exactly as in snapdeal Android application.


问:
Send data from java mail in HTML Table
I am trying to send data from my Java mail application in the form of a HTML table. The problem is that when I receive the mail, the data is in simple text format and not in a table form. Please suggest a solution</p>

```<code>StringBuilder sb1 = new StringBuilder(200);
sb1.append("<html><body>"+ "<table style='border:2px solid black'>");
for(SCSINPojo cat : ar){

    sb1.append("<tr>");
    sb1.append(cat.getINNumber())
       .append("<td>")
       .append(cat.getDescription())
       .append("</td><td>")
       .append(cat.getStatus())
       .append("</td><td>")
       .append(cat.getStatus())
       .append("</td><td>")
       .append(cat.getOwner())
       .append("</td><td>")
       .append(cat.getOwnerGroup())
       .append("</td><td>")
       .append(cat.getSeverity());
    sb1.append("</tr>");
    String in = sb1.toString();

}
sb1.append("</table></body></html>");

message.setText(sb1.toString());

Transport.send(message);
</code>```

答:
Try this -

```<code>MimeMessage simpleMessage = new MimeMessage(mailSession);
</code>```

Then, when you want to set the message body, either call

```<code>simpleMessage.setText(text, "utf-8", "html");
</code>```

or call

```<code>simpleMessage.setContent(text, "text/html; charset=utf-8");
</code>```

Hope this will help you :)

Title: Send data from java mail in HTML Table

Body:
I am trying to send data from my Java mail application in the form of a HTML table. The problem is that when I receive the mail, the data is in simple text format and not in a table form. Please suggest a solution

StringBuilder sb1 = new StringBuilder(200);
sb1.append(""+ "
");
for(SCSINPojo cat : ar){

    sb1.append("
");
    sb1.append(cat.getINNumber())
       .append("")
       .append(cat.getDescription())
       .append("	")
       .append(cat.getStatus())
       .append("	")
       .append(cat.getStatus())
       .append("	")
       .append(cat.getOwner())
       .append("	")
       .append(cat.getOwnerGroup())
       .append("	")
       .append(cat.getSeverity());
    sb1.append("
");
    String in = sb1.toString();

}
sb1.append("
");

message.setText(sb1.toString());

Transport.send(message);

Body:
Try this -

MimeMessage simpleMessage = new MimeMessage(mailSession);

Then, when you want to set the message body, either call

simpleMessage.setText(text, "utf-8", "html");

or call

simpleMessage.setContent(text, "text/html; charset=utf-8");

Hope this will help you :)


问:
Check if a pointer points to a valid structure
I have N statically allocated structures.

```<code>struct exemple{
     ...
}

struct exemple array[N];
struct exemple *test_ptr = 0x3; /* random address */
</code>```

Can I check if test_prt points to a valid address? i.e. it points to one "struct example" allocated.

答:
In general, no, you can't test if a pointer is valid or not.

But, if you want to know if a pointer points to an element of an array, you can:

```<code>if(test_ptr >= &array[0] && test_ptr < &array[N]
        && ((intptr_t)test_ptr - (intptr_t)array)%((intptr_t)(&array[1]) - (intptr_t)array) == 0) {
    // test_ptr points to an element of array
}
</code>```

This works because arrays are allocated contiguously.

Body:
I have N statically allocated structures.

struct exemple{
     ...
}

struct exemple array[N];
struct exemple *test_ptr = 0x3; /* random address */

Can I check if test_prt points to a valid address? i.e. it points to one "struct example" allocated.

Body:
In general, no, you can't test if a pointer is valid or not.

But, if you want to know if a pointer points to an element of an array, you can:

if(test_ptr >= &array[0] && test_ptr < &array[N]
        && ((intptr_t)test_ptr - (intptr_t)array)%((intptr_t)(&array[1]) - (intptr_t)array) == 0) {
    // test_ptr points to an element of array
}

This works because arrays are allocated contiguously.


答:
After adding required PPA file you should write sudo apt-get install nodejs
to install node.js

This will allow you to easily install modules and packages to use with node.js

Because of a conflict with another package, the executable from the Ubuntu repositories is called nodejs instead of node. Keep this in mind as you are running software.

ref: https://www.digitalocean.com/community/tutorials/how-to-install-node-js-on-ubuntu-16-04

Title: Node.js installation: Should it be nodejs or node.js?

Body:
After launching an ec2 Ubuntu 16.04 instance on AWS, I have both:

apt-get install nodejs

and:

apt-get install node.js

Both are runnable but each shows different disk usage.  Which should be the correct one to install Node.js? (Why are there two? How different are they?)


问:
Extract data from one workbook and copy to another workbook
I am trying to copy the data from one workbook  to another workbook.

I searched through Internet and came up with the below code. there is no error in the code.

The code works fine, but the Problem is,  it is opening both the Sheets , but not copying the data in Destination sheet.

in the code below, I have considered x as source sheet and y as Destination sheet.

Could someone suggest, where i am wrong and what is the reason i am not able to copy.

```<code>Sub test()
Dim x As Workbook
Dim y As Workbook
Dim val As Variant
Dim filename As String

Set x = Workbooks.Open("D:\Mikz\xxx.xlsx")

Set y = Sheets("Sheet1").Select
val = x.Sheets("Sheet2").Range("A1").Value
y.Sheets("Sheet1").Range("A1").Value = val

x.Close

End Sub
</code>```

答:
Try:

```<code>Sub test()
Dim wb As Workbook
Dim sht As Worksheet, sht2 As Worksheet

Set wb = Workbooks.Open("Filename")
Set sht = wb.Worksheets("Sheet2")
Set sht2 = ThisWorkbook.Worksheets("Sheet1")

sht2.Range("A1").Value = sht.Range("A1").Value

wb.Close
End Sub
</code>```

But it should throw syntax errors and type mismatches before. Dont use .Select, its not necessary for any functions or task, it can be done without.

Body:
I am trying to copy the data from one workbook  to another workbook.

I searched through Internet and came up with the below code. there is no error in the code.

The code works fine, but the Problem is,  it is opening both the Sheets , but not copying the data in Destination sheet.

in the code below, I have considered x as source sheet and y as Destination sheet.

Could someone suggest, where i am wrong and what is the reason i am not able to copy.

Sub test()
Dim x As Workbook
Dim y As Workbook
Dim val As Variant
Dim filename As String

Set x = Workbooks.Open("D:\Mikz\xxx.xlsx")

Set y = Sheets("Sheet1").Select
val = x.Sheets("Sheet2").Range("A1").Value
y.Sheets("Sheet1").Range("A1").Value = val

x.Close

End Sub

Body:
Try:

Sub test()
Dim wb As Workbook
Dim sht As Worksheet, sht2 As Worksheet

Set wb = Workbooks.Open("Filename")
Set sht = wb.Worksheets("Sheet2")
Set sht2 = ThisWorkbook.Worksheets("Sheet1")

sht2.Range("A1").Value = sht.Range("A1").Value

wb.Close
End Sub

But it should throw syntax errors and type mismatches before. Dont use .Select, its not necessary for any functions or task, it can be done without.