问:
Chrome Image Placement Issue. 1px buffer?
I'm having a hard time explaining this.  But, basically, in Google Chrome I have an issue where I placed an image to the bottom of a div and there is a 1px border or "buffer at the bottom that I can't remove.

Here's what I see!

Chrome:

Opera:

I want the Chrome one to look like the Opera one.

Here is the code!

This is the CSS

Mind the sloppiness.  This website is in a rough draft right now.

```<code>@media screen and (max-width: 450px) {
  * {
    padding: 0;
    margin: 0;
    outline: none;
  }

  .mmenu {
    z-index: -1;
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: #aaa;
  }

  .mobileBody {
    z-index: 1;
    background-color: #fff;
  }

  .mhead {
    background-image: url(../img/head.jpg);
    background-size: cover;
    background-position: center;
    margin: 0;
    padding: 0;
    position: relative;
  }

  .logo {
    margin: auto;
  }

  img.logoImg {
    width: 175px;
    height: auto;
    margin: auto;
    margin-top: 15px;
  }

  .mhead img.cut {
    margin: 0;
    margin-top: 1px;
    padding: 0;
    width: 100%;
    height: auto;
    position: absolute;
    bottom: 0;
    left: 0;
    vertical-align: bottom;
  }

  .card {
    background-color: #fff;
    width: 100%;
    height: auto;
  }

  .final {
    display: flex;

  }

  .flavImg {
    display: flex;
    justify-content: center;
    align-items:center;
    width: 45%;
  }

  .flavImg img {
     height: 80%;
     width: auto;
  }

  .flavDesc {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-flow: column;
  }

  .flavDesc h1 {
    font-size: 21pt;
    text-align: left;
    font-family: 'Dancing Script', cursive;
    -webkit-font-smoothing: subpixel-antialiased;
    margin-bottom: 5px;
  }

  .flavDesc p {
    font-size: 11pt;
    text-align: left;
    font-family: 'Ledger', serif;
    line-height: 125%;
    -webkit-font-smoothing: subpixel-antialiased;
    margin-top: 5px;
  }

  .edit {
    display: none;
  }
}
</code>```

This is in Jade.

Mind the sloppiness.  This website is in a rough draft right now.

```<code>doctype html
html
  head
    title Conecopia Gelato - Ice Cream The Italian Way!

    meta(name="description" content="Conecopia Gelato LLC. is a small family owned Italian ice cream (gelato) stand located within the Springfield Town Center Smart Market in Springfield VA.  At Conecopia we strive to make the most flavorful ice cream possible for our customers to enjoy.")
    meta(name="keywords" content="Gealto,Ice cream,Farmers market,Italian,flavor,fruit,juice,summer,virginia,VA,springfield,springfield town center,saturday,smart market")
    meta(name="author" content="Anthony F. DeSante")
    meta(name="viewport" content="width=device-width, initial-scale=1.0")

    link(href="https://fonts.googleapis.com/css?family=Dancing+Script|Ledger" rel="stylesheet")

    link(rel="stylesheet" type="text/css" href="ast/css/index.css")

  body
    .computer
    .mobile
      .mmenu
        ul.mmainNav
          a(href="#")
            li Home
          a(href="#")
            li Flavors
          a(href="#")
            li Contact Us
          a(href="#")
            li About
        ul.mlowerNav
          a(href="#")
            li Home
        .msocialmedia
          //Social Media Icons Go Here.
      .mobileBody
        .mhead
          .logo
            img(src="./ast/img/logo.png").logoImg
          img(src="./ast/img/cut.png").cut
        .mWeekFlavs.dispHor
          .row
            .card
              .final
                .flavImg
                  img(src="./ast/img/icecream.png")
                .flavDesc
                  .flavName
                    h1 Flavor Name
                  .flavText
                    p Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis aliquam vulputate diam, nulla mattis, sed dictum velit vulputate. Praesent sed justo eu odio laoreet ornare. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
              .edit.ifAdmin
                form(method="post" action="#")
                  input(type="file" name="image" accept="image/*")
                  input(name="flavName" type="text" placeholder="Flavor Name" value="")
                  textarea(row="5" col="auto")
                  input(type="reset")
                  input(name="save" type="submit" value="Save")
          .statusBar
            span#head

        .mAllFlavs.dispHor
br
br
br
br
br
br
br

br
br
br
br
br

br
br
br
br
br
br
br
br
br
br
br
br
br
br
br
br
br
</code>```

This is the HTML (Processed through PrePros)
It's here for those who don't like Jade?

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Conecopia Gelato - Ice Cream The Italian Way!</title>
    <meta name="description" content="Conecopia Gelato LLC. is a small family owned Italian ice cream (gelato) stand located within the Springfield Town Center Smart Market in Springfield VA.  At Conecopia we strive to make the most flavorful ice cream possible for our customers to enjoy.">
    <meta name="keywords" content="Gealto,Ice cream,Farmers market,Italian,flavor,fruit,juice,summer,virginia,VA,springfield,springfield town center,saturday,smart market">
    <meta name="author" content="Anthony F. DeSante">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css?family=Dancing+Script|Ledger" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="ast/css/index.css">
  </head>
  <body>
    <div class="computer"></div>
    <div class="mobile">
      <div class="mmenu">
        <ul class="mmainNav"><a href="#">
            <li>Home</li></a><a href="#">
            <li>Flavors</li></a><a href="#">
            <li>Contact Us</li></a><a href="#">
            <li>About</li></a></ul>
        <ul class="mlowerNav"><a href="#">
            <li>Home</li></a></ul>
        <div class="msocialmedia">
          <!--Social Media Icons Go Here.-->
        </div>
      </div>
      <div class="mobileBody">
        <div class="mhead">
          <div class="logo"><img class="logoImg" src="./ast/img/logo.png"></div><img class="cut" src="./ast/img/cut.png">
        </div>
        <div class="mWeekFlavs dispHor">
          <div class="row">
            <div class="card">
              <div class="final">
                <div class="flavImg"><img src="./ast/img/icecream.png"></div>
                <div class="flavDesc">
                  <div class="flavName">
                    <h1>Flavor Name</h1>
                  </div>
                  <div class="flavText">
                    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis aliquam vulputate diam, nulla mattis, sed dictum velit vulputate. Praesent sed justo eu odio laoreet ornare. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
                  </div>
                </div>
              </div>
              <div class="edit ifAdmin">
                <form method="post" action="#">
                  <input type="file" name="image" accept="image/*">
                  <input name="flavName" type="text" placeholder="Flavor Name" value="">
                  <textarea row="5" col="auto"></textarea>
                  <input type="reset">
                  <input name="save" type="submit" value="Save">
                </form>
              </div>
            </div>
          </div>
          <div class="statusBar"><span id="head"></span></div>
        </div>
        <div class="mAllFlavs dispHor"></div>
      </div>
    </div>
  </body>
