问:
Is there a way to align scrolling text around an image?
I am looking to align my text with this skewed image, but the problem is the text is scrolling. Is there a way to combat this or no?

My goal is to keep the bolded "TITLE HERE" straight across the image but the placeholder text to continue to scroll, but aligning it with the large image to the left. Is this possible? Thanks for your help in advance.

      /*BODY STUFF HERE*/

body {
  background: WHITE;
  background-attachment: fixed;
  font-family: montserrat;
}

a {
  text-decoration: none;
  color: #999;
}

a:hover {
  color: indianred;
}

.title {
  font-family: montserrat;
  font-weight: 900;
  font-size: 6vw;
  position: relative;
  width: 90%;
  left: 200px;
  margin-top: 0%;
}

.title2 {
  font-family: montserrat;
  font-weight: 900;
  font-size: 1.10vw;
  position: static;
  width: 90%;
  margin-left: 45%;
}

.scrollingtext p {
  width: 100%;
  padding: 0 10%;
  font-size: 13px;
}

/*LEFT PROFILE IMAGE HERE*/

.image {
  z-index: -1;
}

.image img {
  position: fixed;
  width: 50%;
  left: -3.5%;
  z-index: -1;
  -webkit-clip-path: polygon(25% 0%, 100% 0%, 71% 100%, 0% 100%);
  clip-path: polygon(25% 0%, 100% 0%, 71% 100%, 0% 100%);
}

/*CELL TABLE STUFF*/

.tablerow {
  display: table-row;
  width: 100%;
}

.table {
  display: table;
}

.cell {
  display: table-cell;
}

.right {
  width: 50%;
}

.left {
  width: 40%;
}

.mobile {
  display: none;
}

@media screen and (max-width: 1024px) {
  .image img {
    width: 100%;
    position: relative;
    padding: px 5% 0;
    margin: 0;
    top: 0;
    left: 0;
  }
  h1 {
    color: #000;
    letter-spacing: normal;
    width: 95%;
    margin-top: 0;
    padding: 0;
    margin: 0;
    font-size: 70PX;
    text-align: center;
    font-style: montserrat;
  }
  .title {
    display: none;
  }
  .cell {
    display: block;
  }
  .desktop {
    display: none;
  }
  .mobile {
    display: inherit;
    text-align: center;
  }
  .right {
    width: 80%;
    margin: 0;
  }
  .farright {
    width: 0;
  }
  #logo {
    height: 25px;
    position: absolute;
  }
  .story {
    color: #FFF;
    font-family: playfair display;
    width: 100%;
    height: 200px;
    text-shadow: 2px 2px 5px #000;
    background-color: #292929;
    display: table;
  }
  .story_inside {
    vertical-align: middle;
    display: table-cell;
  }
  .story h2 {
    font-size: 40px;
    width: 60%;
    padding: 0 15%;
    margin: 0;
    line-height: 35px;
  }
  .story p {
    font-family: montserrat;
    margin: 0;
    width: 70%;
    padding: 10px 15% 0 15%;
  }
  @media screen and (max-width: 400px) {
    h1 {
      color: #000;
      letter-spacing: normal;
      width: 95%;
      margin-top: 0;
      padding: 0;
      margin: 0;
      font-size: 40px;
      text-align: center;
      font-style: montserrat;
    }
    @media screen and (max-width: 1030px) {
      .byline {
        font-size: 16px;
        width: 100%;
        right: 451%;
        float: left;
        position: relative;
        width: 300%;
        bottom: -150px;
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--IMAGE GOES HERE-->
<div class="image">
  <img src="http://via.placeholder.com/350x1150">
</div>

<div class="scrollingtext">

  <!--DESKTOP TITLE AND BYLINE HERE-->
  <div class="title">TITLE HERE
    <p>
  </div>

  <div class="title2"><strong>AUTHOR HERE</strong> / TITLE</div>
  <!--MOBILE TITLE HERE-->
  <div class="table">
    <div class="tablerow">
      <div class="cell left desktop"></div>

      <!--DESKTOP TITLE AND BYLINE HERE-->
      <div class="title">
      </div>

      <div class="cell farright"></div>

    </div>

    <div class="tablerow">

      <div class="cell left desktop">
      </div>

      <div class="cell right">

        <!-- BODY TEXT GOES BELOW HERE -->
        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example.</p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. </p>

      </div>
    </div>
  </div>
</div></code>```

答:
Yes there is a way to do it but I dont know if your going to like the result when scrolling.

Try this;
Create some empty div that will have the width matching your image and make them float to the left so any text will bump on it.

#container{
width :400px;
height:400px;
border:1px solid #000;

}
.filler{
float:left;
clear:left;
border:1px solid #000;
height:15px;
}
#filler1{
width:200px;
}
#filler2{
width:190px;
}
#filler3{
width:180px;
}
#filler4{
width:170px;
}
#filler5{
width:160px;
}
#filler6{
width:150px;
}
#filler7{
width:140px;
}
#filler8{
width:130px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">

<div id="filler1" class="filler"></div>
<div id="filler2" class="filler"></div>
<div id="filler3" class="filler"></div>
<div id="filler4" class="filler"></div>
<div id="filler5" class="filler"></div>
<div id="filler6" class="filler"></div>
<div id="filler7" class="filler"></div>
<div id="filler8" class="filler"></div>

some text to copy and paste and fill the example.
some text to copy and paste and fill the example.
some text to copy and paste and fill the example.
some text to copy and paste and fill the example.
some text to copy and paste and fill the example.

</div></code>```

Body:
I am looking to align my text with this skewed image, but the problem is the text is scrolling. Is there a way to combat this or no?

My goal is to keep the bolded "TITLE HERE" straight across the image but the placeholder text to continue to scroll, but aligning it with the large image to the left. Is this possible? Thanks for your help in advance.

      /*BODY STUFF HERE*/

body {
  background: WHITE;
  background-attachment: fixed;
  font-family: montserrat;
}

a {
  text-decoration: none;
  color: #999;
}

a:hover {
  color: indianred;
}

.title {
  font-family: montserrat;
  font-weight: 900;
  font-size: 6vw;
  position: relative;
  width: 90%;
  left: 200px;
  margin-top: 0%;
}

.title2 {
  font-family: montserrat;
  font-weight: 900;
  font-size: 1.10vw;
  position: static;
  width: 90%;
  margin-left: 45%;
}

.scrollingtext p {
  width: 100%;
  padding: 0 10%;
  font-size: 13px;
}

/*LEFT PROFILE IMAGE HERE*/

.image {
  z-index: -1;
}

.image img {
  position: fixed;
  width: 50%;
  left: -3.5%;
  z-index: -1;
  -webkit-clip-path: polygon(25% 0%, 100% 0%, 71% 100%, 0% 100%);
  clip-path: polygon(25% 0%, 100% 0%, 71% 100%, 0% 100%);
}

/*CELL TABLE STUFF*/

.tablerow {
  display: table-row;
  width: 100%;
}

.table {
  display: table;
}

.cell {
  display: table-cell;
}

.right {
  width: 50%;
}

.left {
  width: 40%;
}

.mobile {
  display: none;
}

@media screen and (max-width: 1024px) {
  .image img {
    width: 100%;
    position: relative;
    padding: px 5% 0;
    margin: 0;
    top: 0;
    left: 0;
  }
  h1 {
    color: #000;
    letter-spacing: normal;
    width: 95%;
    margin-top: 0;
    padding: 0;
    margin: 0;
    font-size: 70PX;
    text-align: center;
    font-style: montserrat;
  }
  .title {
    display: none;
  }
  .cell {
    display: block;
  }
  .desktop {
    display: none;
  }
  .mobile {
    display: inherit;
    text-align: center;
  }
  .right {
    width: 80%;
    margin: 0;
  }
  .farright {
    width: 0;
  }
  #logo {
    height: 25px;
    position: absolute;
  }
  .story {
    color: #FFF;
    font-family: playfair display;
    width: 100%;
    height: 200px;
    text-shadow: 2px 2px 5px #000;
    background-color: #292929;
    display: table;
  }
  .story_inside {
    vertical-align: middle;
    display: table-cell;
  }
  .story h2 {
    font-size: 40px;
    width: 60%;
    padding: 0 15%;
    margin: 0;
    line-height: 35px;
  }
  .story p {
    font-family: montserrat;
    margin: 0;
    width: 70%;
    padding: 10px 15% 0 15%;
  }
  @media screen and (max-width: 400px) {
    h1 {
      color: #000;
      letter-spacing: normal;
      width: 95%;
      margin-top: 0;
      padding: 0;
      margin: 0;
      font-size: 40px;
      text-align: center;
      font-style: montserrat;
    }
    @media screen and (max-width: 1030px) {
      .byline {
        font-size: 16px;
        width: 100%;
        right: 451%;
        float: left;
        position: relative;
        width: 300%;
        bottom: -150px;
      }

TITLE HERE

AUTHOR HERE / TITLE

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example.

Body:
Yes there is a way to do it but I dont know if your going to like the result when scrolling.

Try this;
Create some empty div that will have the width matching your image and make them float to the left so any text will bump on it.

#container{
width :400px;
height:400px;
border:1px solid #000;

}
.filler{
float:left;
clear:left;
border:1px solid #000;
height:15px;
}
#filler1{
width:200px;
}
#filler2{
width:190px;
}
#filler3{
width:180px;
}
#filler4{
width:170px;
}
#filler5{
width:160px;
}
#filler6{
width:150px;
}
#filler7{
width:140px;
}
#filler8{
width:130px;
}

<div id="container">

<div id="filler1" class="filler"></div>
<div id="filler2" class="filler"></div>
<div id="filler3" class="filler"></div>
<div id="filler4" class="filler"></div>
<div id="filler5" class="filler"></div>
<div id="filler6" class="filler"></div>
<div id="filler7" class="filler"></div>
<div id="filler8" class="filler"></div>

some text to copy and paste and fill the example.
some text to copy and paste and fill the example.
some text to copy and paste and fill the example.
some text to copy and paste and fill the example.
some text to copy and paste and fill the example.

</div>


来源: stackexchange

问:
Javascript arrays merge
`

I have two arrays

```<code>a = [a0,a1,a2,..]
b = [b0,b1,b2,..]
</code>```

How to obtain the below array

```<code>c=[[a0,b0],[a1,b1],[a2.b2],[.,.]...]
</code>```

Any help is appreciated

Thanks in advance

答:
Use array#map method, and use the index parameter to get the relevant element from the second array.map method return a new array

var a = ['a0', 'a1', 'a2']
var b = ['b0', 'b1', 'b2']

var c = a.map(function(item, index) {
  return [a[index], b[index]]
})
console.log(c)```

