问:
Next row or id gets deleted from table and database
I have a table of chapters for which I have a delete button for each one. When I am clicking on delete button if the table has more records further the last row of the table gets deleted or the id of row getting pass to the database is wrong.

```<code><!doctype html>
<html>
<head>
<title>Files</title>
</head>
<body>

<form method="post" action="deleteFiles.php" enctype="multipart/form-data">

<style>
td {
    text-align: center;
    border: 1px solid black;
    border-collapse: collapse;
}
</style>

Select rank :
<select name="type" id="type" onchange="this.form.submit()">

<?php if(isset($_POST['type']))
{ ?>
<option value="1"  <?php echo($_POST['type']==1?"selected":"");?>>SSgt</option>

<option value="2"  <?php echo($_POST['type']==2?"selected":"");?>>TSgt</option>
<option value="3" <?php echo($_POST['type']==3?"selected":"");?>>MSgt</option>
</select>
<br><br>
<?php
}
    else
    {
    ?>
    <option value="1">SSgt</option>
<option value="2">TSgt</option>
<option value="3">MSgt</option>
</select>
<br><br>
    <?php
    }
    ?>

<table id="example" style="width:60%">
    <tr>
    <th><font size="5">Files</font></th>
  </tr>

<?php

?>

<?php

ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);

    $dbh = new PDO('mysql:host=174;dbname=airman', 'airman', 'airma');

if(isset($_POST['action'])) {

     $stmt = $dbh->prepare("DELETE FROM `files` WHERE `id`= " . $_POST['id']);

    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if(count($result) > 0)
        {
          echo 'row deleted';
        }
        else{
            echo 'row could not delete';
        }
    }

if(isset($_POST['type']))
{
    $stmt = $dbh->prepare("SELECT * FROM files where type = :type");
    $stmt->bindParam("type", $_POST['type']);
    $stmt->execute();
    $results = $stmt->fetchall(PDO::FETCH_ASSOC);

}
    else{
        $stmt = $dbh->prepare("SELECT * FROM files");
    $stmt->execute();
    $results = $stmt->fetchall(PDO::FETCH_ASSOC);

}

    foreach($results as $file)

    {
    ?>
     <tr>
    <td><?php echo $file['title'];?></td>
    <td><input type="submit" id="<?php echo $file['id']?>" name="action" value="Delete">
        <input type="submit" id="<?php echo $chap['id']?>" name="edit"  value="Edit">
    <input type="hidden" name="id" value="<?php echo $file['id']?>" />

  </tr>
    <?php
}
?>
</table>

</body>

</form>
</html>
<?php
?>
</code>```

EDIT:

```<code>    <!doctype html>
<html>
<head>
<title>Video Files</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>

    $('#form').submit(function(ev) {

        $('<input type="hidden">').attr({ name: 'type', value: $("select[name='type']").val() }).appendTo($(event.currentTarget));
    }

    </script>
<form id="form" method="post" action="deleteVideoFiles.php" enctype="multipart/form-data">

<style>
td {
    text-align: center;
    border: 1px solid black;
    border-collapse: collapse;
}
</style>

    <br><br><br><br>
Select rank :
<select name="type" id="type" onchange="this.form.submit()">

<?php if(isset($_POST['type']))
{
  /*  session_start();

    $_SESSION['vidType'] = $_POST['type'];*/

    ?>
    <option value="">Select rank...</option>
    <option value="1"  <?php echo($_POST['type']==1?"selected":"");?>>SSgt</option>

    <option value="2"  <?php echo($_POST['type']==2?"selected":"");?>>TSgt</option>
    <option value="3" <?php echo($_POST['type']==3?"selected":"");?>>MSgt</option>
    </select>
    <br><br>
    <?php
}
else
{
/*    session_start();

    $_SESSION['vidType'] = $_POST['type'];*/

    ?>
    <option value="">Select rank...</option>
    <option value="1">SSgt</option>
    <option value="2">TSgt</option>
    <option value="3">MSgt</option>
    </select>
    <br><br>
    <?php
}
    ?>

<table id="example" style="width:80%">
    <tr>
        <th><font size="5">Video Files</font></th>
    </tr>

    <?php

    ?>

    <?php

    ini_set('display_errors', 1);
    error_reporting(1);
    ini_set('error_reporting', E_ALL);

    $dbh = new PDO('mysql:host=174.75.54;dbname=handbook', 'airman', 'airman12345');
  //  $dbh = new PDO('mysql:host=localhost;dbname=handbook', 'siddhi', 'siddhi');

    if(isset($_POST['action'])) {

        $stmt = $dbh->prepare("DELETE FROM `videos` WHERE `id`= :id");
        $stmt->bindParam("id", $_POST['id']);
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if(count($result) < 0)
        {
            echo 'row could not delete';
        }
    }

    if(isset($_POST['type']))
    {

        if(!empty($_POST['type']))

        {

            $stmt = $dbh->prepare("SELECT * FROM `videos` where type = :type");
            $stmt->bindParam("type", $_POST['type']);
            $stmt->execute();
            $results = $stmt->fetchall(PDO::FETCH_ASSOC);
            if(count($results) == 0)
            {
                echo 'No records available.';
            }
        }
        else{

            echo 'empty type';
            $stmt = $dbh->prepare("SELECT * FROM `videos`");
            $stmt->execute();
            $results = $stmt->fetchall(PDO::FETCH_ASSOC);
            if(count($results) == 0)
            {
                echo 'No records available.';
            }

        }
    }
  /*  elseif(!empty($_SESSION['vidType'])){

        echo $_SESSION['vidType'];
        echo $_POST['type'];

            $stmt = $dbh->prepare("SELECT * FROM `videos` where type = :type");
            $stmt->bindParam("type", $_SESSION['vidType']);
            $stmt->execute();
            $results = $stmt->fetchall(PDO::FETCH_ASSOC);
            if(count($results) == 0)
            {
                echo 'No records available.';
            }
    }*/

    else{

            $stmt = $dbh->prepare("SELECT * FROM `videos`");
            $stmt->execute();
            $results = $stmt->fetchall(PDO::FETCH_ASSOC);
            if(count($results) == 0)
            {
                echo 'No records available.';
            }
    }
    foreach($results as $file)

    {
        ?>
        <tr>
            <td><?php echo $file['title'];?></td>
            <td>
          <form method="post" action="deleteVideoFiles.php" enctype="multipart/form-data">

              <input type="submit" id="<?php echo $file['id']?>" name="action" value="Delete"><br>
                    <input type="hidden" name="id" value="<?php echo $file['id']?>"/>
             </form> <!-- notice how we built different form for every id-->
            </td>
        </tr>
        <?php
    }
    ?>
</table>

</body>

</form>
</html>
<?php
?>
</code>```

I am sending the id of chapter in for each loop, What is the problem here? Please help thank you..

答:
That is because building the form element this way is going to result for many id inputs inside the same form. something like this

```<code><form>
    <input name="id" value="1">
    <input name="id" value="2">
</form>
</code>```

on your server code the php will set $_POST['id'] to the last one which in this case 2. that is why when press delete button and submit the form you delete the next , or last id you have built in your form

If you need your code work the way you want you have to put every id in different form element, Or you will need some javascript work.

I prefer building different form for each record. replace that code

```<code>foreach($results as $file)
{
?>
<tr>
    <td><?php echo $file['title'];?></td>
    <td><input type="submit" id="<?php echo $file['id']?>" name="action" value="Delete">
    <input type="submit" id="<?php echo $chap['id']?>" name="edit"  value="Edit">
    <input type="hidden" name="id" value="<?php echo $file['id']?>" />
</tr>
<?php
    }
?>
</code>```

with something like this