</html><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</code>```

So if anybody has a way to remove the 1px "buffer" please send it in!

答:
Apparently, I found a solution...

It took me a while to realize that I was just flat out doing bad code.

For those who are wondering, In order to fix this I just wrapped my whole "body" section of my body in a div called

 (Everything except the head)
.  Then I used the pseudo-element ::before and set the background to the image.  After that, all I had to do was mess around with the alignment and the background position and size to make it work out!

I hope that was understandable.

Body:
I'm having a hard time explaining this.  But, basically, in Google Chrome I have an issue where I placed an image to the bottom of a div and there is a 1px border or "buffer at the bottom that I can't remove.

Here's what I see!

Chrome:

Opera:

I want the Chrome one to look like the Opera one.

Here is the code!

This is the CSS

Mind the sloppiness.  This website is in a rough draft right now.

@media screen and (max-width: 450px) {
  * {
    padding: 0;
    margin: 0;
    outline: none;
  }

  .mmenu {
    z-index: -1;
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: #aaa;
  }

  .mobileBody {
    z-index: 1;
    background-color: #fff;
  }

  .mhead {
    background-image: url(../img/head.jpg);
    background-size: cover;
    background-position: center;
    margin: 0;
    padding: 0;
    position: relative;
  }

  .logo {
    margin: auto;
  }

  img.logoImg {
    width: 175px;
    height: auto;
    margin: auto;
    margin-top: 15px;
  }

  .mhead img.cut {
    margin: 0;
    margin-top: 1px;
    padding: 0;
    width: 100%;
    height: auto;
    position: absolute;
    bottom: 0;
    left: 0;
    vertical-align: bottom;
  }

  .card {
    background-color: #fff;
    width: 100%;
    height: auto;
  }

  .final {
    display: flex;

  }

  .flavImg {
    display: flex;
    justify-content: center;
    align-items:center;
    width: 45%;
  }

  .flavImg img {
     height: 80%;
     width: auto;
  }

  .flavDesc {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-flow: column;
  }

  .flavDesc h1 {
    font-size: 21pt;
    text-align: left;
    font-family: 'Dancing Script', cursive;
    -webkit-font-smoothing: subpixel-antialiased;
    margin-bottom: 5px;
  }

  .flavDesc p {
    font-size: 11pt;
    text-align: left;
    font-family: 'Ledger', serif;
    line-height: 125%;
    -webkit-font-smoothing: subpixel-antialiased;
    margin-top: 5px;
  }

  .edit {
    display: none;
  }
}

This is in Jade.

Mind the sloppiness.  This website is in a rough draft right now.

doctype html
html
  head
    title Conecopia Gelato - Ice Cream The Italian Way!

    meta(name="description" content="Conecopia Gelato LLC. is a small family owned Italian ice cream (gelato) stand located within the Springfield Town Center Smart Market in Springfield VA.  At Conecopia we strive to make the most flavorful ice cream possible for our customers to enjoy.")
    meta(name="keywords" content="Gealto,Ice cream,Farmers market,Italian,flavor,fruit,juice,summer,virginia,VA,springfield,springfield town center,saturday,smart market")
    meta(name="author" content="Anthony F. DeSante")
    meta(name="viewport" content="width=device-width, initial-scale=1.0")

    link(href="https://fonts.googleapis.com/css?family=Dancing+Script|Ledger" rel="stylesheet")

    link(rel="stylesheet" type="text/css" href="ast/css/index.css")

  body
    .computer
    .mobile
      .mmenu
        ul.mmainNav
          a(href="#")
            li Home
          a(href="#")
            li Flavors
          a(href="#")
            li Contact Us
          a(href="#")
            li About
        ul.mlowerNav
          a(href="#")
            li Home
        .msocialmedia
          //Social Media Icons Go Here.
      .mobileBody
        .mhead
          .logo
            img(src="./ast/img/logo.png").logoImg
          img(src="./ast/img/cut.png").cut
        .mWeekFlavs.dispHor
          .row
            .card
              .final
                .flavImg
                  img(src="./ast/img/icecream.png")
                .flavDesc
                  .flavName
                    h1 Flavor Name
                  .flavText
                    p Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis aliquam vulputate diam, nulla mattis, sed dictum velit vulputate. Praesent sed justo eu odio laoreet ornare. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
              .edit.ifAdmin
                form(method="post" action="#")
                  input(type="file" name="image" accept="image/*")
                  input(name="flavName" type="text" placeholder="Flavor Name" value="")
                  textarea(row="5" col="auto")
                  input(type="reset")
                  input(name="save" type="submit" value="Save")
          .statusBar
            span#head

        .mAllFlavs.dispHor
br
br
br
br
br
br
br

br
br
br
br
br

br
br
br
br
br
br
br
br
br
br
br
br
br
br
br
br
br

This is the HTML (Processed through PrePros)
It's here for those who don't like Jade?

<!DOCTYPE html>

    <title>Conecopia Gelato - Ice Cream The Italian Way!</title>
    <meta name="description" content="Conecopia Gelato LLC. is a small family owned Italian ice cream (gelato) stand located within the Springfield Town Center Smart Market in Springfield VA.  At Conecopia we strive to make the most flavorful ice cream possible for our customers to enjoy.">
    <meta name="keywords" content="Gealto,Ice cream,Farmers market,Italian,flavor,fruit,juice,summer,virginia,VA,springfield,springfield town center,saturday,smart market">
    <meta name="author" content="Anthony F. DeSante">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css?family=Dancing+Script|Ledger" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="ast/css/index.css">

Home

Flavors

Contact Us

About

Home

Flavor Name

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis aliquam vulputate diam, nulla mattis, sed dictum velit vulputate. Praesent sed justo eu odio laoreet ornare. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

                <form method="post" action="#">
                  <input type="file" name="image" accept="image/*">
                  <input name="flavName" type="text" placeholder="Flavor Name" value="">
                  <textarea row="5" col="auto"></textarea>
                  <input type="reset">
                  <input name="save" type="submit" value="Save">
                </form>

So if anybody has a way to remove the 1px "buffer" please send it in!

Body:
Apparently, I found a solution...

It took me a while to realize that I was just flat out doing bad code.

For those who are wondering, In order to fix this I just wrapped my whole "body" section of my body in a div called <div class="MobileBody">
 (Everything except the head) </div>.  Then I used the pseudo-element ::before and set the background to the image.  After that, all I had to do was mess around with the alignment and the background position and size to make it work out!

I hope that was understandable.


来源: stackexchange

问:
Batch: For loop parameter using variables
I want to create a for loop that uses user input variables in it's parameter. Here is what I have:

```<code>@ECHO off
DEL "./positions.txt"
SET /P start_position= Please enter the start position:
SET /P end_position= Please enter the end position:
SET /P step_size= Please enter the step size:
FOR /L %%A IN (%start_position%,%end_position%,%step_size%) DO (
    ECHO %%A >> positions.txt
)
ECHO( & echo.Done! "positions.txt" was generated. & echo.
pause
</code>```

However this doesn't seem to work. Here is what I get on the output:

```<code>>> Done! "positions.txt" was generated.
</code>```

It runs, but skips over the for loop. What is wrong?

答:
for /L loops use the order start, step, end.

```<code>FOR /L %%A IN (%start_position%,%step_size%,%end_position%) DO (
    ECHO %%A >> positions.txt
)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to create a for loop that uses user input variables in it's parameter. Here is what I have:

@ECHO off
DEL "./positions.txt"
SET /P start_position= Please enter the start position:
SET /P end_position= Please enter the end position:
SET /P step_size= Please enter the step size:
FOR /L %%A IN (%start_position%,%end_position%,%step_size%) DO (
    ECHO %%A >> positions.txt
)
ECHO( & echo.Done! "positions.txt" was generated. & echo.
pause

However this doesn't seem to work. Here is what I get on the output:

>> Done! "positions.txt" was generated.

It runs, but skips over the for loop. What is wrong?

Body:
for /L loops use the order start, step, end.

FOR /L %%A IN (%start_position%,%step_size%,%end_position%) DO (
    ECHO %%A >> positions.txt
)


问:
Linq distinct not working correctly
I'm having a strange problem with a linq query. I'm using LINQPad 4 to make some a query that uses regular expression using LinqToSQL as the LinqPad driver.

Here's the query that I'm trying to make :

```<code>(from match in
from s in SystemErrors
select Regex.Match(s.Description, "...")
select new
{
  FamilyCode = match.Groups["FamilyCode"].Value,
  ProductPrefix = match.Groups["ProductPrefix"].Value,
  BillingGroup = match.Groups["BillingGroup"].Value,
  Debtor = match.Groups["Debtor"].Value
}).Distinct()
</code>```

As you can see I'm trying to extract data from a text description in a log table using groups. The query works, but the Distinct doesn't want to work, it returns a line for all Match.

I have read that distinct should work with anonymous type, matching each property. Even more strange is that distinct does actually do something, it orders the values alphabetically by the FamilyCode (and then by ProductPrefix, etc.).

Has someone an idea on why this isn't working?
Thanks

Here is what is displayed in the SQL tab of LinqPad :

```<code>DECLARE @p0 NVarChar(1000) = 'Big Regexp'
DECLARE @p1 NVarChar(1000) = 'FamilyCode'
DECLARE @p2 NVarChar(1000) = 'ProductPrefix'
DECLARE @p3 NVarChar(1000) = 'BillingGroup'
DECLARE @p4 NVarChar(1000) = 'Debtor'

SELECT DISTINCT [t2].[Description] AS [input], [t2].[value], [t2].[value2], [t2].[value3], [t2].[value4], [t2].[value5]
FROM (
    SELECT [t1].[Description], [t1].[value], @p1 AS [value2], @p2 AS [value3], @p3 AS [value4], @p4 AS [value5]
    FROM (
        SELECT [t0].[Description], @p0 AS [value]
        FROM [SystemError] AS [t0]
        ) AS [t1]
    ) AS [t2]
</code>```

答: On the other hand, you can use .Distinct(IEqualityComparer<T>) overload and provided EqualityComparer for the object that you want to process.

ContentLicense: CC BY-SA 2.5

Title: Linq distinct not working correctly

Body:
I'm having a strange problem with a linq query. I'm using LINQPad 4 to make some a query that uses regular expression using LinqToSQL as the LinqPad driver.

Here's the query that I'm trying to make :

(from match in
from s in SystemErrors
select Regex.Match(s.Description, "...")
select new
{
  FamilyCode = match.Groups["FamilyCode"].Value,
  ProductPrefix = match.Groups["ProductPrefix"].Value,
  BillingGroup = match.Groups["BillingGroup"].Value,
  Debtor = match.Groups["Debtor"].Value
}).Distinct()

As you can see I'm trying to extract data from a text description in a log table using groups. The query works, but the Distinct doesn't want to work, it returns a line for all Match.

I have read that distinct should work with anonymous type, matching each property. Even more strange is that distinct does actually do something, it orders the values alphabetically by the FamilyCode (and then by ProductPrefix, etc.).

Has someone an idea on why this isn't working?
Thanks

Here is what is displayed in the SQL tab of LinqPad :

DECLARE @p0 NVarChar(1000) = 'Big Regexp'
DECLARE @p1 NVarChar(1000) = 'FamilyCode'
DECLARE @p2 NVarChar(1000) = 'ProductPrefix'
DECLARE @p3 NVarChar(1000) = 'BillingGroup'
DECLARE @p4 NVarChar(1000) = 'Debtor'

SELECT DISTINCT [t2].[Description] AS [input], [t2].[value], [t2].[value2], [t2].[value3], [t2].[value4], [t2].[value5]
FROM (
    SELECT [t1].[Description], [t1].[value], @p1 AS [value2], @p2 AS [value3], @p3 AS [value4], @p4 AS [value5]
    FROM (
        SELECT [t0].[Description], @p0 AS [value]
        FROM [SystemError] AS [t0]
        ) AS [t1]
    ) AS [t2]


问:
What XML parser should I use in C++?
I have XML documents that I need to parse and/or I need to build XML documents and write them to text (either files or memory). Since the C++ standard library does not have a library for this, what should I use?

Note: This is intended to be a definitive, C++-FAQ-style question for this. So yes, it is a duplicate of others. I did not simply appropriate those other questions because they tended to ask for something slightly more specific. This question is more generic.

答: One other note about Expat: it's worth looking at for embedded systems work.  However, the documentation you are likely to find on the web is ancient and wrong.  The source code actually has fairly thorough function-level comments, but it will take some perusing for them to make sense.</p>

Title: What XML parser should I use in C++?


问:
Scala: change value in list inside a map
I'm facing a problem:
I want to change one element inside but the code is changing all elements.
I must be doing something wrong.
Here's what I have:

```<code>var critics: Map[String, List[(String, Double)]] = Map(
  "First" -> List(("a", 1.0), ("b", 2.0)),
  "Second" -> List(("c", 3.0), ("d", 4.0))
  )

  def setNewRating(keyMap: String, param1: String, newRating: Double) = {
    val newList = critics(keyMap).map{case (param1, _) => (param1, newRating); case x => x}
    critics = critics + (keyMap -> newList)
    }

    println(critics)

    setNewRating("First", "b", 5.0)

    println(critics)
</code>```

so, I'm looking for the key "First" and getting the List I want to change the "b" from 2.0 to 5.0 but the result I'm getting is:

```<code>critics: Map[String,List[(String, Double)]] = Map(First -> List((a,1.0), (b,2.0)), Second -> List((c,3.0), (d,4.0)))
setNewRating: (keyMap: String, param1: String, newRating: Double)Unit
Map(First -> List((a,1.0), (b,2.0)), Second -> List((c,3.0), (d,4.0)))
Map(First -> List((a,5.0), (b,5.0)), Second -> List((c,3.0), (d,4.0)))
</code>```

The code changed all the values!

thanks in advance,

答:
If you are willing to change from List to Set, you might just be missing MultiMap trait.

A trait for mutable maps with multiple values assigned to a key.

This class is typically used as a mixin. It turns maps which map A to Set[B] objects into multimaps that map A to B objects.

You can find the reference here

Body:
I'm facing a problem:
I want to change one element inside but the code is changing all elements.
I must be doing something wrong.
Here's what I have:

var critics: Map[String, List[(String, Double)]] = Map(
  "First" -> List(("a", 1.0), ("b", 2.0)),
  "Second" -> List(("c", 3.0), ("d", 4.0))
  )

  def setNewRating(keyMap: String, param1: String, newRating: Double) = {
    val newList = critics(keyMap).map{case (param1, _) => (param1, newRating); case x => x}
    critics = critics + (keyMap -> newList)
    }

    println(critics)

    setNewRating("First", "b", 5.0)

    println(critics)

so, I'm looking for the key "First" and getting the List I want to change the "b" from 2.0 to 5.0 but the result I'm getting is:

critics: Map[String,List[(String, Double)]] = Map(First -> List((a,1.0), (b,2.0)), Second -> List((c,3.0), (d,4.0)))
setNewRating: (keyMap: String, param1: String, newRating: Double)Unit
Map(First -> List((a,1.0), (b,2.0)), Second -> List((c,3.0), (d,4.0)))
Map(First -> List((a,5.0), (b,5.0)), Second -> List((c,3.0), (d,4.0)))

The code changed all the values!

thanks in advance,


问:
Method from subclass is called instead of local method
I have the next two classes (Fragments):

```<code>public class FAboutUs extends FDetails {

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        System.out.println("BUBUBU :: AboutUs - onCreate");
        View view = super.onCreateView(inflater, container, savedInstanceState);
        this.init(view, savedInstanceState);
        return view;
    }

    @Override
    protected void init(View view, @Nullable Bundle savedInstanceState) {
        System.out.println("BUBUBU :: AboutUs - init");
        //        super.init(view, savedInstanceState);
    }
}

public class FDetails extends FGlobalBase {

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        System.out.println("BUBUBU :: Details - onCreate");
        View view = inflater.inflate(R.layout.f_details, null);
        FDetails.this.init(view, savedInstanceState);
        return view;
    }

    @Override
    protected void init(View view, @Nullable Bundle savedInstanceState) {
        System.out.println("BUBUBU :: Details - init");
        super.init(view, savedInstanceState);

    }
</code>```

}

I have this printed in my logs:

```<code>BUBUBU :: AboutUs - onCreate
BUBUBU :: Details - onCreate
BUBUBU :: AboutUs - init
BUBUBU :: AboutUs - init
</code>```

I instantiate FAboutUs and it starts from onCreateView inside FAboutUs.
Why does FDetails call the init method inside AboutUs instead of its own method? Am I missing some sort of object oriented programming thing pertaining to protected methods or .... what is going on ?!?!

EDIT
It seems FDetails.this.init(view, savedInstanceState); is calling the init method from FAboutUs instead of its own init method. Why ?!

答:
Consider the following code:

```<code>FAboutUs aboutUs = new FAboutUs();
FDetails details = aboutUs;

aboutUs.init();
details.init();
</code>```

Two last calls call the same method, that is, FAboutUs#init() method.

This is because init() method is overriden in FAboutUs from FDetails, and the object referenced by both references actually has FAboutUs class. In terms of C++ it would be called virtual.

When a call to such a method occurs, Java Virtual Machine looks for the most specific method (that is, a method defined on the level of inheritance closest to the actual object class) with the same signature.

Only non-private methods may be overriden.

More info: https://docs.oracle.com/javase/tutorial/java/IandI/override.html

Body:
I have the next two classes (Fragments):

public class FAboutUs extends FDetails {

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        System.out.println("BUBUBU :: AboutUs - onCreate");
        View view = super.onCreateView(inflater, container, savedInstanceState);
        this.init(view, savedInstanceState);
        return view;
    }

    @Override
    protected void init(View view, @Nullable Bundle savedInstanceState) {
        System.out.println("BUBUBU :: AboutUs - init");
        //        super.init(view, savedInstanceState);
    }
}

