答:
Your constructor of UserBean doesn't assign values to fields.

```<code>public UserBean(String username2, String password2, String firstname2, String lastname2, String email2,
        String usertype2, String datecreated2) {
    username = username2;
    password = password2;
    // ... etc
}
</code>```

Also did you remember to import c:core?

```<code><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
</code>```

Title: JSP displays blank data

Body:
I going crazy here trying to figure out, why my JSP doesn't display data in the table.Seems like servlet connects to MySQL and populates data, however I can not push that data to JSP.setAttribute() method is working(objects are there). I can't extract specific information and display it formatted form in the browser.If someone can point me out how troubleshoot this issue... Why JSTL expression doesn't load proper info.Eclipse doesn't return any errors and whole application compiles.... It's just displays empty page.Below you can find the code.

HINT: I was testing if LIST can be pushed and objects can be displayed.It worked, so objects are "visible" to JSP.When I try to load specific info (username, password or email) it returns blank. Thanks for any help/hints.

Below you can find the code.

UserBean.java

package com.admin;

public class UserBean {
    private String password;
    private String firstname;
    private String lastname;
    private String email;
    private String usertype;
    private String datecreated;
    private String username;

    public UserBean(){};

    public UserBean(String username2, String password2, String firstname2, String lastname2, String email2,
            String usertype2, String datecreated2) {
    }

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getUsertype() {
        return usertype;
    }
    public void setUsertype(String usertype) {
        this.usertype = usertype;
    }
    public String getDatecreated() {
        return datecreated;
    }
    public void setDatecreated(String datecreated) {
        this.datecreated = datecreated;
    }

}

User.DAO.java

package com.admin;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.clientdb.ConnectionManager;

public class UserDAO {

    public static List<UserBean> listOfUsers()
    {
        List<UserBean> userList=new ArrayList<>();
        String query="SELECT * FROM users";

        try
        {
            Connection conn = ConnectionManager.getConnection();
            Statement stm = conn.createStatement();
            ResultSet rs = stm.executeQuery(query);

            while(rs.next())
            {
                String username=rs.getString("username");
                String password=rs.getString("password");
                String firstname=rs.getString("firstname");
                String lastname=rs.getString("lastname");
                String email=rs.getString("email");
                String usertype=rs.getString("usertype");
                String datecreated=rs.getString("date_created");

                UserBean user=new UserBean(username,password,firstname,lastname,email,usertype,datecreated);
                userList.add(user);
            }
            stm.close();
            rs.close();
            conn.close();
        }
        catch(Exception ex){System.out.println(ex);}

        return userList;

}}

UserAdmin.java

package com.admin;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserAdmin extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            List<UserBean> userList = UserDAO.listOfUsers();
            request.getSession().setAttribute("userList",userList);
    request.getRequestDispatcher("userlist.jsp").forward(request,response);
        }
}

userlist.jsp

      Username
      Password
      First Name
      Last Name
      Email
      User Type
      Date Created

  <c:forEach items="${userList}" var="user">

      <c:out value="${user.username}"/>
      <c:out value="${user.password}"/>
      <c:out value="${user.firstname}"/>
      <c:out value="${user.lastname}"/>
      <c:out value="${user.email}"/>
      <c:out value="${user.usertype}"/>
      <c:out value="${user.datecreated}"/>

        RESET

        DELETE

  </c:forEach>

Body:
Your constructor of UserBean doesn't assign values to fields.

public UserBean(String username2, String password2, String firstname2, String lastname2, String email2,
        String usertype2, String datecreated2) {
    username = username2;
    password = password2;
    // ... etc
}

Also did you remember to import c:core?

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


来源: stackexchange

问:
POI XSSFCellStyle drawing borders with PropertyTemplate, when cell setFillForegroundColor and SetFillPattern are set, turns cell completly black
I've found the following question which is similar but not exactly the same:

Setting foreground color for HSSFCellStyle is always coming out black

So I'm creating an XSSFCellStyle for the headers of my table, and giving them a Foreground color with the following:

```<code>    wb = new XSSFWorkbook();
    headerStyle = wb.createCellStyle();
    XSSFColor headerBackgroundColor = new XSSFColor(new java.awt.Color(187,187,187));
    headerStyle.setFillForegroundColor( headerBackgroundColor);
    headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
</code>```

Then I apply it to a cell using the setCellStyle.

Everything there works fine until I try adding a border around that/those cells.

I'm using propertyTemplate.drawBorders(range, borderType, color, extent);

```<code>    CellRangeAddress range = new CellRangeAddress(startRow, endRow, startColumn, endColumn);
    BorderStyle borderType = BorderStyle.MEDIUM;
    short color = IndexedColors.BLACK.getIndex();
    BorderExtent extent = BorderExtent.ALL;
    propertyTemplate.drawBorders(range, borderType, color, extent);
</code>```

When I apply this and generate my sheet, the cells that were styled with the headerStyle are completely black.  I can change the text color to white and I can see all the data is still there.

When I comment out the setFillPattern in the headerStyle, I can see the borders properly, but then the foreground color is white as though the setFillForegroundColor was no set (even though it is).

I've tried using setFillBackgroundColor as well but I get the same results.

Does anyone have any idea where I might be going wrong or is this a known (or unknown?) bug?

Thank you!

Alex

答:
I have used NPOI for XSSF which is for .net . You'll have translate to get equivalent code for Java. </p>

```<code> XSSFFont myFont = (XSSFFont)workbook.CreateFont();
 myFont.FontHeightInPoints = (short)10;
 myFont.FontName = "Arial";
 myFont.Color = IndexedColors.Black.Index;
 myFont.IsBold = false;
 myFont.IsItalic = false;

XSSFCellStyle myCellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
myCellStyle.FillBackgroundColor = IndexedColors.LightYellow.Index;
//myCellStyle.FillPattern = FillPattern.NoFill;
myCellStyle.FillForegroundColor = IndexedColors.LightTurquoise.Index;
myCellStyle.FillPattern = FillPattern.SolidForeground;
myCellStyle.Alignment = HorizontalAlignment.Left;
myCellStyle.VerticalAlignment = VerticalAlignment.Top;
myCellStyle.BorderBottom = BorderStyle.Thin;
myCellStyle.BorderTop = BorderStyle.Thin;
myCellStyle.BorderLeft = BorderStyle.Thin;
myCellStyle.BorderRight = BorderStyle.Thin;
myCellStyle.SetFont(defaultFont);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've found the following question which is similar but not exactly the same:

Setting foreground color for HSSFCellStyle is always coming out black

So I'm creating an XSSFCellStyle for the headers of my table, and giving them a Foreground color with the following:

    wb = new XSSFWorkbook();
    headerStyle = wb.createCellStyle();
    XSSFColor headerBackgroundColor = new XSSFColor(new java.awt.Color(187,187,187));
    headerStyle.setFillForegroundColor( headerBackgroundColor);
    headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

Then I apply it to a cell using the setCellStyle.

Everything there works fine until I try adding a border around that/those cells.

I'm using propertyTemplate.drawBorders(range, borderType, color, extent);

    CellRangeAddress range = new CellRangeAddress(startRow, endRow, startColumn, endColumn);
    BorderStyle borderType = BorderStyle.MEDIUM;
    short color = IndexedColors.BLACK.getIndex();
    BorderExtent extent = BorderExtent.ALL;
    propertyTemplate.drawBorders(range, borderType, color, extent);

When I apply this and generate my sheet, the cells that were styled with the headerStyle are completely black.  I can change the text color to white and I can see all the data is still there.

When I comment out the setFillPattern in the headerStyle, I can see the borders properly, but then the foreground color is white as though the setFillForegroundColor was no set (even though it is).

I've tried using setFillBackgroundColor as well but I get the same results.

Does anyone have any idea where I might be going wrong or is this a known (or unknown?) bug?

Thank you!

Alex

Body:
I have used NPOI for XSSF which is for .net . You'll have translate to get equivalent code for Java.

 XSSFFont myFont = (XSSFFont)workbook.CreateFont();
 myFont.FontHeightInPoints = (short)10;
 myFont.FontName = "Arial";
 myFont.Color = IndexedColors.Black.Index;
 myFont.IsBold = false;
 myFont.IsItalic = false;

XSSFCellStyle myCellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
myCellStyle.FillBackgroundColor = IndexedColors.LightYellow.Index;
//myCellStyle.FillPattern = FillPattern.NoFill;
myCellStyle.FillForegroundColor = IndexedColors.LightTurquoise.Index;
myCellStyle.FillPattern = FillPattern.SolidForeground;
myCellStyle.Alignment = HorizontalAlignment.Left;
myCellStyle.VerticalAlignment = VerticalAlignment.Top;
myCellStyle.BorderBottom = BorderStyle.Thin;
myCellStyle.BorderTop = BorderStyle.Thin;
myCellStyle.BorderLeft = BorderStyle.Thin;
myCellStyle.BorderRight = BorderStyle.Thin;
myCellStyle.SetFont(defaultFont);


问:
Smarty Compiler: Syntax error unknown tag
I have a function named menu in parent.tpl:

```<code>{function menu level=0}
  <ul class="level{$level}">
  {foreach $data as $entry}
    {if is_array($entry)}
      <li>{$entry@key}</li>
      {menu data=$entry level=$level+1}
    {else}
      <li>{$entry}</li>
    {/if}
  {/foreach}
  </ul>
{/function}
</code>```

I want to use this menu function in child.tpl

```<code>{extends file='./base.tpl'}

{block name=head}
  <link href="/css/mypage.css" rel="stylesheet" type="text/css"/>
  <script src="/js/mypage.js"></script>
{/block}

{block name=body}
    {$menu = ['item1','item2','item3' => ['item3-1','item3-2','item3-3' =>
    ['item3-3-1','item3-3-2']],'item4']}
    {menu data=$menu}
{/block}
</code>```

But smarty errors:

```<code>:  Uncaught  --> Smarty Compiler: Syntax error in template "file:/Users/yangchangshu/smarty/child.tpl"  on line 11 "{menu data=$menu}" unknown tag "menu" <--
  thrown in