```<code>foreach($results as $file)
{
?>
<tr>
    <td><?php echo $file['title'];?></td>
    <td>
        <form method="post" action="deleteFiles.php" enctype="multipart/form-data">
            <input type="submit" id="<?php echo $file['id']?>" name="action" value="Delete">
            <input type="submit" id="<?php echo $chap['id']?>" name="edit"  value="Edit">
            <input type="hidden" name="id" value="<?php echo $file['id']?>" />
        </form> <!-- notice how we built different form for every id-->
    </td>
</tr>
<?php
    }
?>
</code>```

Another note :

```<code>$stmt = $dbh->prepare("DELETE FROM `files` WHERE `id`= " . $_POST['id']);
</code>```

using prepared statements this way makes you still vulnerable to SQL injection.

EDIT(reaction to comments)
to send another input along with the delete forms to the PHP server. you can  use JavaScript for that.

1- add that class deleteForm to the delete forms so we can catch those forms and bind to only them.

```<code><form method="post" class="deleteForm" action="deleteVideoFiles.php" enctype="multipart/form-data">
</code>```

2- edit that script tag in your document

```<code><script>
    $(function (){
        $('form.deleteForm').submit(function(ev) {
            $('<input type="hidden">').attr({ name: 'type', value: $("select[name='type']").val() }).appendTo($(ev.currentTarget));
        });
    })

</script>
</code>```

Body:
I have a table of chapters for which I have a delete button for each one. When I am clicking on delete button if the table has more records further the last row of the table gets deleted or the id of row getting pass to the database is wrong.

<!doctype html>

<title>Files</title>

<form method="post" action="deleteFiles.php" enctype="multipart/form-data">

Select rank :
<select name="type" id="type" onchange="this.form.submit()">

<?php if(isset($_POST['type']))
{ ?>
<option value="1"  <?php echo($_POST['type']==1?"selected":"");?>>SSgt</option>

<option value="2"  <?php echo($_POST['type']==2?"selected":"");?>>TSgt</option>
<option value="3" <?php echo($_POST['type']==3?"selected":"");?>>MSgt</option>
</select>

<?php
}
    else
    {
    ?>
    <option value="1">SSgt</option>
<option value="2">TSgt</option>
<option value="3">MSgt</option>
</select>

    <?php
    }
    ?>

    Files

<?php

?>

<?php

ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);

    $dbh = new PDO('mysql:host=174;dbname=airman', 'airman', 'airma');

if(isset($_POST['action'])) {

     $stmt = $dbh->prepare("DELETE FROM `files` WHERE `id`= " . $_POST['id']);

    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if(count($result) > 0)
        {
          echo 'row deleted';
        }
        else{
            echo 'row could not delete';
        }
    }

if(isset($_POST['type']))
{
    $stmt = $dbh->prepare("SELECT * FROM files where type = :type");
    $stmt->bindParam("type", $_POST['type']);
    $stmt->execute();
    $results = $stmt->fetchall(PDO::FETCH_ASSOC);

}
    else{
        $stmt = $dbh->prepare("SELECT * FROM files");
    $stmt->execute();
    $results = $stmt->fetchall(PDO::FETCH_ASSOC);

}

    foreach($results as $file)

    {
    ?>

    <?php echo $file['title'];?>
    <input type="submit" id="<?php echo $file['id']?>" name="action" value="Delete">
        <input type="submit" id="<?php echo $chap['id']?>" name="edit"  value="Edit">
    <input type="hidden" name="id" value="<?php echo $file['id']?>" />

    <?php
}
?>

</form>

<?php
?>

EDIT:

    <!doctype html>

<title>Video Files</title>

<form id="form" method="post" action="deleteVideoFiles.php" enctype="multipart/form-data">

Select rank :
<select name="type" id="type" onchange="this.form.submit()">

<?php if(isset($_POST['type']))
{
  /*  session_start();

    $_SESSION['vidType'] = $_POST['type'];*/

    ?>
    <option value="">Select rank...</option>
    <option value="1"  <?php echo($_POST['type']==1?"selected":"");?>>SSgt</option>

    <option value="2"  <?php echo($_POST['type']==2?"selected":"");?>>TSgt</option>
    <option value="3" <?php echo($_POST['type']==3?"selected":"");?>>MSgt</option>
    </select>

    <?php
}
else
{
/*    session_start();

    $_SESSION['vidType'] = $_POST['type'];*/

    ?>
    <option value="">Select rank...</option>
    <option value="1">SSgt</option>
    <option value="2">TSgt</option>
    <option value="3">MSgt</option>
    </select>

    <?php
}
    ?>

        Video Files

    <?php

    ?>

    <?php

    ini_set('display_errors', 1);
    error_reporting(1);
    ini_set('error_reporting', E_ALL);

    $dbh = new PDO('mysql:host=174.75.54;dbname=handbook', 'airman', 'airman12345');
  //  $dbh = new PDO('mysql:host=localhost;dbname=handbook', 'siddhi', 'siddhi');

    if(isset($_POST['action'])) {

        $stmt = $dbh->prepare("DELETE FROM `videos` WHERE `id`= :id");
        $stmt->bindParam("id", $_POST['id']);
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if(count($result) < 0)
        {
            echo 'row could not delete';
        }
    }

    if(isset($_POST['type']))
    {

        if(!empty($_POST['type']))

        {

            $stmt = $dbh->prepare("SELECT * FROM `videos` where type = :type");
            $stmt->bindParam("type", $_POST['type']);
            $stmt->execute();
            $results = $stmt->fetchall(PDO::FETCH_ASSOC);
            if(count($results) == 0)
            {
                echo 'No records available.';
            }
        }
        else{

            echo 'empty type';
            $stmt = $dbh->prepare("SELECT * FROM `videos`");
            $stmt->execute();
            $results = $stmt->fetchall(PDO::FETCH_ASSOC);
            if(count($results) == 0)
            {
                echo 'No records available.';
            }

        }
    }
  /*  elseif(!empty($_SESSION['vidType'])){

        echo $_SESSION['vidType'];
        echo $_POST['type'];

            $stmt = $dbh->prepare("SELECT * FROM `videos` where type = :type");
            $stmt->bindParam("type", $_SESSION['vidType']);
            $stmt->execute();
            $results = $stmt->fetchall(PDO::FETCH_ASSOC);
            if(count($results) == 0)
            {
                echo 'No records available.';
            }
    }*/

    else{

            $stmt = $dbh->prepare("SELECT * FROM `videos`");
            $stmt->execute();
            $results = $stmt->fetchall(PDO::FETCH_ASSOC);
            if(count($results) == 0)
            {
                echo 'No records available.';
            }
    }
    foreach($results as $file)

    {
        ?>

            <?php echo $file['title'];?>

          <form method="post" action="deleteVideoFiles.php" enctype="multipart/form-data">

              <input type="submit" id="<?php echo $file['id']?>" name="action" value="Delete">

                    <input type="hidden" name="id" value="<?php echo $file['id']?>"/>
             </form>

        <?php
    }
    ?>

</form>

<?php
?>

I am sending the id of chapter in for each loop, What is the problem here? Please help thank you..

Body:
That is because building the form element this way is going to result for many id inputs inside the same form. something like this

<form>
    <input name="id" value="1">
    <input name="id" value="2">
</form>

on your server code the php will set $_POST['id'] to the last one which in this case 2. that is why when press delete button and submit the form you delete the next , or last id you have built in your form

If you need your code work the way you want you have to put every id in different form element, Or you will need some javascript work.

I prefer building different form for each record. replace that code

foreach($results as $file)
{
?>
<tr>
    <td><?php echo $file['title'];?></td>
    <td><input type="submit" id="<?php echo $file['id']?>" name="action" value="Delete">
    <input type="submit" id="<?php echo $chap['id']?>" name="edit"  value="Edit">
    <input type="hidden" name="id" value="<?php echo $file['id']?>" />
</tr>
<?php
    }