public class FDetails extends FGlobalBase {

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        System.out.println("BUBUBU :: Details - onCreate");
        View view = inflater.inflate(R.layout.f_details, null);
        FDetails.this.init(view, savedInstanceState);
        return view;
    }

    @Override
    protected void init(View view, @Nullable Bundle savedInstanceState) {
        System.out.println("BUBUBU :: Details - init");
        super.init(view, savedInstanceState);

    }

}

I have this printed in my logs:

BUBUBU :: AboutUs - onCreate
BUBUBU :: Details - onCreate
BUBUBU :: AboutUs - init
BUBUBU :: AboutUs - init

I instantiate FAboutUs and it starts from onCreateView inside FAboutUs.
Why does FDetails call the init method inside AboutUs instead of its own method? Am I missing some sort of object oriented programming thing pertaining to protected methods or .... what is going on ?!?!

EDIT
It seems FDetails.this.init(view, savedInstanceState); is calling the init method from FAboutUs instead of its own init method. Why ?!

Body:
Consider the following code:

FAboutUs aboutUs = new FAboutUs();
FDetails details = aboutUs;

aboutUs.init();
details.init();

Two last calls call the same method, that is, FAboutUs#init() method.

This is because init() method is overriden in FAboutUs from FDetails, and the object referenced by both references actually has FAboutUs class. In terms of C++ it would be called virtual.

When a call to such a method occurs, Java Virtual Machine looks for the most specific method (that is, a method defined on the level of inheritance closest to the actual object class) with the same signature.

Only non-private methods may be overriden.

More info: https://docs.oracle.com/javase/tutorial/java/IandI/override.html


问:
Auto-login user after Registration in Identityserver4
our registration process is an Angular2 application that calls an .NET Core API. After registration we would like to automatically login the user in Identityserver4, instead of simply redirecting the user to the login page, where he/she will need to re-enter the username/password again.

Has anyone else managed to get this working? Most other solutions seems to be implemented with Identityserver3.

答:
All you need to do is sign in the user in the registration action within your controller responsible for this. In other words you treat your registration controller method in a similar to how you treat your login controller method using this method:

```<code>await HttpContext.Authentication.SignInAsync()
</code>```

This method essentially prepares the HttpContext to issue your browser with a cookie when you return the appropriate IActionResult from it. I'm sure you've seen this or something like it. Just do the same thing in the registration method.

Body:
All you need to do is sign in the user in the registration action within your controller responsible for this. In other words you treat your registration controller method in a similar to how you treat your login controller method using this method:

await HttpContext.Authentication.SignInAsync()

This method essentially prepares the HttpContext to issue your browser with a cookie when you return the appropriate IActionResult from it. I'm sure you've seen this or something like it. Just do the same thing in the registration method.


问:
$_SERVER['PHP_SELF'] intermittently returning two leading forward slashes
Why would $_SERVER['PHP_SELF'] return a filename in one instance as /test/foo.bar and another instance (executed from the same php script) as //test/foo.bar (with double leading forward slashes)?

form.php sends $_GET to login.php. login.php redirects to

```<code>header ('Location: test/foo.bar')
</code>```

foo.bar includes:

```<code>$page = filter_var($_SERVER['SCRIPT_NAME'], FILTER_SANITIZE_STRING);
</code>```

(Additionally, I cannot replicate it on demand. )

答:
The value of $_SERVER['PHP_SELF'] depends on the actual request sent by the client. Apache allows multiple slashes between directory names, so it treats http://example/foo.php the same as http://example//foo.php -- both will call foo.php but the request URI will contain whatever the client requested.

If your script expects only one slash, you will have to manually strip the remaining.

Body:
Why would $_SERVER['PHP_SELF'] return a filename in one instance as /test/foo.bar and another instance (executed from the same php script) as //test/foo.bar (with double leading forward slashes)?

form.php sends $_GET to login.php. login.php redirects to

header ('Location: test/foo.bar')

foo.bar includes:

$page = filter_var($_SERVER['SCRIPT_NAME'], FILTER_SANITIZE_STRING);

(Additionally, I cannot replicate it on demand. )


问:
Logout link with Spring and Thymeleaf
According with the official example (Secure Web Content), I have to use a form and a button with the aim to perform a logout with Spring Security.
Is there a way to use a link with Thymeleaf instead of a button?</p>

答:
"In order to help protect against CSRF attacks, by default, Spring Security Xml Configuration log out requires:

the HTTP method must be a POST

the CSRF token must be added to the
request. You can access it on the ServletRequest using the attribute
_csrf as illustrated above."

Hello Spring Security Xml Config

```<code><form th:action="@{/logout}" method="post">
    <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
    <input type="submit">LOGOUT</input>
</form>
</code>```

Title: Logout link with Spring and Thymeleaf

Body:
"In order to help protect against CSRF attacks, by default, Spring Security Xml Configuration log out requires:

the HTTP method must be a POST

the CSRF token must be added to the
request. You can access it on the ServletRequest using the attribute
_csrf as illustrated above."

Hello Spring Security Xml Config