ContentLicense: CC BY-SA 3.0

Title: Javascript arrays merge

Body:
`

I have two arrays

a = [a0,a1,a2,..]
b = [b0,b1,b2,..]

How to obtain the below array

c=[[a0,b0],[a1,b1],[a2.b2],[.,.]...]

Any help is appreciated

Thanks in advance


问:
How To Translate Delphi record struct to C# and get data from the struct
I recently doing some work on a dll call.the dll was to communicate with a com object.In the Help File ,the Examples were written in Delphi .There was an Event Named OnOperatorInfoMsg, First call a Method Named MethodA，then It raise the Event，the event returns what defined  in delphi was below:

```<code>OnOperatorInfoMsg = procedure(Sender: TObject; wOperatorCount: Integer; OperatorsInfo: Integer) of object;
</code>```

and through the dnspy,I find the Event was Translated to C# Like this:

```<code>  public class OnOperatorInfoMsgEvent
{
    public int wOperatorCount;
    public int operatorsInfo;

    public OnOperatorInfoMsgEvent(int wOperatorCount, int operatorsInfo);
}
</code>```

and the OperatorsInfo in delphi defines like this:

```<code>OPINFO
OPINFO = record
   wAgentID: WORD;
   wSkillGroupID: WORD;
   wWorkGroupID: WORD;
   AgentStatus: AGENT_STATUS;
end;
</code>```

How can I get the wAgentID、wSkillGroupID、AgentStatus in the OperatorsInfo  from C#?

答:
This Problem was solved in Huawei Dev BBS：
http://developer.huawei.com/ict/forum/thread-23981-1-1.html</p>

Body:
I recently doing some work on a dll call.the dll was to communicate with a com object.In the Help File ,the Examples were written in Delphi .There was an Event Named OnOperatorInfoMsg, First call a Method Named MethodA，then It raise the Event，the event returns what defined  in delphi was below:

OnOperatorInfoMsg = procedure(Sender: TObject; wOperatorCount: Integer; OperatorsInfo: Integer) of object;

and through the dnspy,I find the Event was Translated to C# Like this:

  public class OnOperatorInfoMsgEvent
{
    public int wOperatorCount;
    public int operatorsInfo;

    public OnOperatorInfoMsgEvent(int wOperatorCount, int operatorsInfo);
}

and the OperatorsInfo in delphi defines like this:

OPINFO
OPINFO = record
   wAgentID: WORD;
   wSkillGroupID: WORD;
   wWorkGroupID: WORD;
   AgentStatus: AGENT_STATUS;
end;

How can I get the wAgentID、wSkillGroupID、AgentStatus in the OperatorsInfo  from C#?


问:
Replace duplicates Items from a string using Regex
I have a string which looks something like this

```<code>xyz 123;abc;xyz 123;efg;
</code>```

I want to remove the duplicates and keep only one occurrence in the string. I want the output to be like this

```<code>xyz 123;abc;efg;
</code>```

I tried using (?<=;|^)([^;]*);(\1)+(?=;|$) but couldn't figure out how to remove one of the duplicates. Any suggestions ?

答:
Thanks all for your suggestions. Finally i got this working with this regex </p>

```<code>(?<=,|^)([^,]*)(?=.*\\b\\1\\b)(?=,|$)
</code>```

Body:
I have a string which looks something like this

xyz 123;abc;xyz 123;efg;

I want to remove the duplicates and keep only one occurrence in the string. I want the output to be like this

xyz 123;abc;efg;

I tried using (?<=;|^)([^;]*);(\1)+(?=;|$) but couldn't figure out how to remove one of the duplicates. Any suggestions ?

Body:
Thanks all for your suggestions. Finally i got this working with this regex

(?<=,|^)([^,]*)(?=.*\\b\\1\\b)(?=,|$)


问:
Natural size of user avatars twice as large as display size
I am new to web development and I have a question regarding the natural size of profile pictures vs their actual size.

I noticed that when I inspect element on the profile pictures on popular websites, the natural size of the avatar image is usually twice as large as the displayed size.

Some examples:

And when trying this out on my own, I noticed that images do really look better when you make sure the actual (natural) size of the image is twice as large as the displayed size.

As you can see the 64x64 picture looks a lot more crisp than the 32x32 picture. My question is if there is anything special about the two-factor. Can I make it a 128x128 picture and display it as a 32x32 to make it look even better?

答:
Most images on the web are bitmap1 images, which are made of hundreds of thousands of pixels. For example, a 32x32 image would have 32*32 = 1024 pixels. To display the image, the browser would have to go through every single pixel in the image. So the more pixels in the image, the longer it takes to load it.

As for why the image looks better or clearer is because the number of pixels in the original image (natural size) is the same no matter how much you zoom in or out of the image.

So when you zoom in on an image, you get the following result:

(Image from http://scientificcuriosity.blogspot.com/2006/09/how-is-digital-photo-stored.html)

The "squares" you see are individual pixels.

But if you zoom out, you get the opposite effect:

(Image from https://www.researchgate.net/post/How_can_we_quantify_postural_stability_when_a_human_is_standing_without_perturbation_and_with_it)

As you can see, the image is much more clear when scaled down.

But, there is a major disadvantage to large images (in terms of width and height, or number of pixels), they take longer to load.

The more you scale down an image, the more crisp it will look, but also smaller.

Your best option is to use a medium-sized image and display it scaled at 50% to 100%.

[1] https://en.wikipedia.org/wiki/Bitmap


问:
when i right-click on a link goes direct to the page instead of given me the options e.g: "open in a new tab"?
How can I want left click only go to the page and when right click, show the option?</p>

```<code><a ui-sref="app.profile({id: {{user.user_id}}})">Edit</a>
</code>```

答:
Just give href.

```<code><a ui-sref="app.profile({id: {{user.user_id}}})" href>Edit</a>
</code>```

Hope this is what u want!

Body:
How can I want left click only go to the page and when right click, show the option?

Edit

Body:
Just give href.

<a ui-sref="app.profile({id: {{user.user_id}}})" href>Edit</a>

Hope this is what u want!


问:
How to update ListView without freezing the program
So I have a list of strings (ISBNs), and I need to fill a listview with the objects (Book objects) associated with these strings. The problem is that the function I have to get the Book object using the string takes time, and so to get, say 30 books, the wait approaches 4 or 5 seconds.

One approach I've thought of is to get the Book objects one at a time, and to add them to the list as I get them. But this process will freeze the UI until it's done adding them all. If I try to put this process in a new thread, it won't let me add to the any UI objects (since it's from another thread). If I try to put it in an AsyncTask, I can't access the ListView since it's in the MainActivity class.

There must be a way to dynamically update a UI element, I'm sure I've seen it done. Any suggestions?

EDIT:

This is the code I'm using to actually add items to the list:

```<code>//List view and adapter setup
listView = (ListView) findViewById(R.id.listViewCheckout);
bookAdapter = new SearchBookAdapter(getApplicationContext(), R.layout.search_row_layout);
listView.setAdapter(bookAdapter);

for(int i = 0; i < searches.size(); i++) {

    //Get the book
    Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

    //Assign data to the adapter variables
    Bitmap cover = book.getCover();
    String title = book.getTitle();
    String author = book.getAuthor();

    //Add data to the adapter and set the list
    SearchBookDataProvider dataProvider = new SearchBookDataProvider(cover, title, author);
    bookAdapter.add(dataProvider);
    bookAdapter.notifyDataSetChanged();
}
</code>```

答: you can use TimerTask to update the listview or runUiThread() or doInBackground(). But remember should use notifysetChanges() when you update the list.

Body:
So I have a list of strings (ISBNs), and I need to fill a listview with the objects (Book objects) associated with these strings. The problem is that the function I have to get the Book object using the string takes time, and so to get, say 30 books, the wait approaches 4 or 5 seconds.

One approach I've thought of is to get the Book objects one at a time, and to add them to the list as I get them. But this process will freeze the UI until it's done adding them all. If I try to put this process in a new thread, it won't let me add to the any UI objects (since it's from another thread). If I try to put it in an AsyncTask, I can't access the ListView since it's in the MainActivity class.

There must be a way to dynamically update a UI element, I'm sure I've seen it done. Any suggestions?

EDIT:

This is the code I'm using to actually add items to the list:

//List view and adapter setup
listView = (ListView) findViewById(R.id.listViewCheckout);
bookAdapter = new SearchBookAdapter(getApplicationContext(), R.layout.search_row_layout);
listView.setAdapter(bookAdapter);

for(int i = 0; i < searches.size(); i++) {

    //Get the book
    Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

    //Assign data to the adapter variables
    Bitmap cover = book.getCover();
    String title = book.getTitle();
    String author = book.getAuthor();

    //Add data to the adapter and set the list
    SearchBookDataProvider dataProvider = new SearchBookDataProvider(cover, title, author);
    bookAdapter.add(dataProvider);
    bookAdapter.notifyDataSetChanged();
}


问:
how to apply single click on 3 items of listview or how to club 3 items for single click in android
i have listview with 4 items on it ,i need one click event on 3 items of listview.
so how to club three item to apply click event on it .
.

state ,view and comp these three items are on listview

```<code>    holderView.state.setOnClickListener((View.OnClickListener) this);
    holderView.view.setOnClickListener((View.OnClickListener) this);

    holderView.comp.setOnClickListener(new View.OnClickListener() {
    @Override
        public void onClick(View view) {
    }});
</code>```

thanks

答:
You can do this in multiple ways.

1. Implement Onclick listener and set Listener to all.

```<code> holderView.state.setOnClickListener(this);
 holderView.view.setOnClickListener(this);
 holderView.comp.setOnClickListener(this);

 @Override
public void onClick(View v) {
    if (v.getId() == R.id.id1
            || v.getId() == R.id.id2
            || v.getId() == R.id.id3) {
        // Do your task here
    }
}
</code>```

2. Create a single instance of OnCLickListener and set to all.

```<code>     View.OnClickListener clickListener=new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    // Do your stuff
    }
 };