?>

with something like this

foreach($results as $file)
{
?>
<tr>
    <td><?php echo $file['title'];?></td>
    <td>
        <form method="post" action="deleteFiles.php" enctype="multipart/form-data">
            <input type="submit" id="<?php echo $file['id']?>" name="action" value="Delete">
            <input type="submit" id="<?php echo $chap['id']?>" name="edit"  value="Edit">
            <input type="hidden" name="id" value="<?php echo $file['id']?>" />
        </form> <!-- notice how we built different form for every id-->
    </td>
</tr>
<?php
    }
?>

Another note :

$stmt = $dbh->prepare("DELETE FROM `files` WHERE `id`= " . $_POST['id']);

using prepared statements this way makes you still vulnerable to SQL injection.

EDIT(reaction to comments)
to send another input along with the delete forms to the PHP server. you can  use JavaScript for that.

1- add that class deleteForm to the delete forms so we can catch those forms and bind to only them.

<form method="post" class="deleteForm" action="deleteVideoFiles.php" enctype="multipart/form-data">

2- edit that script tag in your document

<script>
    $(function (){
        $('form.deleteForm').submit(function(ev) {
            $('<input type="hidden">').attr({ name: 'type', value: $("select[name='type']").val() }).appendTo($(ev.currentTarget));
        });
    })

</script>


来源: stackexchange

问:
How to make p:panel collapsible by clicking on header?
I'm using PrimeFaces 3.4 collapsible panels. The problem with actual solution is that panel is toggled via clicking in small button on the right. It is not very ergonomic and the user would expect the toggling via clicking anywhere on header.

This is what I want to implement: trigger the toggle via clicking on header and remove the toggle button. This is what I've written:

```<code>$('.ui-panel-titlebar').each(function(){
    var header = $(this);
    var widgetId = 'widget_' + header.attr('id').replace(/:/g, '_').replace(/_header$/, '');
    header.css('cursor', 'pointer');
    var toggler = header.find('a[id$=_toggler]');
    toggler.remove();
    header.click(function(){
        window[widgetId].toggle();
    });
});
</code>```

But I don't like that solution, because first I'm guessing the JavaScript widget Id, and second, I'm removing the rendered toggle button from DOM tree and I would prefer it not to be rendered at all.

Is there a way to achieve the same effect in more elegant way without writing too many code (so, without rewriting the p:panel)? Using extensions based on same licence as PrimeFaces (commerce-friendly) is acceptable as solution.

答:
I wanted to have panels that optionally are togglable by clicking on the header, and also to have the icon at the left side of the panel. I chose to create a custom tag to do so.

my.taglib.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib xmlns="http://java.sun.com/xml/ns/javaee"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
                version="2.0">
  <namespace>http://my.com/jsf/facelets</namespace>
  <tag>
    <tag-name>togglePanel</tag-name>
    <source>tags/togglePanel.xhtml</source>
    <attribute>
      <name>header</name>
      <required>true</required>
      <type>java.lang.String</type>
    </attribute>
    <attribute>
      <name>collapsed</name>
      <required>false</required>
      <type>boolean</type>
    </attribute>
  </tag>
</facelet-taglib>
</code>```

togglePanel.xhtml:

```<code><ui:composition xmlns="http://www.w3.org/1999/xhtml"
                xmlns:c="http://java.sun.com/jsp/jstl/core"
                xmlns:f="http://java.sun.com/jsf/core"
                xmlns:h="http://java.sun.com/jsf/html"
                xmlns:ui="http://java.sun.com/jsf/facelets"
                xmlns:p="http://primefaces.org/ui">

  <c:set var="collapsed" value="#{not empty collapsed and collapsed}" />

  <p:panel toggleable="true" collapsed="#{collapsed}" class="myToggleable">
    <f:facet name="header">
      <a href="#" onclick="document.getElementById(this.parentNode.parentNode.id.replace('_header', '_toggler')).click()"><h:outputText
          value="#{header}"/></a>
    </f:facet>
    <ui:insert />
  </p:panel>

</ui:composition>
</code>```

Style sheet:

```<code>.ui-panel.myToggleable .ui-panel-titlebar {
  position: relative; padding: .5em 1em .3em 2.5em;
}
.ui-panel.myToggleable .ui-panel-title,
.ui-panel.myToggleable .ui-panel-title a {
  display: block; text-decoration: none;
}
.ui-panel.myToggleable .ui-panel-titlebar-icon,
.ui-panel.myToggleable .ui-panel-titlebar-icon:hover {
  position: absolute; left: 10px; top: 10px; margin: 0;
}
</code>```

Now you can use it like this in your XHTML files:

```<code><my:togglePanel header="Header" collapsed="false">
  ...
</my:togglePanel>
</code>```

You should add the following namespace though: xmlns:my="http://my.com/jsf/facelets".

This has been tested using PrimeFaces 6.0.

ContentLicense: CC BY-SA 3.0

Body:
I'm using PrimeFaces 3.4 collapsible panels. The problem with actual solution is that panel is toggled via clicking in small button on the right. It is not very ergonomic and the user would expect the toggling via clicking anywhere on header.

This is what I want to implement: trigger the toggle via clicking on header and remove the toggle button. This is what I've written:

$('.ui-panel-titlebar').each(function(){
    var header = $(this);
    var widgetId = 'widget_' + header.attr('id').replace(/:/g, '_').replace(/_header$/, '');
    header.css('cursor', 'pointer');
    var toggler = header.find('a[id$=_toggler]');
    toggler.remove();
    header.click(function(){
        window[widgetId].toggle();
    });
});

But I don't like that solution, because first I'm guessing the JavaScript widget Id, and second, I'm removing the rendered toggle button from DOM tree and I would prefer it not to be rendered at all.

Is there a way to achieve the same effect in more elegant way without writing too many code (so, without rewriting the p:panel)? Using extensions based on same licence as PrimeFaces (commerce-friendly) is acceptable as solution.

Body:
I wanted to have panels that optionally are togglable by clicking on the header, and also to have the icon at the left side of the panel. I chose to create a custom tag to do so.

my.taglib.xml:

<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib xmlns="http://java.sun.com/xml/ns/javaee"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
                version="2.0">
  <namespace>http://my.com/jsf/facelets</namespace>
  <tag>
    <tag-name>togglePanel</tag-name>
    <source>tags/togglePanel.xhtml</source>
    <attribute>
      <name>header</name>
      <required>true</required>
      <type>java.lang.String</type>
    </attribute>
    <attribute>
      <name>collapsed</name>
      <required>false</required>
      <type>boolean</type>
    </attribute>
  </tag>
</facelet-taglib>

togglePanel.xhtml:

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
                xmlns:c="http://java.sun.com/jsp/jstl/core"
                xmlns:f="http://java.sun.com/jsf/core"
                xmlns:h="http://java.sun.com/jsf/html"
                xmlns:ui="http://java.sun.com/jsf/facelets"
                xmlns:p="http://primefaces.org/ui">

  <c:set var="collapsed" value="#{not empty collapsed and collapsed}" />

  <p:panel toggleable="true" collapsed="#{collapsed}" class="myToggleable">
    <f:facet name="header">
      <a href="#" onclick="document.getElementById(this.parentNode.parentNode.id.replace('_header', '_toggler')).click()"><h:outputText
          value="#{header}"/></a>
    </f:facet>
    <ui:insert />
  </p:panel>

</ui:composition>

Style sheet:

.ui-panel.myToggleable .ui-panel-titlebar {
  position: relative; padding: .5em 1em .3em 2.5em;
}
.ui-panel.myToggleable .ui-panel-title,
.ui-panel.myToggleable .ui-panel-title a {
  display: block; text-decoration: none;
}
.ui-panel.myToggleable .ui-panel-titlebar-icon,
.ui-panel.myToggleable .ui-panel-titlebar-icon:hover {
  position: absolute; left: 10px; top: 10px; margin: 0;
}

Now you can use it like this in your XHTML files:

<my:togglePanel header="Header" collapsed="false">
  ...
</my:togglePanel>

You should add the following namespace though: xmlns:my="http://my.com/jsf/facelets".

This has been tested using PrimeFaces 6.0.


问:
Devise user created with Rails generator cannot sign in
I'm working on a Rails Engine which will depend on Devise.

I created an installer using Rails generator which you can find here. The installer creates the first credentials in order to access the administration panel later.

The problem is that I cannot sign in with those credentials. Weirdly then, if I delete the account and recreate it via Rails console, they do work. I think that's due to something happening during the installer.

Here a snippet of it:

# Binda installer generator ...

def setup_devise
  return if Rails.env.production?
  # Copy the initilializer on the application folder
  template 'config/initializers/devise.rb'
  # Add secret key
  inject_into_file 'config/initializers/devise.rb', after: "config.secret_key = '" do
    SecureRandom.hex(64)
  end
  # Add pepper
  inject_into_file 'config/initializers/devise.rb', after: "config.pepper = '" do
    SecureRandom.hex(64)
  end
  # some other code for mailer ...
end

def create_credentials
  @username = ask("What's your email? ['mail@domain.com']").presence || 'mail@domain.com'
  @password = ask("What's your password? ['password']").presence || 'password'
  Binda::User.create( email: @username, password: @password, password_confirmation: @password )

# Binda installer generator continue ...
```

