问:
Back to top link flashes twice before dissappearing
As per the fiddle below I have a scroll back to top link, but upon clicking the link to scroll back to the top it flashes twice.

I have tried the usual suspects such as the $(body,html), but it still occurs even when I use one of those.

stop() before the fadeIn and fadeOut does help prevent this but causes the fadeIn to be incredibly slow.

Therefore, I was wondering if anyone could explain why this flash of the element is happening and how I could stop it from occurring?

jQuery(function() {
  jQuery(window).scroll(function() {
    if (jQuery(this).scrollTop() > 50) {
      jQuery('#back_top').fadeIn();
    } else {
      jQuery('#back_top').fadeOut();
    }
  });
  jQuery('#back_top').click(function() {
    jQuery('body,html').animate({
      scrollTop: 0
    }, 500);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#back_top {
  background-color: #447282;
  /* button color */
  color: white;
  /* text/arrow color */
  display: none;
  z-index: 999;
  /* float in bottom right corner */
  /* 20 pixels from edge */
  position: fixed;
  right: 10px;
  bottom: 10px;
  /* size of button is 50 pixels*/
  width: 54px;
  height: 54px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  opacity: 0.9;
}

a#back_top {
  font-weight: 600;
  letter-spacing: 2px;
  font-size: 12px;
  text-transform: uppercase;
  text-align: center;
  line-height: 1.6;
  padding-left: 2px;
  padding-top: 8px;
}

a#back_top .arrow:before {
  content: "\e902";
  font-family: 'vishIcon';
  font-style: normal;
  font-weight: 600;
  font-size: 18px;
  line-height: 1;
  speak: none;
  -webkit-font-smoothing: antialiased;
  content: "\e902";
  text-align: center;
  display: block;
  vertical-align: middle;
  cursor: pointer;
  /*     margin-left: -4px; */
}</code>```

What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using
Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default
model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary
to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the
more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"
(The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The
standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions
from the 1914 translation by H. Rackham. Where can I get some? There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly
believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this
the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition,
injected humour, or non-characteristic words etc.
Top```

答:
You can test the reason by adding console.log to

```<code>  jQuery(window).scroll(function() {
      console.log(jQuery(this).scrollTop());
    ...
  });
  jQuery('#back_top').click(function() {
    console.log("start");
      ...
  });
</code>```

The result shows like this

```<code>start
0
379.6666564941406
376.3166809082031
369.6166687011719
360.6833190917969
351.75
340.5833435058594
327.1833190917969
311
294.25
277.5
259.6333312988281
239
217.78334045410156
201.03334045410156
179.81666564941406
158.60000610351562
140.73333740234375
120.63333129882812
102.76667022705078
83.78333282470703
69.26667022705078
54.75
41.349998474121094
29.066667556762695
19.016666412353516
11.199999809265137
5.616666793823242
1.149999976158142
0
</code>```

When you call .animate, first time scrollTop = 0 event happens and then decrease from 379.6666564941406 to 0. so FadeIn happens two separate times.

So you can add a flag to calculate jQuery(window).scroll on animating.

 var animating = false;
jQuery(function() {
  jQuery(window).scroll(function() {
    if (animating) return;
    if (jQuery(this).scrollTop() > 50) {
      jQuery('#back_top').fadeIn();
    } else {
      jQuery('#back_top').fadeOut();
    }
  });
  jQuery('#back_top').click(function() {
    animating = true;
    setTimeout(function(){
       animating = false;
       jQuery('#back_top').fadeOut();
    },500)
    jQuery('body,html').animate({
      scrollTop: 0
    }, 500);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#back_top {
  background-color: #447282;
  /* button color */
  color: white;
  /* text/arrow color */
  display: none;
  z-index: 999;
  /* float in bottom right corner */
  /* 20 pixels from edge */
  position: fixed;
  right: 10px;
  bottom: 10px;
  /* size of button is 50 pixels*/
  width: 54px;
  height: 54px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  opacity: 0.9;
}

a#back_top {
  font-weight: 600;
  letter-spacing: 2px;
  font-size: 12px;
  text-transform: uppercase;
  text-align: center;
  line-height: 1.6;
  padding-left: 2px;
  padding-top: 8px;
}

a#back_top .arrow:before {
  content: "\e902";
  font-family: 'vishIcon';
  font-style: normal;
  font-weight: 600;
  font-size: 18px;
  line-height: 1;
  speak: none;
  -webkit-font-smoothing: antialiased;
  content: "\e902";
  text-align: center;
  display: block;
  vertical-align: middle;
  cursor: pointer;
  /*     margin-left: -4px; */
}</code>```

What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using
Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default
model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary
to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the
more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"
(The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The
standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions
from the 1914 translation by H. Rackham. Where can I get some? There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly
believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this
the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition,
injected humour, or non-characteristic words etc.
Top```

Body:
As per the fiddle below I have a scroll back to top link, but upon clicking the link to scroll back to the top it flashes twice.

I have tried the usual suspects such as the $(body,html), but it still occurs even when I use one of those.

stop() before the fadeIn and fadeOut does help prevent this but causes the fadeIn to be incredibly slow.

Therefore, I was wondering if anyone could explain why this flash of the element is happening and how I could stop it from occurring?

jQuery(function() {
  jQuery(window).scroll(function() {
    if (jQuery(this).scrollTop() > 50) {
      jQuery('#back_top').fadeIn();
    } else {
      jQuery('#back_top').fadeOut();
    }
  });
  jQuery('#back_top').click(function() {
    jQuery('body,html').animate({
      scrollTop: 0
    }, 500);
  });
});

#back_top {
  background-color: #447282;
  /* button color */
  color: white;
  /* text/arrow color */
  display: none;
  z-index: 999;
  /* float in bottom right corner */
  /* 20 pixels from edge */
  position: fixed;
  right: 10px;
  bottom: 10px;
  /* size of button is 50 pixels*/
  width: 54px;
  height: 54px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  opacity: 0.9;
}

a#back_top {
  font-weight: 600;
  letter-spacing: 2px;
  font-size: 12px;
  text-transform: uppercase;
  text-align: center;
  line-height: 1.6;
  padding-left: 2px;
  padding-top: 8px;
}

a#back_top .arrow:before {
  content: "\e902";
  font-family: 'vishIcon';
  font-style: normal;
  font-weight: 600;
  font-size: 18px;
  line-height: 1;
  speak: none;
  -webkit-font-smoothing: antialiased;
  content: "\e902";
  text-align: center;
  display: block;
  vertical-align: middle;
  cursor: pointer;
  /*     margin-left: -4px; */
}

What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using
Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default
model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary
to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the
more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"
(The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The
standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions
from the 1914 translation by H. Rackham. Where can I get some? There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly
believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this
the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition,
injected humour, or non-characteristic words etc.
Top

Body:
You can test the reason by adding console.log to

  jQuery(window).scroll(function() {
      console.log(jQuery(this).scrollTop());
    ...
  });
  jQuery('#back_top').click(function() {
    console.log("start");
      ...
  });

The result shows like this

start
0
379.6666564941406
376.3166809082031
369.6166687011719
360.6833190917969
351.75
340.5833435058594
327.1833190917969
311
294.25
277.5
259.6333312988281
239
217.78334045410156
201.03334045410156
179.81666564941406
158.60000610351562
140.73333740234375
120.63333129882812
102.76667022705078
83.78333282470703
69.26667022705078
54.75
41.349998474121094
29.066667556762695
19.016666412353516
11.199999809265137
5.616666793823242
1.149999976158142
0

When you call .animate, first time scrollTop = 0 event happens and then decrease from 379.6666564941406 to 0. so FadeIn happens two separate times.

So you can add a flag to calculate jQuery(window).scroll on animating.

 var animating = false;
jQuery(function() {
  jQuery(window).scroll(function() {
    if (animating) return;
    if (jQuery(this).scrollTop() > 50) {
      jQuery('#back_top').fadeIn();
    } else {
      jQuery('#back_top').fadeOut();
    }
  });
  jQuery('#back_top').click(function() {
    animating = true;
    setTimeout(function(){
       animating = false;
       jQuery('#back_top').fadeOut();
    },500)
    jQuery('body,html').animate({
      scrollTop: 0
    }, 500);
  });
});

#back_top {
  background-color: #447282;
  /* button color */
  color: white;
  /* text/arrow color */
  display: none;
  z-index: 999;
  /* float in bottom right corner */
  /* 20 pixels from edge */
  position: fixed;
  right: 10px;
  bottom: 10px;
  /* size of button is 50 pixels*/
  width: 54px;
  height: 54px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  opacity: 0.9;
}

a#back_top {
  font-weight: 600;
  letter-spacing: 2px;
  font-size: 12px;
  text-transform: uppercase;
  text-align: center;
  line-height: 1.6;
  padding-left: 2px;
  padding-top: 8px;
}