</code>```

Set it to all your views.

```<code>holderView.state.setOnClickListener(clickListener);
holderView.view.setOnClickListener(clickListener);
holderView.comp.setOnClickListener(clickListener);
</code>```

Body:
i have listview with 4 items on it ,i need one click event on 3 items of listview.
so how to club three item to apply click event on it .
.

state ,view and comp these three items are on listview

    holderView.state.setOnClickListener((View.OnClickListener) this);
    holderView.view.setOnClickListener((View.OnClickListener) this);

    holderView.comp.setOnClickListener(new View.OnClickListener() {
    @Override
        public void onClick(View view) {
    }});

thanks

Body:
You can do this in multiple ways.

1. Implement Onclick listener and set Listener to all.

 holderView.state.setOnClickListener(this);
 holderView.view.setOnClickListener(this);
 holderView.comp.setOnClickListener(this);

 @Override
public void onClick(View v) {
    if (v.getId() == R.id.id1
            || v.getId() == R.id.id2
            || v.getId() == R.id.id3) {
        // Do your task here
    }
}

2. Create a single instance of OnCLickListener and set to all.

     View.OnClickListener clickListener=new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    // Do your stuff
    }
 };

Set it to all your views.

holderView.state.setOnClickListener(clickListener);
holderView.view.setOnClickListener(clickListener);
holderView.comp.setOnClickListener(clickListener);


问:
foreach (Control ctrl in Frm.Controls) in which order it takes controls
I am having a peculiar problem with the order in which TextBox controls are added in to the form's Controls property.

Currently, I have the function:

```<code> public static bool IsValidate(System.Windows.Forms.Form Frm)
 {
     foreach (Control ctrl in Frm.Controls)
         if (ctrl is TextBox)
         //  if (((TextBox)ctrl).AccessibleDescription == "Valid" && ((TextBox)ctrl).Text == string.Empty)
         if (((TextBox)ctrl).AccessibleDescription == "Valid" &&  ((TextBox)ctrl).Text.Trim()== "")
         {
             MessageBox.Show(((TextBox)ctrl).AccessibleName + " Can't be Blank", Program.companyName, MessageBoxButtons.OK, MessageBoxIcon.Stop);
             ((TextBox)ctrl).Focus();
              return false;
         }
         return true;
}
</code>```

But it's iterating through the textboxes randomly, even though I have set their tab indices.

So I develop the same form again and create the textboxes sequentially. But still, when I pass the form to this function, it's iterating through the textboxes randomly.

I want to know if there is any property of the controls that would allow me to manage their flow.

答: You can drop the controls into the form in the designer visually, and then open up the Form.Designer.cs source file and locate where the designer has typed in the code to add the controls to the Controls collection (i.e. the Controls.Add lines) and re-order those lines in the *.Designer.cs by hand. Once you've done that, the designer should leave your changes alone. I noticed that the designer writes them in reverse order. Your foreach should find them in the order that you arranged them.</p>

Body:
I am having a peculiar problem with the order in which TextBox controls are added in to the form's Controls property.

Currently, I have the function:

 public static bool IsValidate(System.Windows.Forms.Form Frm)
 {
     foreach (Control ctrl in Frm.Controls)
         if (ctrl is TextBox)
         //  if (((TextBox)ctrl).AccessibleDescription == "Valid" && ((TextBox)ctrl).Text == string.Empty)
         if (((TextBox)ctrl).AccessibleDescription == "Valid" &&  ((TextBox)ctrl).Text.Trim()== "")
         {
             MessageBox.Show(((TextBox)ctrl).AccessibleName + " Can't be Blank", Program.companyName, MessageBoxButtons.OK, MessageBoxIcon.Stop);
             ((TextBox)ctrl).Focus();
              return false;
         }
         return true;
}

But it's iterating through the textboxes randomly, even though I have set their tab indices.

So I develop the same form again and create the textboxes sequentially. But still, when I pass the form to this function, it's iterating through the textboxes randomly.

I want to know if there is any property of the controls that would allow me to manage their flow.

ContentLicense: CC BY-SA 2.5


问:
EC2 instance outgoing http request rate limits
I'm building a node application on EC2 that queries various external APIs several times per second via http requests.

I cannot work this out from the EC2 documentation - are there any EC2 rate limits for querying external APIs?

E.g. if I'm continuously making 2 or 3 http requests per second from an ec2 instance, will I start getting rate limit errors from ec2?

Thanks

答:
ec2 provides you the virtual machine and (if you configure it) the external connection.

Then it's totally up to you on what you query with it.

AWS provides you the layer 3 network which is charged by traffic amount, not number of requests.


问:
Heroku Node deployment "internal server error"
I have my app deployed to heroku. Once I go to the user signup page and enter my credentials the site immediately crashes, displaying internal server error in the browser, and giving me this in the heroku logs.

I'm not sure what might be the issue so I don't know which code to give? I don't think it has to do with MySQL but considering it's mentioned in the error report, it might be? Either way here is my connection.js:

```<code>const mysql = require('mysql');
let connection;

if (process.env.JAWSDB_URL) {
    connection = mysql.createConnection(process.env.JAWSDB_URL);
} else {
    connection = mysql.createConnection({
        host: 'localhost',
        port: 3306,
        user: 'root',
        password: '',
        database: 'trythis_db'
    });
};

connection.connect(function(err) {
    if (err) {
        console.log(err);
    } else {
        console.log('mysql is connected');
    };
});

module.exports = connection;
</code>```

This is my error code:

```<code>2017-12-04T04:58:51.486756+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306
2017-12-04T04:58:51.486150+00:00 app[web.1]: POST /signup 302 287.664 ms - 46
2017-12-04T04:58:51.486758+00:00 app[web.1]:     at Object._errnoException (util.js:1024:11)
2017-12-04T04:58:51.486758+00:00 app[web.1]:     at _exceptionWithHostPort (util.js:1046:20)
2017-12-04T04:58:51.486759+00:00 app[web.1]:     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)
2017-12-04T04:58:51.486760+00:00 app[web.1]:     --------------------
2017-12-04T04:58:51.486761+00:00 app[web.1]:     at Protocol._enqueue (/app/node_modules/express-mysql-session/node_modules/mysql/lib/protocol/Protocol.js:145:48)
2017-12-04T04:58:51.486762+00:00 app[web.1]:     at Protocol.handshake (/app/node_modules/express-mysql-session/node_modules/mysql/lib/protocol/Protocol.js:52:23)
2017-12-04T04:58:51.486763+00:00 app[web.1]:     at PoolConnection.connect (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Connection.js:130:18)
2017-12-04T04:58:51.486763+00:00 app[web.1]:     at Pool.getConnection (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Pool.js:48:16)
2017-12-04T04:58:51.486764+00:00 app[web.1]:     at Pool.query (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Pool.js:202:8)
2017-12-04T04:58:51.486765+00:00 app[web.1]:     at MySQLStore.set (/app/node_modules/express-mysql-session/lib/index.js:192:19)
2017-12-04T04:58:51.486766+00:00 app[web.1]:     at Session.save (/app/node_modules/express-session/session/session.js:72:25)
2017-12-04T04:58:51.486766+00:00 app[web.1]:     at Session.save (/app/node_modules/express-session/index.js:381:15)
2017-12-04T04:58:51.486767+00:00 app[web.1]:     at ServerResponse.end (/app/node_modules/express-session/index.js:330:21)
2017-12-04T04:58:51.486768+00:00 app[web.1]:     at ServerResponse.redirect (/app/node_modules/express/lib/response.js:947:10)
2017-12-04T04:58:51.638706+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306
2017-12-04T04:58:51.638708+00:00 app[web.1]:     at Object._errnoException (util.js:1024:11)
2017-12-04T04:58:51.638709+00:00 app[web.1]:     at _exceptionWithHostPort (util.js:1046:20)
2017-12-04T04:58:51.638710+00:00 app[web.1]:     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)
2017-12-04T04:58:51.638710+00:00 app[web.1]:     --------------------
2017-12-04T04:58:51.638711+00:00 app[web.1]:     at Protocol._enqueue (/app/node_modules/express-mysql-session/node_modules/mysql/lib/protocol/Protocol.js:145:48)
2017-12-04T04:58:51.638712+00:00 app[web.1]:     at Protocol.handshake (/app/node_modules/express-mysql-session/node_modules/mysql/lib/protocol/Protocol.js:52:23)
2017-12-04T04:58:51.638713+00:00 app[web.1]:     at PoolConnection.connect (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Connection.js:130:18)
2017-12-04T04:58:51.638713+00:00 app[web.1]:     at Pool.getConnection (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Pool.js:48:16)
2017-12-04T04:58:51.638714+00:00 app[web.1]:     at Pool.query (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Pool.js:202:8)
2017-12-04T04:58:51.638802+00:00 app[web.1]:     at session (/app/node_modules/express-session/index.js:460:11)
2017-12-04T04:58:51.638800+00:00 app[web.1]:     at MySQLStore.get (/app/node_modules/express-mysql-session/lib/index.js:130:19)
2017-12-04T04:58:51.638803+00:00 app[web.1]:     at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
2017-12-04T04:58:51.638804+00:00 app[web.1]:     at trim_prefix (/app/node_modules/express/lib/router/index.js:317:13)
2017-12-04T04:58:51.638804+00:00 app[web.1]:     at /app/node_modules/express/lib/router/index.js:284:7
</code>```

答: The first line of the error (Error: connect ECONNREFUSED 127.0.0.1:3306) says that the app is trying to connect to localhost even when it is hosted online, where it should try to connect to the online database. You need to figure out what's wrong in the if-else statements, since, the else loop is being executed, which, I guess, is for your local environment.

Body:
I have my app deployed to heroku. Once I go to the user signup page and enter my credentials the site immediately crashes, displaying internal server error in the browser, and giving me this in the heroku logs.

I'm not sure what might be the issue so I don't know which code to give? I don't think it has to do with MySQL but considering it's mentioned in the error report, it might be? Either way here is my connection.js:

const mysql = require('mysql');
let connection;

if (process.env.JAWSDB_URL) {
    connection = mysql.createConnection(process.env.JAWSDB_URL);
} else {
    connection = mysql.createConnection({
        host: 'localhost',
        port: 3306,
        user: 'root',
        password: '',
        database: 'trythis_db'
    });
};

connection.connect(function(err) {
    if (err) {
        console.log(err);
    } else {
        console.log('mysql is connected');
    };
});

module.exports = connection;

This is my error code:

2017-12-04T04:58:51.486756+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306
2017-12-04T04:58:51.486150+00:00 app[web.1]: POST /signup 302 287.664 ms - 46
2017-12-04T04:58:51.486758+00:00 app[web.1]:     at Object._errnoException (util.js:1024:11)
2017-12-04T04:58:51.486758+00:00 app[web.1]:     at _exceptionWithHostPort (util.js:1046:20)
2017-12-04T04:58:51.486759+00:00 app[web.1]:     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)
2017-12-04T04:58:51.486760+00:00 app[web.1]:     --------------------
2017-12-04T04:58:51.486761+00:00 app[web.1]:     at Protocol._enqueue (/app/node_modules/express-mysql-session/node_modules/mysql/lib/protocol/Protocol.js:145:48)
2017-12-04T04:58:51.486762+00:00 app[web.1]:     at Protocol.handshake (/app/node_modules/express-mysql-session/node_modules/mysql/lib/protocol/Protocol.js:52:23)
2017-12-04T04:58:51.486763+00:00 app[web.1]:     at PoolConnection.connect (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Connection.js:130:18)
2017-12-04T04:58:51.486763+00:00 app[web.1]:     at Pool.getConnection (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Pool.js:48:16)
2017-12-04T04:58:51.486764+00:00 app[web.1]:     at Pool.query (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Pool.js:202:8)
2017-12-04T04:58:51.486765+00:00 app[web.1]:     at MySQLStore.set (/app/node_modules/express-mysql-session/lib/index.js:192:19)
2017-12-04T04:58:51.486766+00:00 app[web.1]:     at Session.save (/app/node_modules/express-session/session/session.js:72:25)
2017-12-04T04:58:51.486766+00:00 app[web.1]:     at Session.save (/app/node_modules/express-session/index.js:381:15)
2017-12-04T04:58:51.486767+00:00 app[web.1]:     at ServerResponse.end (/app/node_modules/express-session/index.js:330:21)
2017-12-04T04:58:51.486768+00:00 app[web.1]:     at ServerResponse.redirect (/app/node_modules/express/lib/response.js:947:10)
2017-12-04T04:58:51.638706+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306
2017-12-04T04:58:51.638708+00:00 app[web.1]:     at Object._errnoException (util.js:1024:11)
2017-12-04T04:58:51.638709+00:00 app[web.1]:     at _exceptionWithHostPort (util.js:1046:20)
2017-12-04T04:58:51.638710+00:00 app[web.1]:     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)
2017-12-04T04:58:51.638710+00:00 app[web.1]:     --------------------
2017-12-04T04:58:51.638711+00:00 app[web.1]:     at Protocol._enqueue (/app/node_modules/express-mysql-session/node_modules/mysql/lib/protocol/Protocol.js:145:48)
2017-12-04T04:58:51.638712+00:00 app[web.1]:     at Protocol.handshake (/app/node_modules/express-mysql-session/node_modules/mysql/lib/protocol/Protocol.js:52:23)
2017-12-04T04:58:51.638713+00:00 app[web.1]:     at PoolConnection.connect (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Connection.js:130:18)
2017-12-04T04:58:51.638713+00:00 app[web.1]:     at Pool.getConnection (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Pool.js:48:16)
2017-12-04T04:58:51.638714+00:00 app[web.1]:     at Pool.query (/app/node_modules/express-mysql-session/node_modules/mysql/lib/Pool.js:202:8)
2017-12-04T04:58:51.638802+00:00 app[web.1]:     at session (/app/node_modules/express-session/index.js:460:11)
2017-12-04T04:58:51.638800+00:00 app[web.1]:     at MySQLStore.get (/app/node_modules/express-mysql-session/lib/index.js:130:19)
2017-12-04T04:58:51.638803+00:00 app[web.1]:     at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
2017-12-04T04:58:51.638804+00:00 app[web.1]:     at trim_prefix (/app/node_modules/express/lib/router/index.js:317:13)
2017-12-04T04:58:51.638804+00:00 app[web.1]:     at /app/node_modules/express/lib/router/index.js:284:7


问:
Scala - Get value of variable through another variable of same object

From the UML diagram, it shows that getGrade(String) is a method of the class Quiz. My understanding is that the String should be the title of the Quiz. But how do you get score of the Quiz based on the title you put in as the parameter?

And the question asks us to " Write Scala code for Quiz class with the given grading scheme for Quiz in getGrade function. For mark above 70 the grade is A.".

Below is my code but it won't work.

```<code>def getGrade(title:String):String={
    if(title.score >= 70)
        val grade:String = A
}
</code>```

答:
val is a keyword that is used to created a stored non-modifiable field or local variable. In your case you probably should map score field of type Double to String representation so this is a computed rather than stored information. What is the purpose of the additional String argument and of availableScore field in the Assignment class is unclear. Here is my best guess:

```<code>abstract class Assignment(val title: String, val score: Double, val availableScore: Double) {
  def grade(studentName: String): String
}