</code>```

How can I solve this?

答:
By the nature of inheritance template Processing the parent template is processed last in the chain. So {menu} is undefined when the child Template is being compiled.
Work around:
put {function menu....} in a subtemplate and {include} it in
{block name=body}</p>

Body:
I have a function named menu in parent.tpl:

{function menu level=0}

  {foreach $data as $entry}
    {if is_array($entry)}

{$entry@key}

      {menu data=$entry level=$level+1}
    {else}

{$entry}

    {/if}
  {/foreach}

{/function}

I want to use this menu function in child.tpl

{extends file='./base.tpl'}

{block name=head}
  <link href="/css/mypage.css" rel="stylesheet" type="text/css"/>

{/block}

{block name=body}
    {$menu = ['item1','item2','item3' => ['item3-1','item3-2','item3-3' =>
    ['item3-3-1','item3-3-2']],'item4']}
    {menu data=$menu}
{/block}

But smarty errors:

:  Uncaught  --> Smarty Compiler: Syntax error in template "file:/Users/yangchangshu/smarty/child.tpl"  on line 11 "{menu data=$menu}" unknown tag "menu" <--
  thrown in

How can I solve this?


问:
Difference between env/bin/python and env/lib/pythonX.Y (note the lib)
Sorry for the noob question - just trying to understand the flow of how python works.

Does anyone know what the difference between env/bin/python and env/lib/python3.6 is? It will be really helpful to know. (Note the different paths - bin and lib)

Thanks :)

EDIT: I only have one version of python installed in the environment. The one thing to notice here is that env/bin/python has a symbolic link to env/bin/python3.6 (which is a binary file, obviously). But there is a directory in env/lib/python3.6 in which there are directories like site-packages where the installed packages are stored.

So my questions is... when is the binary file in /env/bin used and when is the directory accessed? When I say 'python' in the shell, it goes to the bin but when I say 'import django' in the interpreter, it goes to python3.6 in lib and gets the package. Am i on the right track?

答: X and Y represents the version of python you are using.</p>


问:
How do I retrieve the data in the name list attribute (html) using jQuery?
I am trying to retrieve the list of names from the inputs through jQuery.
Could anyone advise how I can do it?

The following inputs for example:

```<code>Henry | 25 | Financial Advisor
Eric  | 28 | Chemistry Professor
Lance | 30 | Database Administrator
</code>```

How can I retrieve the names Henry, Eric, Lance using jQuery and the name[ ] attribute?

HTML

```<code><div id="wrapper">
<div id="form_div">
 <form method="post" action="store_employee.php">
  <table id="employee_table" align=center>
   <tr id="row1">
    <td><input type="text" name="name[]" placeholder="Enter Name"></td>
    <td><input type="text" name="age[]" placeholder="Enter Age"></td>
    <td><input type="text" name="job[]" placeholder="Enter Job"></td>
   </tr>
  </table>
  <input type="button" onclick="add_row();" value="ADD ROW">
  <input type="submit" name="submit_row" value="SUBMIT">
 </form>
</div>
</code>```

Javascript

```<code>    function add_row()
{
    $rowno=jQuery("#employee_table tr").length;
    $rowno=$rowno+1;
    jQuery("#employee_table tr:last").after(
        "<tr id='row"+$rowno+"'>"+
            "<td><input type='text' name='name[]' placeholder='Enter Name'></td>"+
            "<td><input type='text' name='age[]' placeholder='Enter Age'></td>"+
            "<td><input type='text' name='job[]' placeholder='Enter Job'></td>"+
            "<td><input type='button' value='DELETE' onclick=delete_row('row"+$rowno+"')></td>"+
        "</tr>");
    }

function delete_row(rowno)
{
    jQuery('#'+rowno).remove();
}
</code>```

答:
You can use the name attribute to target the right inputs... Then look for the value.

function add_row()
{
  $rowno=jQuery("#employee_table tr").length;
  $rowno=$rowno+1;
  jQuery("#employee_table tr:last").after(
    "
"+
    "<input type='text' name='name[]' placeholder='Enter Name'>	"+
    "<input type='text' name='age[]' placeholder='Enter Age'>	"+
    "<input type='text' name='job[]' placeholder='Enter Job'>	"+
    "<input type='button' value='DELETE' onclick=delete_row('row"+$rowno+"')>	"+
    "
");
}

function delete_row(rowno)
{
  jQuery('#'+rowno).remove();
}

$("#test").on("click",function(){

  var names =[];
  var nameInputs = $("input[name='name[]']");

  for (i=0;i<nameInputs.length;i++){
    names.push(nameInputs.eq(i).val());
  }
  console.log(names.join(","));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="wrapper">
<div id="form_div">
 <form method="post" action="store_employee.php">
  <table id="employee_table" align=center>
   <tr id="row1">
    <td><input type="text" name="name[]" placeholder="Enter Name"></td>
    <td><input type="text" name="age[]" placeholder="Enter Age"></td>
    <td><input type="text" name="job[]" placeholder="Enter Job"></td>
   </tr>
  </table>
  <input type="button" onclick="add_row();" value="ADD ROW">
  <input type="submit" name="submit_row" value="SUBMIT">
 </form>
</div>
<br>
<br>
  <button id="test">Show names in console</button></code>```

Body:
I am trying to retrieve the list of names from the inputs through jQuery.
Could anyone advise how I can do it?

The following inputs for example:

Henry | 25 | Financial Advisor
Eric  | 28 | Chemistry Professor
Lance | 30 | Database Administrator

How can I retrieve the names Henry, Eric, Lance using jQuery and the name[ ] attribute?

HTML

 <form method="post" action="store_employee.php">

    <input type="text" name="name[]" placeholder="Enter Name">
    <input type="text" name="age[]" placeholder="Enter Age">
    <input type="text" name="job[]" placeholder="Enter Job">

  <input type="button" onclick="add_row();" value="ADD ROW">
  <input type="submit" name="submit_row" value="SUBMIT">
 </form>

Javascript

    function add_row()
{
    $rowno=jQuery("#employee_table tr").length;
    $rowno=$rowno+1;
    jQuery("#employee_table tr:last").after(
        "
"+
            "<input type='text' name='name[]' placeholder='Enter Name'>	"+
            "<input type='text' name='age[]' placeholder='Enter Age'>	"+
            "<input type='text' name='job[]' placeholder='Enter Job'>	"+
            "<input type='button' value='DELETE' onclick=delete_row('row"+$rowno+"')>	"+
        "
");
    }

function delete_row(rowno)
{
    jQuery('#'+rowno).remove();
}

Body:
You can use the name attribute to target the right inputs... Then look for the value.

function add_row()
{
  $rowno=jQuery("#employee_table tr").length;
  $rowno=$rowno+1;
  jQuery("#employee_table tr:last").after(
    "<tr id='row"+$rowno+"'>"+
    "<td><input type='text' name='name[]' placeholder='Enter Name'></td>"+
    "<td><input type='text' name='age[]' placeholder='Enter Age'></td>"+
    "<td><input type='text' name='job[]' placeholder='Enter Job'></td>"+
    "<td><input type='button' value='DELETE' onclick=delete_row('row"+$rowno+"')></td>"+
    "</tr>");
}

function delete_row(rowno)
{
  jQuery('#'+rowno).remove();
}

$("#test").on("click",function(){

  var names =[];
  var nameInputs = $("input[name='name[]']");

  for (i=0;i<nameInputs.length;i++){
    names.push(nameInputs.eq(i).val());
  }
  console.log(names.join(","));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="wrapper">
<div id="form_div">
 <form method="post" action="store_employee.php">
  <table id="employee_table" align=center>
   <tr id="row1">
    <td><input type="text" name="name[]" placeholder="Enter Name"></td>
    <td><input type="text" name="age[]" placeholder="Enter Age"></td>
    <td><input type="text" name="job[]" placeholder="Enter Job"></td>
   </tr>
  </table>
  <input type="button" onclick="add_row();" value="ADD ROW">
  <input type="submit" name="submit_row" value="SUBMIT">
 </form>
</div>
<br>
<br>
  <button id="test">Show names in console</button>


问:
Setting up a new domain Heart Internet
I've never done this before so I'm very confused and don't want to start changing things in my heart internet account unless I know what I'm doing. I basically want to create a new domain using an existing one. Like this exsiting-domain.co.uk/new-domain This will be a WordPress site incase that matters. How can I do this? </p>

答:
I believe you are looking to implement an Addon Domain.

What is an Addon Domain?

Title: Setting up a new domain Heart Internet


问:
Should consecutive whitespace in an XML file be ignored by an XML reader?
At my work we have our own XML classes which build a DOM, but I'm not sure how consecutive whitespace should be handled?

e.g.

```<code><some-text>
Hello     World
</some-text>
</code>```

When this is read into the DOM, should the text node include the consecutive whitespace inbetween Hello and World or just reduce it to one space?

Or should the XML source be written like this:

```
<some-text>
Hello     World
</some-text>
```

or if not   than perhaps   ?

答: EDIT: whitespace within tags is considered significant (my initial thoughts on this being like HTML were wrong; google first, answer questions later!) see this explanation</p>

OwnerDisplayName: Ben Daniel

ContentLicense: CC BY-SA 2.5

Body:
At my work we have our own XML classes which build a DOM, but I'm not sure how consecutive whitespace should be handled?

e.g.

<some-text>
Hello     World
</some-text>

When this is read into the DOM, should the text node include the consecutive whitespace inbetween Hello and World or just reduce it to one space?

Or should the XML source be written like this:

<some-text>
Hello     World
</some-text>

or if not   than perhaps   ?

LastEditorDisplayName: Ben Daniel

OwnerDisplayName: Steven A. Lowe

LastEditorDisplayName: Steven A. Lowe


问:
Given a file, find the ten most frequently occurring words as efficiently as possible
This is apparently an interview question (found it in a collection of interview questions), but even if it's not it's pretty cool.

We are told to do this efficiently on all complexity measures. I thought of creating a HashMap that maps the words to their frequency. That would be O(n) in time and space complexity, but since there may be lots of words we cannot assume that we can store everything in memory.

I must add that nothing in the question says that the words cannot be stored in memory, but what if that were the case? If that's not the case, then the question does not seem as challenging.

答: If the word list will not fit in memory, you can split the file until it will.  Generate a histogram of each part (either sequentially or in parallel), and merge the results (the details of which may be a bit fiddly if you want guaranteed correctness for all inputs, but should not compromise the O(n) effort, or the O(n/k) time for k tasks).</p>


问:
Android custom Carousel Image layout
I want to implement the following type image scroll view, which will populate dynamically (imageViews).

I have already tried with  this

But it could not able to give the desired UI effect.
Can any body help me how could this can be achieved.

答:
I think you can try out carousel view here :

In Gradle: compile 'com.synnapps:carouselview:0.1.4'
In XML:

```<code> <com.synnapps.carouselview.CarouselView
    android:id="@+id/carouselView"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    app:fillColor="#FFFFFFFF"
    app:pageColor="#00000000"
    app:radius="6dp"
    app:slideInterval="3000"
    app:strokeColor="#FF777777"
    app:strokeWidth="1dp"/>
</code>```

In class:

```<code>public class SampleCarouselViewActivity extends AppCompatActivity {

CarouselView carouselView;

int[] sampleImages = {R.drawable.image_1, R.drawable.image_2, R.drawable.image_3, R.drawable.image_4, R.drawable.image_5};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sample_carousel_view);

    carouselView = (CarouselView) findViewById(R.id.carouselView);
    carouselView.setPageCount(sampleImages.length);

    carouselView.setImageListener(imageListener);
}

ImageListener imageListener = new ImageListener() {
    @Override
    public void setImageForPosition(int position, ImageView imageView) {
        imageView.setImageResource(sampleImages[position]);
    }
};
</code>```

}

Doc: https://github.com/sayyam/carouselview

Title: Android custom Carousel Image layout

Body:
I think you can try out carousel view here :

In Gradle: compile 'com.synnapps:carouselview:0.1.4'
In XML:

 <com.synnapps.carouselview.CarouselView
    android:id="@+id/carouselView"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    app:fillColor="#FFFFFFFF"
    app:pageColor="#00000000"
    app:radius="6dp"
    app:slideInterval="3000"
    app:strokeColor="#FF777777"
    app:strokeWidth="1dp"/>

In class:

public class SampleCarouselViewActivity extends AppCompatActivity {

CarouselView carouselView;

int[] sampleImages = {R.drawable.image_1, R.drawable.image_2, R.drawable.image_3, R.drawable.image_4, R.drawable.image_5};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sample_carousel_view);

    carouselView = (CarouselView) findViewById(R.id.carouselView);
    carouselView.setPageCount(sampleImages.length);

    carouselView.setImageListener(imageListener);
}

ImageListener imageListener = new ImageListener() {
    @Override
    public void setImageForPosition(int position, ImageView imageView) {
        imageView.setImageResource(sampleImages[position]);
    }
};

}