<form th:action="@{/logout}" method="post">
    <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
    <input type="submit">LOGOUT</input>
</form>


问:
How to subtract rows based on matching column in Pandas?
If I have two dataframes, like these in the example created with:

```<code>df1 = pd.DataFrame({'A': randint(1,11,10), 'B': randint(10,100,10), 'C': randint(100,1000,10)})
df2 = pd.DataFrame({'A': randint(1,11,10), 'B': randint(10,100,10), 'C': randint(100,1000,10)})
df2 = df2.drop_duplicates(subset=['A'])
</code>```

df1

```<code>    A   B   C
0   2   96  826
1   1   64  601
2   1   27  343
3   5   65  600
4   10  68  658
5   6   81  895
6   5   73  440
7   4   54  865
8   1   24  597
9   10  66  928
</code>```

df2

```<code>    A   B   C
0   2   87  669
1   5   99  594
2   6   50  989
3   10  46  767
4   3   56  828
5   4   83  415
6   1   41  332
</code>```

How can I subtract columns B (df['B'] - df2['B']) only if the values from column A are matching? So I can get a new column in df1 like:

```<code>9
23
-14
-34
22
31
-26
-29
-17
20
</code>```

Body:
If I have two dataframes, like these in the example created with:

df1 = pd.DataFrame({'A': randint(1,11,10), 'B': randint(10,100,10), 'C': randint(100,1000,10)})
df2 = pd.DataFrame({'A': randint(1,11,10), 'B': randint(10,100,10), 'C': randint(100,1000,10)})
df2 = df2.drop_duplicates(subset=['A'])

df1

    A   B   C
0   2   96  826
1   1   64  601
2   1   27  343
3   5   65  600
4   10  68  658
5   6   81  895
6   5   73  440
7   4   54  865
8   1   24  597
9   10  66  928

df2

    A   B   C
0   2   87  669
1   5   99  594
2   6   50  989
3   10  46  767
4   3   56  828
5   4   83  415
6   1   41  332

How can I subtract columns B (df['B'] - df2['B']) only if the values from column A are matching? So I can get a new column in df1 like:

9
23
-14
-34
22
31
-26
-29
-17
20

Body:
Try this:

In [61]: df1['new'] = df1.drop('C',1).merge(df2.drop('C',1), on='A',
                                            how='left', suffixes=['','2']) \
                         .eval("new=B-B2", inplace=False)['new']

In [62]: df1
Out[62]:
    A   B    C  new
0   2  96  826    9
1   1  64  601   23
2   1  27  343  -14
3   5  65  600  -34
4  10  68  658   22
5   6  81  895   31
6   5  73  440  -26
7   4  54  865  -29
8   1  24  597  -17
9  10  66  928   20


问:
C# with MySQL Table is specified twice, both as a target for 'UPDATE'
This is my SQL query</p>

```<code>UPDATE Nomina
SET utilidadSemana =
    (SELECT SUM(totalIngresosXSemana - totalGastosXSemana)
        FROM Nomina
        WHERE fechaInicio >= @fechaInicial
        AND fechaFin <= @fechaFinal)
WHERE
    fechaInicio >= @fechaInicial
    AND fechaFin <= @fechaFinal;
</code>```

答:
Your dates are constants, so you can use CROSS JOIN:

```<code>UPDATE Nomina n CROSS JOIN
       (SELECT SUM(totalIngresosXSemana - totalGastosXSemana) as newval
        FROM Nomina
        WHERE fechaInicio >= @fechaInicial AND
              fechaFin <= @fechaFinal
       ) nn
    SET n.utilidadSemana = nn.newval
WHERE fechaInicio >= @fechaInicial AND
      fechaFin <= @fechaFinal;
</code>```

Body:
This is my SQL query

UPDATE Nomina
SET utilidadSemana =
    (SELECT SUM(totalIngresosXSemana - totalGastosXSemana)
        FROM Nomina
        WHERE fechaInicio >= @fechaInicial
        AND fechaFin <= @fechaFinal)
WHERE
    fechaInicio >= @fechaInicial
    AND fechaFin <= @fechaFinal;

Body:
Your dates are constants, so you can use CROSS JOIN:

UPDATE Nomina n CROSS JOIN
       (SELECT SUM(totalIngresosXSemana - totalGastosXSemana) as newval
        FROM Nomina
        WHERE fechaInicio >= @fechaInicial AND
              fechaFin <= @fechaFinal
       ) nn
    SET n.utilidadSemana = nn.newval
WHERE fechaInicio >= @fechaInicial AND
      fechaFin <= @fechaFinal;


问:
How to test that tornado read_message got nothing to read
I have a Tornado chat and I'm doing some tests, most client messages generate a reply from the server, but others must not generate any reply.

I managed to do it with this code, waiting for the read timeout to occur, there is a better way to do it?

```<code>import json
import tornado
from tornado.httpclient import HTTPRequest
from tornado.web import Application
from tornado.websocket import websocket_connect
from tornado.testing import AsyncHTTPTestCase, gen_test

class RealtimeHandler(tornado.websocket.WebSocketHandler):
    def on_message(self, message):
        if message != 'Hi':
            self.write_message('Hi there')
        return

class ChatTestCase(AsyncHTTPTestCase):
    def get_app(self):
        return Application([
            ('/rt', RealtimeHandler),
        ])

    @gen_test
    def test_no_reply(self):
        request = HTTPRequest('ws://127.0.0.1:%d/rt' % self.get_http_port())
        ws = yield websocket_connect(request)

        ws.write_message('Hi')

        with self.assertRaises(tornado.ioloop.TimeoutError):
            response = yield ws.read_message()
</code>```

Also there is a problem when test ends

```<code>======================================================================
ERROR: test_no_reply (myproj.tests.ChatTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/ubuntu/my_env/local/lib/python2.7/site-packages/tornado/testing.py", line 120, in __call__
    result = self.orig_method(*args, **kwargs)
  File "/home/ubuntu/my_env/local/lib/python2.7/site-packages/tornado/testing.py", line 506, in post_coroutine
    self._test_generator.throw(e)
StopIteration
</code>```

答:
Just to illustrate the @Ben Darnell answer.</p>

```<code>from tornado import gen

class ChatTestCase(AsyncHTTPTestCase):
    def get_app(self):
        return Application([
            ('/rt', RealtimeHandler),
        ])

    @gen_test
    def test_no_reply(self):
        request = HTTPRequest('ws://127.0.0.1:%d/rt' % self.get_http_port())
        ws = yield websocket_connect(request)

        ws.write_message('Hi')

        with self.assertRaises(gen.TimeoutError):
            response = yield gen.with_timeout(datetime.timedelta(seconds=4), ws.read_message()
</code>```

Body:
I have a Tornado chat and I'm doing some tests, most client messages generate a reply from the server, but others must not generate any reply.

I managed to do it with this code, waiting for the read timeout to occur, there is a better way to do it?

import json
import tornado
from tornado.httpclient import HTTPRequest
from tornado.web import Application
from tornado.websocket import websocket_connect
from tornado.testing import AsyncHTTPTestCase, gen_test

class RealtimeHandler(tornado.websocket.WebSocketHandler):
    def on_message(self, message):
        if message != 'Hi':
            self.write_message('Hi there')
        return

class ChatTestCase(AsyncHTTPTestCase):
    def get_app(self):
        return Application([
            ('/rt', RealtimeHandler),
        ])

    @gen_test
    def test_no_reply(self):
        request = HTTPRequest('ws://127.0.0.1:%d/rt' % self.get_http_port())
        ws = yield websocket_connect(request)

        ws.write_message('Hi')

        with self.assertRaises(tornado.ioloop.TimeoutError):
            response = yield ws.read_message()

Also there is a problem when test ends