class Quiz(title: String, score: Double, availableScore: Double) extends Assignment(title, score, availableScore) {
  override def grade(studentName: String): String = {
    val grade = score match {
      case s if s >= 70 => "A"
      case s if s >= 50 => "B"
      // map rest ranges from score to grade
      case _ => "F"
    }

    s"$studentName's grade for quiz '$title' is $grade"
  }
}
</code>```

Body:
From the UML diagram, it shows that getGrade(String) is a method of the class Quiz. My understanding is that the String should be the title of the Quiz. But how do you get score of the Quiz based on the title you put in as the parameter?

And the question asks us to " Write Scala code for Quiz class with the given grading scheme for Quiz in getGrade function. For mark above 70 the grade is A.".

Below is my code but it won't work.

def getGrade(title:String):String={
    if(title.score >= 70)
        val grade:String = A
}

Body:
val is a keyword that is used to created a stored non-modifiable field or local variable. In your case you probably should map score field of type Double to String representation so this is a computed rather than stored information. What is the purpose of the additional String argument and of availableScore field in the Assignment class is unclear. Here is my best guess:

abstract class Assignment(val title: String, val score: Double, val availableScore: Double) {
  def grade(studentName: String): String
}

class Quiz(title: String, score: Double, availableScore: Double) extends Assignment(title, score, availableScore) {
  override def grade(studentName: String): String = {
    val grade = score match {
      case s if s >= 70 => "A"
      case s if s >= 50 => "B"
      // map rest ranges from score to grade
      case _ => "F"
    }

    s"$studentName's grade for quiz '$title' is $grade"
  }
}


问:
Are parentheses around the result significant in a return statement?
Is there a difference between these two statements inside a function?

```<code>bool returnValue = true;
// Code that does something
return(returnValue);
</code>```

and this?

```<code>bool returnValue = true;
// Code
return returnValue;
</code>```

The former has parentheses around returnValue.

答:
AFAIK, nothing is different.

In C++, expressions can have the form: expr or (expr).  So, the latter is an expression with more typing.  For further reading about this, refer to a grammar (look for "expression").

ContentLicense: CC BY-SA 4.0

Body:
Is there a difference between these two statements inside a function?

bool returnValue = true;
// Code that does something
return(returnValue);

and this?

bool returnValue = true;
// Code
return returnValue;

The former has parentheses around returnValue.


问:
code to close a matlab app
I have written a Matlab app with the app designer tool, and have successfully coded everything except the pesky (and most likely simple) exit button. The button itself should do what it says, close the app when clicked, but looking online has just led me to dead ends. Here is what I have written down for the exit function; it doesn't work, but its better than writing no code:</p>

```<code> % Button pushed function: ExitButton
    function ExitButtonPushed(app, event)
        Figurename = app.UIFigure ;
        close Figurename
    end
</code>```

答:
writing

```<code>close all force ;
</code>```

seemed to do the trick; as it closes all processes in the Matlab code that were running, which works perfectly for what I want.

Title: code to close a matlab app

Body:
I have written a Matlab app with the app designer tool, and have successfully coded everything except the pesky (and most likely simple) exit button. The button itself should do what it says, close the app when clicked, but looking online has just led me to dead ends. Here is what I have written down for the exit function; it doesn't work, but its better than writing no code:

 % Button pushed function: ExitButton
    function ExitButtonPushed(app, event)
        Figurename = app.UIFigure ;
        close Figurename
    end

Body:
writing

close all force ;

seemed to do the trick; as it closes all processes in the Matlab code that were running, which works perfectly for what I want.


问:
VBS timer clock - Output label
I need some help with this code in Visual Studio VBS, I don't know how to output all the vars in the text.</p>

```<code>    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Dim timer
    Dim timer2
    Dim timer3
    Dim finaltimer
    timer = (sec.Text + 1)
    timer = Format(timer, "00")
    If timer = 60 Then
        timer = 0
        timer2 = (min.Text + 1)
        timer2 = Format(timer2, "00")
        If timer2 = 60 Then
            timer2 = 0
            timer3 = (hour.Text + 1)
            timer3 = Format(timer3, "00")
        End If
    End If
    finaltimer = timer & ":" & timer2 & ":" & timer3
    sec.Text = finaltimer
End Sub
</code>```

答:
Here's a simple example of the StopWatch approach as suggested by jmcilhinney:</p>

```<code>Private SW As New Stopwatch

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    SW.Start()
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Dim ts As TimeSpan = SW.Elapsed
    Label1.Text = ts.ToString("hh\:mm\:ss")
End Sub
</code>```

Title: VBS timer clock - Output label

Body:
I need some help with this code in Visual Studio VBS, I don't know how to output all the vars in the text.

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Dim timer
    Dim timer2
    Dim timer3
    Dim finaltimer
    timer = (sec.Text + 1)
    timer = Format(timer, "00")
    If timer = 60 Then
        timer = 0
        timer2 = (min.Text + 1)
        timer2 = Format(timer2, "00")
        If timer2 = 60 Then
            timer2 = 0
            timer3 = (hour.Text + 1)
            timer3 = Format(timer3, "00")
        End If
    End If
    finaltimer = timer & ":" & timer2 & ":" & timer3
    sec.Text = finaltimer
End Sub

Body:
Here's a simple example of the StopWatch approach as suggested by jmcilhinney:

Private SW As New Stopwatch

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    SW.Start()
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Dim ts As TimeSpan = SW.Elapsed
    Label1.Text = ts.ToString("hh\:mm\:ss")
End Sub


问:
Angular HttpParams is there a way to add square brackets to serialized query params when generating query params with the same key?
When querying my api with multiple query params of the same key but multiple values it is not interpreting the request properly unless square brackets are added to each key. Let me give you an example:

```<code>    let params = new HttpParams();

    params = params.append('color', 'blue');
    params = params.append('color', 'red');

    console.log(params.toString()) // color=blue&color=red
    // Would prefer color[]=blue&color[]=red
</code>```

Is there any way to produce this functionality?

答:
I solved this by writing my own interceptor and generating the query string with another library. Please see below:

Install this library:

```<code>$ npm i query-string --save
</code>```

Add this interceptor:

```<code>import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpParams,
  HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import * as querystring from 'query-string';