a#back_top .arrow:before {
  content: "\e902";
  font-family: 'vishIcon';
  font-style: normal;
  font-weight: 600;
  font-size: 18px;
  line-height: 1;
  speak: none;
  -webkit-font-smoothing: antialiased;
  content: "\e902";
  text-align: center;
  display: block;
  vertical-align: middle;
  cursor: pointer;
  /*     margin-left: -4px; */
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using
Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default
model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary
to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the
more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"
(The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The
standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions
from the 1914 translation by H. Rackham. Where can I get some? There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly
believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this
the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition,
injected humour, or non-characteristic words etc.
<a href="#" id="back_top" style="display: none;"><span class="arrow"></span>Top</a>


来源: stackexchange

问:
Non-breaking space removed by Text API
I'm using the Microsoft Translator Text API to translate parts of a webpage. The platform we use, inserts   in the HTML to render empty lines. So a part of the webpage can be:

```<code><p>
  <span>This is a dummy text</span>
</p>
<p>
  <span> </span>
</p>
</code>```

When I send this to the Microsoft Translator Text API, it returns the following HTML:

```<code><p>
  <span>Il s’agit d’un texte factice</span>
</p>
<p>
  <span></span>
</p>
</code>```

I've set the content type to text/html, and escape the HTML characters to be able to send it to the API (so   will be replaced with  ). But the text that is returned by the API has completely lost the  .

How can I prevent the API from removing the   instances in the HTML? Or is this a bug in the API?

答: A notranslate span may help to prevent translation. You would have to try it to see if it does indeed preserve the nbsp tag.</p>

ContentLicense: CC BY-SA 3.0

Title: Non-breaking space removed by Text API

Body:
I'm using the Microsoft Translator Text API to translate parts of a webpage. The platform we use, inserts   in the HTML to render empty lines. So a part of the webpage can be:

  This is a dummy text

When I send this to the Microsoft Translator Text API, it returns the following HTML:

  Il s’agit d’un texte factice

I've set the content type to text/html, and escape the HTML characters to be able to send it to the API (so   will be replaced with &nbsp;). But the text that is returned by the API has completely lost the  .

How can I prevent the API from removing the   instances in the HTML? Or is this a bug in the API?


问:
replace textarea loaded via ajax with ckeditor
When I have

```<code>   ...
    <textarea name="ta1" id="ta1" cols="50" rows="5"></textarea>
    <script type="text/javascript">
        CKEDITOR.replace( 'ta1' );
    </script>
    ...
</code>```

I get a ckeditor for the textarea.

But I am in need of loading that textarea via ajax, that is I have

```<code><textarea name="ta1" id="ta1" cols="50" rows="5"></textarea>
</code>```

in a php file which I call via ajax on "onload" of the page, and I assign the response to a div's innerHTML.

And down the line I have

```<code><script type="text/javascript">
    CKEDITOR.replace( 'ta1' );
</script>
</code>```

and I just get a plain textarea, ckeditor doesn't replace it, (says that textarea is undefined), is there a work around for this?.

CKEDITOR.replaceAll()

didn't help too.

(I couldn't see the textarea loaded via ajax in view source, shows in firebug though,
does that make any difference?). Any idea what could be wrong?.

答: Stupid me, had to call that replace(...) function right after the ajax response is complete( right after the line where response output is assigned to the div's innerhtml)</p>

ContentLicense: CC BY-SA 2.5

Body:
When I have

   ...
    <textarea name="ta1" id="ta1" cols="50" rows="5"></textarea>

    ...

I get a ckeditor for the textarea.

But I am in need of loading that textarea via ajax, that is I have

<textarea name="ta1" id="ta1" cols="50" rows="5"></textarea>

in a php file which I call via ajax on "onload" of the page, and I assign the response to a div's innerHTML.

And down the line I have

and I just get a plain textarea, ckeditor doesn't replace it, (says that textarea is undefined), is there a work around for this?.

CKEDITOR.replaceAll()

didn't help too.

(I couldn't see the textarea loaded via ajax in view source, shows in firebug though,
does that make any difference?). Any idea what could be wrong?.


问:
Binding two datasets in R when only some of the rows match
Basically, I want to bind two datasets in R by the column "country", and in both datasets this column contains a list of every country. One dataset is of GDP-level data, and the other is of internet penetration data. However, the dataset for internet-level data has a more comprehensive list of countries, with some included (such as Andorra) that are not included in the GDP dataset. I want to bind them together, wherein the dataset maintains its more comprehensive list of countries from the internet data, but the GDP data remains blank for those countries.

Using rbind nets the following error:

Error in rbind(deparse.level, ...) :
  numbers of columns of arguments do not match

Using rbind.fill nets a successful bind, but it just combines the two datasets, without binding by country (i.e. it treats "Austria," in the internet dataset and "Austria," in the GDP dataset as separate rows, though the coulmns both named country is combined into one row).

How do you bind two datasets by row when the column you seek to bind them by is not a 1-to-1 match?

答:
i suggest first cleaning your names with

```<code>library(janitor) clean_names(),
</code>```

then use
library(dplyr) bind_rows() which, in case a column exists in only one data frame, it will still appear

Body:
i suggest first cleaning your names with

library(janitor) clean_names(),

then use
library(dplyr) bind_rows() which, in case a column exists in only one data frame, it will still appear


问:
Rename JPG files according to date created
I want to rename all files in a certain directory. Renaming them to their date of creation.

So if my file is Image1.jpg, it should rename into something like "Jan 16 12:09:42 2011.jpg"

I want to do this through command line. I've been trying:

```<code>stat -f %SB Image0100.jpg
</code>```

But how can I combine this with mv command? And how will I iterate stat and mv through the whole files?

Or are there simple ways to rename all files with their date creation?

答:
Just use exiftool.  Here’s an example from its documentation:</p>

```<code>   exiftool -r '-FileName<CreateDate' -d %Y-%m-%d/%H%M_%%f.%%e dir
        Both the directory and the filename may be changed together via the
        "FileName" tag if the new "FileName" contains a '/'.  The example above
        recursively renames all images in a directory by adding a "CreateDate"
        timestamp to the start of the filename, then moves them into new
        directories named by date.
</code>```

Body:
I want to rename all files in a certain directory. Renaming them to their date of creation.

So if my file is Image1.jpg, it should rename into something like "Jan 16 12:09:42 2011.jpg"

I want to do this through command line. I've been trying:

stat -f %SB Image0100.jpg

But how can I combine this with mv command? And how will I iterate stat and mv through the whole files?

Or are there simple ways to rename all files with their date creation?

Body:
Just use exiftool.  Here’s an example from its documentation:

   exiftool -r '-FileName<CreateDate' -d %Y-%m-%d/%H%M_%%f.%%e dir
        Both the directory and the filename may be changed together via the
        "FileName" tag if the new "FileName" contains a '/'.  The example above
        recursively renames all images in a directory by adding a "CreateDate"
        timestamp to the start of the filename, then moves them into new
        directories named by date.


问:
How to do mathematical comparision with SQL CASE statement
I have a student table around 100k records and I have two types of data in it: student name and level type with selection values primary, secondary, intermediate & university

I want to filter out the student from this table, whose have count > 0, in all level primary, secondary, intermediate & university

I was able to find the sum for each student in each level using the following query

```<code>SELECT
    student_id,
    SUM(CASE WHEN lev_type = 'primary' THEN 1 ELSE 0 END) AS primary,
    SUM(CASE WHEN lev_type = 'secondary' THEN 1 ELSE 0 END) AS secondary,
    SUM(CASE WHEN lev_type = 'intermediate' THEN 1 ELSE 0 END) AS intermediate,
    SUM(CASE WHEN level_type = 'university' THEN 1 ELSE 0 END) AS university
FROM
    student_details
GROUP BY
    student_id
</code>```

and I am getting a result like (note that my result is 92242 row(s))

```<code>attendee_id     primary secondary   intermediate    uni
    student1    0        1                1          2
    student2    0        1                1          0
    student3    88       209              92         32
    student4    0        1                1          0
    student5    0        1                1          0
</code>```

How to filter out student3 from this result?

答:
HAVING might get you what you want.  For example:

```<code>SELECT student_id,
   sum(case when lev_type  = 'primary' then 1 else 0 end) as primary,
   sum(case when  lev_type  = 'secondary' then 1 else 0 end)  as secondary ,
   sum(case when  lev_type  = 'intermediate' then 1 else 0 end)  as intermediate ,
  sum(case when  level_type  = 'university' then 1 else 0 end) as university
from student_details
group by student_id
-- Put the criteria here by which you want to filter
having sum(case when lev_type  = 'primary' then 1 else 0 end) = 0
    and sum(case when  lev_type  = 'secondary' then 1 else 0 end) = 0
    and sum(case when  lev_type  = 'intermediate' then 1 else 0 end) = 0
    and sum(case when  level_type  = 'university' then 1 else 0 end) = 0
</code>```

Body:
I have a student table around 100k records and I have two types of data in it: student name and level type with selection values primary, secondary, intermediate & university

I want to filter out the student from this table, whose have count > 0, in all level primary, secondary, intermediate & university

I was able to find the sum for each student in each level using the following query

SELECT
    student_id,
    SUM(CASE WHEN lev_type = 'primary' THEN 1 ELSE 0 END) AS primary,
    SUM(CASE WHEN lev_type = 'secondary' THEN 1 ELSE 0 END) AS secondary,
    SUM(CASE WHEN lev_type = 'intermediate' THEN 1 ELSE 0 END) AS intermediate,
    SUM(CASE WHEN level_type = 'university' THEN 1 ELSE 0 END) AS university
FROM
    student_details
GROUP BY
    student_id

and I am getting a result like (note that my result is 92242 row(s))

attendee_id     primary secondary   intermediate    uni
    student1    0        1                1          2
    student2    0        1                1          0
    student3    88       209              92         32
    student4    0        1                1          0
    student5    0        1                1          0

How to filter out student3 from this result?

Body:
HAVING might get you what you want.  For example:

SELECT student_id,
   sum(case when lev_type  = 'primary' then 1 else 0 end) as primary,
   sum(case when  lev_type  = 'secondary' then 1 else 0 end)  as secondary ,
   sum(case when  lev_type  = 'intermediate' then 1 else 0 end)  as intermediate ,
  sum(case when  level_type  = 'university' then 1 else 0 end) as university
from student_details
group by student_id
-- Put the criteria here by which you want to filter
having sum(case when lev_type  = 'primary' then 1 else 0 end) = 0
    and sum(case when  lev_type  = 'secondary' then 1 else 0 end) = 0
    and sum(case when  lev_type  = 'intermediate' then 1 else 0 end) = 0
    and sum(case when  level_type  = 'university' then 1 else 0 end) = 0


问:
Checking Symbolic Equation Equality in Matlab
How can one check if symbolic eq1 is equal to symbolic eq2 in Matlab:</p>

```<code>syms a x y
eq1 = a*(x+y)
eq2 = a*x + a*y
</code>```

答:
You could use simplify on the difference, then logical to test if it is equal to 0:

```<code>eqAreEqual = logical(simplify(eq1-eq2) == 0);
</code>```

You could also use simplify on each and isequal for comparison:

```<code>eqAreEqual = isequal(simplify(eq1), simplify(eq2));
</code>```

For example:

```<code>>> syms a x y
>> eq1 = a*(x+y);
>> eq2 = a*x + a*y;
>> eqAreEqual = logical(simplify(eq1-eq2) == 0)

eqAreEqual =

  logical

   1  % True!

>> eqAreEqual = isequal(simplify(eq1), simplify(eq2))

eqAreEqual =

  logical

   1  % Also true!
</code>```

Body:
How can one check if symbolic eq1 is equal to symbolic eq2 in Matlab:

syms a x y
eq1 = a*(x+y)
eq2 = a*x + a*y

Body:
You could use simplify on the difference, then logical to test if it is equal to 0:

eqAreEqual = logical(simplify(eq1-eq2) == 0);

You could also use simplify on each and isequal for comparison:

eqAreEqual = isequal(simplify(eq1), simplify(eq2));

For example:

>> syms a x y
>> eq1 = a*(x+y);
>> eq2 = a*x + a*y;
>> eqAreEqual = logical(simplify(eq1-eq2) == 0)

eqAreEqual =

  logical

   1  % True!

>> eqAreEqual = isequal(simplify(eq1), simplify(eq2))

eqAreEqual =

  logical

   1  % Also true!


问:
VBA Input Box will not close
I currently have a code shown below for entering a password to have the code start. I am a VBA noob so please go easy on me.

Issue: When the input box prompt appears it works fine if the password is correct. If it is incorrect you are given more opportunities to enter it again but lets say you do not know the password and want to close the window, you cannot. The "x" option and cancel options will just cause the input box prompt to refresh rather than closing the window. How can I set the window up to close?

Here is the code in written form:

```<code>    Sub Pword()

        Dim Ans As Boolean
        Const Pword As String = "black2"

        Ans = False

        Do While Ans = False
            If InputBox("Please enter password to continue.", "Enter Password") = Pword Then
                Ans = True
            End If
        Loop

Sheets("Workshop").Range("B15:B20") = ""
Sheets("Workshop").Range("B24:B29") = ""
Sheets("Workshop").Range("B33:B35") = ""
Sheets("Workshop").Range("E5:E11") = ""
Sheets("Workshop").Range("E15:E26") = ""
Sheets("Workshop").Range("H5:H17") = ""

MsgBox "All data has been cleared."

End Sub
</code>```

答:
Add a check to see if it's an empty string, like this:</p>

```<code>    Dim sResult As String
    Do While Ans = False
        sResult = InputBox("Please enter password to continue.", "Enter Password")
        If sResult = Pword Then
            Ans = True
        ElseIf sResult = "" Then
            Exit Do ' or Exit Sub depending on what you want to happen afterwards
        End If
    Loop
</code>```

Title: VBA Input Box will not close

Body:
I currently have a code shown below for entering a password to have the code start. I am a VBA noob so please go easy on me.

Issue: When the input box prompt appears it works fine if the password is correct. If it is incorrect you are given more opportunities to enter it again but lets say you do not know the password and want to close the window, you cannot. The "x" option and cancel options will just cause the input box prompt to refresh rather than closing the window. How can I set the window up to close?

Here is the code in written form:

    Sub Pword()

        Dim Ans As Boolean
        Const Pword As String = "black2"

        Ans = False

        Do While Ans = False
            If InputBox("Please enter password to continue.", "Enter Password") = Pword Then
                Ans = True
            End If
        Loop

Sheets("Workshop").Range("B15:B20") = ""
Sheets("Workshop").Range("B24:B29") = ""
Sheets("Workshop").Range("B33:B35") = ""
Sheets("Workshop").Range("E5:E11") = ""
Sheets("Workshop").Range("E15:E26") = ""
Sheets("Workshop").Range("H5:H17") = ""

MsgBox "All data has been cleared."

End Sub

Body:
Add a check to see if it's an empty string, like this:

    Dim sResult As String
    Do While Ans = False
        sResult = InputBox("Please enter password to continue.", "Enter Password")
        If sResult = Pword Then
            Ans = True
        ElseIf sResult = "" Then
            Exit Do ' or Exit Sub depending on what you want to happen afterwards
        End If
    Loop


问:
Notify email when Azure Storage table gets new entry
Is there an inbuilt way to notify an email when a new entry is added to the Table?

I am asking for anything programatically just within their own UI

答:
Okay, so the easiest way to see the data is to use their desktop app

Use https://azure.microsoft.com/en-us/features/storage-explorer/


问:
Why does event.mouseWheelScroll.delta always return 0 using SFML?
I am testing out the feature in the SFML library mouseWheelScroll.delta but I always get a return value of 0. Why could this be?

My code that I used is below, note that on some of the first lines of code in the program I initialised the variable sf::Event event;.

```<code>    if (event.type == sf::Event::MouseWheelScrolled) {
    std::cout << "wheel movement: " << event.mouseWheelScroll.delta << std::endl;
}
</code>```

Does the SFML library need a window or could it use the console? (I only ask because I am creating a console application)

答:
Thank you for the help everyone, it turns out that I had a problem with the line sf::RenderWindow v(sf::VideoMode::getDesktopMode(), "SFML"); and this was because the VC++ add-on wasn't installed, which is why I was always getting a "could not find "winmm.lib"" error.

Both of these code samples that others provided work, it was just me... sorry, but it is much appreciated!

Body:
I am testing out the feature in the SFML library mouseWheelScroll.delta but I always get a return value of 0. Why could this be?

My code that I used is below, note that on some of the first lines of code in the program I initialised the variable sf::Event event;.

    if (event.type == sf::Event::MouseWheelScrolled) {
    std::cout << "wheel movement: " << event.mouseWheelScroll.delta << std::endl;
}

Does the SFML library need a window or could it use the console? (I only ask because I am creating a console application)


问:
When scaling is determined, why is there a need for both screen size and density?
When scaling (A layout, an image, and so on), Android determines the scaling based on two factors: Screen size and screen density.

Why is there a need for both of them?

For simplicity, let's assume an app that has a single layout file, with several elements defined with dp units, and with no provided alternative resources.
In such a case, a scaling is applied (listing 2, Italic added):

At runtime, the system ensures the best possible display on the
  current screen with the following procedure for any given resource:

The system uses the appropriate alternative resource [...]

If no matching resource is available, the system uses the default
  resource and scales it up or down as needed to match the current
  screen size and density

Now, given the above,  what would not be possible, scaling-wise, if scaling would have been determined only by one of these factors?

A side note:

Numerous resources online regards the scaling functionality, but I'm having a hard time finding a direct explanation for the need of Android to use both size and density factors for it.

To add on that, the most cited resource, Supporting Multiple Screens, left things unclear for me when first stating that the four generalized sizes (small, medium, large, xlarge) are deprecated beginning with Android 3.2, while later repeatedly referring to those generalizations as if they are still used (E.g., when stating that "the system uses the appropriate resources based on the generalized size or density"), and other documentation pages do so as well (E.g., the table here).

On the other hand, the above cited page defines only one type of independency - a density independency, and not a size independency. Therefore, I was left confused.

答:
You usually need bigger margins or layout with different positions (like side by side instead of vertical) with the same views in bigger screens (small, large, xlarge, etc).

But for densitities (mdpi, hdpi, xhdpi, etc) usually you just need bigger image resources (bigger with the original resolution and thickness) so you dont rely on the default scale up image algorithm of Android for images (leading to blur images).


答:
You can simply add a where statement as follows:</p>

```<code>SELECT student_id,
      SUM(case when lev_type  = 'primary' then 1 else 0 end) as primary,
      SUM(case when lev_type  = 'secondary' then 1 else 0 end)  as secondary ,
      SUM(case when lev_type  = 'intermediate' then 1 else 0 end)  as intermediate ,
      SUM(case when lev_type  = 'university' then 1 else 0 end) as university
 FROM student_details
 GROUP BY student_id
 WHERE primary = 0 OR secondary = 0 OR intermediate = 0 OR university  = 0
</code>```

Title: How to do mathematical comparision with SQL CASE statement

Body:
You can simply add a where statement as follows:

SELECT student_id,
      SUM(case when lev_type  = 'primary' then 1 else 0 end) as primary,
      SUM(case when lev_type  = 'secondary' then 1 else 0 end)  as secondary ,
      SUM(case when lev_type  = 'intermediate' then 1 else 0 end)  as intermediate ,
      SUM(case when lev_type  = 'university' then 1 else 0 end) as university
 FROM student_details
 GROUP BY student_id
 WHERE primary = 0 OR secondary = 0 OR intermediate = 0 OR university  = 0


问:
UpperBody detection using haar cascade
I'm trying to detect the upper body using haar cascade.
But still I'm not getting any detection on the image.

```<code>import numpy as np

import cv2

cascade = cv2.CascadeClassifier('haarcascade_upperbody.xml');

imgPath = '/home/ayush/Desktop/images.jpeg';
img = cv2.imread(imgPath);
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY);

body = cascade.detectMultiScale(
    gray,
    scaleFactor = 1.1,
    minNeighbors = 5,
    minSize = (30,30),
    flags = cv2.CASCADE_SCALE_IMAGE
)

for (x, y, w, h) in body:
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)

cv2.imshow('Upper Body',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Why is it so?
I'm using OpenCV3.

答:
It is possible that your scaleFactor is too small. I tried running your code exactly (though with my own image) and found no results at 1.1, but found results at 1.01.

See here for a description of how the parameter affects your results.

Title: UpperBody detection using haar cascade

Body:
I'm trying to detect the upper body using haar cascade.
But still I'm not getting any detection on the image.

import numpy as np

import cv2

cascade = cv2.CascadeClassifier('haarcascade_upperbody.xml');

imgPath = '/home/ayush/Desktop/images.jpeg';
img = cv2.imread(imgPath);
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY);

body = cascade.detectMultiScale(
    gray,
    scaleFactor = 1.1,
    minNeighbors = 5,
    minSize = (30,30),
    flags = cv2.CASCADE_SCALE_IMAGE
)

for (x, y, w, h) in body:
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)

cv2.imshow('Upper Body',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Why is it so?
I'm using OpenCV3.


问:
C#: Multiple handlers with different generic types
I would like to implement some handler logic, based on the type of a parameter. Take for example, implementing an exception filter attribute for WebAPI:

```<code>public class ExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is NotImplementedException)
        {
            context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
        }
    }
}
</code>```

This looks perfectly fine on its own, but what I would like to do, is add several handlers for different types of exceptions, e.g. DbEntityValidationException, or some other custom exceptions that my business logic may throw.

Now of course, I could easily add another if-block to check if the exception is a certain type, but I would rather avoid this and break out the handling of different exception types into separate classes.

An interface for such a class might look like this

```<code>public interface ExceptionHandler<T> where T : Exception {
    void Handle(HttpActionExecutedContext context, T exception);
}
</code>```

I would now like to add the implementations of these ExceptionHandlers into a collection in the ExceptionFilterAttribte, so I can check if there is a handler for the exception that was encountered and do the appropriate casting and call the handler. However, I can not figure out, how I would have to implement this part, since I cannot add implementations of the ExceptionHandler interface with different generic types T into a single collection (e.g. class DbEntityValidationExceptionHandler : ExceptionHandler<DbEntityValidationException>):

```<code>    private List<ExceptionHandler<Exception>> handlers = new List<ExceptionHandler<Exception>>()
    {
        new DbEntityValidationExceptionHandler() // does not compile...
    };