======================================================================
ERROR: test_no_reply (myproj.tests.ChatTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/ubuntu/my_env/local/lib/python2.7/site-packages/tornado/testing.py", line 120, in __call__
    result = self.orig_method(*args, **kwargs)
  File "/home/ubuntu/my_env/local/lib/python2.7/site-packages/tornado/testing.py", line 506, in post_coroutine
    self._test_generator.throw(e)
StopIteration

Body:
Just to illustrate the @Ben Darnell answer.

from tornado import gen

class ChatTestCase(AsyncHTTPTestCase):
    def get_app(self):
        return Application([
            ('/rt', RealtimeHandler),
        ])

    @gen_test
    def test_no_reply(self):
        request = HTTPRequest('ws://127.0.0.1:%d/rt' % self.get_http_port())
        ws = yield websocket_connect(request)

        ws.write_message('Hi')

        with self.assertRaises(gen.TimeoutError):
            response = yield gen.with_timeout(datetime.timedelta(seconds=4), ws.read_message()


问:
wpf , binding and datacontext
This is my ViewModel -

```<code> public class ViewModel
{
    public ObservableCollection<Person> Persons { get; set; }
}
</code>```

and this is Class Person:

```<code>public class Person : INotifyPropertyChanged
{
    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            _firstName = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
</code>```

Now, every time one of the persons's FirstName is changing I want to do some tasks,
lets say raise a messagebox.

How do I do that ?

答:
You need to implement INotifyPropertyChanged

```<code>public class Person : INotifyPropertyChanged
{
    private string firstName;
    public string FirstName
    {
       get { return this.firstName;}
       set
       {
          this.firstName = value;
          this.RaisePropertyChanged("FirstName");
          MessageBox.Show("Hello World");
       }
    }
}

public event PropertyChangedEventHandler PropertyChanged;

protected void RaisePropertyChanged(string propertyName)
{
     PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
     if ((propertyChanged != null))
     {
         propertyChanged(this, new PropertyChangedEventArgs(propertyName));
     }
}
</code>```

Title: wpf , binding and datacontext

Body:
This is my ViewModel -

 public class ViewModel
{
    public ObservableCollection<Person> Persons { get; set; }
}

and this is Class Person:

public class Person : INotifyPropertyChanged
{
    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            _firstName = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Now, every time one of the persons's FirstName is changing I want to do some tasks,
lets say raise a messagebox.

How do I do that ?

Body:
You need to implement INotifyPropertyChanged

public class Person : INotifyPropertyChanged
{
    private string firstName;
    public string FirstName
    {
       get { return this.firstName;}
       set
       {
          this.firstName = value;
          this.RaisePropertyChanged("FirstName");
          MessageBox.Show("Hello World");
       }
    }
}

public event PropertyChangedEventHandler PropertyChanged;

protected void RaisePropertyChanged(string propertyName)
{
     PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
     if ((propertyChanged != null))
     {
         propertyChanged(this, new PropertyChangedEventArgs(propertyName));
     }
}


答:
to do it without loops:</p>

```<code>Sub change()
Dim rng As Range
Dim rngsear As Range
Dim lastrow As Long
With ActiveSheet
    lastrow = .Range("D" & .Rows.Count).End(xlUp).Row
    Set rng = .Range("D15:D" & lastrow)
    Set rngsear = .Range("C15:C" & lastrow)
    rngsear.Value = .Evaluate("IF((" & rng.Address & " >= 40000)*(" & rng.Address & " < 60000)," & rngsear.Address & " * -1," & rngsear.Address & ")")
End With

End Sub
</code>```

Title: VBA if value in range 1 then value in range 2 multiple by -1

Body:
This is columns C and G in excel

($12,843.63)    40100
($9,584.60)     53450
($67,933.38)    53500
($2,615.56)     54900
$43,378.11      72100
$607.91         72100
$14,843.94      72400
$286.62         72440
$3,283.73       72500
$46.50          72500
$9,392.28       75400
$3,754.16       81100
$540.00         81300
$6,186.20       82110
$4,658.21       82140
$13,576.61      82160
$35,467.33      82200
$196.18         82600
$10.83          83100
$34.84          83140
$22,535.60      85240
$691.47         85260
$145.00         85300
($45.00)        85980
$1,010.00       86500
$32,249.97      99150
($8,992.44)     99200
$0.00           72100

'If the value in the second range is between 40000 and 60000 then the value in the first range is multiplied by -1

Dim rng As Range
Dim rngsear As Range
Set rng = Range("D15:D" & lastrow)
Set rngsear = Range("C15:C" & lastrow)
If rng.Value >= (40000 < 60000) Then
rngsear.Value = -rngsear.Value
End If

It says I have a run-time error '91'
Object variable or With block variable not set
I'm not sure how to make it loop properly.

Body:
to do it without loops:

Sub change()
Dim rng As Range
Dim rngsear As Range
Dim lastrow As Long
With ActiveSheet
    lastrow = .Range("D" & .Rows.Count).End(xlUp).Row
    Set rng = .Range("D15:D" & lastrow)
    Set rngsear = .Range("C15:C" & lastrow)
    rngsear.Value = .Evaluate("IF((" & rng.Address & " >= 40000)*(" & rng.Address & " < 60000)," & rngsear.Address & " * -1," & rngsear.Address & ")")
End With

End Sub


问:
Couldn't connect to Webspshere MQ from Jboss EAP 7
I am using Jboss EAP 7 and IBM MQ 8.0.

When I try to connect to MQ from the Jboss I am getting below issues.

```<code>15:27:29,872 ERROR [org.springframework.web.context.ContextLoader] (ServerService Thread Pool -- 68) Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'inputConnectionFactoryCache' defined in ServletContext resource [/WEB-INF/xml/spring-config/spring-config-unit.xml]: Cannot resolve reference to bean 'EventConnectionFactory1' while setting bean property 'targetConnectionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'it00EventConnectionFactory': Invocation of init method failed; nested exception is org.springframework.jndi.TypeMismatchNamingException: Object of type [class com.ibm.mq.connector.outbound.ConnectionFactoryImpl] available at JNDI location [EventQueueFactory1] is not assignable to [javax.jms.QueueConnectionFactory]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1317)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1076)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:574)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:187)
    at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:198)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:100)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:82)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EventQueueFactory1': Invocation of init method failed; nested exception is org.springframework.jndi.TypeMismatchNamingException: Object of type [class com.ibm.mq.connector.outbound.ConnectionFactoryImpl] available at JNDI location [EventQueueFactory1] is not assignable to [javax.jms.QueueConnectionFactory]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1412)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
    ... 25 more
Caused by: org.springframework.jndi.TypeMismatchNamingException: Object of type [class com.ibm.mq.connector.outbound.ConnectionFactoryImpl] available at JNDI location [it00EventQueueFactory] is not assignable to [javax.jms.QueueConnectionFactory]
    at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:180)
    at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:104)
    at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:105)
    at org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java:201)
    at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:187)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1469)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1409)
    ... 32 more
</code>```

答:
The JMS connection factories come in sever flavors:

```<code>com.ibm.mq.connector.outbound.ManagedConnectionFactoryImpl
com.ibm.mq.connector.outbound.ManagedQueueConnectionFactoryImpl
com.ibm.mq.connector.outbound.ManagedTopicConnectionFactoryImpl
</code>```

You have:

```<code>Caused by: org.springframework.jndi.TypeMismatchNamingException: Object of type [class com.ibm.mq.connector.outbound.ConnectionFactoryImpl] available at JNDI location [it00EventQueueFactory] is not assignable to [javax.jms.QueueConnectionFactory]
</code>```

You are providing a ConnectionFactory, but the code is expecting a QueueConnectionFactory.

You should change your IBM MQ configuration to provide a:

```<code>com.ibm.mq.connector.outbound.ManagedQueueConnectionFactoryImpl
</code>```

Body:
I am using Jboss EAP 7 and IBM MQ 8.0.

When I try to connect to MQ from the Jboss I am getting below issues.

15:27:29,872 ERROR [org.springframework.web.context.ContextLoader] (ServerService Thread Pool -- 68) Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'inputConnectionFactoryCache' defined in ServletContext resource [/WEB-INF/xml/spring-config/spring-config-unit.xml]: Cannot resolve reference to bean 'EventConnectionFactory1' while setting bean property 'targetConnectionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'it00EventConnectionFactory': Invocation of init method failed; nested exception is org.springframework.jndi.TypeMismatchNamingException: Object of type [class com.ibm.mq.connector.outbound.ConnectionFactoryImpl] available at JNDI location [EventQueueFactory1] is not assignable to [javax.jms.QueueConnectionFactory]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1317)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1076)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:574)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:187)
    at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:198)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:100)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:82)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EventQueueFactory1': Invocation of init method failed; nested exception is org.springframework.jndi.TypeMismatchNamingException: Object of type [class com.ibm.mq.connector.outbound.ConnectionFactoryImpl] available at JNDI location [EventQueueFactory1] is not assignable to [javax.jms.QueueConnectionFactory]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1412)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
    ... 25 more
Caused by: org.springframework.jndi.TypeMismatchNamingException: Object of type [class com.ibm.mq.connector.outbound.ConnectionFactoryImpl] available at JNDI location [it00EventQueueFactory] is not assignable to [javax.jms.QueueConnectionFactory]
    at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:180)
    at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:104)
    at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:105)
    at org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java:201)
    at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:187)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1469)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1409)
    ... 32 more

Body:
The JMS connection factories come in sever flavors:

com.ibm.mq.connector.outbound.ManagedConnectionFactoryImpl
com.ibm.mq.connector.outbound.ManagedQueueConnectionFactoryImpl
com.ibm.mq.connector.outbound.ManagedTopicConnectionFactoryImpl

You have:

Caused by: org.springframework.jndi.TypeMismatchNamingException: Object of type [class com.ibm.mq.connector.outbound.ConnectionFactoryImpl] available at JNDI location [it00EventQueueFactory] is not assignable to [javax.jms.QueueConnectionFactory]

You are providing a ConnectionFactory, but the code is expecting a QueueConnectionFactory.

You should change your IBM MQ configuration to provide a:

com.ibm.mq.connector.outbound.ManagedQueueConnectionFactoryImpl


问:
How to train this neural network?
I programmed a simple back propagation NN. Here is the code snippet:

```<code>        for (int i = 0; i < 10000; i++)
        {

            /// i1 = Convert.ToDouble(textBox1.Text);
            //i2 = Convert.ToDouble(textBox2.Text);
            //desired = Convert.ToDouble(textBox3.Text);

            Random rnd = new Random();
            i1 = rnd.Next(0, 1);
            Random rnd1 = new Random();
            i2 = rnd1.Next(0, 1);
            if(i1 == 1 && i2 == 1)
            {
                desired = 0;
            }
            else if(i1 == 0&&i2 == 0)
            {
                desired = 0;
            }
            else
            {
                desired = 1;
            }

            //hidden layer hidden values
            h1 = i1 * w1 + i2 * w2; //i1*w1+i2*w2
            h2 = i1 * w3 + i2 * w4;//i1*w3+i2*w4
            h3 = i1 * w5 + i2 * w6;//i1*w5+i2*w6;

            //hidden layer hidden values

            //VALUE OF HIDDEN LAYER
            h1v = Sigmoid(h1);
            h2v = Sigmoid(h2);
            h3v = Sigmoid(h3);
            //VALUE OF HIDDEN LAYER

            //output final
            output = h1v * w7 + h2v * w8 + h3v * w9;
            outputS = Sigmoid(output);
            //output final

            //BACKPROPAGATION

            //MARGIN ERROR
            Error = desired - outputS; //desired-cena jaka ma byc OutputS-zgadnienta cena

            //Margin Error

            //DElta output sum
            deltaoutputsum = Derivative(output) * Error; //output bez sigmoida i error
                                                         //Delta output sum

            //weight of w7,w8,w9.
            w7b = w7; //0.3
            w8b = w8; // 0.5
            w9b = w9;// 0.9
            w7 = w7 + deltaoutputsum * h1v; //waga w7
            w8 = w8 + deltaoutputsum * h2v; //waga w8
            w9 = w9 + deltaoutputsum * h3v; //waga w9
                                            //weights of w7,w8,w9.

            //DELTA HIDDEN SUm
            h1 = deltaoutputsum * w7b * Derivative(h1);
            h2 = deltaoutputsum * w8b * Derivative(h2);
            h3 = deltaoutputsum * w9b * Derivative(h3);
            //DELTA HIDDEN SUM

            //weights 1,2,3,4,5,6
            w1 = w1 - h1 * i1;
            w2 = w2 - h1 * i2;
            w3 = w3 - h2 * i1;
            w4 = w4 - h2 * i2;
            w5 = w5 - h3 * i1;
            w6 = w6 - h3 * i2;
            label1.Text = outputS.ToString();
            label2.Text = w1.ToString();
            label3.Text = w2.ToString();
            label4.Text = w3.ToString();
            label5.Text = w4.ToString();
            label6.Text = w5.ToString();
            label7.Text = w6.ToString();
            label8.Text = w7.ToString();
            label9.Text = w8.ToString();
            label10.Text = w9.ToString();
            //weights 1,2,3,4,5,6

        }
</code>```