Here the full code.

More info

I found out that even if I modify devise.rb file the new configuration is not loaded until the end of the installer. This means the new salt/pepper isn't considered while creating the first user. How can I reload it before running the create_credentials method?

答:
Sorted!

The problem is that if you add salt/pepper configuration to the devise.rb of your application you need to reload the environment before being able to create a user with the new settings.

To do that I moved the user creation into a task. This way the installer to reload the environment (and Devise config as weel) and is able to set the encrypted password correctly.

Installer

```<code># lib/generators/myEngine/install/install_generator.rb
def create_credentials
  rake 'binda_create_initial_user'
end
</code>```

Task

```<code># lib/tasks/binda.rake
desc "Create initial user"
task :binda_create_initial_user => :environment do
  username = 'mail@domain.com'
  password = 'password'
  Binda::User.create!( email: username, password: password, password_confirmation: password )
end
</code>```

If you want to keep asking for mail and password:

# lib/tasks/binda.rake
desc "Create first user"
task :binda_create_initial_user => :environment do
    STDOUT.puts "What is your email? [mail@domain.com]"
  username = STDIN.gets.strip
  username = 'mail@domain.com' if username.blank?
    STDOUT.puts "What is your password? [password]"
  password = STDIN.gets.strip
  password = 'password' if password.blank?
  Binda::User.create!( email: username, password: password, password_confirmation: password )