</code>```

How can I keep references to the different implementations of my ExceptionHandler<T> interface in a collection? Or is this approach completely misguided and there is a much better way of handling this type of situation? Any suggestions are greatly appreciated.

答:
you can do this with Variant Generic Interface</p>

```<code>class TestException : Exception
{
}
class TestException2:Exception
{
}

class foo : ExceptionHandler<TestException> { }
class bar : ExceptionHandler<TestException2> { }

public interface ExceptionHandler<out T> where T : Exception
{ }

class Program
{
    static void Main(string[] args)
    {
        List<ExceptionHandler<Exception>> a = new List<ExceptionHandler<Exception>>();
        a.Add(new foo());
        a.Add(new bar());
    }

}
</code>```

Body:
I would like to implement some handler logic, based on the type of a parameter. Take for example, implementing an exception filter attribute for WebAPI:

public class ExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is NotImplementedException)
        {
            context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
        }
    }
}

This looks perfectly fine on its own, but what I would like to do, is add several handlers for different types of exceptions, e.g. DbEntityValidationException, or some other custom exceptions that my business logic may throw.

Now of course, I could easily add another if-block to check if the exception is a certain type, but I would rather avoid this and break out the handling of different exception types into separate classes.

An interface for such a class might look like this

public interface ExceptionHandler<T> where T : Exception {
    void Handle(HttpActionExecutedContext context, T exception);
}

I would now like to add the implementations of these ExceptionHandlers into a collection in the ExceptionFilterAttribte, so I can check if there is a handler for the exception that was encountered and do the appropriate casting and call the handler. However, I can not figure out, how I would have to implement this part, since I cannot add implementations of the ExceptionHandler interface with different generic types T into a single collection (e.g. class DbEntityValidationExceptionHandler : ExceptionHandler<DbEntityValidationException>):

    private List<ExceptionHandler<Exception>> handlers = new List<ExceptionHandler<Exception>>()
    {
        new DbEntityValidationExceptionHandler() // does not compile...
    };

How can I keep references to the different implementations of my ExceptionHandler<T> interface in a collection? Or is this approach completely misguided and there is a much better way of handling this type of situation? Any suggestions are greatly appreciated.

Body:
you can do this with Variant Generic Interface

class TestException : Exception
{
}
class TestException2:Exception
{
}

class foo : ExceptionHandler<TestException> { }
class bar : ExceptionHandler<TestException2> { }

public interface ExceptionHandler<out T> where T : Exception
{ }

class Program
{
    static void Main(string[] args)
    {
        List<ExceptionHandler<Exception>> a = new List<ExceptionHandler<Exception>>();
        a.Add(new foo());
        a.Add(new bar());
    }

}


问:
Responsive React App via CSS
Right now, my app looks almost exactly how I want it too via larger screens. https://imgur.com/a/MCe5D - As you shrink the screen size down, the two columns (trending up and trending down) will get closer and closer until they are just about touching, which is great. But at that instance when they no longer get any closer, I would like to have the Trending Down and it's contents move underneath the Trending Up column, to be more mobile friendly. Here's a pen showing the area that is being affected.

```<code>//The whole area surrounding the two columns
.playersColumns {
display: flex;
flex-direction: row;
justify-content: space-evenly;
padding-left: 150px;
padding-right: 150px;
padding-top: 25px;
overflow-y: scroll;
}