It is very simple to solve XOR problems. But I'dont now how to predict the output. Here i must provide answear to set the weights, but how to predict?
It train 10,000 on random training data.
Now when it is trained how to predict the answear?
Please help.
Sorry for my english but I dont now it very well.

h1-3 are weights of nodes
h1v are values of nodes
w1-10 are weights

答:
I believe your problem lies in how you are training.

Do the following and I believe your program will be correct

Try training each of the data sets one after another instead of random, random works for continuous floating point values, but when you are working with XOR, you might run into issues where training too much on one or two sets of values (because of the nature of random) will cause issues moving the wieghts back toward a value that works with other input XOR values. So train on [1,1], then immediately [1,0] then [0,1] and then [0, 0] and repeat over and over.

Make sure the derivative function is correct; the derivative of a sigmoid should be sigmoid(x) - sigmoid(x)^2

name your hidden sum values something different than h1, h2 etc.. if you use that for the hidden node input values.

If you do those things, it appears you should have something exactly mathematically equivalent to what "how to build a neural-network" has.

I would also recommend having values that aren't persistent initialized inside your loop instead of outside.  I may be wrong, but I don't think any value except your w1 w2 w3 etc... values need to be persistent through every training iteration.  Not doing this causes hard to catch bugs and make reading the code harder since you can't guarantee variables aren't being modified elsewhere.

Title: How to train this neural network?

Body:
I programmed a simple back propagation NN. Here is the code snippet:

        for (int i = 0; i < 10000; i++)
        {

            /// i1 = Convert.ToDouble(textBox1.Text);
            //i2 = Convert.ToDouble(textBox2.Text);
            //desired = Convert.ToDouble(textBox3.Text);

            Random rnd = new Random();
            i1 = rnd.Next(0, 1);
            Random rnd1 = new Random();
            i2 = rnd1.Next(0, 1);
            if(i1 == 1 && i2 == 1)
            {
                desired = 0;
            }
            else if(i1 == 0&&i2 == 0)
            {
                desired = 0;
            }
            else
            {
                desired = 1;
            }

            //hidden layer hidden values
            h1 = i1 * w1 + i2 * w2; //i1*w1+i2*w2
            h2 = i1 * w3 + i2 * w4;//i1*w3+i2*w4
            h3 = i1 * w5 + i2 * w6;//i1*w5+i2*w6;

            //hidden layer hidden values

            //VALUE OF HIDDEN LAYER
            h1v = Sigmoid(h1);
            h2v = Sigmoid(h2);
            h3v = Sigmoid(h3);
            //VALUE OF HIDDEN LAYER

            //output final
            output = h1v * w7 + h2v * w8 + h3v * w9;
            outputS = Sigmoid(output);
            //output final

            //BACKPROPAGATION

            //MARGIN ERROR
            Error = desired - outputS; //desired-cena jaka ma byc OutputS-zgadnienta cena

            //Margin Error

            //DElta output sum
            deltaoutputsum = Derivative(output) * Error; //output bez sigmoida i error
                                                         //Delta output sum

            //weight of w7,w8,w9.
            w7b = w7; //0.3
            w8b = w8; // 0.5
            w9b = w9;// 0.9
            w7 = w7 + deltaoutputsum * h1v; //waga w7
            w8 = w8 + deltaoutputsum * h2v; //waga w8
            w9 = w9 + deltaoutputsum * h3v; //waga w9
                                            //weights of w7,w8,w9.

            //DELTA HIDDEN SUm
            h1 = deltaoutputsum * w7b * Derivative(h1);
            h2 = deltaoutputsum * w8b * Derivative(h2);
            h3 = deltaoutputsum * w9b * Derivative(h3);
            //DELTA HIDDEN SUM

            //weights 1,2,3,4,5,6
            w1 = w1 - h1 * i1;
            w2 = w2 - h1 * i2;
            w3 = w3 - h2 * i1;
            w4 = w4 - h2 * i2;
            w5 = w5 - h3 * i1;
            w6 = w6 - h3 * i2;
            label1.Text = outputS.ToString();
            label2.Text = w1.ToString();
            label3.Text = w2.ToString();
            label4.Text = w3.ToString();
            label5.Text = w4.ToString();
            label6.Text = w5.ToString();
            label7.Text = w6.ToString();
            label8.Text = w7.ToString();
            label9.Text = w8.ToString();
            label10.Text = w9.ToString();
            //weights 1,2,3,4,5,6

        }

It is very simple to solve XOR problems. But I'dont now how to predict the output. Here i must provide answear to set the weights, but how to predict?
It train 10,000 on random training data.
Now when it is trained how to predict the answear?
Please help.
Sorry for my english but I dont now it very well.

h1-3 are weights of nodes
h1v are values of nodes
w1-10 are weights


问:
Is there any way to launch an app into a "modal view"
I'm trying to get an intro to be the first thing a user sees when they launch the app, and when they're done with the intro, it will be dismissed with the modal dismiss animation. Is there any way to dismiss the initial view controller in that way, or do I have to create a custom animation?</p>

答:
The correct way to do this is to display the actual initialViewController as usual, and when that loads, present the modal view overtop of it without an animation.</p>

```<code>present(modalIntroView, animated: false, completion: nil)
</code>```

Body:
The correct way to do this is to display the actual initialViewController as usual, and when that loads, present the modal view overtop of it without an animation.

present(modalIntroView, animated: false, completion: nil)


问:
Pandas: changing the row indices to column indices. Or Vice versa
```<code>import pandas as pd
df = pd.DataFrame(data={'start':[1,2,3],'zone':['a','b','c']});
df['end']=[4,5,6]
df.set_index('zone',drop=True,inplace=True,append=False)
print(df)

      start  end
zone
a         1    4
b         2    5
c         3    6
</code>```

I would like to modify this dataframe to become:

```<code>zone  a              b            c
      start  end     start  end   start  end
      1        4     2      5     3      6
</code>```

By changing the row indices to column indices. I need this because I want to melt the dataframe later, so it would become a long table. But I do not know how to melt the row index along with the column index. But getting this output would allow me to simply use:

```<code>pd.melt(df)
</code>```

To get the long table.
If there is a way to change the column indices to row indices, I could then skip the step where I change the row indices to column indices, and get the long table straight away.

Please help.

答:
Try this using stack,to_frame, and T for transpose:

```<code>df.stack().to_frame().T
</code>```

Output:

```<code>zone     a         b         c
     start end start end start end
0        1   4     2   5     3   6
</code>```

Body:
import pandas as pd
df = pd.DataFrame(data={'start':[1,2,3],'zone':['a','b','c']});
df['end']=[4,5,6]
df.set_index('zone',drop=True,inplace=True,append=False)
print(df)

      start  end
zone
a         1    4
b         2    5
c         3    6

I would like to modify this dataframe to become:

zone  a              b            c
      start  end     start  end   start  end
      1        4     2      5     3      6

By changing the row indices to column indices. I need this because I want to melt the dataframe later, so it would become a long table. But I do not know how to melt the row index along with the column index. But getting this output would allow me to simply use:

pd.melt(df)

To get the long table.
If there is a way to change the column indices to row indices, I could then skip the step where I change the row indices to column indices, and get the long table straight away.

Please help.

Body:
Try this using stack,to_frame, and T for transpose:

df.stack().to_frame().T

Output:

zone     a         b         c
     start end start end start end
0        1   4     2   5     3   6


问:
C++ all prime numbers function not working
So i am really new at programming, i was messing around and decided to try coding a Prime generator. The idea is the user inputs the maximum number the computer should check for a prime, and it outputs a text file with all the primes till there.
So i've written this piece of code.

```<code>#include <iostream>
#include <string>
#include <Windows.h>
#include <fstream>

using namespace std;
int isPrime(int num) {
    for (int a = 1; a <= num/2; a++)
        if (num % a == 0)
            return 0;
    return 1;
}

int main() {
    ofstream out_data("primes.txt");
    std::string name;
    int quantity;
    int maximum = 1000000;
    std::cout << "What is your name ?\n";
    getline(std::cin, name);
    std::cout << "What is the biggest number you want to get as a prime " << name << "? Please note that the maximum is " << maximum <<" \n";
    std::cin >> quantity;
    if (quantity <= maximum) {
        for (int b = 1; b < quantity; b++) {
            if (isPrime(b) == 1) {
                std::cout << b << "\n";
                out_data << b << "\n";
            }
        }
        std::cout << "The computer has finished calculating primes. Please check your folder for a .txt file.";
        Sleep(60000);
    }
    if (quantity > maximum) {
        std::cout << "Oh, i'm sorry. The computer can not calculate till " << quantity << ".";
        Sleep(15000);
    }
    return 0;
}
</code>```

The file and the console shows just the number 1. I spent some time trying to find out what's wrong with the code and got nowhere. In my mind the for loop would repeat itself and the if statement until b

答:
I believe your issue lies within your isPrime funcion. The first iteration of the for loop when a = 1 will always catch the if statement due to any num % 1 = 0.
Start your for loop with a = 2.