@Injectable()
export class QueryParamInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (!request.params.keys().length || request.method !== 'GET') {
      return next.handle(request);
    }

    let { params } = request;

    let queryParams = this.createQueryParams(params);

    let queryString = querystring.stringify(queryParams, { arrayFormat: 'bracket' });

    let urlWithParams = request.urlWithParams.replace(request.params.toString(), queryString);

    request = request.clone({
      url: urlWithParams,
      params: new HttpParams(),
    });

    return next.handle(request);
  }

  private createQueryParams(params: HttpParams): { [key: string]: string } {
    let queryParams = {};

    for (let key of params.keys()) {
      let values = params.getAll(key);

      if (!values) {
        continue;
      }

      if (values.length === 1) {
        queryParams[key] = values[0];

        continue;
      }

      queryParams[key] = values;
    }

    return queryParams;
  }
}
</code>```

Body:
When querying my api with multiple query params of the same key but multiple values it is not interpreting the request properly unless square brackets are added to each key. Let me give you an example:

    let params = new HttpParams();

    params = params.append('color', 'blue');
    params = params.append('color', 'red');

    console.log(params.toString()) // color=blue&color=red
    // Would prefer color[]=blue&color[]=red

Is there any way to produce this functionality?

Body:
I solved this by writing my own interceptor and generating the query string with another library. Please see below:

Install this library:

$ npm i query-string --save

Add this interceptor:

import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpParams,
  HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import * as querystring from 'query-string';

@Injectable()
export class QueryParamInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (!request.params.keys().length || request.method !== 'GET') {
      return next.handle(request);
    }

    let { params } = request;

    let queryParams = this.createQueryParams(params);

    let queryString = querystring.stringify(queryParams, { arrayFormat: 'bracket' });

    let urlWithParams = request.urlWithParams.replace(request.params.toString(), queryString);

    request = request.clone({
      url: urlWithParams,
      params: new HttpParams(),
    });

    return next.handle(request);
  }

  private createQueryParams(params: HttpParams): { [key: string]: string } {
    let queryParams = {};

    for (let key of params.keys()) {
      let values = params.getAll(key);

      if (!values) {
        continue;
      }

      if (values.length === 1) {
        queryParams[key] = values[0];

        continue;
      }

      queryParams[key] = values;
    }

    return queryParams;
  }
}


问:
ICloneable Exists in Two Assemblies
Our dot net core 2.0 project has some classes that implement ICloneable (they have a .Clone() method that returns an object). Now, we are using a package Microsoft.Azure.Amqp and when building the project now gives an error:

Error  CS0433  The type 'ICloneable' exists in both 'Microsoft.Azure.Amqp, Version=2.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' and 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'

Both have ICloneable in the "System" namespace, so how can the compiler know which one to use? Is there a way to say which DLL to use for that reference?

答: The question here has a solution to this problem. I'll summarise it briefly. Go to the reference in your project, and change "Aliases" to a value of your choosing. To use code from this assembly now, you will need to use the extern keyword like so at the top of your file: extern alias aliasname. Then you can reference code from this assembly like so: aliasname::System.ICloneable.

Title: ICloneable Exists in Two Assemblies


问:
Why does the while loop not go through the loop, it stops after the first 3 inputs?
I'm trying to get this program to calculate how much these movies will cost the customer, but the while loop only asks the first three questions it never prints the total, the tax or anything else. Please help me solve this problem!

```<code>def checkout():
    The_Bourne_Identity = 1
    Harry_Potter = 2
    Holy_Cross = 3
    Arrival = 4
    Hidden = 5

    price_of_movie = 0
    price_of_movie2 = 0
    price_of_movie3 = 0
    price_of_movie4 = 0
    price_of_movie5 = 0

    ans = 0
    response = 'y'

    while response == 'y':
        ans = int(input('What movie do you have?'))
        q1 = int(input('How many of these do you have'))
        response =input('Do you have a different movie?: type y for yes: ')
        if ans == The_Bourne_Identity:
            price_of_movie = 9.99 * q1
            return price_of_movie
        elif ans == Harry_Potter:
            price_of_movie2 = 15.99 * q1
            return price_of_movie2

        elif ans == Holy_Cross:
            price_of_movie3 = 4.75 * q1
            return price_of_movie3
        elif ans == Arrival:
            price_of_movie4 = 24.99 * q1
            return price_of_movie4

        elif ans == Hidden:
            price_of_movie4 = 29.98 * q1
            return price_of_movie5

    movie_total_price =  price_of_movie + price_of_movie2 + price_of_movie3 + price_of_movie4 + price_of_movie5

    movie_tax = movie_total_price * .07
    total_cost = movie_tax + movie_total_price

    print("Your movies cost,", movie_total_price)
    print("Your tax will be,", movie_tax)
    print("Your total cost,", total_cost)

def main():
    checkout()
main()
</code>```

when I run it just does the first 3 questions and stops

答:
You are returning midway. The rest codes in the method will not be executed. Instead of return just use movie_total_price for total-cost and add up. Change your method like this (could be refactored a LOT more):

```<code>def checkout():
    The_Bourne_Identity = 1
    Harry_Potter = 2
    Holy_Cross = 3
    Arrival = 4
    Hidden = 5

    price_of_movie = 0
    price_of_movie2 = 0
    price_of_movie3 = 0
    price_of_movie4 = 0
    price_of_movie5 = 0
    movie_total_price = 0
    ans = 0
    response = 'y'

    while response == 'y':
        ans = int(input('What movie do you have?'))
        q1 = int(input('How many of these do you have'))
        response =input('Do you have a different movie?: type y for yes: ')

        if ans == The_Bourne_Identity:
            movie_total_price += 9.99 * q1
        elif ans == Harry_Potter:
            movie_total_price += 15.99 * q1
        elif ans == Holy_Cross:
            movie_total_price += 4.75 * q1
        elif ans == Arrival:
            movie_total_price += 24.99 * q1
        elif ans == Hidden:
            movie_total_price += 29.98 * q1

    movie_tax = movie_total_price * .07
    total_cost = movie_tax + movie_total_price

    print("Your movies cost,", movie_total_price)
    print("Your tax will be,", movie_tax)
    print("Your total cost,", total_cost)
</code>```

Body:
I'm trying to get this program to calculate how much these movies will cost the customer, but the while loop only asks the first three questions it never prints the total, the tax or anything else. Please help me solve this problem!

def checkout():
    The_Bourne_Identity = 1
    Harry_Potter = 2
    Holy_Cross = 3
    Arrival = 4
    Hidden = 5

    price_of_movie = 0
    price_of_movie2 = 0
    price_of_movie3 = 0
    price_of_movie4 = 0
    price_of_movie5 = 0

    ans = 0
    response = 'y'

    while response == 'y':
        ans = int(input('What movie do you have?'))
        q1 = int(input('How many of these do you have'))
        response =input('Do you have a different movie?: type y for yes: ')
        if ans == The_Bourne_Identity:
            price_of_movie = 9.99 * q1
            return price_of_movie
        elif ans == Harry_Potter:
            price_of_movie2 = 15.99 * q1
            return price_of_movie2

        elif ans == Holy_Cross:
            price_of_movie3 = 4.75 * q1
            return price_of_movie3
        elif ans == Arrival:
            price_of_movie4 = 24.99 * q1
            return price_of_movie4

        elif ans == Hidden:
            price_of_movie4 = 29.98 * q1
            return price_of_movie5

    movie_total_price =  price_of_movie + price_of_movie2 + price_of_movie3 + price_of_movie4 + price_of_movie5

    movie_tax = movie_total_price * .07
    total_cost = movie_tax + movie_total_price

    print("Your movies cost,", movie_total_price)
    print("Your tax will be,", movie_tax)
    print("Your total cost,", total_cost)

def main():
    checkout()
main()

when I run it just does the first 3 questions and stops

Body:
You are returning midway. The rest codes in the method will not be executed. Instead of return just use movie_total_price for total-cost and add up. Change your method like this (could be refactored a LOT more):

def checkout():
    The_Bourne_Identity = 1
    Harry_Potter = 2
    Holy_Cross = 3
    Arrival = 4
    Hidden = 5

    price_of_movie = 0
    price_of_movie2 = 0
    price_of_movie3 = 0
    price_of_movie4 = 0
    price_of_movie5 = 0
    movie_total_price = 0
    ans = 0
    response = 'y'

    while response == 'y':
        ans = int(input('What movie do you have?'))
        q1 = int(input('How many of these do you have'))
        response =input('Do you have a different movie?: type y for yes: ')

        if ans == The_Bourne_Identity:
            movie_total_price += 9.99 * q1
        elif ans == Harry_Potter:
            movie_total_price += 15.99 * q1
        elif ans == Holy_Cross:
            movie_total_price += 4.75 * q1
        elif ans == Arrival:
            movie_total_price += 24.99 * q1
        elif ans == Hidden:
            movie_total_price += 29.98 * q1

    movie_tax = movie_total_price * .07
    total_cost = movie_tax + movie_total_price

    print("Your movies cost,", movie_total_price)
    print("Your tax will be,", movie_tax)
    print("Your total cost,", total_cost)


问:
JSON with Dynamic Keys while using Retrofit in Android
I'm new in using Retrofit with Android. I'm stuck at a point where I make a request to the REST Api and the response has a dynamic keys. Can anyone tell me what is the best way to parse the JSON something like this.

```<code>{
  "Meta Data": {
    "1. Information": "Intraday (1min) prices and volumes",
    "2. Symbol": "MSFT",
    "3. Last Refreshed": "2017-12-01 16:00:00",
    "4. Interval": "1min",
    "5. Output Size": "Compact",
    "6. Time Zone": "US/Eastern"
  },
  "Time Series (1min)": {
    "2017-12-01 16:00:00": {
      "1. open": "84.2000",
      "2. high": "84.2600",
      "3. low": "84.1800",
      "4. close": "84.2000",
      "5. volume": "3311341"
    },
    "2017-12-01 15:59:00": {
      "1. open": "84.2500",
      "2. high": "84.2600",
      "3. low": "84.2000",
      "4. close": "84.2000",
      "5. volume": "175169"
    },
    "2017-12-01 15:58:00": {
      "1. open": "84.2800",
      "2. high": "84.3000",
      "3. low": "84.2400",
      "4. close": "84.2550",
      "5. volume": "139520"
    }

  }
}
</code>```

答:
I think this might help you:

```<code>  JSONObject timeJsonObject = mainObject.getJSONObject("Time Series (1min)");

    Iterator<String> keysItr = timeJsonObject.keys();
    while (keysItr.hasNext()) {
        String key = keysItr.next();

        //now here you get key as : 2017-12-01 16:00:00

        //do here code as:

        JSONObject individualObject = timeJsonObject.getJSONObject(key);

        String openTime = individualObject.getString("1. open");
        String highTime = individualObject.getString("1. high");
        String lowTime = individualObject.getString("1. low");
        String closeTime = individualObject.getString("1. close");
        String volumeTime = individualObject.getString("1. volumne");

    }