//The two columns of player info
.playersBody {
overflow: auto;
flex-direction: column;
justify-content: center;
flex-wrap: wrap;
min-width: 255px;
}
</code>```

That pen isn't very useful, but it shows my exact code and which tags are where. I tried putting the 2nd column of player info and trend header inside of the first one, but that just made it one large column (which is what I want, but only when the screen is shrunk)

Any help is appreciated — if there is a better way to display the code or layout, let me know.

答:
I recommend looking into Media Queries.
Here is a short video to show you the basics.

You can set a threshold that will trigger separate styles under those conditions. It can be very useful when you want your UI to do something different at different sizes.

```<code>@media only screen
and (*Your threshold criteria goes here* EXAMPLE:  max-width : 1000px) {
  //css goes here with whatever css you want to fire at this threshold
}
</code>```

Title: Responsive React App via CSS

Body:
Right now, my app looks almost exactly how I want it too via larger screens. https://imgur.com/a/MCe5D - As you shrink the screen size down, the two columns (trending up and trending down) will get closer and closer until they are just about touching, which is great. But at that instance when they no longer get any closer, I would like to have the Trending Down and it's contents move underneath the Trending Up column, to be more mobile friendly. Here's a pen showing the area that is being affected.

//The whole area surrounding the two columns
.playersColumns {
display: flex;
flex-direction: row;
justify-content: space-evenly;
padding-left: 150px;
padding-right: 150px;
padding-top: 25px;
overflow-y: scroll;
}

//The two columns of player info
.playersBody {
overflow: auto;
flex-direction: column;
justify-content: center;
flex-wrap: wrap;
min-width: 255px;
}

That pen isn't very useful, but it shows my exact code and which tags are where. I tried putting the 2nd column of player info and trend header inside of the first one, but that just made it one large column (which is what I want, but only when the screen is shrunk)

Any help is appreciated — if there is a better way to display the code or layout, let me know.

Body:
I recommend looking into Media Queries.
Here is a short video to show you the basics.

You can set a threshold that will trigger separate styles under those conditions. It can be very useful when you want your UI to do something different at different sizes.

@media only screen
and (*Your threshold criteria goes here* EXAMPLE:  max-width : 1000px) {
  //css goes here with whatever css you want to fire at this threshold
}


问:
How to discard CoreData changes in one object when RKObjectManager failed to post object
how to discard CoreData changes made to an instance of NSManagedObject when POST/PUT request of this object fails in RKObjectManager?

```<code>NSManagedObject *object = ...;
[object setValue:@"test" forKey: @"test"];
[[RKObjectManager sharedManager] postObject:object
                                 parameters:nil
                                    success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { NSLog(@"success, nothing to do"); }
                                    failure:^(RKObjectRequestOperation *operation, NSError *error) {
  // I want to discard changes made to object here
}
</code>```

UPDATE: RestKit 0.20

答:
Swift solution:

```<code>import CoreData

extension NSManagedObject {
    func cancelChanges() {
        managedObjectContext?.refresh(self, mergeChanges: false)
    }
}
</code>```

Using:

```<code>object.cancelChanges()
</code>```

Body:
how to discard CoreData changes made to an instance of NSManagedObject when POST/PUT request of this object fails in RKObjectManager?

NSManagedObject *object = ...;
[object setValue:@"test" forKey: @"test"];
[[RKObjectManager sharedManager] postObject:object
                                 parameters:nil
                                    success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { NSLog(@"success, nothing to do"); }
                                    failure:^(RKObjectRequestOperation *operation, NSError *error) {
  // I want to discard changes made to object here
}

UPDATE: RestKit 0.20

Body:
Swift solution:

import CoreData

extension NSManagedObject {
    func cancelChanges() {
        managedObjectContext?.refresh(self, mergeChanges: false)
    }
}

Using:

object.cancelChanges()


问:
Adding "hoverIntent" to .live function
Real simple question here - how do I add the .hoverIntent plugin from Brian Cherne to the following code in place of the .live("hover", function

```<code>        $(".highlight").live("hover", function(){
            $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"-94px", "margin-left":"-152px"}, 500);

        });