end
```

Body:
I'm working on a Rails Engine which will depend on Devise.

I created an installer using Rails generator which you can find here. The installer creates the first credentials in order to access the administration panel later.

The problem is that I cannot sign in with those credentials. Weirdly then, if I delete the account and recreate it via Rails console, they do work. I think that's due to something happening during the installer.

Here a snippet of it:

# Binda installer generator ...

def setup_devise
  return if Rails.env.production?
  # Copy the initilializer on the application folder
  template 'config/initializers/devise.rb'
  # Add secret key
  inject_into_file 'config/initializers/devise.rb', after: "config.secret_key = '" do
    SecureRandom.hex(64)
  end
  # Add pepper
  inject_into_file 'config/initializers/devise.rb', after: "config.pepper = '" do
    SecureRandom.hex(64)
  end
  # some other code for mailer ...
end

def create_credentials
  @username = ask("What's your email? ['mail@domain.com']").presence || 'mail@domain.com'
  @password = ask("What's your password? ['password']").presence || 'password'
  Binda::User.create( email: @username, password: @password, password_confirmation: @password )

# Binda installer generator continue ...

Here the full code.

More info

I found out that even if I modify devise.rb file the new configuration is not loaded until the end of the installer. This means the new salt/pepper isn't considered while creating the first user. How can I reload it before running the create_credentials method?

Body:
Sorted!

The problem is that if you add salt/pepper configuration to the devise.rb of your application you need to reload the environment before being able to create a user with the new settings.

To do that I moved the user creation into a task. This way the installer to reload the environment (and Devise config as weel) and is able to set the encrypted password correctly.

Installer

# lib/generators/myEngine/install/install_generator.rb
def create_credentials
  rake 'binda_create_initial_user'
end

Task

# lib/tasks/binda.rake
desc "Create initial user"
task :binda_create_initial_user => :environment do
  username = 'mail@domain.com'
  password = 'password'
  Binda::User.create!( email: username, password: password, password_confirmation: password )
end

If you want to keep asking for mail and password:

# lib/tasks/binda.rake
desc "Create first user"
task :binda_create_initial_user => :environment do
    STDOUT.puts "What is your email? [mail@domain.com]"
  username = STDIN.gets.strip
  username = 'mail@domain.com' if username.blank?
    STDOUT.puts "What is your password? [password]"
  password = STDIN.gets.strip
  password = 'password' if password.blank?
  Binda::User.create!( email: username, password: password, password_confirmation: password )
end


问:
Open pdf file with Django
I'm trying to merge two pdf files in Django with PyPDF2 and ReportLab. My view is as follows:

```<code>@login_required
def export_to_pdf(request, user_id):
    member = Member.objects.filter(user_id=user_id).values('user_id',
                                                           'user__first_name',
                                                           'user__last_name',
                                                           'company_name',
                                                           'vat_number',
                                                           'address',
                                                           'postcode',
                                                           'city',
                                                           'user__email',
                                                           'telephone',
                                                           'subscription__type__name',
                                                           'subscription__type__limit',
                                                           ).annotate(num_calculations=Count('user__calculations'))[0]

    company_address = "{}, {} {}".format(member['address'], member['postcode'], member['city'])
    buffer = BytesIO()

    # Create the PDF object, using the BytesIO object as its "file."
    p = canvas.Canvas(buffer, pagesize=A4)
    p.setFont('Helvetica-Bold', 8)
    p.drawString(70, 765, "{}".format(member['company_name']))

    p.drawString(70, 731, "{}".format(company_address))
    p.drawString(70, 714, "{}".format(member['telephone']))
    p.drawString(335, 697, "{}".format(member['vat_number']))

    p.drawString(335, 697, "{}".format(member['vat_number']))
    p.save()

    buffer.seek(0)
    new_pdf = PdfFileReader(buffer)
    existing_pdf = PdfFileReader(open('master/files/file.pdf', "rb"))

    page = existing_pdf.getPage(0)
    page.mergePage(new_pdf.getPage(0))

    output = PdfFileWriter()
    output.addPage(page)
    output_stream = open("master/files/new_file.pdf", "wb")
    output.write(output_stream)
    output_stream.close()

    with open('master/files/new_file.pdf', 'r', encoding="Latin-1") as pdf:
        response = HttpResponse(pdf.read(), content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=some_file.pdf'
        return response
</code>```

The project tree is as follows :

Thus, I create new file and then I open an existing file file.pdf, and then I merge those two files. At the end I create a file for output new_file.pdf.

That works fine, but the problem is with the file which is returned.
If I run export_to_pdf function I should get new_file.pdf. I get that file, but the content of that file is only what I created with

```<code>p = canvas.Canvas(buffer, pagesize=A4)
p.setFont('Helvetica-Bold', 8)
p.drawString(70, 765, "{}".format(member['company_name']))

p.drawString(70, 731, "{}".format(company_address))
p.drawString(70, 714, "{}".format(member['telephone']))
p.drawString(335, 697, "{}".format(member['vat_number']))

p.drawString(335, 697, "{}".format(member['vat_number']))
p.save()
</code>```

There is no content of the merged file file.pdf.

But If I open the new_file.pdf direct with clicking on it, I get everything like it should be.

Any advice what I do wrong?

答:
I solved it. In case someone else has the same problem.

I just changed one line

```<code>with open('master/files/new_file.pdf', 'rb') as pdf:
</code>```

Thus instead of r I added rb. And then also the encoding was no more needed.

Title: Open pdf file with Django

Body:
I'm trying to merge two pdf files in Django with PyPDF2 and ReportLab. My view is as follows:

@login_required
def export_to_pdf(request, user_id):
    member = Member.objects.filter(user_id=user_id).values('user_id',
                                                           'user__first_name',
                                                           'user__last_name',
                                                           'company_name',
                                                           'vat_number',
                                                           'address',
                                                           'postcode',
                                                           'city',
                                                           'user__email',
                                                           'telephone',
                                                           'subscription__type__name',
                                                           'subscription__type__limit',
                                                           ).annotate(num_calculations=Count('user__calculations'))[0]

    company_address = "{}, {} {}".format(member['address'], member['postcode'], member['city'])
    buffer = BytesIO()

    # Create the PDF object, using the BytesIO object as its "file."
    p = canvas.Canvas(buffer, pagesize=A4)
    p.setFont('Helvetica-Bold', 8)
    p.drawString(70, 765, "{}".format(member['company_name']))

    p.drawString(70, 731, "{}".format(company_address))
    p.drawString(70, 714, "{}".format(member['telephone']))
    p.drawString(335, 697, "{}".format(member['vat_number']))

    p.drawString(335, 697, "{}".format(member['vat_number']))
    p.save()

    buffer.seek(0)
    new_pdf = PdfFileReader(buffer)
    existing_pdf = PdfFileReader(open('master/files/file.pdf', "rb"))

    page = existing_pdf.getPage(0)
    page.mergePage(new_pdf.getPage(0))

    output = PdfFileWriter()
    output.addPage(page)
    output_stream = open("master/files/new_file.pdf", "wb")
    output.write(output_stream)
    output_stream.close()

    with open('master/files/new_file.pdf', 'r', encoding="Latin-1") as pdf:
        response = HttpResponse(pdf.read(), content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=some_file.pdf'
        return response

The project tree is as follows :

Thus, I create new file and then I open an existing file file.pdf, and then I merge those two files. At the end I create a file for output new_file.pdf.

That works fine, but the problem is with the file which is returned.
If I run export_to_pdf function I should get new_file.pdf. I get that file, but the content of that file is only what I created with

p = canvas.Canvas(buffer, pagesize=A4)
p.setFont('Helvetica-Bold', 8)
p.drawString(70, 765, "{}".format(member['company_name']))

p.drawString(70, 731, "{}".format(company_address))
p.drawString(70, 714, "{}".format(member['telephone']))
p.drawString(335, 697, "{}".format(member['vat_number']))

p.drawString(335, 697, "{}".format(member['vat_number']))
p.save()

There is no content of the merged file file.pdf.

But If I open the new_file.pdf direct with clicking on it, I get everything like it should be.

Any advice what I do wrong?

Body:
I solved it. In case someone else has the same problem.

I just changed one line

with open('master/files/new_file.pdf', 'rb') as pdf:

Thus instead of r I added rb. And then also the encoding was no more needed.


问:
Generic function to create controls at runtime
I want to add controls to my aspx web form at runtime using C#.

I would like to write a generic function which will create any type of control (Eg: textbox, lable, button etc).

Any ideas please.
Thanks
BB

答:
You can do this, as long as the control types you want to use all have a default constructor. </p>

```<code>T AddControl<T>() where T : WebControl, new()
{
    T ctrl = new T();
    ...
    return ctrl;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can do this, as long as the control types you want to use all have a default constructor.

T AddControl<T>() where T : WebControl, new()
{
    T ctrl = new T();
    ...
    return ctrl;
}


问:
how can I remove token CRM:XXXX000 from email subject line in CRM2016
Can anyone help to remove the token like CRM:XXXX000 from subject line of email generated through plugin code ?

CRM 2011 had some settings to remove this but in CRM 2016 I am not getting that  setting.

Am  I missing something or CRM2016 does not allow it ?

答:
That is the tracking token which alows CRM to (as the name implies) keep track of the emails.

To remove the tracking token go to Settings > Administration > System settings > Tab Email and uncheck "Use Tracking Token"


问:
What does `(c = *str) != 0` mean?
```<code>int equiv (char, char);
int nmatches(char *str, char comp) {
    char c;
    int n=0;
    while ((c = *str) != 0) {
       if (equiv(c,comp) != 0) n++;
      str++;
    }
    return (n);
}
</code>```

What does "(c = *str) != 0" actually mean?
Can someone please explain it to me or help give me the correct terms to search for an explanation myself?

答:
This expression has two parts:

c = *str - this is a simple assignment of c from dereferencing a pointer,

val != 0 - this is a comparison to zero.

This works, because assignment is an expression, i.e. it has a value. The value of the assignment is the same as the value being assigned, in this case, the char pointed to by the pointer. So basically, you have a loop that traces a null-terminated string to the end, assigning each individual char to c as it goes.

Note that the != 0 part is redundant in C, because the control expression of a while loop is implicitly compared to zero:

```<code>while ((c = *str)) {
    ...
}
</code>```

The second pair of parentheses is optional from the syntax perspective, but it's kept in assignments like that in order to indicate that the assignment is intentional. In other words, it tells the readers of your code that you really meant to write an assignment c = *str, and not a comparison c == *str, which is a lot more common inside loop control blocks. The second pair of parentheses also suppresses the compiler warning.

Title: What does `(c = *str) != 0` mean?

Body:
int equiv (char, char);
int nmatches(char *str, char comp) {
    char c;
    int n=0;
    while ((c = *str) != 0) {
       if (equiv(c,comp) != 0) n++;
      str++;
    }
    return (n);
}

What does "(c = *str) != 0" actually mean?
Can someone please explain it to me or help give me the correct terms to search for an explanation myself?

Body:
This expression has two parts:

c = *str - this is a simple assignment of c from dereferencing a pointer,

val != 0 - this is a comparison to zero.

This works, because assignment is an expression, i.e. it has a value. The value of the assignment is the same as the value being assigned, in this case, the char pointed to by the pointer. So basically, you have a loop that traces a null-terminated string to the end, assigning each individual char to c as it goes.

Note that the != 0 part is redundant in C, because the control expression of a while loop is implicitly compared to zero:

while ((c = *str)) {
    ...
}

The second pair of parentheses is optional from the syntax perspective, but it's kept in assignments like that in order to indicate that the assignment is intentional. In other words, it tells the readers of your code that you really meant to write an assignment c = *str, and not a comparison c == *str, which is a lot more common inside loop control blocks. The second pair of parentheses also suppresses the compiler warning.


问:
Angular - Add component B inside component A
I have the following structure in my project,

```<code>src
- component-a
-- component-a.component.ts
-- component-a.html
-- component-a.scss
-- component-a.component.spec.ts

- component-b
-- component-b.component.ts
-- component-b.html
-- component-b.scss
-- component-b.component.spec.ts

- app.component.ts
- app.module.ts
- app.html
</code>```

I'm using component-a inside my app.component.ts, so I have included it in declarations in the app.module.ts.

```<code>declarations: [
        App, ComponentA,
    ],
</code>```

And in the app.html: <component-a></component-a>

Now I want to add component-b inside my component-a.
So whatever I tried, when I use <component-b></component-b> inside component-a.html I get this error:

```<code>Unhandled Promise rejection: Template parse errors:
'component-b' is not a known element:
1. If 'component-b' is an Angular component, then verify that it is part of this module.
2. If 'component-b' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
      [ERROR ->]<component-b></component-b>
"): ng:///AppModule/ComponentA.html@7:6 ; Zone: <root> ; Task: Promise.then ; Value:
</code>```

How do use component-b in component-a.html?

I tried importing component-b in component-a.component.ts

I tried importing and adding component-b in the app.module.ts
declarations.

答:
Create a module for both components.

Import component B into component A's module imports.

Done.

Example (A Module)

```<code>import {NgModule} from '@angular/core';

import {BModule} from '@components/b/b.module';

@NgModule({
  imports: [
    BModule
  ],
  exports: [
    AComponent
  ],
  declarations: [
    AComponent
  ]
})

export class AModule {}
</code>```

Example (B Module):

```<code>import {NgModule} from '@angular/core';

@NgModule({
  exports: [
    BComponent
  ],
  declarations: [
    BComponent
  ]
})

export class BModule {}
</code>```

Body:
I have the following structure in my project,

src
- component-a
-- component-a.component.ts
-- component-a.html
-- component-a.scss
-- component-a.component.spec.ts

- component-b
-- component-b.component.ts
-- component-b.html
-- component-b.scss
-- component-b.component.spec.ts

- app.component.ts
- app.module.ts
- app.html

I'm using component-a inside my app.component.ts, so I have included it in declarations in the app.module.ts.

declarations: [
        App, ComponentA,
    ],

And in the app.html: <component-a></component-a>

Now I want to add component-b inside my component-a.
So whatever I tried, when I use <component-b></component-b> inside component-a.html I get this error:

Unhandled Promise rejection: Template parse errors:
'component-b' is not a known element:
1. If 'component-b' is an Angular component, then verify that it is part of this module.
2. If 'component-b' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
      [ERROR ->]<component-b></component-b>
"): ng:///AppModule/ComponentA.html@7:6 ; Zone: <root> ; Task: Promise.then ; Value:

How do use component-b in component-a.html?

I tried importing component-b in component-a.component.ts

I tried importing and adding component-b in the app.module.ts
declarations.

Body:
Create a module for both components.

Import component B into component A's module imports.

Done.

Example (A Module)

import {NgModule} from '@angular/core';

import {BModule} from '@components/b/b.module';

@NgModule({
  imports: [
    BModule
  ],
  exports: [
    AComponent
  ],
  declarations: [
    AComponent
  ]
})

export class AModule {}

Example (B Module):

import {NgModule} from '@angular/core';

@NgModule({
  exports: [
    BComponent
  ],
  declarations: [
    BComponent
  ]
})

export class BModule {}


问:
Running Different Macros Based on Values in Range
Im busy trying to write code that calls different macros based on the value of a cell across an entire range on VBA.

So for the example I have a range S20:S21.

When the value in cell S20 is equal to 1, I want to call macro1.
When the value in cell S21 is equal to 2, I want to call macro2.

When there is no match I have a time that it will test it in the next 5 seconds again where it will start from the top checking if cell S20 is 1 or of S20 is 2.

This is currently the code I have.

```<code>    Dim TimeToRun

Sub auto_open()
    Call ScheduleCopyPriceOver
End Sub

Sub ScheduleCopyPriceOver()
    TimeToRun = Now + TimeValue("00:00:05")
    Application.OnTime TimeToRun, "CopyPriceOver"
End Sub

Sub CopyPriceOver()
Application.ScreenUpdating = False

    Number = Range("S20:S22").Value

    If Number = 1 Then

    Call Macro1
    Call ScheduleCopyPriceOver

    ElseIf Number = 2 Then

    Call Macro2
    Call ScheduleCopyPriceOver

    Else

    Call ScheduleCopyPriceOver
    End If

End Sub

Sub auto_close()
    On Error Resume Next
    Application.OnTime TimeToRun, "CopyPriceOver", , False
End Sub
</code>```

答:
Your CopyPriceOver sub has some issues, I've pointed them out in comments below

```<code>Sub CopyPriceOver()
    Application.ScreenUpdating = False
    ' Number = Range("S20:S22").Value
    ' You're trying to assign 3 cells' values to one number!
    ' You should declare Number first, declaring it as an integer would quickly flag to you
    ' the error caused by assigning 3 cells to it. I've opted to not use the
    ' variable at all, since you're checking different values anyway...

    ' You should full qualify ranges to a specific sheet, this example uses a With block:
    With ThisWorkbook.Sheets("SheetNameHere")
        ' Test for individual cells' values, you specified values for S20 and S21...
        If .Range("S20").Value = 1 Then
            ' You don't need the "Call" command, see my comment after the code
            Macro1
        ElseIf .Range("S21").Value = 2 Then
            Macro2
        End If
    End With

    ' You called ScheduleCopyPriceOver in every If condition, simply call it afterwards
    ScheduleCopyPriceOver

    ' You disabled screen updating and never re-enabled it
    Application.ScreenUpdating = True
End Sub
</code>```

With respect to the Call command, see this SO question: Should I use Call keyword in VB/VBA?

Your catch-all use of On Error Resume Next also raises red flags in auto_close, you should diagnose and fix errors rather than hide them!

Body:
Im busy trying to write code that calls different macros based on the value of a cell across an entire range on VBA.

So for the example I have a range S20:S21.

When the value in cell S20 is equal to 1, I want to call macro1.
When the value in cell S21 is equal to 2, I want to call macro2.

When there is no match I have a time that it will test it in the next 5 seconds again where it will start from the top checking if cell S20 is 1 or of S20 is 2.

This is currently the code I have.

    Dim TimeToRun

Sub auto_open()
    Call ScheduleCopyPriceOver
End Sub

Sub ScheduleCopyPriceOver()
    TimeToRun = Now + TimeValue("00:00:05")
    Application.OnTime TimeToRun, "CopyPriceOver"
End Sub

Sub CopyPriceOver()
Application.ScreenUpdating = False

    Number = Range("S20:S22").Value

    If Number = 1 Then

    Call Macro1
    Call ScheduleCopyPriceOver

    ElseIf Number = 2 Then

    Call Macro2
    Call ScheduleCopyPriceOver

    Else

    Call ScheduleCopyPriceOver
    End If

End Sub

Sub auto_close()
    On Error Resume Next
    Application.OnTime TimeToRun, "CopyPriceOver", , False
End Sub

Body:
Your CopyPriceOver sub has some issues, I've pointed them out in comments below

Sub CopyPriceOver()
    Application.ScreenUpdating = False
    ' Number = Range("S20:S22").Value
    ' You're trying to assign 3 cells' values to one number!
    ' You should declare Number first, declaring it as an integer would quickly flag to you
    ' the error caused by assigning 3 cells to it. I've opted to not use the
    ' variable at all, since you're checking different values anyway...

    ' You should full qualify ranges to a specific sheet, this example uses a With block:
    With ThisWorkbook.Sheets("SheetNameHere")
        ' Test for individual cells' values, you specified values for S20 and S21...
        If .Range("S20").Value = 1 Then
            ' You don't need the "Call" command, see my comment after the code
            Macro1
        ElseIf .Range("S21").Value = 2 Then
            Macro2
        End If
    End With

    ' You called ScheduleCopyPriceOver in every If condition, simply call it afterwards
    ScheduleCopyPriceOver

    ' You disabled screen updating and never re-enabled it
    Application.ScreenUpdating = True
End Sub

With respect to the Call command, see this SO question: Should I use Call keyword in VB/VBA?

Your catch-all use of On Error Resume Next also raises red flags in auto_close, you should diagnose and fix errors rather than hide them!


问:
How can I retrieve the content of a specific stashed file after have pull the new version of my project form GIT?
I am not so into GIT and I have the following problem.

I have some uncommitted file in my project that I have stashed by this statment:

```<code>git stash
</code>```

Then I have pull the repository taking the work of a coolegue, that seems have correctly overwrite the changes of my stashed file.

Now I want to retrieve the content of a specific stashed file without lose the modification of my collegue.

I don't want to override the pulled version but only access to the code of the stashed version of a specific file.

Performing git stash list I obtain:

```<code>$ git stash list
stash@{0}: WIP on master: fd2a59b First version of iterate/aggregate for data received from dataservice
stash@{1}: WIP on master: 4910263 DSS project added
</code>```

How can I do it from the shell?

答:
Solved by myself:

1) First show the stashed file using the git stash show statment:

```<code>$ git stash show
 glis-toolkit/src/main/synapse-config/api/glisTest2.xml | 8 ++++++++
 1 file changed, 8 insertions(+)
</code>```

2) Then I save this stashed version (from the stash 0) in another backup file by:

```<code>$ git show stash@{0}:glis-toolkit/src/main/synapse-config/api/glisTest2.xml  >  glisTest2Bck.xml
</code>```

Body:
I am not so into GIT and I have the following problem.

I have some uncommitted file in my project that I have stashed by this statment:

git stash

Then I have pull the repository taking the work of a coolegue, that seems have correctly overwrite the changes of my stashed file.

Now I want to retrieve the content of a specific stashed file without lose the modification of my collegue.

I don't want to override the pulled version but only access to the code of the stashed version of a specific file.

Performing git stash list I obtain:

$ git stash list
stash@{0}: WIP on master: fd2a59b First version of iterate/aggregate for data received from dataservice
stash@{1}: WIP on master: 4910263 DSS project added

How can I do it from the shell?

Body:
Solved by myself:

1) First show the stashed file using the git stash show statment:

$ git stash show
 glis-toolkit/src/main/synapse-config/api/glisTest2.xml | 8 ++++++++
 1 file changed, 8 insertions(+)

2) Then I save this stashed version (from the stash 0) in another backup file by:

$ git show stash@{0}:glis-toolkit/src/main/synapse-config/api/glisTest2.xml  >  glisTest2Bck.xml


问:
How do I access the datacontext of a silverlight control in the codebehind
I've a silverlight control I am instantiating like so:

```<code><MyControls:SomeControl DataContext="{Binding}" />
</code>```

In the codebehind of this file, how can I get access to this datacontext? this.DataContext is equal to null.

Edit (more info):

I am building an extension for an existing silverlight application. My point where I integrate with the app looks like this:

```<code><DataTemplate x:Key="AnImportantIdentifierUsedByTheHostApp">
    <MyControls:SomeControl DataContext="{Binding}" />
</DataTemplate>
</code>```

Inside my control, I am able to bind against properties like so:

```<code><Hyperlink NavigateUri="{Binding Path=UriWithSlug}">
</code>```

And this all works fine. However for certain functionality (specifically, I need to use a WebBrowser control and the NavigateToString() method), I need to access properties from the DataContext.

Basically in the codebehind, I need to do something to the effect of:

```<code>myWebBrowser.NavigateToString(DataContext.MyHTMLStringProperty);
</code>```

答:
The answer of course is super straight forward and something I'm sure everyone probably assumed I was doing...

The DataContext is not available until the control's Loaded event has fired.

```<code>public MyUserControl() {
    var dc = this.DataContext // DataContext is null here in the ctor.

    this.Loaded += (s, e) => {
        var sc2 = this.DataContext // Loaded event fires, DataContext exists!
    };
}
</code>```

Again, I'm sure this is probably obvious to a lot of SL devs but it completely tripped me up.

Body:
I've a silverlight control I am instantiating like so:

<MyControls:SomeControl DataContext="{Binding}" />

In the codebehind of this file, how can I get access to this datacontext? this.DataContext is equal to null.

Edit (more info):

I am building an extension for an existing silverlight application. My point where I integrate with the app looks like this:

<DataTemplate x:Key="AnImportantIdentifierUsedByTheHostApp">
    <MyControls:SomeControl DataContext="{Binding}" />
</DataTemplate>

Inside my control, I am able to bind against properties like so:

<Hyperlink NavigateUri="{Binding Path=UriWithSlug}">

And this all works fine. However for certain functionality (specifically, I need to use a WebBrowser control and the NavigateToString() method), I need to access properties from the DataContext.

Basically in the codebehind, I need to do something to the effect of:

myWebBrowser.NavigateToString(DataContext.MyHTMLStringProperty);

Body:
The answer of course is super straight forward and something I'm sure everyone probably assumed I was doing...

The DataContext is not available until the control's Loaded event has fired.

public MyUserControl() {
    var dc = this.DataContext // DataContext is null here in the ctor.

    this.Loaded += (s, e) => {
        var sc2 = this.DataContext // Loaded event fires, DataContext exists!
    };
}

Again, I'm sure this is probably obvious to a lot of SL devs but it completely tripped me up.


问:
Differences in these subclass definitions?
Could someone explain what is the difference between the following class definitions derived from BaseClass and in what cases it would matter how they are defined:

```<code>class BaseClass(object):
    def __init__(self):
        # ...

    def as_dict(self):
        # ...

class SomeClass(BaseClass):

    def as_dict(self):
        # Does this somehow change the method compared to 'AnotherClass.as_dict()' below
        return super(SomeClass, self).as_dict()

class AnotherClass(BaseClass): pass

SomeOtherClass = BaseClass
</code>```

答:
This is using BaseClass with a different name.

```<code>class AnotherClass(BaseClass): pass
</code>```

This is using BaseClass but modifying the method "as_dict". Inside the as_dict method, you can do anything (ie.modify the parameters sent to this method) then run the usual function of the as_dict method with super(SomeClass, self).as_dict()

```<code>class SomeClass(BaseClass):
    def as_dict(self):
        # Does this somehow change the method compared to 'AnotherClass.as_dict()' below
        return super(SomeClass, self).as_dict()
</code>```

This is simply assigning BaseClass to SomeOtherClass, which means they can use BaseClass through both keywords.

```<code>SomeOtherClass = BaseClass
</code>```

Body:
Could someone explain what is the difference between the following class definitions derived from BaseClass and in what cases it would matter how they are defined:

class BaseClass(object):
    def __init__(self):
        # ...

    def as_dict(self):
        # ...

class SomeClass(BaseClass):

    def as_dict(self):
        # Does this somehow change the method compared to 'AnotherClass.as_dict()' below
        return super(SomeClass, self).as_dict()

class AnotherClass(BaseClass): pass

SomeOtherClass = BaseClass

Body:
This is using BaseClass with a different name.

class AnotherClass(BaseClass): pass

This is using BaseClass but modifying the method "as_dict". Inside the as_dict method, you can do anything (ie.modify the parameters sent to this method) then run the usual function of the as_dict method with super(SomeClass, self).as_dict()

class SomeClass(BaseClass):
    def as_dict(self):
        # Does this somehow change the method compared to 'AnotherClass.as_dict()' below
        return super(SomeClass, self).as_dict()

This is simply assigning BaseClass to SomeOtherClass, which means they can use BaseClass through both keywords.