Doc: https://github.com/sayyam/carouselview


问:
Error somehow related to using the footer of library mpdf
I'm using CodeIgniter with the mpdf library to create pdf files.

It works just fine until I try to add a footer.
Every time I add the footer, whenever I try to open the generated file I get this error:

File Does Not Begin With '%PDF-' Local\EWH-6160-0

If I skip the footer, it works fine, I don't understand how the error is related to the footer.

This is the controller that creates the pdf:

```<code>    public function print_beneficiaries($cod){

    $mpdf = new mPDF( 'utf-8', 'A3' );

    $name = $this->natural_md->client_name($cod);
    $account = $this->formats->retrieve_account($cod);
    $data = $this->formats->beneficiaries( $cod );
    $date = $this->formats->mult_contract( $cod );
    $list = array();

    if($data > 0){
        $i = 1;
        foreach ( $data as $benef ){
            array_push( $list, array(
                    'cod' => $cod,
                    'id_beneficiary' => $benef['id_beneficiary'],
                    'name' => $benef['beneficiary_name'],
                    'relationship' => $benef['relationship'],
                    'benef_percentage' => $benef['benef_percentage'],
                    'identification' => $benef['identification'],
                    'identification_type' => $benef['identification_type'],
                    'address' => $benef['address'],
                    'email' => $benef['email'],
                    'telephone' => $benef['telephone'],
                    'celphone' => $benef['celphone'],
                    'letter' => $this->utilities->get_letter($i)
            ) );

            $i = $i + 1;
        }
    }
    else
        $list = array();

    $mpdf->SetFooter("{PAGENO}/{nb}");
    $mpdf->WriteHTML($this->load->view( 'pdf/pn_beneficiaries', array(
            'list' => $list,
            'account_name' => ucwords($name[0]['names']),
            'account_id' => $account == null ? 0 : $account->id,
            'account' => $account == '' ? 0 :$cuenta->account_name,
            'day' =>    sprintf('%02d', $date[0]['day']),
            'month' =>  sprintf('%02d', $date[0]['month']),
            'year' =>   $date[0]['year'],
    ), true ) );
    $mpdf->Output("Beneficiaries - ".$cod.".pdf", "I");

}
</code>```

The view from which the controller retrieves the data is this:

```<code>    <!DOCTYPE html>
    <head>
     <meta charset="UTF-8">
     <title>Beneficiaries</title>
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <link rel="stylesheet" href="<?php echo base_url();?
     >/assets/css/bootstrap.min.css" />
     <link rel="stylesheet" href="<?php echo base_url();?
     >/assets/css/font.css" />
     <style>
      body{
          color: #0a0a0a;
          font-size: 12px;
          font-family: Calibri, sans-serif;
      }
      .foot{
           position: absolute;
           bottom: 0;
           left: 900px;
           width: 100%;
           float: right;
       }
      .espacio{
          margin-top: 4px;
          width: 900px;
      }
      .espacio h3{
          text-align: center;
          font-weight: 700;
      }
      .per{
          font-size: 14px;
          text-align: justify;
      }
      table{
         font-size: 16px;
      }
      th{
          padding:4px;
          text-align: center;
      }
      table.border td{
          border: solid 2px #B1B1B1;
      }
      td{
          padding:4px;
      }
      u{
          height: 2px;
      }
      .logo{
          text-align: center;
      }
      @media print {
          #with_print {
              display: none;
          }
      }
     </style>
    </head>
    <body>
     <header>
      <div class="row">
       <div class="container logo">
            <img src="<?php echo base_url();?>/assets/img/logo-inver-
             new.jpg" width="180px">
       </div>
      </div>
     </header>
     <div class="container espacio" >
      <h3>
         Beneficiary designation
      </h3>
      <div class="espacio per">
         <p>
           some text
        </p>
      </div>
      <div class="row">
       <div class="container">
         <table border="1" class="border">
           <tr>
            <td colspan="3" style=" background-color: #30859B; color: #fff;
            font-size: 16px; margin: 5px;">Fecha</td>
           </tr>
           <tr>
               <td style=" font-size: 16px;"><?php echo $day; ?></td>
               <td style=" font-size: 16px;"><?php echo $month; ?></td>
               <td style=" font-size: 16px;"><?php echo $year; ?></td>
           </tr>
          </table>
         </div>
        </div>
        <br>
        <div class="row">
          <?php $cont = 0; $filas=count($list);?>
          <?php foreach ($list as $row):?>
              <div class="container">
               <table border="1" align="center" class="border">
                <tr>
                 <td colspan="2"  style=" background-color: #30859B; color:
                 #fff;">Beneficiario <?php echo $row['letter']; ?></td>
                </tr>
                <tr>
                 <td colspan="2">Nombre del Beneficiario: <span style="font-
                 size: 18px; font-style: italic; color:
                 #2b2b2b;">  <?php echo $row['name']; ?> </span>
                 </td>
                </tr>
                <tr>
                 <td  style="width: 500px;">Parentesco:  <span style="font-
                 size: 18px; font-style: italic; color:
                 #2b2b2b;">  <?php echo $row['relationship']; ?>
                 </span> </td>
                 <td  style="width: 500px;">% del Beneficiario:  <span
                 style="font-size: 18px; font-style: italic; color:
                 #2b2b2b;">
                    <?php
                      if(!empty($row['benef_percentage']))
                      {echo $row['benef_percentage'].' %';}
                      ?></span> </td>
                </tr>
                <tr>
                 <td>No. Identificación: <span style="font-size: 18px; font-
                 style: italic; color: #2b2b2b;">  <?php echo
                 $row['identification']; ?></span> </td>
                 <td>Tipo de Identificación:  <span style="font-size: 18px;
                 font-style: italic; color: #2b2b2b;">  <?php echo
                 $row['identification_type']; ?> </span> </td>
                </tr>
                <tr>
                 <td colspan="2">Dirección del Beneficiario: <span
                 style="font-size: 18px; font-style: italic; color:
                 #2b2b2b;">   <?php echo $row['address']; ?>
                 </span> </td>
                </tr>
                <tr>
                 <td colspan="2">Correo Electrónico: <span style="font-size:
                 18px; font-style: italic; color: #2b2b2b;">   <?
                 php echo $row['email']; ?></span> </td>
                </tr>
                <tr>
                 <td>Teléfono Domicilio: <span style="font-size: 18px; font-
                 style: italic; color: #2b2b2b;">  <?php echo
                 $row['telephone']; ?></span> </td>
                 <td>Teléfono Celular: <span style="font-size: 18px; font-
                 style: italic; color: #2b2b2b;">  <?php echo
                 $row['celphone']; ?> </span> </td>
                </tr>
               </table>
              </div>
              <?php $cont++;
                  if ($cont%5==0 && $filas>5) {
                      echo '
                      <pagebreak>
                      ';
                  }
               ?>
              <?php endforeach; ?>
        </div>
        <br>
        <div class="col-xs-12">
         <table style="margin-top: 10px;">
            <tr>
                <td>Nombre de la cuenta: <?php echo $filas ?></td>
                <td style="border-bottom: solid 1px #000; width: 100%"><?php
                  if (isset($account) && ($account!='')) {
                        echo $account;
                  }else{
                    echo $account_name;
                  }
                ?></td>
            </tr>
        </table>
    </div>

    <div class="col-xs-12 espacio">
        <p style="text-align: justify;"><span style=" font-weight:
        bold;">Nota:</span>Other text</p>
    </div>

    <div class="col-xs-12">
        <table style="margin-top: 10px;">
            <tr >
                <td  style="width: 100px;"></td>
                <td style="border-top: solid 1px #000; width: 250px; text-
                align: center; font-size: 16px;" >Firma del Cliente</td>
                <td  style="width: 100px;"></td>
                <td style="border-top: solid 1px #000; ; width: 350px; text-
                align: center; font-size: 16px;" >Firma del
                Cliente<br>Cuenta Mancomunada</td>
                <td  style="width: 100px;"></td>
                <td style="border-top: solid 1px #000;width: 290px; text-
                align: center; font-size: 16px;">
                        Firma del Funcionario IPB
                </td>

            </tr>
        </table>
    </div>

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

答: I found the answer in a similar post.  I opened the file on word and the error was: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead on the mpdf.php file line 12492.  I searched for the solution, just change the original code: $hd = preg_replace('/\{DATE\s+(.*?)\}/e',"date('\\1')",$hd);  to this: $hd = preg_replace_callback('/\{DATE\s+(.*?)\}/m', function($m){ return date($m[1]);},$hd);

Body:
I'm using CodeIgniter with the mpdf library to create pdf files.

It works just fine until I try to add a footer.
Every time I add the footer, whenever I try to open the generated file I get this error:

File Does Not Begin With '%PDF-' Local\EWH-6160-0

If I skip the footer, it works fine, I don't understand how the error is related to the footer.

This is the controller that creates the pdf:

    public function print_beneficiaries($cod){

    $mpdf = new mPDF( 'utf-8', 'A3' );

    $name = $this->natural_md->client_name($cod);
    $account = $this->formats->retrieve_account($cod);
    $data = $this->formats->beneficiaries( $cod );
    $date = $this->formats->mult_contract( $cod );
    $list = array();

    if($data > 0){
        $i = 1;
        foreach ( $data as $benef ){
            array_push( $list, array(
                    'cod' => $cod,
                    'id_beneficiary' => $benef['id_beneficiary'],
                    'name' => $benef['beneficiary_name'],
                    'relationship' => $benef['relationship'],
                    'benef_percentage' => $benef['benef_percentage'],
                    'identification' => $benef['identification'],
                    'identification_type' => $benef['identification_type'],
                    'address' => $benef['address'],
                    'email' => $benef['email'],
                    'telephone' => $benef['telephone'],
                    'celphone' => $benef['celphone'],
                    'letter' => $this->utilities->get_letter($i)
            ) );

            $i = $i + 1;
        }
    }
    else
        $list = array();

    $mpdf->SetFooter("{PAGENO}/{nb}");
    $mpdf->WriteHTML($this->load->view( 'pdf/pn_beneficiaries', array(
            'list' => $list,
            'account_name' => ucwords($name[0]['names']),
            'account_id' => $account == null ? 0 : $account->id,
            'account' => $account == '' ? 0 :$cuenta->account_name,
            'day' =>    sprintf('%02d', $date[0]['day']),
            'month' =>  sprintf('%02d', $date[0]['month']),
            'year' =>   $date[0]['year'],
    ), true ) );
    $mpdf->Output("Beneficiaries - ".$cod.".pdf", "I");

}

The view from which the controller retrieves the data is this:

    <!DOCTYPE html>

     <meta charset="UTF-8">
     <title>Beneficiaries</title>
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <link rel="stylesheet" href="<?php echo base_url();?
     >/assets/css/bootstrap.min.css" />
     <link rel="stylesheet" href="<?php echo base_url();?
     >/assets/css/font.css" />

            <img src="<?php echo base_url();?>/assets/img/logo-inver-
             new.jpg" width="180px">

         Beneficiary designation

           some text

            Fecha

               <?php echo $day; ?>
               <?php echo $month; ?>
               <?php echo $year; ?>

          <?php $cont = 0; $filas=count($list);?>
          <?php foreach ($list as $row):?>

                 Beneficiario <?php echo $row['letter']; ?>

                 Nombre del Beneficiario:   <?php echo $row['name']; ?>

                 Parentesco:    <?php echo $row['relationship']; ?>

                 % del Beneficiario:
                    <?php
                      if(!empty($row['benef_percentage']))
                      {echo $row['benef_percentage'].' %';}
                      ?>

                 No. Identificación:   <?php echo
                 $row['identification']; ?>
                 Tipo de Identificación:    <?php echo
                 $row['identification_type']; ?>

                 Dirección del Beneficiario:    <?php echo $row['address']; ?>

                 Correo Electrónico:    <?
                 php echo $row['email']; ?>

                 Teléfono Domicilio:   <?php echo
                 $row['telephone']; ?>
                 Teléfono Celular:   <?php echo
                 $row['celphone']; ?>

              <?php $cont++;
                  if ($cont%5==0 && $filas>5) {
                      echo '
                      <pagebreak>
                      ';
                  }
               ?>
              <?php endforeach; ?>

                Nombre de la cuenta: <?php echo $filas ?>
                <?php
                  if (isset($account) && ($account!='')) {
                        echo $account;
                  }else{
                    echo $account_name;
                  }
                ?>

Nota:Other text

                Firma del Cliente

                Firma del
                Cliente
Cuenta Mancomunada

                        Firma del Funcionario IPB


问:
Compressing PCM
I'm recording sound from Microsoft.Xna.Framework.Audio.Microphone Is there any way to compress it after words? The best will be to have mp3 or wmv files, but I can't find any solution.  The cloud computing will be to slow i think.</p>

答: Unfortunately, there is no framework support for audio compression. Although you could technically implement the algorithm yourself in managed code, it will probably consume too much processing power and your application won't pass Microsoft certification.</p>

Title: Compressing PCM


问:
Is it possible to get commits history for one file in gitlab api?
I want to get the commits or the last commit for one file in gitlab api like this:

GET /projects/:id/repository/commits?path=fileName

Gitlab support or not?

答:
Now you can do:

```<code>/projects/:id/repository/commits?path=:file_path
</code>```

and receive array of commits about specific file.

Link to documentation

Body:
Now you can do:

/projects/:id/repository/commits?path=:file_path

and receive array of commits about specific file.

Link to documentation

ContentLicense: CC BY-SA 4.0


问:
window.scrollTo() not working
```<code>window.scrollTo(0,0);
</code>```

Desired result: page scrolls up to top

Tried it attached to button click and nothing happens.

I have pages of information and when the user clicks on the next/previous page button at the bottom, I want the window to scroll back up to the top.

What's going wrong here? Is there some other App Maker method we're supposed to use within App Maker?

答:
Check out: Google Apps Script UI: Scroll to top of screen

I haven't tried this, but from this post something like:

```<code>var element = app.currentPage.getElement();
element.scrollTop = 0;
// (And if you need left as well)
element.scrollLeft = 0;
</code>```

Title: window.scrollTo() not working

Body:
window.scrollTo(0,0);

Desired result: page scrolls up to top

Tried it attached to button click and nothing happens.

I have pages of information and when the user clicks on the next/previous page button at the bottom, I want the window to scroll back up to the top.

What's going wrong here? Is there some other App Maker method we're supposed to use within App Maker?

Body:
Check out: Google Apps Script UI: Scroll to top of screen

I haven't tried this, but from this post something like:

var element = app.currentPage.getElement();
element.scrollTop = 0;
// (And if you need left as well)
element.scrollLeft = 0;


问:
Can see JSON data in a form in Mozilla but not in Chrome?
Here is the Updated Plnkr.

I am trying to load a simple JSON file into a form using Angular js. But I am not seeing any data in the text boxes in Chrome but I can see in Mozilla. For chrome I am getting below error

XMLHttpRequest cannot load file:///C:/Users/hp/Desktop/site/site.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Where am I going wrong?

```<code>  <!DOCTYPE html>
  <html ng-app="myApp">
  <head>
  <title>Hello</title>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

  <script>
   myApp = angular.module('myApp',[]);
   myApp.controller('myController', function($scope,$http){
   $http.get('site.json').success(function(response){
        $scope.myData=response;
     });
    });
  </script>

  </head>
 <body ng-controller="myController">

   <div ng-repeat="data in myData">
      <input type="text" name="">{{data.siteno}}
      <input type="text" name="">{{data.sitename}}
   </div>
 </body>
 </html>
</code>```

答: This happens since I am directly trying to run locally without any server. So easy solution for this would be to download a webserver plug in for chrome then you can run from the server url. I presume Mozilla must have already an inbuilt plug in which doesn't throw this error.</p>

Body:
Here is the Updated Plnkr.

I am trying to load a simple JSON file into a form using Angular js. But I am not seeing any data in the text boxes in Chrome but I can see in Mozilla. For chrome I am getting below error

XMLHttpRequest cannot load file:///C:/Users/hp/Desktop/site/site.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Where am I going wrong?

  <!DOCTYPE html>

  <title>Hello</title>

      <input type="text" name="">{{data.siteno}}
      <input type="text" name="">{{data.sitename}}


问:
OpenLayers 3: Sync/Unsync Different Maps Events
Let's say I have N different maps on the screen, I want to be able based on a condition, let s say a value coming from a checkbox or a different control to be able to sync all the map events (zoom/pan/rotation) and unsync them accordingly.
   Can this be achieved in OpenLayers 3 using native code?</p>

答:
I'm working on a project with fairly heavy WMS layers and hit a problem with Alvin's solution.  For the first map OL waits for any interaction to end before requesting an updated WMS layer.  But for the second map it appears to treat each step triggered by the function as a separate interaction and therefore generates a separate WMS layer request at each step.  In my case this was seriously affecting performance.

I've come up with a compromise solution that waits for interaction to end and then animates the second map to match the first.  This is a first attempt and could probably be improved:

```<code>// attributes to synchronise between maps
var synchedAttributes = ['resolution', 'center']