</code>```

Here "while-loop" iterates for all keys for "2017-12-01 16:00:00,2017-12-01 15:59:00,2017-12-01 15:58:00" and so on. It will iterate for how many keys will added in this section.

Body:
I'm new in using Retrofit with Android. I'm stuck at a point where I make a request to the REST Api and the response has a dynamic keys. Can anyone tell me what is the best way to parse the JSON something like this.

{
  "Meta Data": {
    "1. Information": "Intraday (1min) prices and volumes",
    "2. Symbol": "MSFT",
    "3. Last Refreshed": "2017-12-01 16:00:00",
    "4. Interval": "1min",
    "5. Output Size": "Compact",
    "6. Time Zone": "US/Eastern"
  },
  "Time Series (1min)": {
    "2017-12-01 16:00:00": {
      "1. open": "84.2000",
      "2. high": "84.2600",
      "3. low": "84.1800",
      "4. close": "84.2000",
      "5. volume": "3311341"
    },
    "2017-12-01 15:59:00": {
      "1. open": "84.2500",
      "2. high": "84.2600",
      "3. low": "84.2000",
      "4. close": "84.2000",
      "5. volume": "175169"
    },
    "2017-12-01 15:58:00": {
      "1. open": "84.2800",
      "2. high": "84.3000",
      "3. low": "84.2400",
      "4. close": "84.2550",
      "5. volume": "139520"
    }

  }
}

Body:
I think this might help you:

  JSONObject timeJsonObject = mainObject.getJSONObject("Time Series (1min)");

    Iterator<String> keysItr = timeJsonObject.keys();
    while (keysItr.hasNext()) {
        String key = keysItr.next();

        //now here you get key as : 2017-12-01 16:00:00

        //do here code as:

        JSONObject individualObject = timeJsonObject.getJSONObject(key);

        String openTime = individualObject.getString("1. open");
        String highTime = individualObject.getString("1. high");
        String lowTime = individualObject.getString("1. low");
        String closeTime = individualObject.getString("1. close");
        String volumeTime = individualObject.getString("1. volumne");

    }

Here "while-loop" iterates for all keys for "2017-12-01 16:00:00,2017-12-01 15:59:00,2017-12-01 15:58:00" and so on. It will iterate for how many keys will added in this section.


问:
Can anyone suggest me how to use carousel in angular2
I need to include angular2-carousel for the images present in the table. Can anyone help me to do this?

This is the HTML code I tried:

```<code>  <div class="row">
    <div class="col-md-12">
      <carousel>
        <img src="http://www.tripathihospital.com/images/hospital.jpg" style="margin:auto;">
          <div class="carousel-caption">
            <h3 style="background-color: transparent;color: white;">Slide {{index + 1}}</h3>
          </div>
       </carousel>
    </div>
  </div>
 </td>
</code>```

Console output:

```<code>Uncaught Error: Template parse errors:
'carousel' is not a known element:
1. If 'carousel' is an Angular component, then verify that it is part of this module.
</code>```

答:
Website states that selector for carousel is not <carousel> but is <carousel-component>.

Update the selector.

Body:
I need to include angular2-carousel for the images present in the table. Can anyone help me to do this?

This is the HTML code I tried:

      <carousel>

Slide {{index + 1}}

       </carousel>

Console output:

Uncaught Error: Template parse errors:
'carousel' is not a known element:
1. If 'carousel' is an Angular component, then verify that it is part of this module.


问:
does passportjs automatically add user to res.locals?
In my template, settings.pug, user.name is being accessed. Which is unclear how it's getting there as controller looks like this:</p>

```<code>const express = require('express');
const router = express.Router();

router.get('/', function(req, res){
    res.render('settings');
});

module.exports = router;
</code>```

答:
never mind I found code that I had written long time ago in main controller</p>

```<code>router.use(function(req,res,next){
  if (req.user) res.locals.user = req.user;
  next();
});
</code>```

Body:
In my template, settings.pug, user.name is being accessed. Which is unclear how it's getting there as controller looks like this:

const express = require('express');
const router = express.Router();

router.get('/', function(req, res){
    res.render('settings');
});

module.exports = router;

Body:
never mind I found code that I had written long time ago in main controller

router.use(function(req,res,next){
  if (req.user) res.locals.user = req.user;
  next();
});


问:
Why won't my program terminate when i input END?
I am trying to terminate my code when "END" is input into the console, however my code wont play fair and I can't seem to see where it is going wrong, btw I haven't learnt how to debug as of yet so this has largely got to do with why i can't figure it out. please do help if you can. </p>

```<code>import java.util.*;
class Main
{
public static void main(String args[])
{
    int j = 0;
    while (j++ <= 3) {
        // Create Scanner object to take input from command prompt
        Scanner s=new Scanner(System.in);
        // Take input from the user and store it in st
        String st = "";
        while (!st.equals("END")) {
            {
                st=s.nextLine();
                // Initialize the variable count to 0
                int count=0;
                // Convert String st to char array
                char[] c=st.toCharArray();
                // Loop till end of string
                for(int i=0;i<st.length();i++)

                // If character at index 'i' is not a space, then increment count
                    if(c[i]!=' ') count++;
                // Print no.of spaces
                System.out.printf("[%4d] spaces in ", +(st.length()-count));
                // Print no.of spaces
                System.out.println('"' + st + '"');

            }
            j++;
        }
    }
}
</code>```

答: Since you have while (j++ <= 3) {  ... } your program will end if you enter "END" two times.

Body:
I am trying to terminate my code when "END" is input into the console, however my code wont play fair and I can't seem to see where it is going wrong, btw I haven't learnt how to debug as of yet so this has largely got to do with why i can't figure it out. please do help if you can.

import java.util.*;
class Main
{
public static void main(String args[])
{
    int j = 0;
    while (j++ <= 3) {
        // Create Scanner object to take input from command prompt
        Scanner s=new Scanner(System.in);
        // Take input from the user and store it in st
        String st = "";
        while (!st.equals("END")) {
            {
                st=s.nextLine();
                // Initialize the variable count to 0
                int count=0;
                // Convert String st to char array
                char[] c=st.toCharArray();
                // Loop till end of string
                for(int i=0;i<st.length();i++)

                // If character at index 'i' is not a space, then increment count
                    if(c[i]!=' ') count++;
                // Print no.of spaces
                System.out.printf("[%4d] spaces in ", +(st.length()-count));
                // Print no.of spaces
                System.out.println('"' + st + '"');

            }
            j++;
        }
    }
}


问:
How to update a video call in Recents Call logs in iOS
I like to update the localized caller name in Recents call logs once the video call starts and if user taps that particular caller in Recents logs it will again connect with the caller from the application. Like used in imo and Google Duo.</p>

答:
FYI - the below code is written in Obj-C,

To update the localized the caller name:

```<code>CXCallUpdate *callUpdate = [[CXCallUpdate alloc] init];
callUpdate.remoteHandle = [[CXHandle alloc] initWithType:CXHandleTypeGeneric value:[NSString stringWithFormat:@"%@", phoneNumber]];
callUpdate.localizedCallerName = displayName;
[provider reportCallWithUUID:callUUID updated:callUpdate];
</code>```

For Recent call logs, refer this answer

Body:
FYI - the below code is written in Obj-C,

To update the localized the caller name:

CXCallUpdate *callUpdate = [[CXCallUpdate alloc] init];
callUpdate.remoteHandle = [[CXHandle alloc] initWithType:CXHandleTypeGeneric value:[NSString stringWithFormat:@"%@", phoneNumber]];
callUpdate.localizedCallerName = displayName;
[provider reportCallWithUUID:callUUID updated:callUpdate];

For Recent call logs, refer this answer


问:
Excel VBA "else" statement counting wrongly
I have created an "If ElseIf Else" statement that will count the strings in a strings. It does count the keywords/strings that I want to be counted but it is counting the "others"/ Else items wrongly. As shown below highlighted in red, I should only have 6 strings that should be labelled as "others" but it counted as 8. It is a total of 18 rows but on the total results it counted it as 20.
I am newby in VBA and needing experts advise. Thank you.

```<code>Option Compare Text

Public Sub Keywords()

Dim row_number As Long
Dim count_of_corp_or_windows As Long
Dim count_of_mcafee As Long
Dim count_of_token As Long
Dim count_of_host_or_ipass As Long
Dim count_of_others As Long
Dim count_of_X As Long
Dim count_of_all As Long
Dim items As Variant

row_number = 0
count_of_corp_or_windows = 0
count_of_mcafee = 0
count_of_token = 0
count_of_host_or_ipass = 0
count_of_X = 0
count_of_others = 0
count_of_all = 0
Do

row_number = row_number + 1
items = Sheets("LoginPassword").Range("N" & row_number)
    If InStr(items, "corp") Or InStr(items, "windows") Then
        count_of_corp_or_windows = count_of_corp_or_windows + 1
    ElseIf InStr(items, "mcafee") Then
        count_of_mcafee = count_of_mcafee + 1
    ElseIf InStr(items, "token") Then
        count_of_token = count_of_token + 1
    ElseIf InStr(items, "host") Or InStr(items, "ipass") Then
        count_of_host_or_ipass = count_of_host_or_ipass + 1
    ElseIf InStr(items, "X A") Then
        count_of_X = count_of_X + 1
    Else:
        count_of_others = count_of_others + 1