</code>```

Here's the full code:

```<code>    $(document).ready(function(){

        $('#sliding_grid li').hover(function() {
          $(this).css('z-index',1).data('origTop',$(this).css('top')).data('origLeft',$(this).css('left')).addClass('highlight');

        }, function() {
          $(this).css('z-index', 0);
        });

        $(".highlight").live("hover", function(){
            $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"0", "margin-left":"0"}, 500);

        });

        $(".highlight").live("mouseout", function(){
            $(this).animate({"width": "148px", "height":"90px", "top: ":$(this).data('origTop'), "left":$(this).data('origLeft'), "margin-top: ":"0", "margin-left":"0"}, 500, function(){
             $(this).removeClass('highlight');
            });

        });

    });
</code>```

答:
```<code>function animateFn(){
     $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"-94px", "margin-left":"-152px"},200);
}

function reseteFn(){
    $(this).animate({"width": "148px", "height":"90px", "top: ":$(this).data('origTop'), "left":$(this).data('origLeft'), "margin-top: ":"0", "margin-left":"0"}, 500, function(){
         $(this).removeClass('highlight');
    });
}

var config = {
     over: animateFn, // function = onMouseOver callback (REQUIRED)
     timeout: 200, // number = milliseconds delay before onMouseOut
     out: reseteFn // function = onMouseOut callback (REQUIRED)
};

$(".highlight").hoverIntent(config)
</code>```

Title: Adding "hoverIntent" to .live function

Body:
Real simple question here - how do I add the .hoverIntent plugin from Brian Cherne to the following code in place of the .live("hover", function

        $(".highlight").live("hover", function(){
            $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"-94px", "margin-left":"-152px"}, 500);

        });

Here's the full code:

    $(document).ready(function(){

        $('#sliding_grid li').hover(function() {
          $(this).css('z-index',1).data('origTop',$(this).css('top')).data('origLeft',$(this).css('left')).addClass('highlight');

        }, function() {
          $(this).css('z-index', 0);
        });

        $(".highlight").live("hover", function(){
            $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"0", "margin-left":"0"}, 500);

        });

        $(".highlight").live("mouseout", function(){
            $(this).animate({"width": "148px", "height":"90px", "top: ":$(this).data('origTop'), "left":$(this).data('origLeft'), "margin-top: ":"0", "margin-left":"0"}, 500, function(){
             $(this).removeClass('highlight');
            });

        });

    });


问:
React invariant error
I'm running into the following error only when I test this in our staging environment, though the code runs without error when I run it locally.

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

There are two ways I can get the view to load without triggering the error.

I remove the onClick={handleClick} prop on the <Tabs /> styled-component

If I explicitly define the individual <Tab /> components as spans i.e. Your Tasks

List component

```<code>import React from 'react';
import styled from 'styled-components';

import ListItem from '../components/ListItem';

const List = ({ handleFiltering, listItems, match }) => {
  const handleClick = (e) => {
    handleFiltering(e.target.dataset.filter);
  }

  return (
    <ListWrapper>
      <Tabs onClick={handleClick}>
        <Tab data-filter="yourTasks">Your Tasks</Tab>
        <Tab data-filter="allTasks">All Tasks</Tab>
        <Tab data-filter="assignedTasks">Assigned</Tab>
      </Tabs>

      { _.map(listItems, item => <ListItem key={item._id} item={item} /> )}
    </ListWrapper>
  );
}

const ListWrapper = styled.section`
  flex: 1;
`;

const Tabs = styled.div`
  display: flex;
  margin-bottom: 10px;
`;

const Tab = styled.span`
  background-color: #F6F6F6;
`;

export default List;
</code>```

from parent ListContainer component where handleFiltering is defined

```<code>...

handleFiltering(filterType, list) {
  list = list || this.state.list;

  const filterTypes = {
    allTasks: () => list,
    yourTasks: () => (list.filter(item => item.assignedTo === this.userId)),
    assignedTasks: () => (list.filter(item => item.createdBy === this.userId)),
  }

  this.setState(() => {
    return { filteredList: filterTypes[filterType]() }
  });
}

...
</code>```

I did run through the "master" invariant SO post with no luck.

答:
The issue was, as Rick Jolly had mentioned in the comments, that the styled-components were defined after the component declaration.

I believe this is likely due to how things are being minified when bundled for prod/staging, but welcome more feedback there if someone knows more.

@rick-jolly, feel free to post as answer and I will attribute yours as the accepted solution.

Title: React invariant error

Body:
I'm running into the following error only when I test this in our staging environment, though the code runs without error when I run it locally.

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

There are two ways I can get the view to load without triggering the error.

I remove the onClick={handleClick} prop on the <Tabs /> styled-component

If I explicitly define the individual <Tab /> components as spans i.e. Your Tasks

List component

import React from 'react';
import styled from 'styled-components';

import ListItem from '../components/ListItem';

const List = ({ handleFiltering, listItems, match }) => {
  const handleClick = (e) => {
    handleFiltering(e.target.dataset.filter);
  }

  return (
    <ListWrapper>
      <Tabs onClick={handleClick}>
        <Tab data-filter="yourTasks">Your Tasks</Tab>
        <Tab data-filter="allTasks">All Tasks</Tab>
        <Tab data-filter="assignedTasks">Assigned</Tab>
      </Tabs>

      { _.map(listItems, item => <ListItem key={item._id} item={item} /> )}
    </ListWrapper>
  );
}

const ListWrapper = styled.section`
  flex: 1;
`;

const Tabs = styled.div`
  display: flex;
  margin-bottom: 10px;
`;

const Tab = styled.span`
  background-color: #F6F6F6;
`;

export default List;

from parent ListContainer component where handleFiltering is defined

...

handleFiltering(filterType, list) {
  list = list || this.state.list;

  const filterTypes = {
    allTasks: () => list,
    yourTasks: () => (list.filter(item => item.assignedTo === this.userId)),
    assignedTasks: () => (list.filter(item => item.createdBy === this.userId)),
  }

  this.setState(() => {
    return { filteredList: filterTypes[filterType]() }
  });
}

...

I did run through the "master" invariant SO post with no luck.


问:
Latitude and Longitude based on Zip Code
My requirement is to get the Latitude and Longitude value for a particular zip code. Is there any API that I can use to get these information. As I am working in a company so the requirement is coming for our team is to find the latitude and longitude value for a particular zip code. So we were thinking to build a new service for this. So what reliable data source we can use to get these information back if we are passing zip code to our service. Or what can be the best approach that I can propose to my PM about this requirement. Any pointers will be appreciated.

Just to add, that data source should have all the zip codes, latitudes and longitude in a world. Not that much accurate but mostly it should cover around more than 95% coverage.

Update

I did some research and I found that I can use Maxmind data for this but Maxmind data doesn't cover all the zip code list.

答: I have a situation where there are 12 warehouses nationwide and I needed to find the nearest one that has inventory for an item.  My simple solution was to take the absolute value of the difference between the target zip code and the 12 warehouses.  And then, simply ordering them by the lowest to highest difference in zip code numbers and querying the inventory in that order.  It seems that just getting the ABS(zip1 - zip2), yields the closet distance between two zipcodes.  </p>


问:
How to run a Java program (distributed as a Windows exe) under Linux?
I have a very simple JAVA app that is distributed as a single Windows executable file and I would like to run it on a Linux computer. I could extract the content of the exe file with 7-zip, but I don't know what to do next.

There are multiple levels of subfolders with .class files and image files for the software's user interface (no source files).

The root folder doesn't contain any class files, but it contains many subfolders, including a META-INF subfolder. This META-INF folder contains one MANIFEST.MF file, in which there is a line like this:
Main-Class: subfolder1.subfolder2.Software

How can I make it run? Is there a way to run it on a Linux computer's JVM?

答:
I extracted the content of the Windows executable file with 7-ZIP,
created a JAR file and executed it with these commands:</p>

```<code>cd MyAppName
jar cfm MyAppName.jar .\META-INF\MANIFEST.MF .
java -jar MyAppName.jar
</code>```

Body:
I extracted the content of the Windows executable file with 7-ZIP,
created a JAR file and executed it with these commands:

cd MyAppName
jar cfm MyAppName.jar .\META-INF\MANIFEST.MF .
java -jar MyAppName.jar


问:
How can I print the Students info?
Is there a way I can print my students with the information provided?
I created a service class with all the information about the course, where I wish to input my students info on a very simple way.

student class:

```<code>public class student {

    //Fields
    private static String classNumber = "264";
    private static String className = "Transfiguration";
    private static String instructor = "Professor McGonagall";

    private int studentId;
    private String firstname;
    private String lastname;
    private String address;
    private String city;
    private String state;
    private String email;

    //Getters and setters

    static String getClassNumber(){
        return (classNumber);
    }
    static String getClassName(){
        return (className);
    }
    static String getInstructor(){
        return (instructor);
    }
    static void setClassName(String name){
        className = name;
    }

    int getStudentId(){
        return (studentId);
    }
    String getFirstName(){
        return (firstname);
    }
    String getLastName(){
        return (lastname);
    }
    String getAddress(){
        return (address);
    }
    String getCity(){
        return (city);
    }
    String getState(){
        return (state);
    }
    String getEmail(){
        return (email);
    }
    void setFirstName(String first) {
        this.firstname = first;
    }
    void setLastName(String last) {
        this.lastname = last;
    }
    void setAddress(String rua) {
        this.address = rua;
    }
    void setCity(String cidade) {
        this.city = cidade;
    }
    void setEmail(Sring correio) {
        this.email = correio;
     }
     //Contructors
    student(String la) {
        this.firstname = first;
        this.lastname = last;
        this.studentId += 1000;
    }
    student(String la, int id, String first, String last, String rua, String cidade, String correio) {

        this(la);

        this.address = rua;
        this.city = cidade;
        this.email = correio;

     }

    public String toString() {
        String data = "Course: " + classNumber + " " + className +
                    "\t instructor: " + instructor +
                    "\t Student Number: " + id +
                    "\t Student Name: "  + firstname + " " + lastname +
                    "\t Address: " + rua + cidade +
                    "\t Email: " + correio;
        return (data);
    }

}
</code>```

studentTest class:

```<code>public class studentTest {
    public static void main (String [] args) {

        System.out.println("Course: " + student.getClassNumber() + student.getClassName());

        student a = new student("Kakashi", "Hatake", "W 69th st", "NY", "khsensei@ninja.com");
        student b = new student("Albus", "Dumbledore", "W 116th st", "NY", "princip-al@hogwarts.com" );
        student c = new student("Hyuk", "Jang", "321 Maple St", "NJ", "jh@actors.com");
        student d = new student("Michael", "Jackson", "543 thriller st", "NY", "mj@singer.com");
        student e = new student("Hamilton", "Alexander", "E 86th st", "NY", "justyouwait@broadway.com");

        String fname = a.firstname;
        System.out.println("First Name: " + fname);

        System.out.println(a.toString());
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);
        System.out.println(e);
    }
}
</code>```

What I wish to do is print all the information on their proper place, however I must have forgotten something pretty serious that I'm getting error messages. Are the students info linked properly to the first class?

--

A few of the error messages I get:
"student.java:114: error: class studentTest is public, should be declared in a file named studentTest.java" - for this one, I've tried before and I can put both classes on the same file, why wouldn't be working now?

Some symbols can't be found:

symbol: variable first
location: class student
student.java:83: error: cannot find symbol
             this.lastname = last;

the same also happens with the variables id, last, rua, cidade, and correio.

there's also an error about the constructor
     constructor student.student(String) is no applicable
           (actual and formal argument lists differ in length)
     constructor student.student(String, int, String, String, String, String) is no applicable
student.java:124 error: no suitable constructor found for student (String, String...)

答:
The problem in the code is in this line:

String fname = a.firstname;

You are basically trying to access a private field when you actually want to do is:

String fname = a.getFirstName();

The other problem is the constructor:

```<code>student(String la) {
        this.firstname = first;
        this.lastname = last;
        this.studentId += 1000;
    }