// call this on moveend
var syncPanZoom = function(maps, evt){

  maps.forEach(function(map){

    synchedAttributes.forEach(function(attribute) {

      var value = evt.target.getView().get(attribute);

      if (map.olmap.getView().get(attribute) !== value){
        var animateObject = {};
        animateObject[attribute] = value;
        animateObject.duration = 500;
        map.olmap.getView().animate(animateObject)
      }

    });

  });

};
</code>```

Body:
I'm working on a project with fairly heavy WMS layers and hit a problem with Alvin's solution.  For the first map OL waits for any interaction to end before requesting an updated WMS layer.  But for the second map it appears to treat each step triggered by the function as a separate interaction and therefore generates a separate WMS layer request at each step.  In my case this was seriously affecting performance.

I've come up with a compromise solution that waits for interaction to end and then animates the second map to match the first.  This is a first attempt and could probably be improved:

// attributes to synchronise between maps
var synchedAttributes = ['resolution', 'center']

// call this on moveend
var syncPanZoom = function(maps, evt){

  maps.forEach(function(map){

    synchedAttributes.forEach(function(attribute) {

      var value = evt.target.getView().get(attribute);

      if (map.olmap.getView().get(attribute) !== value){
        var animateObject = {};
        animateObject[attribute] = value;
        animateObject.duration = 500;
        map.olmap.getView().animate(animateObject)
      }

    });

  });

};


问:
C++ String Interview Question
I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised of the first and last n-characters, and then proceed to correct any bugs and to also make the function as efficient as possible, I came up with the solution below, however the interviewer claimed there was an even faster more optimal way:

Original code:

```<code>std::string first_last_n(int n, std::string s)
{
   std::string first_n = s.substr(0,n);
   std::string last_n = s.substr(s.size()-n-1,n);
   return first_n + last_n;
}
</code>```

My code:

```<code>bool first_last_n(const std::size_t& n, const std::string& s, std::string& r)
{
   if (s.size() < n)
      return false;
   r.reserve(2 * n);
   r.resize(0);
   r.append(s.data(),s.data() + n);
   r.append(s.data() + (s.size() - n), s.data() + s.size());
   return true;
}
</code>```

Summary of my changes:

Changed the interface to take a return string as reference (assuming RVO and rvalues are not available yet)

Removed temporary strings being constructed via substr

Passed input string as a const reference inorder to get around temporary instantiation of input

Fixed off-by-1 error in last_n string

Reduced the number of times each character is touched down to once, or twice (in the event of an overlapping scenario)

Placed a check in the event the string s's size is less than n, returning false for failure.

Assuming only native C++ is allowed, is there some other way of doing the above more efficiently or optimally?

Note 1: The original input string instance is not to be modified.

Note 2: All solutions must pass the following test case, otherwise they are not valid.

```<code>void test()
{
   {
      std::string s = "0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "0123456789ABC0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "1234321";
      std::string r = first_last_n(5,s);
      assert(r == "1234334321");
   }

}
</code>```

答: How about removing the middle N-2n characters, where N is the length of the source string?</p>

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.

Title: C++ String Interview Question

Body:
I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised of the first and last n-characters, and then proceed to correct any bugs and to also make the function as efficient as possible, I came up with the solution below, however the interviewer claimed there was an even faster more optimal way:

Original code:

std::string first_last_n(int n, std::string s)
{
   std::string first_n = s.substr(0,n);
   std::string last_n = s.substr(s.size()-n-1,n);
   return first_n + last_n;
}

My code:

bool first_last_n(const std::size_t& n, const std::string& s, std::string& r)
{
   if (s.size() < n)
      return false;
   r.reserve(2 * n);
   r.resize(0);
   r.append(s.data(),s.data() + n);
   r.append(s.data() + (s.size() - n), s.data() + s.size());
   return true;
}

Summary of my changes:

Changed the interface to take a return string as reference (assuming RVO and rvalues are not available yet)

Removed temporary strings being constructed via substr

Passed input string as a const reference inorder to get around temporary instantiation of input

Fixed off-by-1 error in last_n string

Reduced the number of times each character is touched down to once, or twice (in the event of an overlapping scenario)

Placed a check in the event the string s's size is less than n, returning false for failure.

Assuming only native C++ is allowed, is there some other way of doing the above more efficiently or optimally?

Note 1: The original input string instance is not to be modified.

Note 2: All solutions must pass the following test case, otherwise they are not valid.

void test()
{
   {
      std::string s = "0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "0123456789ABC0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "1234321";
      std::string r = first_last_n(5,s);
      assert(r == "1234334321");
   }

}


问:
Implicit wait Selenium
I've a number of tests and using selenium to run them. I've looked a mixed reviews when search for what and where to use implicit waits. Should it only be used when initialising the test or should it be used anytime you want to implicitly wait for an element to be found?</p>

```<code>driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
</code>```

答:
Implicit waits should really only be used when initializing your driver(if ever).  Explicit waits are much easier to track when debugging and are designed to be more fine-grained, such as inside a Page Object.

Setting an implicit wait time on your driver has a global effect on your wait times while keeping the setting fairly hidden from the consumer or future maintainer.  This can be problematic especially when paired with explicit wait times via WebDriverWait. You could end up with unexpected additions to your wait times.

Here's an example of an explicit wait:

```<code>var webDriverWait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));