```<code>   int isPrime(int num) {
        for (int a = 2; a <= num/2; a++)
            if (num % a == 0)
                return 0;
        return 1;
    }
</code>```

Since num / 2 = 0, the for loop is never entered when num = 1. Therefore, your isPrime() funtion will return 1 and it will let it output. All other nums will enter the for loop and return 0.

Body:
So i am really new at programming, i was messing around and decided to try coding a Prime generator. The idea is the user inputs the maximum number the computer should check for a prime, and it outputs a text file with all the primes till there.
So i've written this piece of code.

#include <iostream>
#include <string>
#include <Windows.h>
#include <fstream>

using namespace std;
int isPrime(int num) {
    for (int a = 1; a <= num/2; a++)
        if (num % a == 0)
            return 0;
    return 1;
}

int main() {
    ofstream out_data("primes.txt");
    std::string name;
    int quantity;
    int maximum = 1000000;
    std::cout << "What is your name ?\n";
    getline(std::cin, name);
    std::cout << "What is the biggest number you want to get as a prime " << name << "? Please note that the maximum is " << maximum <<" \n";
    std::cin >> quantity;
    if (quantity <= maximum) {
        for (int b = 1; b < quantity; b++) {
            if (isPrime(b) == 1) {
                std::cout << b << "\n";
                out_data << b << "\n";
            }
        }
        std::cout << "The computer has finished calculating primes. Please check your folder for a .txt file.";
        Sleep(60000);
    }
    if (quantity > maximum) {
        std::cout << "Oh, i'm sorry. The computer can not calculate till " << quantity << ".";
        Sleep(15000);
    }
    return 0;
}

The file and the console shows just the number 1. I spent some time trying to find out what's wrong with the code and got nowhere. In my mind the for loop would repeat itself and the if statement until b

Body:
I believe your issue lies within your isPrime funcion. The first iteration of the for loop when a = 1 will always catch the if statement due to any num % 1 = 0.
Start your for loop with a = 2.

   int isPrime(int num) {
        for (int a = 2; a <= num/2; a++)
            if (num % a == 0)
                return 0;
        return 1;
    }

Since num / 2 = 0, the for loop is never entered when num = 1. Therefore, your isPrime() funtion will return 1 and it will let it output. All other nums will enter the for loop and return 0.


问:
Confused about perl's Entities.pm
Ok, I'm a bit confused here.

I am trying to create a feed for an iPhone app encoded in utf8.

There are many latin characters (accute, etc) for our Spanish content. I use the decode_entities function from the Entities.pm lib, but I'm noticing that the char values that it converts to are breaking my feed -- what I mean is that the feed is not valid, even though there are CDATA tags around the title field. Upon further investigation, I've discovered that this lib is converting from an html entity to it's corresponding unicode value but it is using the ISO-8859 instead of utf8.

How do I convert from an html-entity to utf8?

答:
So it turns out that the problem was not Entities.pm, but rather the format that I was using to open the file. I took it for granted that Perl would automatically open the file in Utf-8.

I added the line below to the top of my file, and the feed is now considered valid:

use open ':encoding(utf8)';

Title: Confused about perl's Entities.pm


问:
Dart final functions
Is it possible for the _distance variable to be final but still keep the type signatures in the constructor for a Dart object?

```<code>Function _distance;

ExampleConstuctor(num distanceFunction(T a, T b)) {
  _distance = distanceFunction;
}
</code>```

答:
In 1.24.0, we are introducing a new syntax to do exactly this:

https://github.com/dart-lang/sdk/blob/master/CHANGELOG.md#language-1

```<code>typedef F = void Function();  // F is the name for a `void` callback.
int Function(int) f;  // A field `f` that contains an int->int function.

class A<T> {
  // The parameter `callback` is a function that takes a `T` and returns
  // `void`.
  void forEach(void Function(T) callback);
}

// The new function type supports generic arguments.
typedef Invoker = T Function<T>(T Function() callback);
</code>```

Until then you could also use various typedefs declared in package:func:

https://pub.dartlang.org/packages/func

Title: Dart final functions

Body:
Is it possible for the _distance variable to be final but still keep the type signatures in the constructor for a Dart object?

Function _distance;

ExampleConstuctor(num distanceFunction(T a, T b)) {
  _distance = distanceFunction;
}

Body:
In 1.24.0, we are introducing a new syntax to do exactly this:

https://github.com/dart-lang/sdk/blob/master/CHANGELOG.md#language-1

typedef F = void Function();  // F is the name for a `void` callback.
int Function(int) f;  // A field `f` that contains an int->int function.

class A<T> {
  // The parameter `callback` is a function that takes a `T` and returns
  // `void`.
  void forEach(void Function(T) callback);
}

// The new function type supports generic arguments.
typedef Invoker = T Function<T>(T Function() callback);

Until then you could also use various typedefs declared in package:func:

https://pub.dartlang.org/packages/func


问:
Send email using codeigniter on localhost
I am trying to create a send email form and my code keeps giving me the error message that the email is not being sent. This is my first time creating a form like this on codeigniter. Please help,

Here's my controller:

```<code>  <?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Contactus extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->library('email');
    }
    public function index(){
        $this->load->helper('url');

        $this->load->view('base');
        $this->load->view('contactUs');
    }
    public function send_mail(){
        //read parameters from $_POST using input class
        $name = $this->input->post('name');
        $email = $this->input->post('email');
        $subject = $this->input->post('subject');
        $message = $this->input->post('yourMessage');

        $config = Array(
            'protocol' => 'smtp',
            'smtp_host' => 'your host',
            'smtp_port' => port for host,
            'smtp_user' => 'user@example.com',
            'smtp_pass' => 'yourpassword',
            'mailtype' => 'html',
            'charset' => 'iso-8859-1',
            'wordwrap' => TRUE
        );
        $this->load->library('email', $config);

        $this->email->set_newline("\r\n");

        $this->email->from($email, $name);
        $this->email->to('example@example.com');

        $this->email->subject($subject);
        $this->email->message($message);

        if ($this->email->send()){
            // mail sent
            $this->session->set_flashdata('msg','<div class="alert alert-success text-center">Your mail has been sent successfully!</div>');
            redirect('contactus/send_mail');
        }else{
            //error
            $this->session->set_flashdata('msg','<div class="alert alert-danger text-center">There is error in sending mail! Please try again later</div>');
            redirect('contactus/index');
        }
    }
}
</code>```

Here's my Html file:

```<code>    <html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/contact.css">
        <title>Contact Us</title>
    </head>
    <body>
        <h1><center>Contact Us</center></h1>
        <hr>
        <div class="container">
            <div id="home-search">
                <form action= "<?php echo site_url("contactus/send_mail"); ?>" method='POST'>
                    <div class="row">
                    <div class="col-md-8 col-md-offset-2">
                        <img src="http://oasissanjose.com/uploads/3/6/2/4/3624456/8429182_orig.png" class="pull-right" width="200" height="250">

                        <div class="panel panel-primary">
                            <h2 class="lead section-lead panel-heading">Questions, Concerns? Contact us using the email template below:</h2>
                            <h3 class="text-info panel-body"><center>All Fields are Mandatory</center></h3>
                            <div class="form-all">
                                    <div class="form-group">
                                        <label for="name">Full Name<span class="form-required">*</span></label>
                                        <input type="text" class="form-control" id="name" name="name" placeholder="Jane Doe" required/>
                                    </div>
                                    <div class="form-group">
                                        <label for="email">Email Address<span class="form-required">*</span></label>
                                        <input type="email" class="form-control" id="email" name="email" placeholder="jane.doe@example.com" required/>
                                    </div>
                                    <div class="form-group">
                                        <label for="subject">Subject<span class="form-required">*</span></label>
                                        <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" required/>
                                    </div>
                                    <div class="form-group ">
                                        <label for="yourMessage">Your Message<span class="form-required">*</span></label>
                                        <textarea  class="form-control" id="yourMessage" name="yourMessage" placeholder="Message" required></textarea>
                                    </div>
                                    <input type="submit" class="btn btn-primary" name="submit" value="Send Message" >
                                <br>
                            </div>
                        </div>
                        <br><br>
                        <img src="http://content.presentermedia.com/files/animsp/00005000/5562/question_mark_serious_thinker_md_wm.gif" class="pull-right" width="400" height="250">
                    </div>
                </div>
                </form>
                <?php echo $this->session->flashdata('msg'); ?>
            </div>
        </div>
        <!-- End of Container -->
    </body>
</html>
</code>```

答:
```<code>$config = Array(
  'protocol' => 'smtp',
  'smtp_host' => 'ssl://smtp.googlemail.com',
  'smtp_port' => 465,
  'smtp_user' => 'xxx',
  'smtp_pass' => 'xxx',
  'mailtype'  => 'html',
  'charset'   => 'iso-8859-1',
  'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");

// Set to, from, message, etc.

$result = $this->email->send();
</code>```

For more info : https://www.codeigniter.com/user_guide/libraries/email.html

Body:
I am trying to create a send email form and my code keeps giving me the error message that the email is not being sent. This is my first time creating a form like this on codeigniter. Please help,