</code>```

both first and last variables do not exist in this context.

Title: How can I print the Students info?

Body:
Is there a way I can print my students with the information provided?
I created a service class with all the information about the course, where I wish to input my students info on a very simple way.

student class:

public class student {

    //Fields
    private static String classNumber = "264";
    private static String className = "Transfiguration";
    private static String instructor = "Professor McGonagall";

    private int studentId;
    private String firstname;
    private String lastname;
    private String address;
    private String city;
    private String state;
    private String email;

    //Getters and setters

    static String getClassNumber(){
        return (classNumber);
    }
    static String getClassName(){
        return (className);
    }
    static String getInstructor(){
        return (instructor);
    }
    static void setClassName(String name){
        className = name;
    }

    int getStudentId(){
        return (studentId);
    }
    String getFirstName(){
        return (firstname);
    }
    String getLastName(){
        return (lastname);
    }
    String getAddress(){
        return (address);
    }
    String getCity(){
        return (city);
    }
    String getState(){
        return (state);
    }
    String getEmail(){
        return (email);
    }
    void setFirstName(String first) {
        this.firstname = first;
    }
    void setLastName(String last) {
        this.lastname = last;
    }
    void setAddress(String rua) {
        this.address = rua;
    }
    void setCity(String cidade) {
        this.city = cidade;
    }
    void setEmail(Sring correio) {
        this.email = correio;
     }
     //Contructors
    student(String la) {
        this.firstname = first;
        this.lastname = last;
        this.studentId += 1000;
    }
    student(String la, int id, String first, String last, String rua, String cidade, String correio) {

        this(la);

        this.address = rua;
        this.city = cidade;
        this.email = correio;

     }

    public String toString() {
        String data = "Course: " + classNumber + " " + className +
                    "\t instructor: " + instructor +
                    "\t Student Number: " + id +
                    "\t Student Name: "  + firstname + " " + lastname +
                    "\t Address: " + rua + cidade +
                    "\t Email: " + correio;
        return (data);
    }

}

studentTest class:

public class studentTest {
    public static void main (String [] args) {

        System.out.println("Course: " + student.getClassNumber() + student.getClassName());

        student a = new student("Kakashi", "Hatake", "W 69th st", "NY", "khsensei@ninja.com");
        student b = new student("Albus", "Dumbledore", "W 116th st", "NY", "princip-al@hogwarts.com" );
        student c = new student("Hyuk", "Jang", "321 Maple St", "NJ", "jh@actors.com");
        student d = new student("Michael", "Jackson", "543 thriller st", "NY", "mj@singer.com");
        student e = new student("Hamilton", "Alexander", "E 86th st", "NY", "justyouwait@broadway.com");

        String fname = a.firstname;
        System.out.println("First Name: " + fname);

        System.out.println(a.toString());
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);
        System.out.println(e);
    }
}

What I wish to do is print all the information on their proper place, however I must have forgotten something pretty serious that I'm getting error messages. Are the students info linked properly to the first class?

--

A few of the error messages I get:
"student.java:114: error: class studentTest is public, should be declared in a file named studentTest.java" - for this one, I've tried before and I can put both classes on the same file, why wouldn't be working now?

Some symbols can't be found:

symbol: variable first
location: class student
student.java:83: error: cannot find symbol
             this.lastname = last;

the same also happens with the variables id, last, rua, cidade, and correio.

there's also an error about the constructor
     constructor student.student(String) is no applicable
           (actual and formal argument lists differ in length)
     constructor student.student(String, int, String, String, String, String) is no applicable
student.java:124 error: no suitable constructor found for student (String, String...)

Body:
The problem in the code is in this line:

String fname = a.firstname;

You are basically trying to access a private field when you actually want to do is:

String fname = a.getFirstName();

The other problem is the constructor:

student(String la) {
        this.firstname = first;
        this.lastname = last;
        this.studentId += 1000;
    }

both first and last variables do not exist in this context.


问:
Dynamically assign event in javascript object
I have following javascript class:

```<code>var ImageGallery = function(arr) {
    var ImgArr = arr;
    var MainImgId = "";

    this.build = function() {
        var div = document.createElement("div");
        for (var i = 0; i < ImgArr.length; i++) {
            var img = document.createElement("img");
            img.scr = ImgArr[i];
            // what to do next, how to assign loadMainImage function ?????
            img.onclick =
            div.appendChild(img);

        }
    }

    this.loadMainImage = function(imgPath) {
        document.getElementById(MainImgId).src = imgPath;
    }
}
</code>```

next, in code I create an object of that class:

```<code>var gallery = new ImageGallery(someArrWithPaths);
gallery.MainImgId = 'idOfMainImg';
gallery.build();
</code>```

How can I assign img.onclick event to launch loadMainImage(imgPath) function every time I click on the image?

Thanks a lot!

答:
You need to capture the current value of this (which refers to the ImageGallery object) and invoke loadMainImage on it within onclick. Inside onclick, this refers to the image itself, so this.src will give you the image source:

```<code>var self = this;
img.onclick = function() {
  self.loadMainImage(this.src);
};
</code>```

Body:
I have following javascript class:

var ImageGallery = function(arr) {
    var ImgArr = arr;
    var MainImgId = "";

    this.build = function() {
        var div = document.createElement("div");
        for (var i = 0; i < ImgArr.length; i++) {
            var img = document.createElement("img");
            img.scr = ImgArr[i];
            // what to do next, how to assign loadMainImage function ?????
            img.onclick =
            div.appendChild(img);

        }
    }

    this.loadMainImage = function(imgPath) {
        document.getElementById(MainImgId).src = imgPath;
    }
}

next, in code I create an object of that class:

var gallery = new ImageGallery(someArrWithPaths);
gallery.MainImgId = 'idOfMainImg';
gallery.build();

How can I assign img.onclick event to launch loadMainImage(imgPath) function every time I click on the image?

Thanks a lot!

Body:
You need to capture the current value of this (which refers to the ImageGallery object) and invoke loadMainImage on it within onclick. Inside onclick, this refers to the image itself, so this.src will give you the image source:

var self = this;
img.onclick = function() {
  self.loadMainImage(this.src);
};


问:
Is there a way to get std:string's buffer
Is there a way to get the "raw" buffer o a std::string?

I'm thinking of something similar to CString::GetBuffer(). For example, with CString I would do:

```<code>CString myPath;
::GetCurrentDirectory(MAX_PATH+1, myPath.GetBuffer(MAX_PATH));
myPath.ReleaseBuffer();
</code>```

So, does std::string have something similar?

答:
According to this MSDN article, I think this is the best approach for what you want to do using std::wstring directly.  Second best is std::unique_ptr<wchar_t[]> and third best is using std::vector<wchar_t>.  Feel free to read the article and draw you own conclusions.

```<code>// Get the length of the text string
// (Note: +1 to consider the terminating NUL)
const int bufferLength = ::GetWindowTextLength(hWnd) + 1;
// Allocate string of proper size
std::wstring text;
text.resize(bufferLength);
// Get the text of the specified control
// Note that the address of the internal string buffer
// can be obtained with the &text[0] syntax
::GetWindowText(hWnd, &text[0], bufferLength);
// Resize down the string to avoid bogus double-NUL-terminated strings
text.resize(bufferLength - 1);
</code>```

Body:
Is there a way to get the "raw" buffer o a std::string?

I'm thinking of something similar to CString::GetBuffer(). For example, with CString I would do:

CString myPath;
::GetCurrentDirectory(MAX_PATH+1, myPath.GetBuffer(MAX_PATH));
myPath.ReleaseBuffer();

So, does std::string have something similar?

Body:
According to this MSDN article, I think this is the best approach for what you want to do using std::wstring directly.  Second best is std::unique_ptr<wchar_t[]> and third best is using std::vector<wchar_t>.  Feel free to read the article and draw you own conclusions.

// Get the length of the text string
// (Note: +1 to consider the terminating NUL)
const int bufferLength = ::GetWindowTextLength(hWnd) + 1;
// Allocate string of proper size
std::wstring text;
text.resize(bufferLength);
// Get the text of the specified control
// Note that the address of the internal string buffer
// can be obtained with the &text[0] syntax
::GetWindowText(hWnd, &text[0], bufferLength);
// Resize down the string to avoid bogus double-NUL-terminated strings
text.resize(bufferLength - 1);


问:
PHP Multidimensional Array Iterating From Text File
I have a text file named C.txt. The contens of the text file goes as following:

Name,      BPrice, SPrice, Display

  Nokia 520,  20000,  21000,  1

  Xiaomi123,  15000,  17000,  0

  Xiaomi Redmi,   30000,  32000,  1

I have accessed the file using the following code:

```<code><?php

    $file = fopen("C.txt", "r");
    while(!feof($file)){
        $content = fgets($file);
        $products[] = $content;
    }

    var_dump($products);