SomeOtherClass = BaseClass


问:
Need to open fancybox content on page scroll instead of click somewhere
I am using fancybox. Here it fancybox will display on clicking somewhere but i need to display after page scroll. Now i am looking for fancybox. Anyone can suggest me any plugin like fancybox with scrolling not clicking.

Now i have tried with fancybox so here is code of fancybox. But you can help me with any plugin.

$(document).ready(function() {
  $(".fancybox").fancybox();
 });```
<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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.0.47/jquery.fancybox.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.0.47/jquery.fancybox.min.css" rel="stylesheet"/>

 <img src="http://farm9.staticflickr.com/8140/30366640446_eb359921c5_m.jpg" alt="" />
</code>```

答:
Mousewheel event listener taken from this: Get mouse wheel events in jQuery?

I also created a jsFiddle: https://jsfiddle.net/jmL7zgzt/

$(document).ready(function() {
  $(".fancybox").fancybox();
});
$(window).bind('mousewheel DOMMouseScroll', function(event){
    if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
        // scroll up
    }
    else {
       // scroll up
           if (!$("html").hasClass("fancybox-enabled")) $('.fancybox').click()
    }
});```
<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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.0.47/jquery.fancybox.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.0.47/jquery.fancybox.min.css" rel="stylesheet"/>

 <img src="http://farm9.staticflickr.com/8140/30366640446_eb359921c5_m.jpg" alt="" />
</code>```

Body:
I am using fancybox. Here it fancybox will display on clicking somewhere but i need to display after page scroll. Now i am looking for fancybox. Anyone can suggest me any plugin like fancybox with scrolling not clicking.

Now i have tried with fancybox so here is code of fancybox. But you can help me with any plugin.

$(document).ready(function() {
  $(".fancybox").fancybox();
 });

<link href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.0.47/jquery.fancybox.min.css" rel="stylesheet"/>

Body:
Mousewheel event listener taken from this: Get mouse wheel events in jQuery?

I also created a jsFiddle: https://jsfiddle.net/jmL7zgzt/

$(document).ready(function() {
  $(".fancybox").fancybox();
});
$(window).bind('mousewheel DOMMouseScroll', function(event){
    if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
        // scroll up
    }
    else {
       // scroll up
           if (!$("html").hasClass("fancybox-enabled")) $('.fancybox').click()
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.0.47/jquery.fancybox.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.0.47/jquery.fancybox.min.css" rel="stylesheet"/>

<a class="fancybox" id="single_1" href="http://farm9.staticflickr.com/8140/30366640446_eb359921c5_b.jpg" title="Morning on Camaret (Tony N.)">
 <img src="http://farm9.staticflickr.com/8140/30366640446_eb359921c5_m.jpg" alt="" />
</a>


问:
Spring MVC @Pathvariable won't work
I have an interface and an implementation class:

Interface

```<code>@RequestMapping(value = CUSTOMER_PATH + "{id}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON + CHARSET_UTF_8_ENCODING})
    Response getCustomerDetails(@PathVariable(CONTACT_ID) String id);
</code>```

Impl

```<code>@Override
public Response getCustomerDetails(String id) {
    String methodname = "getCustomerDetails: ";
    LOG.info(methodname + "Get Customer Details");

    Response response;
    System.out.println("******************id: " + id);

    if (StringUtils.isEmpty(id)) {
        response = Response.status(Status.BAD_REQUEST).entity(MockData.customerDetailsInvalid).build();
        LOG.info(methodname + "Returning Customer's Details - Status: Invalid Request");
    } else {
        response = Response.status(Status.OK).entity(MockData.customerDetails).build();
        LOG.info(methodname + "Returning Customer's Details - Status: OK");

    }

    return response;
}
</code>```

The path ..../MockDataProvider-war/services/mock/customers/7 returns “invalid request”.
The value for id is printed out as null, even though it should be 7.

Anyone know why id is null?

答:
Fixed it by changing the Interface from:

```<code>Response getCustomerDetails(@PathVariable(CONTACT_ID) String id);
</code>```

to:

```<code>Response getCustomerDetails(String id);
</code>```

and the Impl from:

```<code>public Response getCustomerDetails(String id)
</code>```

to

```<code>public Response getCustomerDetails(@PathVariable(CONTACT_ID) String id)
</code>```

Title: Spring MVC @Pathvariable won't work

Body:
I have an interface and an implementation class:

Interface

@RequestMapping(value = CUSTOMER_PATH + "{id}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON + CHARSET_UTF_8_ENCODING})
    Response getCustomerDetails(@PathVariable(CONTACT_ID) String id);

Impl

@Override
public Response getCustomerDetails(String id) {
    String methodname = "getCustomerDetails: ";
    LOG.info(methodname + "Get Customer Details");

    Response response;
    System.out.println("******************id: " + id);

    if (StringUtils.isEmpty(id)) {
        response = Response.status(Status.BAD_REQUEST).entity(MockData.customerDetailsInvalid).build();
        LOG.info(methodname + "Returning Customer's Details - Status: Invalid Request");
    } else {
        response = Response.status(Status.OK).entity(MockData.customerDetails).build();
        LOG.info(methodname + "Returning Customer's Details - Status: OK");

    }

    return response;
}

The path ..../MockDataProvider-war/services/mock/customers/7 returns “invalid request”.
The value for id is printed out as null, even though it should be 7.

Anyone know why id is null?

Body:
Fixed it by changing the Interface from:

Response getCustomerDetails(@PathVariable(CONTACT_ID) String id);

to:

Response getCustomerDetails(String id);

and the Impl from:

public Response getCustomerDetails(String id)

to

public Response getCustomerDetails(@PathVariable(CONTACT_ID) String id)


问:
How to set image height for all browser?
Before I posting this question I have checked this forum and google but the methods is not working for me. May be I am doing wrong.

I have a page which is look like this :
enter image description here

In this page I have few images and for that I am using following css code:

```<code>display: inline-block;
width: 100% \9;
max-width: 100%;
min-height: 75px;
height: auto !important;
height: 75px;
</code>```

Now in Firefox browser both top and bottom images are showing correct size but in internet explorer all images are showing full height ( filled up entire website)!!

Now If I remove this line

```<code>height: auto !important;
</code>```

then on internet explorer image height is perfect but on Firefox bottom images are stretch.

How can I solved this problem ?

Thanks.

答:
please try this.

```<code>{
    display: inline-block;
    max-height: 75px;
    min-height: 75px;
    width: auto;
}
</code>```

About your all image height will be 75px but width may be not same for all and if you want image also same then please use below.

```<code>{
    display: inline-block;
    max-height: 75px;
    min-height: 75px;
    width: 100%;
}
</code>```

If all images have same width then there will no issue but if width are not same for all images then may be some images will be stretch.

Body:
Before I posting this question I have checked this forum and google but the methods is not working for me. May be I am doing wrong.

I have a page which is look like this :
enter image description here

In this page I have few images and for that I am using following css code:

display: inline-block;
width: 100% \9;
max-width: 100%;
min-height: 75px;
height: auto !important;
height: 75px;

Now in Firefox browser both top and bottom images are showing correct size but in internet explorer all images are showing full height ( filled up entire website)!!

Now If I remove this line

height: auto !important;

then on internet explorer image height is perfect but on Firefox bottom images are stretch.

How can I solved this problem ?

Thanks.

Body:
please try this.

{
    display: inline-block;
    max-height: 75px;
    min-height: 75px;
    width: auto;
}

About your all image height will be 75px but width may be not same for all and if you want image also same then please use below.

{
    display: inline-block;
    max-height: 75px;
    min-height: 75px;
    width: 100%;
}

If all images have same width then there will no issue but if width are not same for all images then may be some images will be stretch.