    End If

Loop Until items = ""

count_of_all = count_of_corp_or_windows + count_of_mcafee + count_of_token + count_of_host_or_ipass + count_of_X + count_of_others

Range("N2").Select

Selection.End(xlDown).Select
lastCell = ActiveCell.Address

ActiveCell.Offset(3, 0).Value = "Count"
ActiveCell.Offset(4, 0).Value = count_of_corp_or_windows
ActiveCell.Offset(5, 0).Value = count_of_mcafee
ActiveCell.Offset(6, 0).Value = count_of_token
ActiveCell.Offset(7, 0).Value = count_of_host_or_ipass
ActiveCell.Offset(8, 0).Value = count_of_X
ActiveCell.Offset(9, 0).Value = count_of_others
ActiveCell.Offset(11, 0).Value = count_of_all
ActiveCell.Offset(3, 1).Value = "Keywords"
ActiveCell.Offset(4, 1).Value = "Corp or Windows"
ActiveCell.Offset(5, 1).Value = "Mcafee"
ActiveCell.Offset(6, 1).Value = "Token"
ActiveCell.Offset(7, 1).Value = "Host or ipass"
ActiveCell.Offset(8, 1).Value = "X accounts"
ActiveCell.Offset(9, 1).Value = "Others"
ActiveCell.Offset(11, 1).Value = "Total"
ActiveCell.Offset(3, -1).Value = "Percent"
ActiveCell.Offset(4, -1).Value = count_of_corp_or_windows / count_of_all
ActiveCell.Offset(5, -1).Value = count_of_mcafee / count_of_all
ActiveCell.Offset(6, -1).Value = count_of_token / count_of_all
ActiveCell.Offset(7, -1).Value = count_of_host_or_ipass / count_of_all
ActiveCell.Offset(8, -1).Value = count_of_X / count_of_all
ActiveCell.Offset(9, -1).Value = count_of_others / count_of_all
End Sub
</code>```

答: count_of_others is never set to zero after an iteration since it is out of the loop. This should happen for other counter variables too.

Body:
I have created an "If ElseIf Else" statement that will count the strings in a strings. It does count the keywords/strings that I want to be counted but it is counting the "others"/ Else items wrongly. As shown below highlighted in red, I should only have 6 strings that should be labelled as "others" but it counted as 8. It is a total of 18 rows but on the total results it counted it as 20.
I am newby in VBA and needing experts advise. Thank you.

Option Compare Text

Public Sub Keywords()

Dim row_number As Long
Dim count_of_corp_or_windows As Long
Dim count_of_mcafee As Long
Dim count_of_token As Long
Dim count_of_host_or_ipass As Long
Dim count_of_others As Long
Dim count_of_X As Long
Dim count_of_all As Long
Dim items As Variant

row_number = 0
count_of_corp_or_windows = 0
count_of_mcafee = 0
count_of_token = 0
count_of_host_or_ipass = 0
count_of_X = 0
count_of_others = 0
count_of_all = 0
Do

row_number = row_number + 1
items = Sheets("LoginPassword").Range("N" & row_number)
    If InStr(items, "corp") Or InStr(items, "windows") Then
        count_of_corp_or_windows = count_of_corp_or_windows + 1
    ElseIf InStr(items, "mcafee") Then
        count_of_mcafee = count_of_mcafee + 1
    ElseIf InStr(items, "token") Then
        count_of_token = count_of_token + 1
    ElseIf InStr(items, "host") Or InStr(items, "ipass") Then
        count_of_host_or_ipass = count_of_host_or_ipass + 1
    ElseIf InStr(items, "X A") Then
        count_of_X = count_of_X + 1
    Else:
        count_of_others = count_of_others + 1

    End If

Loop Until items = ""

count_of_all = count_of_corp_or_windows + count_of_mcafee + count_of_token + count_of_host_or_ipass + count_of_X + count_of_others

Range("N2").Select

Selection.End(xlDown).Select
lastCell = ActiveCell.Address

ActiveCell.Offset(3, 0).Value = "Count"
ActiveCell.Offset(4, 0).Value = count_of_corp_or_windows
ActiveCell.Offset(5, 0).Value = count_of_mcafee
ActiveCell.Offset(6, 0).Value = count_of_token
ActiveCell.Offset(7, 0).Value = count_of_host_or_ipass
ActiveCell.Offset(8, 0).Value = count_of_X
ActiveCell.Offset(9, 0).Value = count_of_others
ActiveCell.Offset(11, 0).Value = count_of_all
ActiveCell.Offset(3, 1).Value = "Keywords"
ActiveCell.Offset(4, 1).Value = "Corp or Windows"
ActiveCell.Offset(5, 1).Value = "Mcafee"
ActiveCell.Offset(6, 1).Value = "Token"
ActiveCell.Offset(7, 1).Value = "Host or ipass"
ActiveCell.Offset(8, 1).Value = "X accounts"
ActiveCell.Offset(9, 1).Value = "Others"
ActiveCell.Offset(11, 1).Value = "Total"
ActiveCell.Offset(3, -1).Value = "Percent"
ActiveCell.Offset(4, -1).Value = count_of_corp_or_windows / count_of_all
ActiveCell.Offset(5, -1).Value = count_of_mcafee / count_of_all
ActiveCell.Offset(6, -1).Value = count_of_token / count_of_all
ActiveCell.Offset(7, -1).Value = count_of_host_or_ipass / count_of_all
ActiveCell.Offset(8, -1).Value = count_of_X / count_of_all
ActiveCell.Offset(9, -1).Value = count_of_others / count_of_all
End Sub


问:
PHP: how to parse a huge xml file
I need to parse a huge XML that contains lots of job entries, like this

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<items>
  <item>
    <title><![CDATA[...]]></title>
    <description><![CDATA[...]]></description>
    <link><![CDATA[...]]></link>
    <city><![CDATA[...]]></city>
    <state><![CDATA[...]]></state>
    <position><![CDATA[...]]></position>
    <company><![CDATA[...]]></company>
    <category_id><![CDATA[...]]></category_id>
    <job_id>...</job_id>
    <salary><![CDATA[...]]></salary>
    <term><![CDATA[...]]></term>
  </item>

  ....

</items>
</code>```

The server has enough memory to fully read that file but when if comes to parsing, it fails with "memory exhausted" error. Does PHP provide ways that would allow to split that file nicely or parse it in parts or anything that can be of help here. Thanks for any ideas and suggestions!

答: http://www.php.net/xmlreader can process it without using a ton of memory.</p>

Title: PHP: how to parse a huge xml file

Body:
I need to parse a huge XML that contains lots of job entries, like this

<?xml version="1.0" encoding="ISO-8859-1"?>
<items>
  <item>
    <title><![CDATA[...]]></title>
    <description><![CDATA[...]]></description>
    <link><![CDATA[...]]></link>
    <city><![CDATA[...]]></city>
    <state><![CDATA[...]]></state>
    <position><![CDATA[...]]></position>
    <company><![CDATA[...]]></company>
    <category_id><![CDATA[...]]></category_id>
    <job_id>...</job_id>
    <salary><![CDATA[...]]></salary>
    <term><![CDATA[...]]></term>
  </item>

  ....

</items>

The server has enough memory to fully read that file but when if comes to parsing, it fails with "memory exhausted" error. Does PHP provide ways that would allow to split that file nicely or parse it in parts or anything that can be of help here. Thanks for any ideas and suggestions!


问:
add new column if not exists in sqlite
Hi Im using this query in sqlite

```<code>tx.executeSql('CREATE TABLE IF NOT EXISTS STU_REMAINDER( REG_NO VARCHAR(15), REM_ID INTEGER, REM_DATETIME DATETIME, DETAILS VARCHAR(500),STATUS INTEGER )');
</code>```

I want to add column SCH_ID in this table, if not exist in this column. Thank you.

答:
I prefer using a GUI Firefox addon Sqlite Manager to work with Sqlite database. You can download it from below url

https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/

You can view queries in it too when you add or alter table.

Title: add new column if not exists in sqlite

Body:
Hi Im using this query in sqlite

tx.executeSql('CREATE TABLE IF NOT EXISTS STU_REMAINDER( REG_NO VARCHAR(15), REM_ID INTEGER, REM_DATETIME DATETIME, DETAILS VARCHAR(500),STATUS INTEGER )');

I want to add column SCH_ID in this table, if not exist in this column. Thank you.


答:
Because you have two while loops nested. You input "END" in the second while loop and after that the second loop ends that's correct. But as you see, after it ends it will start the first loop which is while (j++ <= 3) { and in this while loop it waits for an input from user 3 times, which corresponds to Scanner s=new Scanner(System.in);, therefore it is normal for your program not to exit. If you want your program to finish after some input you may want to use  System.exit(-1); command. I've added code according to your comments.

```<code>import java.util.*;

class Main {

public static void main(String args[]) {
int j = 0;
while (j++ <= 3) {
  // Create Scanner object to take input from command prompt
  Scanner s = new Scanner(System.in);
  // Take input from the user and store it in st
  String st = s.nextLine();
    if (!st.equals("END")) {
    // Initialize the variable count to 0
    int count = 0;
    // Convert String st to char array
    char[] c = st.toCharArray();
    // Loop till end of string
    for (int i = 0; i < st.length(); i++)

    // If character at index 'i' is not a space, then increment count
    {
      if (c[i] != ' ') {
        count++;
      }
    }
    // Print no.of spaces
    System.out.printf("[%4d] spaces in ", +(st.length() - count));
    // Print no.of spaces
    System.out.println('"' + st + '"');
  } else {
    System.exit(-1);
  }
}
}
}
</code>```

Title: Why won't my program terminate when i input END?

Body:
Because you have two while loops nested. You input "END" in the second while loop and after that the second loop ends that's correct. But as you see, after it ends it will start the first loop which is while (j++ <= 3) { and in this while loop it waits for an input from user 3 times, which corresponds to Scanner s=new Scanner(System.in);, therefore it is normal for your program not to exit. If you want your program to finish after some input you may want to use  System.exit(-1); command. I've added code according to your comments.

import java.util.*;

class Main {

public static void main(String args[]) {
int j = 0;
while (j++ <= 3) {
  // Create Scanner object to take input from command prompt
  Scanner s = new Scanner(System.in);
  // Take input from the user and store it in st
  String st = s.nextLine();
    if (!st.equals("END")) {
    // Initialize the variable count to 0
    int count = 0;
    // Convert String st to char array
    char[] c = st.toCharArray();
    // Loop till end of string
    for (int i = 0; i < st.length(); i++)

    // If character at index 'i' is not a space, then increment count
    {
      if (c[i] != ' ') {
        count++;
      }
    }
    // Print no.of spaces
    System.out.printf("[%4d] spaces in ", +(st.length() - count));
    // Print no.of spaces
    System.out.println('"' + st + '"');
  } else {
    System.exit(-1);
  }
}
}
}


问:
How to add specific padding in conv2d
I am trying to pass a tensor to a CNN in python. I am using tf.layers.conv2d for this. I want to get the output dimensions as half of the input. I understand that I can use a padding of 'same' followed by a max pooling layer to achieve this, but another way that I found out in a recent paper is to use a 3x3 kernel with a 2x2 stride in addition to a 1x1 padding

Now, as I understand, conv2d allows for a parameter called padding which can be either 'valid' or 'same', which does not allow for a padding of a specific length.

Is there any way that this can be achieved directly in the operation? I am asking since the idea is to use multiple convolution layers, each successively halving the dimensions both length and width-wise.

If someone can point out a similar topic or help with this, it would be great.

Edit:

I have been asked to include the code. But there is not much of a code since I am stuck at the very first point where the CNN needs to be designed. Nonetheless, here is the part that accepts the initial input and starts defining the CNN (here I have kept padding='same' since I was checking if that would work):

```<code>def conv2d(z):
    output = tf.layers.conv2d(z,strides=[2,2],filters=3,padding='same',kernel_size=3);
</code>```

I am stuck at this point since going any further needs this initial layer to be correctly defined as successive layers will also work on the same principle.

Also, my initial input size is a 224x224 image with 1 channel (grayscale image)

答:
So, I found an answer to this.
There is an inbuilt function called pad in tensorflow, which can be used to solve it.
What I am doing is this

```<code>output = tf.pad(output, paddings, "CONSTANT")
output = tf.layers.conv2d(output,strides=[2,2],kernel_size=3,filters=3)
</code>```

This means I am using a tf.pad before every layer wherein the variable 'paddings' is defined as below

```<code>paddings=tf.constant([[0,0], [1,1],[1,1],[0,0]])
</code>```

This ensures that each layer is padded before being passed on for convolution, thus giving the output as desired

Title: How to add specific padding in conv2d

Body:
I am trying to pass a tensor to a CNN in python. I am using tf.layers.conv2d for this. I want to get the output dimensions as half of the input. I understand that I can use a padding of 'same' followed by a max pooling layer to achieve this, but another way that I found out in a recent paper is to use a 3x3 kernel with a 2x2 stride in addition to a 1x1 padding

Now, as I understand, conv2d allows for a parameter called padding which can be either 'valid' or 'same', which does not allow for a padding of a specific length.

Is there any way that this can be achieved directly in the operation? I am asking since the idea is to use multiple convolution layers, each successively halving the dimensions both length and width-wise.

If someone can point out a similar topic or help with this, it would be great.

Edit:

I have been asked to include the code. But there is not much of a code since I am stuck at the very first point where the CNN needs to be designed. Nonetheless, here is the part that accepts the initial input and starts defining the CNN (here I have kept padding='same' since I was checking if that would work):

def conv2d(z):
    output = tf.layers.conv2d(z,strides=[2,2],filters=3,padding='same',kernel_size=3);

I am stuck at this point since going any further needs this initial layer to be correctly defined as successive layers will also work on the same principle.

Also, my initial input size is a 224x224 image with 1 channel (grayscale image)

Body:
So, I found an answer to this.
There is an inbuilt function called pad in tensorflow, which can be used to solve it.
What I am doing is this

output = tf.pad(output, paddings, "CONSTANT")
output = tf.layers.conv2d(output,strides=[2,2],kernel_size=3,filters=3)

This means I am using a tf.pad before every layer wherein the variable 'paddings' is defined as below

paddings=tf.constant([[0,0], [1,1],[1,1],[0,0]])

This ensures that each layer is padded before being passed on for convolution, thus giving the output as desired


问:
Presto URL Functions
I need to pull urls from a database, re-formatting them slightly in the process. Some of the URLs in the db have port numbers specified, some don't. I'm using Presto's handy URL extraction functions, such as url_extract_port.

However, when the following sql encounters a url where no port is specified, it returns null - even for rows that are not in fact null. (If I remove the url_extract_port function I get the link value, but without the port.)

```<code>SELECT
  concat(
    url_extract_protocol(link)
    ,'://'
    ,url_extract_host(link)
    ,':'
    ,cast(url_extract_port(link) AS VARCHAR)
  )
   AS  url
 FROM db.schema.urltable
WHERE link is not null
</code>```

Is there a way to specify in the sql that i only want to use url_extract_port when a port is specified?

答:
The coalesce function solves the problem, with the url_extract_port line changed to:

```<code>,coalesce(cast(url_extract_port(link) AS VARCHAR),'')
</code>```

In cases where the port is not present, url_extract_port returns null. Thus, when used as shown with coalesce, the default value, in this case an empty string, is returned instead.

Title: Presto URL Functions

Body:
I need to pull urls from a database, re-formatting them slightly in the process. Some of the URLs in the db have port numbers specified, some don't. I'm using Presto's handy URL extraction functions, such as url_extract_port.

However, when the following sql encounters a url where no port is specified, it returns null - even for rows that are not in fact null. (If I remove the url_extract_port function I get the link value, but without the port.)

SELECT
  concat(
    url_extract_protocol(link)
    ,'://'
    ,url_extract_host(link)
    ,':'
    ,cast(url_extract_port(link) AS VARCHAR)
  )
   AS  url
 FROM db.schema.urltable
WHERE link is not null

Is there a way to specify in the sql that i only want to use url_extract_port when a port is specified?

Body:
The coalesce function solves the problem, with the url_extract_port line changed to:

,coalesce(cast(url_extract_port(link) AS VARCHAR),'')

In cases where the port is not present, url_extract_port returns null. Thus, when used as shown with coalesce, the default value, in this case an empty string, is returned instead.


问:
Errors in command-line while running Java programs
I have a complete Java program, but the way that my professor is going to check to make sure that the program is working correctly is through CMD using the command