?>
</code>```

var_dump($products) gives output:

array(4) { [0]=> string(33) "Name, BPrice, SPrice, Display " [1]=> string(29) "Nokia 520,  20000,  21000,  1   " [2]=> string(29) "Xiaomi123,  15000,  17000,  0   " [3]=> string(30) "Xiaomi Redmi,   30000,  32000,  1   " }

What I wanted to do, is to separate the Name, BPrice, SPrice and Display columns and their values using explode() method. So, I tried the following:

```<code><?php

        for($i=1; $i<count($products); $i++){

              $contents[] = explode(",", $products[$i]);

        }

        var_dump($contents);

?>
</code>```

var_dump($contents) yields:

array(3) { [0]=> array(4) { [0]=> string(9) "Nokia 520" [1]=> string(6) "  20000" [2]=> string(6) "    21000" [3]=> string(5) "    1   " } [1]=> array(4) { [0]=> string(9) "Xiaomi123" [1]=> string(6) "  15000" [2]=> string(6) "    17000" [3]=> string(5) "    0   " } [2]=> array(4) { [0]=> string(12) "Xiaomi Redmi" [1]=> string(6) "  30000" [2]=> string(6) "    32000" [3]=> string(3) "    1   " } }

NOTE: I wanted to access only the values of the columns and not the headers, hence for($i=1; $i<count($products); $i++)

Now here is where I'm facing the problem. How do I access this two dimensional array $contents?

I have tried the foreach loop as following:

```<code>foreach ($contents as $key => $value) {
    echo $value[$key];
}
</code>```

But that results in:

Nokia 520  15000   32000

I cannot seem to figure out why it is not printing the rest of the two rows! Any help would be greatly appreciated. Thanks in advance! :)

答:
Your problem is in the echo $value[$key];.
The $key variable in this context holds the key of current $contents array member, while you are using it to access the value of the inside array, the product data.

Since this is a multi-dimensional array, you will need multiple loops to print it all out. So if you'd like to do that, it would work like this:

```<code>foreach ($contents as $productValues) {
    foreach ($productValues as $productValue) {
        echo $productValue;
    }
    echo PHP_EOL;
}
</code>```

Body:
I have a text file named C.txt. The contens of the text file goes as following:

Name,      BPrice, SPrice, Display

  Nokia 520,  20000,  21000,  1

  Xiaomi123,  15000,  17000,  0

  Xiaomi Redmi,   30000,  32000,  1

I have accessed the file using the following code:

<?php

    $file = fopen("C.txt", "r");
    while(!feof($file)){
        $content = fgets($file);
        $products[] = $content;
    }

    var_dump($products);

?>

var_dump($products) gives output:

array(4) { [0]=> string(33) "Name, BPrice, SPrice, Display " [1]=> string(29) "Nokia 520,  20000,  21000,  1   " [2]=> string(29) "Xiaomi123,  15000,  17000,  0   " [3]=> string(30) "Xiaomi Redmi,   30000,  32000,  1   " }

What I wanted to do, is to separate the Name, BPrice, SPrice and Display columns and their values using explode() method. So, I tried the following:

<?php

        for($i=1; $i<count($products); $i++){

              $contents[] = explode(",", $products[$i]);

        }

        var_dump($contents);

?>

var_dump($contents) yields:

array(3) { [0]=> array(4) { [0]=> string(9) "Nokia 520" [1]=> string(6) "  20000" [2]=> string(6) "    21000" [3]=> string(5) "    1   " } [1]=> array(4) { [0]=> string(9) "Xiaomi123" [1]=> string(6) "  15000" [2]=> string(6) "    17000" [3]=> string(5) "    0   " } [2]=> array(4) { [0]=> string(12) "Xiaomi Redmi" [1]=> string(6) "  30000" [2]=> string(6) "    32000" [3]=> string(3) "    1   " } }

NOTE: I wanted to access only the values of the columns and not the headers, hence for($i=1; $i<count($products); $i++)

Now here is where I'm facing the problem. How do I access this two dimensional array $contents?

I have tried the foreach loop as following:

foreach ($contents as $key => $value) {
    echo $value[$key];
}

But that results in:

Nokia 520  15000   32000

I cannot seem to figure out why it is not printing the rest of the two rows! Any help would be greatly appreciated. Thanks in advance! :)

Body:
Your problem is in the echo $value[$key];.
The $key variable in this context holds the key of current $contents array member, while you are using it to access the value of the inside array, the product data.

Since this is a multi-dimensional array, you will need multiple loops to print it all out. So if you'd like to do that, it would work like this:

foreach ($contents as $productValues) {
    foreach ($productValues as $productValue) {
        echo $productValue;
    }
    echo PHP_EOL;
}


问:
how can i mix or and and in an if statement in bash?
i have this function that accepts 3 parameters , ech one contain of 4 numbers and a capital letter for example : "1234A"
and i want to print 1 if the second parameter is bigger than the third one and smaller than the first one ,
i wrote this function that i cutted the 4 numbers in a parameter for each parameter and the letter in diffrent paramater for each one and i began to compare
but the problem it print nothing !!

anyone know how to do things  in one if statement rather than two if statements ??

what i did :

```<code>function check {
    curr_letter=`echo "$1" | cut -c5`
    min_letter=`echo "$3" | cut -c5`
    sm_letter=`echo "$2" | cut -c5`
    curr_nums=`echo "$1" | cut -c1-4`
    min_nums=`echo "$3" | cut -c1-4`
    sm_nums=`echo "$2" | cut -c1-4`
    if [[ sm_nums -eq curr_nums && sm_letter < curr_letter ]] ; then
      if [[ sm_nums -eq min_nums && sm_letter > min_letter ]] ; then
        echo 1
      fi
      if [[ sm_nums > min_nums ]] ; then
        echo 1
      fi
    fi

    if [[ sm_nums < curr_nums ]] ; then
      if [[ sm_nums -eq min_nums && sm_letter > min_letter ]] ; then
        echo 1
      fi
      if [[ sm_nums > min_nums ]] ; then
        echo 1
      fi
    fi
}
</code>```

i get nothing when i test this in bash , i get an empty line..
this is how i tested it :

```<code>p=`check "1617B" "1617A" "0000A"` echo $p
</code>```

Body:
i have this function that accepts 3 parameters , ech one contain of 4 numbers and a capital letter for example : "1234A"
and i want to print 1 if the second parameter is bigger than the third one and smaller than the first one ,
i wrote this function that i cutted the 4 numbers in a parameter for each parameter and the letter in diffrent paramater for each one and i began to compare
but the problem it print nothing !!

anyone know how to do things  in one if statement rather than two if statements ??

what i did :

function check {
    curr_letter=`echo "$1" | cut -c5`
    min_letter=`echo "$3" | cut -c5`
    sm_letter=`echo "$2" | cut -c5`
    curr_nums=`echo "$1" | cut -c1-4`
    min_nums=`echo "$3" | cut -c1-4`
    sm_nums=`echo "$2" | cut -c1-4`
    if [[ sm_nums -eq curr_nums && sm_letter < curr_letter ]] ; then
      if [[ sm_nums -eq min_nums && sm_letter > min_letter ]] ; then
        echo 1
      fi
      if [[ sm_nums > min_nums ]] ; then
        echo 1
      fi
    fi

    if [[ sm_nums < curr_nums ]] ; then
      if [[ sm_nums -eq min_nums && sm_letter > min_letter ]] ; then
        echo 1
      fi
      if [[ sm_nums > min_nums ]] ; then
        echo 1
      fi
    fi
}

i get nothing when i test this in bash , i get an empty line..
this is how i tested it :

p=`check "1617B" "1617A" "0000A"` echo $p

Body:
why not just

awk '$3 <= $2 && $2 <= $1 {print 1}'

or if you need a function

check() { awk '$3 <= $2 && $2 <= $1 {print 1}' <<< "$@"; }

or

check() { awk "BEGIN{if($3 <= $2 && $2 <= $1) print 1}"; }


问:
Passing imageView to new activity imageView
Currently, my app allows the user to click on a "default avatar pic" and then select from a group of images. This image is then returned to the first activity via "startActivityForResult". My next task is to take the image that is now set in the first activity and send it to a third activity when the user presses the "submit button". Right now, I'm trying the below code, but it's not working as I don't know which image is going to be selected by the user until it's selected. Can anyone help me out here?</p>

```<code>    findViewById(R.id.buttonSubmit).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.select_avatar);
            intent.putExtra("IMAGE", bitmap);
            startActivity(intent);
        }
    });

             //second activity
             Bitmap bitmap = intent.getParcelableExtra("Bitmap");
             imageViewAvatar.findViewById(R.id.imageViewFinalAvatar);
             imageViewAvatar.setImageBitmap(bitmap);