webDriverWait.Until(ExpectedConditions.ElementExists(By.Id("testId"));
</code>```

A more thorough comparison of the pros and cons between the two and when to use them can be found here.

Title: Implicit wait Selenium

Body:
I've a number of tests and using selenium to run them. I've looked a mixed reviews when search for what and where to use implicit waits. Should it only be used when initialising the test or should it be used anytime you want to implicitly wait for an element to be found?

driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);

Body:
Implicit waits should really only be used when initializing your driver(if ever).  Explicit waits are much easier to track when debugging and are designed to be more fine-grained, such as inside a Page Object.

Setting an implicit wait time on your driver has a global effect on your wait times while keeping the setting fairly hidden from the consumer or future maintainer.  This can be problematic especially when paired with explicit wait times via WebDriverWait. You could end up with unexpected additions to your wait times.

Here's an example of an explicit wait:

var webDriverWait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));

webDriverWait.Until(ExpectedConditions.ElementExists(By.Id("testId"));

A more thorough comparison of the pros and cons between the two and when to use them can be found here.


问:
plot of non-parametric vs parametric 'prob' outcomes
I am not able to plot for the aforesaid question on binary outcome.

Let

```<code>data=data.frame(feature1=c(rep(1,10),rep(2,10),rep(3,10)),
                feature2=c(rep(letters[1:2],15)),
                 Outcome=sample(0:1,30,replace = T))

ggplot(data,aes(feature1,Outcome)) +
  geom_point() +
  geom_smooth(method = 'glm',method.args=list(family='binomial')) +
  facet_wrap(~feature2)
</code>```

here I get only points at 1s and 0s, But I want points at probabilities by non-parametric model.(i.e (Outcome==1)/(all Outcomes(0s and 1s) for a particular 'feature1' segregated by 'feature2')

I know I can form a column for required probabilities from NonParametric model, but it will be very tedious to do for all combination of 'facet_wrap' and 'aes'

答:
Rather than "non-parametric model", I would call (Outcome==1)/(all Outcomes(0s and 1s) the mean. We can use stat_summary to summarize data with an arbitrary summary function, like mean(). In this case, I think you want

```<code>stat_summary(geom = "point", fun.y = mean)
</code>```

Certain geoms, like geom_boxplot, are just clever uses of stat_summary.

OwnerDisplayName: Hemant Rupani

Body:
I am not able to plot for the aforesaid question on binary outcome.

Let

data=data.frame(feature1=c(rep(1,10),rep(2,10),rep(3,10)),
                feature2=c(rep(letters[1:2],15)),
                 Outcome=sample(0:1,30,replace = T))

ggplot(data,aes(feature1,Outcome)) +
  geom_point() +
  geom_smooth(method = 'glm',method.args=list(family='binomial')) +
  facet_wrap(~feature2)

here I get only points at 1s and 0s, But I want points at probabilities by non-parametric model.(i.e (Outcome==1)/(all Outcomes(0s and 1s) for a particular 'feature1' segregated by 'feature2')

I know I can form a column for required probabilities from NonParametric model, but it will be very tedious to do for all combination of 'facet_wrap' and 'aes'

Body:
Rather than "non-parametric model", I would call (Outcome==1)/(all Outcomes(0s and 1s) the mean. We can use stat_summary to summarize data with an arbitrary summary function, like mean(). In this case, I think you want

stat_summary(geom = "point", fun.y = mean)

Certain geoms, like geom_boxplot, are just clever uses of stat_summary.


问:
Itext7 generate pdf with Exception "Pdf indirect object belongs to other PDF document. Copy object to current pdf document."
i want to generate a pdf with itext 7,but some wrong happens to us:

```<code>com.itextpdf.kernel.PdfException: Pdf indirect object belongs to other PDF document. Copy object to current pdf document.
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:195) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:185) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:115) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:187) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:115) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:187) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:115) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfWriter.writeToBody(PdfWriter.java:383) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfWriter.flushObject(PdfWriter.java:289) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfDocument.flushObject(PdfDocument.java:1572) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfObject.flush(PdfObject.java:159) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfObject.flush(PdfObject.java:127) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfObjectWrapper.flush(PdfObjectWrapper.java:94) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfPage.flush(PdfPage.java:495) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfPage.flush(PdfPage.java:454) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfDocument.close(PdfDocument.java:785) ~[kernel-7.0.2.jar:na]
at com.itextpdf.layout.Document.close(Document.java:120) ~[layout-7.0.2.jar:na]
at com.xcz.afbp.thirdparty.service.impl.GeneratePDFService.generatePDF(GeneratePDFService.java:160) ~[classes/:na]
</code>```

my generate code :

```<code>public void generatePDF(CreditQueryData creditQueryData, Map<String, UserCreditContentView> contentViewMap, List<PackageCreditContentView> needRetrievedCreditContentList, File pdfFile, BigDecimal score) throws Exception {

    if (!pdfFile.exists()) {
        boolean x = pdfFile.createNewFile();
        if (!x) {
            LOG.error("生成文件出错" + pdfFile.getPath());
            return;
        }
    }

    PdfDocument pdf = new PdfDocument(new PdfWriter(new FileOutputStream(pdfFile)));
    Document document = new Document(pdf, PageSize.A4);
    document.setRenderer(new DocumentRenderer(document));

    pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new WatermarkingEventHandler());

    try {
        //operate code just add tableA tableB tableC...

    } catch (Exception e) {
        LOG.info();
    } finally {
        document.close(); //exception throws here
    }

}
</code>```

my only style code in itext7:

```<code> private PdfFont bfChinese = null;
</code>```

will be init in service constructor invoked:

```<code> public GeneratePDFService() {
    String PdfFontPath = EnvironmentUtils.getClasspathFilePath("font/MSYH.TTF");
    try {
        bfChinese =  PdfFontFactory.createFont(PdfFontPath, "Identity-H", true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

i have tried set my font to static,but not works.

this is the place throw exception:

```<code>private void write(PdfIndirectReference indirectReference) {
        if (document != null && !indirectReference.getDocument().equals(document)) {
            throw new PdfException(PdfException.PdfIndirectObjectBelongsToOtherPdfDocument);
        }
        if (indirectReference.getRefersTo() == null) {
            write(PdfNull.PDF_NULL);
        } else if (indirectReference.getGenNumber() == 0) {
            writeInteger(indirectReference.getObjNumber()).
                    writeBytes(endIndirectWithZeroGenNr);
        } else {
            writeInteger(indirectReference.getObjNumber()).
                    writeSpace().
                    writeInteger(indirectReference.getGenNumber()).
                    writeBytes(endIndirect);
        }
    }
</code>```

it's means i have two different document ,but i do not know when i have create another document.
Thanks in advance for suggestions.

答:
To improve preformance you should reuse FontProgram:

```<code>private FontProgram bfChinese = null;

public GeneratePDFService() {
    String PdfFontPath = EnvironmentUtils.getClasspathFilePath("font/MSYH.TTF");
    try {
        bfChinese =  FontProgramFactory.createFont(PdfFontPath);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

And then:

```<code>public void createPdf() {
    ...
    PdfFont font = PdfFontFactory.createFont(bfChinese, "Identity-H", true);
    Paragraph p = new Paragraph("test").setFont(font);
    document.add(p);
    ...
}
</code>```

Body:
i want to generate a pdf with itext 7,but some wrong happens to us:

com.itextpdf.kernel.PdfException: Pdf indirect object belongs to other PDF document. Copy object to current pdf document.
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:195) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:185) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:115) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:187) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:115) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:187) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfOutputStream.write(PdfOutputStream.java:115) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfWriter.writeToBody(PdfWriter.java:383) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfWriter.flushObject(PdfWriter.java:289) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfDocument.flushObject(PdfDocument.java:1572) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfObject.flush(PdfObject.java:159) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfObject.flush(PdfObject.java:127) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfObjectWrapper.flush(PdfObjectWrapper.java:94) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfPage.flush(PdfPage.java:495) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfPage.flush(PdfPage.java:454) ~[kernel-7.0.2.jar:na]
at com.itextpdf.kernel.pdf.PdfDocument.close(PdfDocument.java:785) ~[kernel-7.0.2.jar:na]
at com.itextpdf.layout.Document.close(Document.java:120) ~[layout-7.0.2.jar:na]
at com.xcz.afbp.thirdparty.service.impl.GeneratePDFService.generatePDF(GeneratePDFService.java:160) ~[classes/:na]

my generate code :

public void generatePDF(CreditQueryData creditQueryData, Map<String, UserCreditContentView> contentViewMap, List<PackageCreditContentView> needRetrievedCreditContentList, File pdfFile, BigDecimal score) throws Exception {

    if (!pdfFile.exists()) {
        boolean x = pdfFile.createNewFile();
        if (!x) {
            LOG.error("生成文件出错" + pdfFile.getPath());
            return;
        }
    }

    PdfDocument pdf = new PdfDocument(new PdfWriter(new FileOutputStream(pdfFile)));
    Document document = new Document(pdf, PageSize.A4);
    document.setRenderer(new DocumentRenderer(document));

    pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new WatermarkingEventHandler());

    try {
        //operate code just add tableA tableB tableC...

    } catch (Exception e) {
        LOG.info();
    } finally {
        document.close(); //exception throws here
    }

}

my only style code in itext7:

 private PdfFont bfChinese = null;

will be init in service constructor invoked:

 public GeneratePDFService() {
    String PdfFontPath = EnvironmentUtils.getClasspathFilePath("font/MSYH.TTF");
    try {
        bfChinese =  PdfFontFactory.createFont(PdfFontPath, "Identity-H", true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

i have tried set my font to static,but not works.

this is the place throw exception:

private void write(PdfIndirectReference indirectReference) {
        if (document != null && !indirectReference.getDocument().equals(document)) {
            throw new PdfException(PdfException.PdfIndirectObjectBelongsToOtherPdfDocument);
        }
        if (indirectReference.getRefersTo() == null) {
            write(PdfNull.PDF_NULL);
        } else if (indirectReference.getGenNumber() == 0) {
            writeInteger(indirectReference.getObjNumber()).
                    writeBytes(endIndirectWithZeroGenNr);
        } else {
            writeInteger(indirectReference.getObjNumber()).
                    writeSpace().
                    writeInteger(indirectReference.getGenNumber()).
                    writeBytes(endIndirect);
        }
    }

it's means i have two different document ,but i do not know when i have create another document.
Thanks in advance for suggestions.

Body:
To improve preformance you should reuse FontProgram:

private FontProgram bfChinese = null;

public GeneratePDFService() {
    String PdfFontPath = EnvironmentUtils.getClasspathFilePath("font/MSYH.TTF");
    try {
        bfChinese =  FontProgramFactory.createFont(PdfFontPath);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

And then:

public void createPdf() {
    ...
    PdfFont font = PdfFontFactory.createFont(bfChinese, "Identity-H", true);
    Paragraph p = new Paragraph("test").setFont(font);
    document.add(p);
    ...
}


问:
Editext setError disappears
I have an Editext where i'm performing validation that is working well but on pressing space msg got disapper.Can anyone please point out where we are doing wrong.
Please find the image below for more clarity :

After pressing space bar:

The following code we are using:

```<code>        txtFullName.addTextChangedListener(new MyTextWatcher(txtFullName));
        txtEmail.addTextChangedListener(new MyTextWatcher(txtEmail));

 private class MyTextWatcher implements TextWatcher {

        private View view;

        private MyTextWatcher(View view) {
            this.view = view;
        }

        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void afterTextChanged(Editable editable) {
            switch (view.getId()) {
                case R.id.txtFullName:
                    if (txtFullName.getText().toString().length() >= 10) {
                        txtFullName.setError(getString(R.string.limit_exceeds));
                        txtFullName.requestFocus();
                    }
                    break;
                case R.id.txtEmail:
                    if (txtEmail.getText().toString().length() >= 20) {
                        txtEmail.setError(getString(R.string.limit_exceeds));
                        txtEmail.requestFocus();
                    }
                    break;
                    default:
                    break;
            }
     }
</code>```

答:
Original answer

According to the screenshot, the entered text is 10 characters.

Pressing space adds one more character making txtEmail.getText().toString().length() to be 11 , and triggers the TextWatcher, which only displays error if the text is 10 characters or shorter.

Title: Editext setError disappears

Body:
I have an Editext where i'm performing validation that is working well but on pressing space msg got disapper.Can anyone please point out where we are doing wrong.
Please find the image below for more clarity :

After pressing space bar:

The following code we are using:

        txtFullName.addTextChangedListener(new MyTextWatcher(txtFullName));
        txtEmail.addTextChangedListener(new MyTextWatcher(txtEmail));

 private class MyTextWatcher implements TextWatcher {

        private View view;

        private MyTextWatcher(View view) {
            this.view = view;
        }

        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void afterTextChanged(Editable editable) {
            switch (view.getId()) {
                case R.id.txtFullName:
                    if (txtFullName.getText().toString().length() >= 10) {
                        txtFullName.setError(getString(R.string.limit_exceeds));
                        txtFullName.requestFocus();
                    }
                    break;
                case R.id.txtEmail:
                    if (txtEmail.getText().toString().length() >= 20) {
                        txtEmail.setError(getString(R.string.limit_exceeds));
                        txtEmail.requestFocus();
                    }
                    break;
                    default:
                    break;
            }
     }


问:
Symfony 3 bcrypt password does not verify
Most likely I am missing some silly stuff, but I spent quite some time on this, so any help is appreciated.

The authentication is based upon this tutorial

I am using bcrypt to encode the password and it seems that is working properly on user signup.

But when logging in it throws error below, even though the password entered is correct:

Invalid credentials.

I verified that the email and password arrive properly at the login authenticator ( login form is submitted via Ajax ).

Also the getUser() method seems to be doing its job of retrieving $user object and the corresponding password from the db.

The security.yml is set as follows:

```<code>security:
encoders:
    UsedBundle\Entity\User:
        algorithm: bcrypt
</code>```

This is the registration controller:

```<code>namespace UsedBundle\Controller;

use UsedBundle\Form\UserType;
use UsedBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use UsedBundle\Service\sendEmail;

class RegistrationController extends Controller
{
/**
 * @Route("/inscription", name="inscription")
 */
public function registerAction(Request $request)
{
    $user = new User();
    $form = $this->createForm(UserType::class, $user);

    if ($request->isMethod('POST')) {
       $form->submit($request->request->get($form->getName('user')));
        if(!$form->isValid()){
           // handle invalid form
        }
        if ($form->isSubmitted() && $form->isValid()) {
            $password = $this->get('security.password_encoder')
                ->encodePassword($user, $user->getPlainPassword());
            $user->setPassword($password);
            $user->setUserKey( $user->getEmail() );
            $user->setUserKeyTime();
            $user->setDateReg();

            $em = $this->getDoctrine()->getManager('used');
            $em->persist($user);
            $em->flush();

            return new JsonResponse(array(
                'status' => 'ok',
                'message' => 'Success!')
            );
        }
    }else{
        return $this->render(
            'common/register.html.twig',
            array('form' => $form->createView())
        );
    }
}
}
</code>```

The login form authenticator ( setup as a service ):

```<code>namespace UsedBundle\Security;

use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security;
use UsedBundle\Entity\User;
use UsedBundle\Repository\UserRepository;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;

class FormLoginAuthenticator extends AbstractFormLoginAuthenticator
{
private $container;

public function __construct(ContainerInterface $container)
{
    $this->container = $container;
}

public function getCredentials(Request $request)
{
    if ($request->getPathInfo() != '/login_check') {
        return;
    }
    $username = $request->request->get('_email');
    $request->getSession()->set(Security::LAST_USERNAME, $username);
    $password = $request->request->get('_password');
    return array(
        'username' => $username,
        'password' => $password
    );
}

public function getUser($credentials, UserProviderInterface $userProvider)
{
    $username = $credentials['username'];
    $user = $this->container
         ->get('doctrine')
         ->getRepository('UsedBundle:User', 'used')
         ->findOneByemail( $username );
    return $user;
}

public function checkCredentials($credentials, UserInterface $user)
{
    $plainPassword = $credentials['password'];
    $encoder = $this->container->get('security.password_encoder');

    if (!$encoder->isPasswordValid($user, $plainPassword)){
        throw new BadCredentialsException();
    }else{
        $this->pass_error = 'no error';
    }
}

protected function getLoginUrl()
{
    return $this->container->get('router')
        ->generate('homepage');
}

protected function getDefaultSuccessRedirectUrl()
{
    return $this->container->get('router')
        ->generate('homepage');
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
    // AJAX! Return some JSON
    if ($request->isXmlHttpRequest()) {
        return new JsonResponse(
            array('userId' => $token->getUser()->getId(),
                'statut' => 'ok'
                )
        );
    }
    // for non-AJAX requests, return the normal redirect
    return parent::onAuthenticationSuccess($request, $token, $providerKey);
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    return new JsonResponse(
        array('message' => $exception->getMessageKey(),
            'statut' => 'error',
            'passerror' => $this->pass_error )

    );
}
</code>```

Excerpt of var_dump($user) on checkCredentials() as requested

```<code>object(UsedBundle\Entity\User)#329 (15) {
["id":"UsedBundle\Entity\User":private]=>
int(7)
["avatar":"UsedBundle\Entity\User":private]=>
string(11) "dsfdfafadfa"
["name":"UsedBundle\Entity\User":private]=>
string(9) "dfdffadfa"
["password":"UsedBundle\Entity\User":private]=>
string(64)   "jjuewij/sc9Af17i+ZXAUcrdiZX83HHMLjTNVSnJ34qGCp6BAxisVtjiG3Nm+uH5"
["plainPassword":"UsedBundle\Entity\User":private]=>
NULL
["email":"UsedBundle\Entity\User":private]=>
string(22) "myemail@gmail.com"
["phone":"UsedBundle\Entity\User":private]=>
string(12) "445454545454"
["roles":"UsedBundle\Entity\User":private]=>
string(9) "ROLE_USER"
["isActive":"UsedBundle\Entity\User":private]=>
bool(true)
</code>```

as requested, excerpts of var_dump($exception) on onAuthenticationFailure()

```<code>object(Symfony\Component\Security\Core\Exception\BadCredentialsException)#322 (8) {
["token":"Symfony\Component\Security\Core\Exception\AuthenticationException":private]=>
object(Symfony\Component\Security\Guard\Token\PreAuthenticationGuardToken)#61 (6) {
["credentials":"Symfony\Component\Security\Guard\Token\PreAuthenticationGuardToken":private]=>
array(2) {
  ["username"]=>
  string(22) "myemail@gmail.com"
  ["password"]=>
  string(8) "senha444"
}
["guardProviderKey":"Symfony\Component\Security\Guard\Token\PreAuthenticationGuardToken":private]=>
string(6) "main_0"
["user":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
NULL
["roles":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
array(0) {
}
["authenticated":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
bool(false)
["attributes":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
array(0) {
}
}
["message":protected]=>
string(0) ""
["string":"Exception":private]=>
string(0) ""
["code":protected]=>
int(0)
["file":protected]=>
string(78) "/Users/BAMAC/Sites/Symfony1/src/UsedBundle/Security  /FormLoginAuthenticator.php"
["line":protected]=>
int(58)
</code>```

答:
After Edwin put me in the right direction, I managed to get this to work. In reality the encryption was not the only issue.
The changes concern mainly the registration controller, where the code for password encryption was modified.
I also changed the form authenticator which is now based upon this

as the previous base indicated on my question is outdated.

Finally, Symfony are not very much friends with Ajax, so the Ajax URL was adapted to work for dev environment.

Here is the whole code:

security.yml

```<code>security:
encoders:
    UsedBundle\Entity\User:
        algorithm: bcrypt
providers:
    db_provider:
        entity:
            class: UsedBundle:User
            property: email
            manager_name: used

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false

    main:
        anonymous: ~
        provider: db_provider
        form_login:
            login_path: /
            username_parameter: _email
            check_path: /login_check
        guard:
            authenticators:
                - app.form_login_authenticator
        logout:
            path:   /logout
            target: /
access_control:
    - { path: ^/admin, roles: ROLE_ADMIN }
    - { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }
</code>```

Changes on registration controller:

```<code> if ($form->isSubmitted() && $form->isValid()) {
     $this->formData = $request->request->get($form->getName('user'));
     $this->plainPassword = $this->formData['plainPassword']['first'];
     $password = $this->get('security.password_encoder')
                ->encodePassword($user, $this->plainPassword );
  .....
</code>```

The new authenticator:

```<code>namespace UsedBundle\Security;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Security;

class FormLoginAuthenticator extends AbstractGuardAuthenticator
{
private $container;

public function __construct(ContainerInterface $container)
{
    $this->container = $container;
}

public function getCredentials(Request $request)
{
    if ($request->getPathInfo() != '/login_check') {
        return;
    }
    $email = $request->request->get('_email');
    $request->getSession()->set(Security::LAST_USERNAME, $email);
    $password = $request->request->get('_password');
    return array(
        'email' => $email,
        'password' => $password
    );
}

public function getUser($credentials, UserProviderInterface $userProvider)
{
    $email = $credentials['email'];
    return $this->user = $this->container
         ->get('doctrine')
         ->getRepository('UsedBundle:User', 'used')
         ->findOneByemail( $email );
}

public function checkCredentials($credentials, UserInterface $user)
{
    $plainPassword = $credentials['password'];
    $encoder = $this->container->get('security.password_encoder');
    if (!$encoder->isPasswordValid($user, $plainPassword)){
        throw new BadCredentialsException();
    }else{
        return true;
    }
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
    $session=$request->getSession();
    $session->set('seller_id', $token->getUser()->getId());
    $session->set('email', $token->getUser()->getEmail());
    return new JsonResponse(
        array(
            'userId' => $token->getUser()->getId(),
            'message' => $this->credentials,
            'statut' => 'ok',
            'roles' => $token->getUser()->getRoles(),
            'email' => $token->getUser()->getEmail(),
            )
    );

    // for non-AJAX requests, return the normal redirect
    //return parent::onAuthenticationSuccess($request, $token, $providerKey);
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    $data = array(
        'message' => strtr($exception->getMessageKey(), $exception->getMessageData())

        // or to translate this message
        // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
    );

    return new JsonResponse($data, Response::HTTP_FORBIDDEN);
}

/**
 * Called when authentication is needed, but it's not sent
 */
public function start(Request $request, AuthenticationException $authException = null)
{

    $data = array(
        'message' => 'Authentication Required'
    );

    return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);

}

public function supportsRememberMe()
{
    return false;
}

}
</code>```

The login controller:

```<code>namespace UsedBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class LoginController extends Controller
{
/**
 * @Route("/login", name="login")
 */
public function loginAction(Request $request)
{
    $helper = $this->get('security.authentication_utils');
    return $this->render('common/login.html.twig', array(
        // last username entered by the user (if any)
        'last_username' => $helper->getLastUsername(),
        // last authentication error (if any)
        'error' => $helper->getLastAuthenticationError(),
    ));

}

/**
 * @Route("/login_check", name="security_login_check")
 */
public function loginCheckAction()
{
    // will never be executed
}
}
</code>```

And this is how the Ajax url should look like while in dev:]

```<code>            $.ajax({
            url: "/app_dev.php/login_check",
            type: "POST",
            dataType: "json",
            data: str,
            success: function(data) {
    .....
</code>```

Body:
Most likely I am missing some silly stuff, but I spent quite some time on this, so any help is appreciated.

The authentication is based upon this tutorial

I am using bcrypt to encode the password and it seems that is working properly on user signup.

But when logging in it throws error below, even though the password entered is correct:

Invalid credentials.

I verified that the email and password arrive properly at the login authenticator ( login form is submitted via Ajax ).

Also the getUser() method seems to be doing its job of retrieving $user object and the corresponding password from the db.

The security.yml is set as follows:

security:
encoders:
    UsedBundle\Entity\User:
        algorithm: bcrypt

This is the registration controller:

namespace UsedBundle\Controller;

use UsedBundle\Form\UserType;
use UsedBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use UsedBundle\Service\sendEmail;

class RegistrationController extends Controller
{
/**
 * @Route("/inscription", name="inscription")
 */
public function registerAction(Request $request)
{
    $user = new User();
    $form = $this->createForm(UserType::class, $user);

    if ($request->isMethod('POST')) {
       $form->submit($request->request->get($form->getName('user')));
        if(!$form->isValid()){
           // handle invalid form
        }
        if ($form->isSubmitted() && $form->isValid()) {
            $password = $this->get('security.password_encoder')
                ->encodePassword($user, $user->getPlainPassword());
            $user->setPassword($password);
            $user->setUserKey( $user->getEmail() );
            $user->setUserKeyTime();
            $user->setDateReg();

            $em = $this->getDoctrine()->getManager('used');
            $em->persist($user);
            $em->flush();

            return new JsonResponse(array(
                'status' => 'ok',
                'message' => 'Success!')
            );
        }
    }else{
        return $this->render(
            'common/register.html.twig',
            array('form' => $form->createView())
        );
    }
}
}

The login form authenticator ( setup as a service ):

namespace UsedBundle\Security;

use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security;
use UsedBundle\Entity\User;
use UsedBundle\Repository\UserRepository;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;

class FormLoginAuthenticator extends AbstractFormLoginAuthenticator
{
private $container;

public function __construct(ContainerInterface $container)
{
    $this->container = $container;
}

public function getCredentials(Request $request)
{
    if ($request->getPathInfo() != '/login_check') {
        return;
    }
    $username = $request->request->get('_email');
    $request->getSession()->set(Security::LAST_USERNAME, $username);
    $password = $request->request->get('_password');
    return array(
        'username' => $username,
        'password' => $password
    );
}

public function getUser($credentials, UserProviderInterface $userProvider)
{
    $username = $credentials['username'];
    $user = $this->container
         ->get('doctrine')
         ->getRepository('UsedBundle:User', 'used')
         ->findOneByemail( $username );
    return $user;
}

public function checkCredentials($credentials, UserInterface $user)
{
    $plainPassword = $credentials['password'];
    $encoder = $this->container->get('security.password_encoder');

    if (!$encoder->isPasswordValid($user, $plainPassword)){
        throw new BadCredentialsException();
    }else{
        $this->pass_error = 'no error';
    }
}

protected function getLoginUrl()
{
    return $this->container->get('router')
        ->generate('homepage');
}

protected function getDefaultSuccessRedirectUrl()
{
    return $this->container->get('router')
        ->generate('homepage');
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
    // AJAX! Return some JSON
    if ($request->isXmlHttpRequest()) {
        return new JsonResponse(
            array('userId' => $token->getUser()->getId(),
                'statut' => 'ok'
                )
        );
    }
    // for non-AJAX requests, return the normal redirect
    return parent::onAuthenticationSuccess($request, $token, $providerKey);
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    return new JsonResponse(
        array('message' => $exception->getMessageKey(),
            'statut' => 'error',
            'passerror' => $this->pass_error )

    );
}

Excerpt of var_dump($user) on checkCredentials() as requested

object(UsedBundle\Entity\User)#329 (15) {
["id":"UsedBundle\Entity\User":private]=>
int(7)
["avatar":"UsedBundle\Entity\User":private]=>
string(11) "dsfdfafadfa"
["name":"UsedBundle\Entity\User":private]=>
string(9) "dfdffadfa"
["password":"UsedBundle\Entity\User":private]=>
string(64)   "jjuewij/sc9Af17i+ZXAUcrdiZX83HHMLjTNVSnJ34qGCp6BAxisVtjiG3Nm+uH5"
["plainPassword":"UsedBundle\Entity\User":private]=>
NULL
["email":"UsedBundle\Entity\User":private]=>
string(22) "myemail@gmail.com"
["phone":"UsedBundle\Entity\User":private]=>
string(12) "445454545454"
["roles":"UsedBundle\Entity\User":private]=>
string(9) "ROLE_USER"
["isActive":"UsedBundle\Entity\User":private]=>
bool(true)

as requested, excerpts of var_dump($exception) on onAuthenticationFailure()

object(Symfony\Component\Security\Core\Exception\BadCredentialsException)#322 (8) {
["token":"Symfony\Component\Security\Core\Exception\AuthenticationException":private]=>
object(Symfony\Component\Security\Guard\Token\PreAuthenticationGuardToken)#61 (6) {
["credentials":"Symfony\Component\Security\Guard\Token\PreAuthenticationGuardToken":private]=>
array(2) {
  ["username"]=>
  string(22) "myemail@gmail.com"
  ["password"]=>
  string(8) "senha444"
}
["guardProviderKey":"Symfony\Component\Security\Guard\Token\PreAuthenticationGuardToken":private]=>
string(6) "main_0"
["user":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
NULL
["roles":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
array(0) {
}
["authenticated":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
bool(false)
["attributes":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
array(0) {
}
}
["message":protected]=>
string(0) ""
["string":"Exception":private]=>
string(0) ""
["code":protected]=>
int(0)
["file":protected]=>
string(78) "/Users/BAMAC/Sites/Symfony1/src/UsedBundle/Security  /FormLoginAuthenticator.php"
["line":protected]=>
int(58)

Body:
After Edwin put me in the right direction, I managed to get this to work. In reality the encryption was not the only issue.
The changes concern mainly the registration controller, where the code for password encryption was modified.
I also changed the form authenticator which is now based upon this

as the previous base indicated on my question is outdated.

Finally, Symfony are not very much friends with Ajax, so the Ajax URL was adapted to work for dev environment.

Here is the whole code:

security.yml

security:
encoders:
    UsedBundle\Entity\User:
        algorithm: bcrypt
providers:
    db_provider:
        entity:
            class: UsedBundle:User
            property: email
            manager_name: used

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false

    main:
        anonymous: ~
        provider: db_provider
        form_login:
            login_path: /
            username_parameter: _email
            check_path: /login_check
        guard:
            authenticators:
                - app.form_login_authenticator
        logout:
            path:   /logout
            target: /
access_control:
    - { path: ^/admin, roles: ROLE_ADMIN }
    - { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }

Changes on registration controller:

 if ($form->isSubmitted() && $form->isValid()) {
     $this->formData = $request->request->get($form->getName('user'));
     $this->plainPassword = $this->formData['plainPassword']['first'];
     $password = $this->get('security.password_encoder')
                ->encodePassword($user, $this->plainPassword );
  .....

The new authenticator:

namespace UsedBundle\Security;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Security;

class FormLoginAuthenticator extends AbstractGuardAuthenticator
{
private $container;

public function __construct(ContainerInterface $container)
{
    $this->container = $container;
}

public function getCredentials(Request $request)
{
    if ($request->getPathInfo() != '/login_check') {
        return;
    }
    $email = $request->request->get('_email');
    $request->getSession()->set(Security::LAST_USERNAME, $email);
    $password = $request->request->get('_password');
    return array(
        'email' => $email,
        'password' => $password
    );
}

public function getUser($credentials, UserProviderInterface $userProvider)
{
    $email = $credentials['email'];
    return $this->user = $this->container
         ->get('doctrine')
         ->getRepository('UsedBundle:User', 'used')
         ->findOneByemail( $email );
}

public function checkCredentials($credentials, UserInterface $user)
{
    $plainPassword = $credentials['password'];
    $encoder = $this->container->get('security.password_encoder');
    if (!$encoder->isPasswordValid($user, $plainPassword)){
        throw new BadCredentialsException();
    }else{
        return true;
    }
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
    $session=$request->getSession();
    $session->set('seller_id', $token->getUser()->getId());
    $session->set('email', $token->getUser()->getEmail());
    return new JsonResponse(
        array(
            'userId' => $token->getUser()->getId(),
            'message' => $this->credentials,
            'statut' => 'ok',
            'roles' => $token->getUser()->getRoles(),
            'email' => $token->getUser()->getEmail(),
            )
    );

    // for non-AJAX requests, return the normal redirect
    //return parent::onAuthenticationSuccess($request, $token, $providerKey);
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    $data = array(
        'message' => strtr($exception->getMessageKey(), $exception->getMessageData())

        // or to translate this message
        // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
    );

    return new JsonResponse($data, Response::HTTP_FORBIDDEN);
}

/**
 * Called when authentication is needed, but it's not sent
 */
public function start(Request $request, AuthenticationException $authException = null)
{

    $data = array(
        'message' => 'Authentication Required'
    );

    return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);

}

public function supportsRememberMe()
{
    return false;
}

}

The login controller:

namespace UsedBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class LoginController extends Controller
{
/**
 * @Route("/login", name="login")
 */
public function loginAction(Request $request)
{
    $helper = $this->get('security.authentication_utils');
    return $this->render('common/login.html.twig', array(
        // last username entered by the user (if any)
        'last_username' => $helper->getLastUsername(),
        // last authentication error (if any)
        'error' => $helper->getLastAuthenticationError(),
    ));

}

/**
 * @Route("/login_check", name="security_login_check")
 */
public function loginCheckAction()
{
    // will never be executed
}
}

And this is how the Ajax url should look like while in dev:]

            $.ajax({
            url: "/app_dev.php/login_check",
            type: "POST",
            dataType: "json",
            data: str,
            success: function(data) {
    .....


问:
How to make AMP accordion expanded and collapsed smoothly
I do not find, there is any option or event to make the feel of accordion as my expectation in AMP's accordion library. However, I have done many changes using jquery but now I need to expand and collapse item smoothly. Is there any way to do this.</p>

答:
You may find this thread helpful to solve your issue. It stated that:

Currently there is no animation for the expand/collapse action. This means that it may be difficult for the user to track the behavior of the interface if multiple items are collapsing at the same time that their target element is expanding.

There is no scrolling adjustment when amp-accordion closes or opens, which means if a large enough (or large enough set of) amp-accordion(s) closes above the current viewport, the content inside the viewport could shift dramatically (even entirely out of view)

Needs some way for multiple amp-accordion elements to communicate with each other (could be a parent element with an attribute something like "auto-collapse-children")

Also, check this Content Collapse jQuery plugin to smoothly collapse and expand content by clicking the panel header, which acts as an accordion.