Here's my controller:

  <?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Contactus extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->library('email');
    }
    public function index(){
        $this->load->helper('url');

        $this->load->view('base');
        $this->load->view('contactUs');
    }
    public function send_mail(){
        //read parameters from $_POST using input class
        $name = $this->input->post('name');
        $email = $this->input->post('email');
        $subject = $this->input->post('subject');
        $message = $this->input->post('yourMessage');

        $config = Array(
            'protocol' => 'smtp',
            'smtp_host' => 'your host',
            'smtp_port' => port for host,
            'smtp_user' => 'user@example.com',
            'smtp_pass' => 'yourpassword',
            'mailtype' => 'html',
            'charset' => 'iso-8859-1',
            'wordwrap' => TRUE
        );
        $this->load->library('email', $config);

        $this->email->set_newline("\r\n");

        $this->email->from($email, $name);
        $this->email->to('example@example.com');

        $this->email->subject($subject);
        $this->email->message($message);

        if ($this->email->send()){
            // mail sent
            $this->session->set_flashdata('msg','
Your mail has been sent successfully!
');
            redirect('contactus/send_mail');
        }else{
            //error
            $this->session->set_flashdata('msg','
There is error in sending mail! Please try again later
');
            redirect('contactus/index');
        }
    }
}

Here's my Html file:

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/contact.css">
        <title>Contact Us</title>

Contact Us

                <form action= "<?php echo site_url("contactus/send_mail"); ?>" method='POST'>

Questions, Concerns? Contact us using the email template below:

All Fields are Mandatory

                                        Full Name*
                                        <input type="text" class="form-control" id="name" name="name" placeholder="Jane Doe" required/>

                                        Email Address*
                                        <input type="email" class="form-control" id="email" name="email" placeholder="jane.doe@example.com" required/>

                                        Subject*
                                        <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" required/>

                                        Your Message*
                                        <textarea  class="form-control" id="yourMessage" name="yourMessage" placeholder="Message" required></textarea>

                                    <input type="submit" class="btn btn-primary" name="submit" value="Send Message" >

                </form>
                <?php echo $this->session->flashdata('msg'); ?>

Body:
$config = Array(
  'protocol' => 'smtp',
  'smtp_host' => 'ssl://smtp.googlemail.com',
  'smtp_port' => 465,
  'smtp_user' => 'xxx',
  'smtp_pass' => 'xxx',
  'mailtype'  => 'html',
  'charset'   => 'iso-8859-1',
  'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");

// Set to, from, message, etc.

$result = $this->email->send();

For more info : https://www.codeigniter.com/user_guide/libraries/email.html


问:
Disable babel strict mode from webpack.config.js
So far I haven't found any COMPLETE example on this.  There are answers talking about babel-plugin-transform-strict-mode, but no code about how it should be configured.

Can anybody provide a simple working code snippet for how to configure the babel loader to disable strict mode?  Thanks

答:
I'll add a simple config below.

Also note that if you use ES6 syntax (like import instead of require), webpack will automatically add "use strict" as all ES6 modules are expected to be strict mode code.

```<code>var config = {
    entry: {
        home: buildBundle( 'home' ),
    },
    output: {
        path: BUILD_DIR,
        filename: '[name]-bundle.js'
    },
    module : {
        loaders : [
            {
                test: /\.js?/,
                include: APP_DIR,
                use: {
                    loader: 'babel-loader',
                    options: {
                        "presets": [
                            ['es2015', {modules: false}]
                        ],
                    }
                },
                exclude: /node_modules/
            },
        ]
    },
};
</code>```

Body:
I'll add a simple config below.

Also note that if you use ES6 syntax (like import instead of require), webpack will automatically add "use strict" as all ES6 modules are expected to be strict mode code.

var config = {
    entry: {
        home: buildBundle( 'home' ),
    },
    output: {
        path: BUILD_DIR,
        filename: '[name]-bundle.js'
    },
    module : {
        loaders : [
            {
                test: /\.js?/,
                include: APP_DIR,
                use: {
                    loader: 'babel-loader',
                    options: {
                        "presets": [
                            ['es2015', {modules: false}]
                        ],
                    }
                },
                exclude: /node_modules/
            },
        ]
    },
};


问:
Insert image into jsp page
I am sorry that I need to ask this but I already spent three days trying to do this. I am buidling Java Web application and I want to include image to JSP page. Project name is realestates and I have Files folder inside realestates folder.

My code is like this:

```<code><img alt="govno" src="<%=request.getContextPath() + "/Files/kurac.jpg"%>" style="width: 400px; height: 300px;">
</code>```

This is what gets generated on page after I open it in browser:

```<code><img alt="govno" src="/realestates/Files/kurac.jpg" style="width: 400px; height: 300px;">
</code>```

BUT, image is not dispayed, only alt "govno" is written. I have tried many many paths (relative, absolute, changed folder structure million times and whatever I could think of and find on internet but nothing helped). Who would say that such a thing will be so hard to do???

Folder structure on Tomcat server after deployment is:

```<code>webapps
 - realestates
   |- WEB-INF
   |- Files
     |- kurac.jpg
</code>```

答:
Looks like you got yourself (and everyone else) confused of where the image is.
From your question, it seems to be at webapps/realestates/Files/kurac.jpg, so this should work:

```<code><img src="/realestates/Files/kurac.jpg">
</code>```

From your first comment, it is at C:/Users/Lazar/Documents/workspace-sts-3.8.3.RELEASE/realestates/Files/kurac.jpg, so it will not be accessible via http://.
This won't work.

From your later comment, it is at /webapp/realestates/WEB-INF/Files/kurac.jpg.
Files inside WEB-INF are not publicly accessible.
This won't work either.

As a last resort, move the image file to webapps/ROOT directory.
Try http://localhost/kurac.jpg from your browser.
Replace localhost with your server hostname as necessary.
If it works, this will work as well:

```<code><img src="/kurac.jpg">
</code>```

If it doesn't, there is something wrong with your Tomcat configuration.
Try reinstalling.

Title: Insert image into jsp page

Body:
I am sorry that I need to ask this but I already spent three days trying to do this. I am buidling Java Web application and I want to include image to JSP page. Project name is realestates and I have Files folder inside realestates folder.

My code is like this:

<img alt="govno" src="<%=request.getContextPath() + "/Files/kurac.jpg"%>" style="width: 400px; height: 300px;">

This is what gets generated on page after I open it in browser:

BUT, image is not dispayed, only alt "govno" is written. I have tried many many paths (relative, absolute, changed folder structure million times and whatever I could think of and find on internet but nothing helped). Who would say that such a thing will be so hard to do???

Folder structure on Tomcat server after deployment is:

webapps
 - realestates
   |- WEB-INF
   |- Files
     |- kurac.jpg

Body:
Looks like you got yourself (and everyone else) confused of where the image is.
From your question, it seems to be at webapps/realestates/Files/kurac.jpg, so this should work:

<img src="/realestates/Files/kurac.jpg">

From your first comment, it is at C:/Users/Lazar/Documents/workspace-sts-3.8.3.RELEASE/realestates/Files/kurac.jpg, so it will not be accessible via http://.
This won't work.

From your later comment, it is at /webapp/realestates/WEB-INF/Files/kurac.jpg.
Files inside WEB-INF are not publicly accessible.
This won't work either.

As a last resort, move the image file to webapps/ROOT directory.
Try http://localhost/kurac.jpg from your browser.
Replace localhost with your server hostname as necessary.
If it works, this will work as well:

<img src="/kurac.jpg">

If it doesn't, there is something wrong with your Tomcat configuration.
Try reinstalling.


问:
How to create a loop using values from a different file?
I have a file containing following numbers
file1.txt

```<code>1
5
6
8
14
</code>```

I have another file named rmsd.txt which contains values like the following

```<code>1 2.12
2 3.1243
3 4.156
4 3.22
5 3.882
6 8.638
7 8.838
8 7.5373
9 10.7373
10 8.3527
11 3.822
12 5.672
13 7.23
14 5.9292
</code>```

I want to get the values of column 2 from rmsd.txt for the numbers present in file.txt. I want to get something like the following

```<code>1 2.12
5 3.882
6 8.638
8 7.5373
14 5.9292
</code>```

I can do that by do like that grep 1 rmsd.txt and so on but it will take a long time. I was trying a for loop something like

```<code>for a in awk '{print $1}' file.txt; do
grep $a rmsd.txt >result.txt
done
</code>```

But it didn't work. Maybe it is very simple and I am thinking in a wrong direction. Any help will be highly appreciated.

答:
This is tailor made job for awk:

```<code>awk 'NR==FNR{a[$1]; next} $1 in a' file1.txt msd.txt

1 2.12
5 3.882
6 8.638
8 7.5373
14 5.9292
</code>```

Most likely it a duplicate, as soon as I find a good dup, I will mark it so.

Body:
I have a file containing following numbers
file1.txt

1
5
6
8
14

I have another file named rmsd.txt which contains values like the following

1 2.12
2 3.1243
3 4.156
4 3.22
5 3.882
6 8.638
7 8.838
8 7.5373
9 10.7373
10 8.3527
11 3.822
12 5.672
13 7.23
14 5.9292

I want to get the values of column 2 from rmsd.txt for the numbers present in file.txt. I want to get something like the following

1 2.12
5 3.882
6 8.638
8 7.5373
14 5.9292

I can do that by do like that grep 1 rmsd.txt and so on but it will take a long time. I was trying a for loop something like

for a in awk '{print $1}' file.txt; do
grep $a rmsd.txt >result.txt
done

But it didn't work. Maybe it is very simple and I am thinking in a wrong direction. Any help will be highly appreciated.

Body:
This is tailor made job for awk:

awk 'NR==FNR{a[$1]; next} $1 in a' file1.txt msd.txt

1 2.12
5 3.882
6 8.638
8 7.5373
14 5.9292

Most likely it a duplicate, as soon as I find a good dup, I will mark it so.


答:
awk to the rescue!

```<code>$ awk 'NR==FNR{a[$1];next} $1 in a' file1 file2

1 2.12
5 3.882
6 8.638
8 7.5373
14 5.9292
</code>```

or with sort/join

```<code>$ join <(sort file1) <(sort file2) | sort -n
</code>```

or grep/sed

```<code>$ grep -f <(sed 's/.*/^&\\b/' file1) file2
</code>```

Title: How to create a loop using values from a different file?

Body:
awk to the rescue!

$ awk 'NR==FNR{a[$1];next} $1 in a' file1 file2

1 2.12
5 3.882
6 8.638
8 7.5373
14 5.9292

or with sort/join

$ join <(sort file1) <(sort file2) | sort -n

or grep/sed

$ grep -f <(sed 's/.*/^&\\b/' file1) file2