</code>```

答:
If you need to receive an ImageView on another activity, you might face scalability problems in the future with your app.

If you have your avatar image on the first activity selected, that drawable selection can be saved in a local storage like Shared Preferences, then in your second activity and any other activity you have on the future you can retrieve that value from SharedPreferences as-well, for example:

Store your Drawable idName: (You DON'T want to store the int id because that id changes if you add more drawables and it can break your app in the future)

```<code>int[] drawablesArray = {R.id.monkey, R.id.balloon};
int id = drawablesArray[imageSelectedIndex];
String idName = getResources().getResourceEntryName(id);

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("avatarPicture",idName);
editor.apply();
</code>```

Retrieve your Drawable idName on the second Activity:

```<code>SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
int avatarPicture = preferences.getString("avatarPicture", "");
if(!avatarPicture.isEmpty())
{
    imageView2ndActivity.setBackgroundResource(getResources().getIdentifier(idName, "drawable", getPackageName()));
}
</code>```

Hope it helps.

Body:
Currently, my app allows the user to click on a "default avatar pic" and then select from a group of images. This image is then returned to the first activity via "startActivityForResult". My next task is to take the image that is now set in the first activity and send it to a third activity when the user presses the "submit button". Right now, I'm trying the below code, but it's not working as I don't know which image is going to be selected by the user until it's selected. Can anyone help me out here?

    findViewById(R.id.buttonSubmit).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.select_avatar);
            intent.putExtra("IMAGE", bitmap);
            startActivity(intent);
        }
    });

             //second activity
             Bitmap bitmap = intent.getParcelableExtra("Bitmap");
             imageViewAvatar.findViewById(R.id.imageViewFinalAvatar);
             imageViewAvatar.setImageBitmap(bitmap);

Body:
If you need to receive an ImageView on another activity, you might face scalability problems in the future with your app.

If you have your avatar image on the first activity selected, that drawable selection can be saved in a local storage like Shared Preferences, then in your second activity and any other activity you have on the future you can retrieve that value from SharedPreferences as-well, for example:

Store your Drawable idName: (You DON'T want to store the int id because that id changes if you add more drawables and it can break your app in the future)

int[] drawablesArray = {R.id.monkey, R.id.balloon};
int id = drawablesArray[imageSelectedIndex];
String idName = getResources().getResourceEntryName(id);

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("avatarPicture",idName);
editor.apply();

Retrieve your Drawable idName on the second Activity:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
int avatarPicture = preferences.getString("avatarPicture", "");
if(!avatarPicture.isEmpty())
{
    imageView2ndActivity.setBackgroundResource(getResources().getIdentifier(idName, "drawable", getPackageName()));
}

Hope it helps.


问:
What are these "none" at the bottom of my output?
Brand new to python. When using the map function in python, i get a series of the word "none" as an output when i run my function. ive added screenshot below.

Code

```<code>def rawGradeToLetter(grade):
   if grade >= 90:
      print ("A")
   elif grade < 90 and grade >= 80:
      print ("B")
   elif grade < 80 and grade >= 70:
      print ("C")
   elif grade < 70 and grade >= 60:
      print ("D")
   elif grade < 60:
      print ("F")

def convertRawsToLetters(myList):
   return list(map(rawGradeToLetter, myList))
</code>```

Example run:

```<code>>>> convertRawsToLetters([90,80,70])
A
B
C
[None, None, None]
</code>```

I have a feeling it has something to do with the word list before the map function, but if I remove that all I get is the address of the map like "map object at 0x8g9b7ea51950".

答:
You need to return the grades, not print them. Printing the grades displays them on screen instead of giving a value back to the caller.

```<code>def rawGradeToLetter(grade):
   if grade >= 90:
      return "A"
   elif grade < 90 and grade >= 80:
      return "B"
   elif grade < 80 and grade >= 70:
      return "C"
   elif grade < 70 and grade >= 60:
      return "D"
   elif grade < 60:
      return "F"
</code>```

Without a return statement your function implicitly returns None, which explains why you're seeing [None, None, None] in your output.

Body:
Brand new to python. When using the map function in python, i get a series of the word "none" as an output when i run my function. ive added screenshot below.

Code

def rawGradeToLetter(grade):
   if grade >= 90:
      print ("A")
   elif grade < 90 and grade >= 80:
      print ("B")
   elif grade < 80 and grade >= 70:
      print ("C")
   elif grade < 70 and grade >= 60:
      print ("D")
   elif grade < 60:
      print ("F")

def convertRawsToLetters(myList):
   return list(map(rawGradeToLetter, myList))

Example run:

>>> convertRawsToLetters([90,80,70])
A
B
C
[None, None, None]

I have a feeling it has something to do with the word list before the map function, but if I remove that all I get is the address of the map like "map object at 0x8g9b7ea51950".

Body:
You need to return the grades, not print them. Printing the grades displays them on screen instead of giving a value back to the caller.

def rawGradeToLetter(grade):
   if grade >= 90:
      return "A"
   elif grade < 90 and grade >= 80:
      return "B"
   elif grade < 80 and grade >= 70:
      return "C"
   elif grade < 70 and grade >= 60:
      return "D"
   elif grade < 60:
      return "F"

Without a return statement your function implicitly returns None, which explains why you're seeing [None, None, None] in your output.


问:
using while loop does not save data to file in c
I want take input from user and then save that input into the file. In my below code if I remove my while loop then the file is appended but I want this loop so that user can enter data upto 500 characters.</p>

```<code>int main()
{
    char Buffer1[5];

    FILE *ot;
    fopen_s(&ot, "D:\\export1.txt", "a+");

    fseek(ot, 0L, SEEK_END);

    int sz = ftell(ot);

    printf("Enter Data.\n");

    while (sz<500) {

        for (int i = 0; i < 5; i++) {
            scanf_s("%c", &Buffer1[i]);
        }

        // write data to file

        for (int i = 0; i < 5; i++) {
            fputc(Buffer1[i], ot);
        }

         sz = ftell(ot);
    }

    fclose(ot);
    _gettch();
    return 0;
}
</code>```

答:
```<code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <conio.h>

#define ARRAY_LIMIT 10
int main()
{
    char array[ARRAY_LIMIT];
    int i = 0;
    FILE *ot;
    fopen_s(&ot, "export1.txt", "a+");

    fseek(ot, 0L, SEEK_END);

    int sz = ftell(ot);

    printf("Enter Data.\n");

    while (sz < 500)
    {
        while (i < ARRAY_LIMIT)
        {
            array[i] = getch();
            printf("%c", array[i++]);
        }
        i = 0;
        fwrite(array, sizeof(array), 1, ot);

        sz = ftell(ot);
        //be on the safe side...
        if (sz != 500 && 500 - sz < ARRAY_LIMIT)
            i = ARRAY_LIMIT - (500 - sz);
    }

    fclose(ot);
    return 0;
}
</code>```

Body:
I want take input from user and then save that input into the file. In my below code if I remove my while loop then the file is appended but I want this loop so that user can enter data upto 500 characters.

int main()
{
    char Buffer1[5];

    FILE *ot;
    fopen_s(&ot, "D:\\export1.txt", "a+");

    fseek(ot, 0L, SEEK_END);

    int sz = ftell(ot);

    printf("Enter Data.\n");

    while (sz<500) {

        for (int i = 0; i < 5; i++) {
            scanf_s("%c", &Buffer1[i]);
        }

        // write data to file

        for (int i = 0; i < 5; i++) {
            fputc(Buffer1[i], ot);
        }

         sz = ftell(ot);
    }

    fclose(ot);
    _gettch();
    return 0;
}


答:
Try this function for parsing cvs files into an associative array with the column names as array keys:

```<code>function csvArray($file) {
    $csv = array_map('str_getcsv', file($file));
    array_walk($csv, function(&$a) use ($csv) {
      $a = array_combine($csv[0], $a);
    });
    array_shift($csv);
return $csv;
}
</code>```

Then result of

```<code>$phones = csvArray('c.txt');
print_r($phones);
</code>```

Is:

```<code>Array
(
    [0] => Array
        (
            [Name] => Nokia 520
            [ BPrice] =>  20000
            [ SPrice] =>  21000
            [ Display] =>  1
        )

    [1] => Array
        (
            [Name] => Xiaomi123
            [ BPrice] =>  15000
            [ SPrice] =>  17000
            [ Display] =>  0
        )

    [2] => Array
        (
            [Name] => Xiaomi Redmi
            [ BPrice] =>  30000
            [ SPrice] =>  32000
            [ Display] =>  1
        )

)
</code>```

Title: PHP Multidimensional Array Iterating From Text File

Body:
Try this function for parsing cvs files into an associative array with the column names as array keys:

function csvArray($file) {
    $csv = array_map('str_getcsv', file($file));
    array_walk($csv, function(&$a) use ($csv) {
      $a = array_combine($csv[0], $a);
    });
    array_shift($csv);
return $csv;
}

Then result of

$phones = csvArray('c.txt');
print_r($phones);

Is:

Array
(
    [0] => Array
        (
            [Name] => Nokia 520
            [ BPrice] =>  20000
            [ SPrice] =>  21000
            [ Display] =>  1
        )

    [1] => Array
        (
            [Name] => Xiaomi123
            [ BPrice] =>  15000
            [ SPrice] =>  17000
            [ Display] =>  0
        )

    [2] => Array
        (
            [Name] => Xiaomi Redmi
            [ BPrice] =>  30000
            [ SPrice] =>  32000
            [ Display] =>  1
        )

)