 "java Caesar input.txt output.txt"

But the issues I am running into are that when I compile using "javac Caesar.java" it will compile and create a Caesar.class file in the folder, but when I try run it as "java caesar input.txt output.txt" it says Error: Could not find or load main class caesar.

What am I doing wrong here?

I can provide additional information as needed.

```<code>package caaesar;

import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;

/**
 *
 * @author Connorbboggs
 * Version 12.03.2017
 */
public class Caaesar
{

private static Scanner sc;
private static FileWriter fw;
private static BufferedWriter bw;
private Scanner inp;
private Scanner outp;
//DecodeChar class provided by you
public static char decodeChar(int n, char ch)
{
    int ord;
    if (ch >= 'A' && ch <= 'Z')
    {
        ord = ch - 'A';
        ord += n;
        ord %= 26;
        return (char)(ord + 'A');
    }
    else if (ch >= 'a' && ch <= 'z')
    {
        ord = ch - 'a';
        ord += n;
        ord %= 26;
        return (char)(ord + 'a');
    }
    else
    {
        return ch;
    }
}

public static void main(String[] args)
{
    //File input for decode.txt with the encrypted text
    File inputFile = new File(args[0]);
    //Output for the decrypted text
    File outputFile = new File(args[1]);
    try
    {
        //input from inputFile
        sc = new Scanner(inputFile);
        int shift = sc.nextInt();
        String decoded = "";
        //while lines are available text is fed to inputFile
        while( sc.hasNextLine())
        {
            //Lines being fed into string line
            String line = sc.nextLine();
            //for loop to feed into decoded using decodeChar
            for(int i=0; i<line.length(); i++)
            {
                decoded += decodeChar(shift, line.charAt(i));
            }
            decoded += '\n';
        }
        //Just to verify that the text is decrypted
        System.out.println(decoded);
        try
        {
            //create a fileWriter for outputFile
            fw = new FileWriter(outputFile);
            //write "decoded" to the file
            fw.write(decoded);
            //close the file
            fw.close();
        }
        //exception catching
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }
    //more exception
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
}

}
</code>```

答:
First of all javac Caesar.java should say file not found...

Your Caaesar class is part of the caaesar package.

The fully qualified class name is caaesar.Caaesar, which is how you run this class

Body:
I have a complete Java program, but the way that my professor is going to check to make sure that the program is working correctly is through CMD using the command

 "java Caesar input.txt output.txt"

But the issues I am running into are that when I compile using "javac Caesar.java" it will compile and create a Caesar.class file in the folder, but when I try run it as "java caesar input.txt output.txt" it says Error: Could not find or load main class caesar.

What am I doing wrong here?

I can provide additional information as needed.

package caaesar;

import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;

/**
 *
 * @author Connorbboggs
 * Version 12.03.2017
 */
public class Caaesar
{

private static Scanner sc;
private static FileWriter fw;
private static BufferedWriter bw;
private Scanner inp;
private Scanner outp;
//DecodeChar class provided by you
public static char decodeChar(int n, char ch)
{
    int ord;
    if (ch >= 'A' && ch <= 'Z')
    {
        ord = ch - 'A';
        ord += n;
        ord %= 26;
        return (char)(ord + 'A');
    }
    else if (ch >= 'a' && ch <= 'z')
    {
        ord = ch - 'a';
        ord += n;
        ord %= 26;
        return (char)(ord + 'a');
    }
    else
    {
        return ch;
    }
}

public static void main(String[] args)
{
    //File input for decode.txt with the encrypted text
    File inputFile = new File(args[0]);
    //Output for the decrypted text
    File outputFile = new File(args[1]);
    try
    {
        //input from inputFile
        sc = new Scanner(inputFile);
        int shift = sc.nextInt();
        String decoded = "";
        //while lines are available text is fed to inputFile
        while( sc.hasNextLine())
        {
            //Lines being fed into string line
            String line = sc.nextLine();
            //for loop to feed into decoded using decodeChar
            for(int i=0; i<line.length(); i++)
            {
                decoded += decodeChar(shift, line.charAt(i));
            }
            decoded += '\n';
        }
        //Just to verify that the text is decrypted
        System.out.println(decoded);
        try
        {
            //create a fileWriter for outputFile
            fw = new FileWriter(outputFile);
            //write "decoded" to the file
            fw.write(decoded);
            //close the file
            fw.close();
        }
        //exception catching
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }
    //more exception
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
}

}


问:
How to make JRuby 1.6 default to Ruby 1.9?
what is the best way to make JRuby to run in 1.9 mode by default?

i.e, I want to run rake test instead of jruby --1.9 -S rake test

Thank you

答:
Use the JRUBY_OPTS environment variable.  JRUBY_OPTS holds a list of arguments that are added to any arguments specified on the command line.

For example (on Linux):

```
$ jruby -v
jruby 1.6.0.RC1 (ruby 1.8.7 patchlevel 330) (2011-01-10 769f847) (Java HotSp...
$ export JRUBY_OPTS=--1.9
$ jruby -v
jruby 1.6.0.RC1 (ruby 1.9.2 trunk 136) (2011-01-10 769f847) (Java HotSpot(TM...
$ export JRUBY_OPTS=--1.8
$ jruby -v
jruby 1.6.0.RC1 (ruby 1.8.7 patchlevel 330) (2011-01-10 769f847) (Java HotSpo...
```

Body:
Use the JRUBY_OPTS environment variable.  JRUBY_OPTS holds a list of arguments that are added to any arguments specified on the command line.

For example (on Linux):

$ jruby -v
jruby 1.6.0.RC1 (ruby 1.8.7 patchlevel 330) (2011-01-10 769f847) (Java HotSp...
$ export JRUBY_OPTS=--1.9
$ jruby -v
jruby 1.6.0.RC1 (ruby 1.9.2 trunk 136) (2011-01-10 769f847) (Java HotSpot(TM...
$ export JRUBY_OPTS=--1.8
$ jruby -v
jruby 1.6.0.RC1 (ruby 1.8.7 patchlevel 330) (2011-01-10 769f847) (Java HotSpo...