问:
Prevent user to check check box randomly using javascript
I have following test checkboxes. A user can select any checkbox in any order.
My question is how I can use javascript/jquery to prevent user to select checkbox randomly.
I would like user to click first checkbox, than second and so on.

```<code>1 <input type="checkbox" name="sports" value="1"  /><br />

2 <input type="checkbox" name="sports" value="2"  /><br />

3 <input type="checkbox" name="sports" value="3"  /><br />

 4 <input type="checkbox" name="sports" value="4"  />
</code>```

I need help writing script that would only allows to check each of the chckboxx in order  - left to right.

Many Thanks in advance

Re- Edited Question:

```<code>   <div class="siblings">
     <ul>
       <table class="table table-bordered">
      <?php
       $count = 1;

      for($x=0; $x < 5; $x++){
       ?>
      <td>
     <div class="thumb">
      <label for="image <?php echo $count;?>"><img class="img"
     src="http://s5.tinypic.com/30v0ncn_th.jpg"/></label>
     <input type="checkbox" class="chk " id="image <?php echo $count;?>"
      name="tick" value="0" />
      </div>
      </td>

     <?php
     $count++;

     }

      ?>
     </table>
    </ul>
    </div>
    </table>
</code>```

答:
How about disabling next ones and enabling if previous one is checked?

$(function() {

  var sportsSelector = 'input[type="checkbox"][name="sports"]';
  $(sportsSelector)
    .on('click', function() {
      var $this = $(this);

      if($this.is(':checked')) {
        $this
          .nextAll(sportsSelector)
          .first()
          .removeAttr('disabled')
          .removeAttr('checked');
        return;
      }

      $this
        .nextAll(sportsSelector)
        .attr('disabled', 'disabled')
        .removeAttr('checked');
    })
    .attr('disabled', 'disabled')
    .removeAttr('checked')
    .first().removeAttr('disabled');

});```
<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>

1 <input type="checkbox" name="sports" value="1" /><br />

2 <input type="checkbox" name="sports" value="2" /><br />

3 <input type="checkbox" name="sports" value="3" /><br />

4 <input type="checkbox" name="sports" value="4" /></code>```

Body:
I have following test checkboxes. A user can select any checkbox in any order.
My question is how I can use javascript/jquery to prevent user to select checkbox randomly.
I would like user to click first checkbox, than second and so on.

1 <input type="checkbox" name="sports" value="1"  />

2 <input type="checkbox" name="sports" value="2"  />

3 <input type="checkbox" name="sports" value="3"  />

 4 <input type="checkbox" name="sports" value="4"  />

I need help writing script that would only allows to check each of the chckboxx in order  - left to right.

Many Thanks in advance

Re- Edited Question:

      <?php
       $count = 1;

      for($x=0; $x < 5; $x++){
       ?>

      <label for="image <?php echo $count;?>">
     <input type="checkbox" class="chk " id="image <?php echo $count;?>"
      name="tick" value="0" />

     <?php
     $count++;

     }

      ?>

Body:
How about disabling next ones and enabling if previous one is checked?

$(function() {

  var sportsSelector = 'input[type="checkbox"][name="sports"]';
  $(sportsSelector)
    .on('click', function() {
      var $this = $(this);

      if($this.is(':checked')) {
        $this
          .nextAll(sportsSelector)
          .first()
          .removeAttr('disabled')
          .removeAttr('checked');
        return;
      }

      $this
        .nextAll(sportsSelector)
        .attr('disabled', 'disabled')
        .removeAttr('checked');
    })
    .attr('disabled', 'disabled')
    .removeAttr('checked')
    .first().removeAttr('disabled');

});

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

1 <input type="checkbox" name="sports" value="1" /><br />

2 <input type="checkbox" name="sports" value="2" /><br />

3 <input type="checkbox" name="sports" value="3" /><br />

4 <input type="checkbox" name="sports" value="4" />


来源: stackexchange

问:
Remove a table row with checkbox in Javascript
I have a problem in my Javascript code. When I click on the checkbox, I can add player to the table, and I can delete them from the table. But when next I add somebody to the table, the deleted rows are inserted too into the table. I hope you can understand, whats my problem, and you can help for me.

$(document).ready(function()    {
    var players = ["Csabi", "Egér", "Miki", "Mazsi", "Sanyi", "Stam", "Szaki", "Tibi", "Tóni", "Zsolti"];
    var count = players.length;
    var row = "";
    var row1 = "";
    var doubles = "";
    var tr1 = "
";
    var tr2 = "	0	72	";
        $(document).on('click','input[type=button]',function(){
        newPlayer   =   document.getElementById("newplayer").value;
        players.push(newPlayer);
        i = count + 1;
        alert(i);
        });
//Generate players from 'players' array
    for (i = 0; i < players.length; i++) {
        var div = document.createElement('div');
        var input   =   document.createElement('input');
        var label   =   document.createElement('label');
        input.type  =   "checkbox";
        input.value =   players[i];
        input.className =   "players";
        div.className = 'player';
        label.className =   "labelplayer";
        label.innerHTML = players[i];
        document.getElementsByClassName('playerarray')[0].appendChild(div);
        document.getElementsByClassName("player")[i].appendChild(input);
        document.getElementsByClassName("player")[i].appendChild(label);
//        alert("generate" + players[i]);
    };

    var jatekosok   =   [];
    $("input.players").change(function () {
        var checked =   $(this).prop("checked");
        if (checked) {
            row +=  tr1 + $(this).attr("value") + tr2;
            jatekosok.push($(this).attr("value"));
            var szam    =   jatekosok.length;
            document.getElementById("row").innerHTML =   row;
            alert("Játékosok száma: "+szam);
            for (i = 0; i < szam; i++) {
                alert("A játékhoz hozzáadva: " + jatekosok[i]);
                document.getElementsByClassName("name")[i].id    =   jatekosok[i];
            };
        }
        else  {
            var removeplayer    =  $(this).attr("value");
            alert("A törölt játékos: " + removeplayer);
            var rows = document.getElementById(removeplayer);
            rows.parentNode.removeChild(rows);
            alert("Megtörtént");
            var removeplayer    =  $(this).attr("value");
            var index = jatekosok.indexOf(removeplayer);
            alert(index);
            if (index > -1) {
                jatekosok.splice(index, 1);
                var szam    =   jatekosok.length;
                for (i = 0; i < szam; i++) {
                    alert("A játékhoz hozzáadva: " + jatekosok[i]);
                    document.getElementsByClassName("name")[i].id    =   jatekosok[i];
                    alert(i);
                };
            };
       }
    });
    $(".double").change(function () {
        if ($(this).prop("checked")) {
            doubles += $(this).attr("value");
            document.getElementById("footer").innerHTML = doubles;
        }
    });

//Dartboard events
    $("#dartboard #areas g").children().hover(
            function () {
                $(this).css("opacity", "0.6");
            },
            function () {
                $(this).css("opacity", "1");
            }
    );
    $("#dartboard #areas g").children().click(function () {
        alert($(this).attr("id"));
    });
    $(document).ready(function () {
        $("#azs").click(function () {
            alert("0");
        });
    });
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>fieldset    {
    width: 500px;
}
div.player    {
    color:blue;
    text-align:left;
    width: 98px;
    border:1px solid black;
    float:left;
}
input.players   {

}
input#azs {
    position:relative;
    top:485px;
    right:515px;
}
input#undo {
    position:relative;
    top:485px;
    right:165px;
}
iframe  {
    border:none;
    width:521px;
    height:516px;
}
iframe#dartboard {
    background-color:black;
    border:1px solid black;
    float:left;
}
svg#selecctor {
    position:relative;
    top:-194px;
    left:318px;
}
div#table {
    position:absolute;
    left:535px;
    top:16px;
}
table {
    border-spacing:0px;
}
td {
    border: 1px solid #ecefea;
    border-spacing: 0px;
}
tr {
    height:34px;
}
tr.name {
    font-size:23px;
}
td.header {
    background-color:white;
    box-shadow:0px -6px 14px 13px black inset;
    color:white;
    font-size:17px;
    width:350px;
    padding-left:6px;
}
td.scoreheader {
    width:120px;
    visibility:hidden;
}
td.name{
    background-color:white;
    padding-left:6px;
    width:100px;
}
td.score {
    text-align:center;
    width:60px;
    box-shadow:0px -6px 24px 8px red inset;
    color:white;
    background-color:white;
}
td.score1 {
    border:none;
    width:33px;
    text-align:center;
    box-shadow:0px -6px 16px 8px green inset;
    font-size:19px;
    color:white;
    background-color:white;
}
table {
    font-family:arial;
    font-weight:bold;
    width:420px;
    position:relative;
    left:0px;
    top:0px;
}
table#row   {
    width:348px;
}</code>```

<!DOCTYPE html>

    <title>Borvirág Darts</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="style.css">

    <fieldset>
        <legend>Játék beállítása</legend>
        <form>

            Új játékos:<input id="newplayer" type="text" name="player" value="">
            <input type="button" name="newPlayer" value="Hozzáad"/>

            <input class="double" type="checkbox" name="double" value="DoubleIn">Double In

            <input class="double" type="checkbox" name="double" value="DoubleOut">Double Out

            <input class="game" type="radio" name="game" value="301">301

            <input class="game" type="radio" name="game" value="501">501

            <input class="game" type="radio" name="game" value="Cricket">Cricket

            <input class="game" type="button" name="Submit" value="Game On" />
        </form>
    </fieldset>

A csoport - 1. forduló  DOBÁS  PONT

```

答:
It looks like when you're removing a player, you're not removing it from the players array but are just removing the physical row.

However, when you add a player you are using the players array by pushing to it (which still contains all players including removed players).

ContentLicense: CC BY-SA 3.0

Body:
I have a problem in my Javascript code. When I click on the checkbox, I can add player to the table, and I can delete them from the table. But when next I add somebody to the table, the deleted rows are inserted too into the table. I hope you can understand, whats my problem, and you can help for me.

$(document).ready(function()    {
    var players = ["Csabi", "Egér", "Miki", "Mazsi", "Sanyi", "Stam", "Szaki", "Tibi", "Tóni", "Zsolti"];
    var count = players.length;
    var row = "";
    var row1 = "";
    var doubles = "";
    var tr1 = "
";
    var tr2 = "	0	72	";
        $(document).on('click','input[type=button]',function(){
        newPlayer   =   document.getElementById("newplayer").value;
        players.push(newPlayer);
        i = count + 1;
        alert(i);
        });
//Generate players from 'players' array
    for (i = 0; i < players.length; i++) {
        var div = document.createElement('div');
        var input   =   document.createElement('input');
        var label   =   document.createElement('label');
        input.type  =   "checkbox";
        input.value =   players[i];
        input.className =   "players";
        div.className = 'player';
        label.className =   "labelplayer";
        label.innerHTML = players[i];
        document.getElementsByClassName('playerarray')[0].appendChild(div);
        document.getElementsByClassName("player")[i].appendChild(input);
        document.getElementsByClassName("player")[i].appendChild(label);
//        alert("generate" + players[i]);
    };

    var jatekosok   =   [];
    $("input.players").change(function () {
        var checked =   $(this).prop("checked");
        if (checked) {
            row +=  tr1 + $(this).attr("value") + tr2;
            jatekosok.push($(this).attr("value"));
            var szam    =   jatekosok.length;
            document.getElementById("row").innerHTML =   row;
            alert("Játékosok száma: "+szam);
            for (i = 0; i < szam; i++) {
                alert("A játékhoz hozzáadva: " + jatekosok[i]);
                document.getElementsByClassName("name")[i].id    =   jatekosok[i];
            };
        }
        else  {
            var removeplayer    =  $(this).attr("value");
            alert("A törölt játékos: " + removeplayer);
            var rows = document.getElementById(removeplayer);
            rows.parentNode.removeChild(rows);
            alert("Megtörtént");
            var removeplayer    =  $(this).attr("value");
            var index = jatekosok.indexOf(removeplayer);
            alert(index);
            if (index > -1) {
                jatekosok.splice(index, 1);
                var szam    =   jatekosok.length;
                for (i = 0; i < szam; i++) {
                    alert("A játékhoz hozzáadva: " + jatekosok[i]);
                    document.getElementsByClassName("name")[i].id    =   jatekosok[i];
                    alert(i);
                };
            };
       }
    });
    $(".double").change(function () {
        if ($(this).prop("checked")) {
            doubles += $(this).attr("value");
            document.getElementById("footer").innerHTML = doubles;
        }
    });

//Dartboard events
    $("#dartboard #areas g").children().hover(
            function () {
                $(this).css("opacity", "0.6");
            },
            function () {
                $(this).css("opacity", "1");
            }
    );
    $("#dartboard #areas g").children().click(function () {
        alert($(this).attr("id"));
    });
    $(document).ready(function () {
        $("#azs").click(function () {
            alert("0");
        });
    });
    });

fieldset    {
    width: 500px;
}
div.player    {
    color:blue;
    text-align:left;
    width: 98px;
    border:1px solid black;
    float:left;
}
input.players   {

}
input#azs {
    position:relative;
    top:485px;
    right:515px;
}
input#undo {
    position:relative;
    top:485px;
    right:165px;
}
iframe  {
    border:none;
    width:521px;
    height:516px;
}
iframe#dartboard {
    background-color:black;
    border:1px solid black;
    float:left;
}
svg#selecctor {
    position:relative;
    top:-194px;
    left:318px;
}
div#table {
    position:absolute;
    left:535px;
    top:16px;
}
table {
    border-spacing:0px;
}
td {
    border: 1px solid #ecefea;
    border-spacing: 0px;
}
tr {
    height:34px;
}
tr.name {
    font-size:23px;
}
td.header {
    background-color:white;
    box-shadow:0px -6px 14px 13px black inset;
    color:white;
    font-size:17px;
    width:350px;
    padding-left:6px;
}
td.scoreheader {
    width:120px;
    visibility:hidden;
}
td.name{
    background-color:white;
    padding-left:6px;
    width:100px;
}
td.score {
    text-align:center;
    width:60px;
    box-shadow:0px -6px 24px 8px red inset;
    color:white;
    background-color:white;
}
td.score1 {
    border:none;
    width:33px;
    text-align:center;
    box-shadow:0px -6px 16px 8px green inset;
    font-size:19px;
    color:white;
    background-color:white;
}
table {
    font-family:arial;
    font-weight:bold;
    width:420px;
    position:relative;
    left:0px;
    top:0px;
}
table#row   {
    width:348px;
}

<!DOCTYPE html>

    <title>Borvirág Darts</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="style.css">

    <fieldset>
        <legend>Játék beállítása</legend>
        <form>

            Új játékos:<input id="newplayer" type="text" name="player" value="">
            <input type="button" name="newPlayer" value="Hozzáad"/>

            <input class="double" type="checkbox" name="double" value="DoubleIn">Double In

            <input class="double" type="checkbox" name="double" value="DoubleOut">Double Out

            <input class="game" type="radio" name="game" value="301">301

            <input class="game" type="radio" name="game" value="501">501

            <input class="game" type="radio" name="game" value="Cricket">Cricket

            <input class="game" type="button" name="Submit" value="Game On" />
        </form>
    </fieldset>

A csoport - 1. forduló  DOBÁS  PONT


问:
Get python script to run on boot up in mac
How would I get a python script to run everytime the computer boots?</p>

答: You could create a login hook (be careful, it runs as root)</p>

ContentLicense: CC BY-SA 2.5


问:
Using audio_play_sound() in a if statement GameMaker
I am trying to use the command:

```<code>audio_play_sound()
</code>```

I am trying to insert it into this piece of code, so that when the player jumps, a sound plays.

```<code>if (key_jump) && (jumps > 0)
{
     jumps -=1;
     vsp = -jumpspeed;
}
</code>```

Code that causes problem:

```<code>if (key_jump) && (jumps > 0)
{
     jumps -=1;
     vsp = -jumpspeed;
     audio_play_sound(snd_jump)
}
</code>```

Simply inserting the line into the if statement does not work, and gives the error WRONG NUMBER OF ARGUMENTS IN FUNCTION. This is rather confusing, perhaps I am using the wrong command? Thanks in advance

答:
The problem is stated in the error, you're providing the wrong number of arguments to the audo_play_sound function.

from the docs

```<code>audio_play_sound(index, priority, loop);
</code>```

Body:
I am trying to use the command:

audio_play_sound()

I am trying to insert it into this piece of code, so that when the player jumps, a sound plays.

if (key_jump) && (jumps > 0)
{
     jumps -=1;
     vsp = -jumpspeed;
}

Code that causes problem:

if (key_jump) && (jumps > 0)
{
     jumps -=1;
     vsp = -jumpspeed;
     audio_play_sound(snd_jump)
}

Simply inserting the line into the if statement does not work, and gives the error WRONG NUMBER OF ARGUMENTS IN FUNCTION. This is rather confusing, perhaps I am using the wrong command? Thanks in advance

Body:
The problem is stated in the error, you're providing the wrong number of arguments to the audo_play_sound function.

from the docs

audio_play_sound(index, priority, loop);


问:
Conditional Formatting in Excel with C#
I need to apply a color to a cell's text if the value is not same as a value in another column. What would be the best approach for it ? The way I can think of is quite expensive.

```<code> for (int i = 0; i < ColumnARange.Cells.Count; i++)
                    {
                        if (ColumnARange.Cells[i, 1] != ColumnBRange.Cells[i, 1])
                        {
                            Range currCell = ColumnBRange.Cells[i, 1];
                            currCell.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
                        }
                    }
</code>```

Tried conditional formatting as below, but in vain.

```<code>FormatCondition cond = ColumnBRange.FormatConditions.Add(XlFormatConditionType.xlCellValue, XlFormatConditionOperator.xlNotEqual, ColumnARange);
                cond.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
</code>```

I am using VSTO,C#

答:
Let's say you want to color cells B1:B10 if their values are not equal to those of A1:A10, i.e.

B1<>A1 results in B1 being colored, B2<>A2 results in B2 being colored etc.

Then you can do the following

```<code>Range columnBRange = (Range)oSheet.Range[oSheet.Cells[1,2], oSheet.Cells[10,2]];

Range columnARange = (Range)oSheet.Range[oSheet.Cells[1,1], oSheet.Cells[1,1]];

FormatCondition cond = (FormatCondition) ColumnBRange.FormatConditions.Add(XlFormatConditionType.xlCellValue, XlFormatConditionOperator.xlNotEqual, "="+ColumnARange.Address[false,true]);
cond.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red); //Red letters
cond.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightYellow); //Light yellow cell background
</code>```

Note that prepending "=" to ColumnARange.Address[false,true] is required because otherwise the Add method uses the Address as a literal string instead of a cell reference.

If you take look at the conditional formatting rule applied to the B1:B10 cells in the Excel sheet it will state Cell Value <> B1 for every cell in the range which is a bit confusing IMO but the formatting is applied correctly nonetheless.

For completeness: I'm using optional objects on Range.Address property like so  Range.Address[isRowAbsolute,isColumnAbsolute]

Title: Conditional Formatting in Excel with C#

Body:
I need to apply a color to a cell's text if the value is not same as a value in another column. What would be the best approach for it ? The way I can think of is quite expensive.

 for (int i = 0; i < ColumnARange.Cells.Count; i++)
                    {
                        if (ColumnARange.Cells[i, 1] != ColumnBRange.Cells[i, 1])
                        {
                            Range currCell = ColumnBRange.Cells[i, 1];
                            currCell.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
                        }
                    }

Tried conditional formatting as below, but in vain.

FormatCondition cond = ColumnBRange.FormatConditions.Add(XlFormatConditionType.xlCellValue, XlFormatConditionOperator.xlNotEqual, ColumnARange);
                cond.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

I am using VSTO,C#

Body:
Let's say you want to color cells B1:B10 if their values are not equal to those of A1:A10, i.e.

B1<>A1 results in B1 being colored, B2<>A2 results in B2 being colored etc.

Then you can do the following

Range columnBRange = (Range)oSheet.Range[oSheet.Cells[1,2], oSheet.Cells[10,2]];

Range columnARange = (Range)oSheet.Range[oSheet.Cells[1,1], oSheet.Cells[1,1]];

FormatCondition cond = (FormatCondition) ColumnBRange.FormatConditions.Add(XlFormatConditionType.xlCellValue, XlFormatConditionOperator.xlNotEqual, "="+ColumnARange.Address[false,true]);
cond.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red); //Red letters
cond.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightYellow); //Light yellow cell background

Note that prepending "=" to ColumnARange.Address[false,true] is required because otherwise the Add method uses the Address as a literal string instead of a cell reference.

If you take look at the conditional formatting rule applied to the B1:B10 cells in the Excel sheet it will state Cell Value <> B1 for every cell in the range which is a bit confusing IMO but the formatting is applied correctly nonetheless.

For completeness: I'm using optional objects on Range.Address property like so  Range.Address[isRowAbsolute,isColumnAbsolute]


问:
php Warning: parse_ini_file, failed to open stream: No such file or directory in
I created an config.ini file with db credentials and parsing that file in my dbconnect.php page like this way -

```<code>$config = parse_ini_file('../somefolder/config.ini');
$connection = mysqli_connect($config['servername'],$config['username'],$config['password'],$config['dbname']);
</code>```

it is connecting the database and returns data in my first page. But when I go to another page which calls the same dbconnect.php, it shows the error

Warning: parse_ini_file('../somefolder/config.ini'): failed to open stream: No such file or directory in E:\wamp64\www\sample\dbconnect.php on line 12

Any help appreciated, thank you

答:
The path to parse_ini_file() has to change if the script you included it in is housed in a directory separate from the first file. Just adding (or removing) two dots and a forward slash could solve your problem. Besides, showing us your file structure would go a long way. This link could also help:
PHP directory problems</p>

Body:
I created an config.ini file with db credentials and parsing that file in my dbconnect.php page like this way -

$config = parse_ini_file('../somefolder/config.ini');
$connection = mysqli_connect($config['servername'],$config['username'],$config['password'],$config['dbname']);

it is connecting the database and returns data in my first page. But when I go to another page which calls the same dbconnect.php, it shows the error

Warning: parse_ini_file('../somefolder/config.ini'): failed to open stream: No such file or directory in E:\wamp64\www\sample\dbconnect.php on line 12

Any help appreciated, thank you


问:
camera ios 10.2, swift 3
I try create a camera like Snapchat with swift 3 in ios 10.2 but the problem is when I run the app in my iPhone. The UIView appear empty. This is my code.

```<code>import UIKit
import AVFoundation

class TakeSelfieViewController: UIViewController {

@IBOutlet var cameraView: UIView!

var captureSession : AVCaptureSession?
var stillImageOutput: AVCaptureStillImageOutput?
var previewLayer : AVCaptureVideoPreviewLayer?

override func viewDidLoad() {
    super.viewDidLoad()

    captureSession = AVCaptureSession()
    captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080
    let deviceDiscoverySession = AVCaptureDeviceDiscoverySession(deviceTypes: [AVCaptureDeviceType.builtInDuoCamera, AVCaptureDeviceType.builtInTelephotoCamera,AVCaptureDeviceType.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: AVCaptureDevicePosition.front)
    for device in (deviceDiscoverySession?.devices)! {
        if device.position == AVCaptureDevicePosition.front{
            do {
                let input = try AVCaptureDeviceInput(device: device)
                if (captureSession?.canAddInput(input))!{
                    captureSession?.addInput(input)
                    stillImageOutput = AVCaptureStillImageOutput()
                    stillImageOutput?.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
                    if (captureSession?.canAddOutput(stillImageOutput))! {
                        captureSession?.addOutput(stillImageOutput)
                        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                        previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
                        previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
                        cameraView.layer.addSublayer(previewLayer!)
                        captureSession?.startRunning()
                    }
                }
            } catch{
                print("Error Occured when trying get camera")
            }
        }
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override var prefersStatusBarHidden: Bool {

    return true

}
</code>```

In my Info.plist I have added the Privacy - Camera Usage Description

What's happening?

答:
You need to set the frame of the previewLayer.</p>

```<code>previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.frame = cameraView.frame // this line is new
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
</code>```

Title: camera ios 10.2, swift 3

Body:
I try create a camera like Snapchat with swift 3 in ios 10.2 but the problem is when I run the app in my iPhone. The UIView appear empty. This is my code.

import UIKit
import AVFoundation

class TakeSelfieViewController: UIViewController {

@IBOutlet var cameraView: UIView!

var captureSession : AVCaptureSession?
var stillImageOutput: AVCaptureStillImageOutput?
var previewLayer : AVCaptureVideoPreviewLayer?

override func viewDidLoad() {
    super.viewDidLoad()

    captureSession = AVCaptureSession()
    captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080
    let deviceDiscoverySession = AVCaptureDeviceDiscoverySession(deviceTypes: [AVCaptureDeviceType.builtInDuoCamera, AVCaptureDeviceType.builtInTelephotoCamera,AVCaptureDeviceType.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: AVCaptureDevicePosition.front)
    for device in (deviceDiscoverySession?.devices)! {
        if device.position == AVCaptureDevicePosition.front{
            do {
                let input = try AVCaptureDeviceInput(device: device)
                if (captureSession?.canAddInput(input))!{
                    captureSession?.addInput(input)
                    stillImageOutput = AVCaptureStillImageOutput()
                    stillImageOutput?.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
                    if (captureSession?.canAddOutput(stillImageOutput))! {
                        captureSession?.addOutput(stillImageOutput)
                        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                        previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
                        previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
                        cameraView.layer.addSublayer(previewLayer!)
                        captureSession?.startRunning()
                    }
                }
            } catch{
                print("Error Occured when trying get camera")
            }
        }
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override var prefersStatusBarHidden: Bool {

    return true

}

In my Info.plist I have added the Privacy - Camera Usage Description

What's happening?

Body:
You need to set the frame of the previewLayer.

previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.frame = cameraView.frame // this line is new
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect


问:
Screensaver loads image in radom location after inactivity, restarts if user does anything
I have the following two pieces of code (awful but I have no idea what I'm doing):

var stage = new createjs.Stage("canvas");
createjs.Ticker.on("tick", tick);

// Simple loading for demo purposes.
var image = document.createElement("img");
image.src = "http://dossierindustries.co/wp-content/uploads/2017/07/DossierIndustries_Cactus-e1499205396119.png";

var _obstacle = new createjs.Bitmap(image);
setInterval(clone, 1000);

function clone() {
    var bmp = _obstacle.clone();
    bmp.x= Math.floor((Math.random() * 1920) + 1);
    bmp.y = Math.floor((Math.random() * 1080) + 1);
    stage.addChild(bmp);
}

function tick(event) {
    stage.update(event);
}

<canvas id="canvas" width="1920" height="1080"></canvas>```

Basically what I'm hoping to achieve is that when a user is inactive for x amount of time the full page (no matter on size) slowly fills with the repeated image. When anything happens they all clear and it begins again after the set amount of inactivity.

The code above relies on an external resource which I'd like to avoid and needs to work on Wordpress.

Site is viewable at dossierindustries.co

答:
Rather than interpret your code, I made a quick demo showing how I might approach this.

The big difference is that drawing new images over time is going to add up (they have to get rendered every frame), so this approach uses a cached container with one child, and each tick it just adds more to the cache (similar to the "updateCache" demo in GitHub.

Here is the fiddle.
http://jsfiddle.net/dcs5zebm/

Key pieces:

```<code>// Move the contents each tick, and update the cache
shape.x = Math.random() * stage.canvas.width;
shape.y = Math.random() * stage.canvas.height;
container.updateCache("source-over");

// Only do it when idle
function tick(event) {
  if (idle) { addImage(); }
  stage.update(event);
}

// Use a timeout to determine when idle. Clear it when the mouse moves.
var idle = false;
document.body.addEventListener("mousemove", resetIdle);
function resetIdle() {
    clearTimeout(this.timeout);
    container.visible = false;
    idle = false;
    this.timeout = setTimeout(goIdle, TIMEOUT);
}
resetIdle();
function goIdle() {
    idle = true;
    container.cache(0, 0, stage.canvas.width, stage.canvas.height);
    container.visible = true;
}
</code>```

Caching the container means this runs the same speed forever (no overhead), but you still have control over the rest of the stage (instead of just turning off auto-clear). If you have more complicated requirements, you can get fancier -- but this basically does what you want I think.

Body:
I have the following two pieces of code (awful but I have no idea what I'm doing):

var stage = new createjs.Stage("canvas");
createjs.Ticker.on("tick", tick);

// Simple loading for demo purposes.
var image = document.createElement("img");
image.src = "http://dossierindustries.co/wp-content/uploads/2017/07/DossierIndustries_Cactus-e1499205396119.png";

var _obstacle = new createjs.Bitmap(image);
setInterval(clone, 1000);

function clone() {
    var bmp = _obstacle.clone();
    bmp.x= Math.floor((Math.random() * 1920) + 1);
    bmp.y = Math.floor((Math.random() * 1080) + 1);
    stage.addChild(bmp);
}

function tick(event) {
    stage.update(event);
}

<canvas id="canvas" width="1920" height="1080"></canvas>

Basically what I'm hoping to achieve is that when a user is inactive for x amount of time the full page (no matter on size) slowly fills with the repeated image. When anything happens they all clear and it begins again after the set amount of inactivity.

The code above relies on an external resource which I'd like to avoid and needs to work on Wordpress.

Site is viewable at dossierindustries.co

Body:
Rather than interpret your code, I made a quick demo showing how I might approach this.

The big difference is that drawing new images over time is going to add up (they have to get rendered every frame), so this approach uses a cached container with one child, and each tick it just adds more to the cache (similar to the "updateCache" demo in GitHub.

Here is the fiddle.
http://jsfiddle.net/dcs5zebm/

Key pieces:

// Move the contents each tick, and update the cache
shape.x = Math.random() * stage.canvas.width;
shape.y = Math.random() * stage.canvas.height;
container.updateCache("source-over");

// Only do it when idle
function tick(event) {
  if (idle) { addImage(); }
  stage.update(event);
}

// Use a timeout to determine when idle. Clear it when the mouse moves.
var idle = false;
document.body.addEventListener("mousemove", resetIdle);
function resetIdle() {
    clearTimeout(this.timeout);
    container.visible = false;
    idle = false;
    this.timeout = setTimeout(goIdle, TIMEOUT);
}
resetIdle();
function goIdle() {
    idle = true;
    container.cache(0, 0, stage.canvas.width, stage.canvas.height);
    container.visible = true;
}

Caching the container means this runs the same speed forever (no overhead), but you still have control over the rest of the stage (instead of just turning off auto-clear). If you have more complicated requirements, you can get fancier -- but this basically does what you want I think.


问:
Optimize Apply() While() in R
The data below is being used to perform comparative analysis. I wrote the code using apply() and while(), and even though it works as expected, I haven't been successful in optimizing it further. Current run time is more than couple of hours in larger data set.

Following is small example data set:

data_1

```<code>A B C D
2 1 3 2.5
</code>```

data_2

```<code>P Q R S
3 2 4 5.5
</code>```

Data

```<code> A   B   C   D
1.0 0.5 1.3 1.5
1.5 1.2 5.5 3.5
1.1 0.5 1.3 1.5
1.5 1.2 5.5 3.5
1.5 1.2 5.5 3.5
1.1 0.5 1.3 1.5
1.5 1.2 5.5 3.5
1.0 0.5 1.3 1.5
</code>```

Code

```<code># Row counter
rowLine <<- 0

# Set current column to first one
columnLine <<- 1

# Preserve column header and dimensions for final data
finalData <- Data

# Find recursively
findThreshold <- function () {

  if ( columnLine <= ncol(Data) ){

    # Initialize row navigation to zero
    rowLine  <<- 1

    # Navigate through rows
    while (rowLine <= nrow(Data)){

      # If outside threshold
      if ( (Data[rowLine, columnLine] < data_1[columnLine]) |
           (Data[rowLine, columnLine] > data_2[columnLine])){

        finalData[rowLine, columnLine] <<- 1

      } else {

        finalData[rowLine, columnLine] <<- 0

      }

      # Increment row counter
      rowLine <<- rowLine + 1

    }
  }

  # Increment column counter
  columnLine <<- columnLine + 1

}

# Apply
apply(Data, 2, function(x) findThreshold())
</code>```

I also understand using <<- is a big no when it comes using it with loops and recursively analysis like apply().

Please suggest how I can improve this logic further, thanks.

答:
Sounds like a simple Map exercise:

```<code>data.frame(Map(function(d,l,h) d < l | d > h, Data, data_1, data_2))
#     A     B    C     D
#1 TRUE  TRUE TRUE  TRUE
#2 TRUE FALSE TRUE FALSE
#3 TRUE  TRUE TRUE  TRUE
#4 TRUE FALSE TRUE FALSE
#5 TRUE FALSE TRUE FALSE
#6 TRUE  TRUE TRUE  TRUE
#7 TRUE FALSE TRUE FALSE
#8 TRUE  TRUE TRUE  TRUE
</code>```

Just wrap the logical comparison in as.integer if you want a 0/1 output instead:

```<code>data.frame(Map(function(d,l,h) as.integer(d < l | d > h), Data, data_1, data_2))
</code>```

If your data are matrix objects to start with, you could use sweep:

```<code>sweep(Data, 2, data_1, FUN=`<`) | sweep(Data, 2, data_2, FUN=`>`)
#        A     B    C     D
#[1,] TRUE  TRUE TRUE  TRUE
#[2,] TRUE FALSE TRUE FALSE
#[3,] TRUE  TRUE TRUE  TRUE
#[4,] TRUE FALSE TRUE FALSE
#[5,] TRUE FALSE TRUE FALSE
#[6,] TRUE  TRUE TRUE  TRUE
#[7,] TRUE FALSE TRUE FALSE
#[8,] TRUE  TRUE TRUE  TRUE
</code>```

Title: Optimize Apply() While() in R

Body:
The data below is being used to perform comparative analysis. I wrote the code using apply() and while(), and even though it works as expected, I haven't been successful in optimizing it further. Current run time is more than couple of hours in larger data set.

Following is small example data set:

data_1

A B C D
2 1 3 2.5

data_2

P Q R S
3 2 4 5.5

Data

 A   B   C   D
1.0 0.5 1.3 1.5
1.5 1.2 5.5 3.5
1.1 0.5 1.3 1.5
1.5 1.2 5.5 3.5
1.5 1.2 5.5 3.5
1.1 0.5 1.3 1.5
1.5 1.2 5.5 3.5
1.0 0.5 1.3 1.5

Code

# Row counter
rowLine <<- 0

# Set current column to first one
columnLine <<- 1

# Preserve column header and dimensions for final data
finalData <- Data

# Find recursively
findThreshold <- function () {

  if ( columnLine <= ncol(Data) ){

    # Initialize row navigation to zero
    rowLine  <<- 1

    # Navigate through rows
    while (rowLine <= nrow(Data)){

      # If outside threshold
      if ( (Data[rowLine, columnLine] < data_1[columnLine]) |
           (Data[rowLine, columnLine] > data_2[columnLine])){

        finalData[rowLine, columnLine] <<- 1

      } else {

        finalData[rowLine, columnLine] <<- 0

      }

      # Increment row counter
      rowLine <<- rowLine + 1

    }
  }

  # Increment column counter
  columnLine <<- columnLine + 1

}

# Apply
apply(Data, 2, function(x) findThreshold())

I also understand using <<- is a big no when it comes using it with loops and recursively analysis like apply().

Please suggest how I can improve this logic further, thanks.

Body:
Sounds like a simple Map exercise:

data.frame(Map(function(d,l,h) d < l | d > h, Data, data_1, data_2))
#     A     B    C     D
#1 TRUE  TRUE TRUE  TRUE
#2 TRUE FALSE TRUE FALSE
#3 TRUE  TRUE TRUE  TRUE
#4 TRUE FALSE TRUE FALSE
#5 TRUE FALSE TRUE FALSE
#6 TRUE  TRUE TRUE  TRUE
#7 TRUE FALSE TRUE FALSE
#8 TRUE  TRUE TRUE  TRUE

Just wrap the logical comparison in as.integer if you want a 0/1 output instead:

data.frame(Map(function(d,l,h) as.integer(d < l | d > h), Data, data_1, data_2))

If your data are matrix objects to start with, you could use sweep:

sweep(Data, 2, data_1, FUN=`<`) | sweep(Data, 2, data_2, FUN=`>`)
#        A     B    C     D
#[1,] TRUE  TRUE TRUE  TRUE
#[2,] TRUE FALSE TRUE FALSE
#[3,] TRUE  TRUE TRUE  TRUE
#[4,] TRUE FALSE TRUE FALSE
#[5,] TRUE FALSE TRUE FALSE
#[6,] TRUE  TRUE TRUE  TRUE
#[7,] TRUE FALSE TRUE FALSE
#[8,] TRUE  TRUE TRUE  TRUE


问:
Have an 'Unidentified' Class in Accord.Net SVM
I'm using the MultiClassSupportVectorMachine class to do some classification. Specifically, my data has 24 dimensions, with the values being grouped pretty close together. I will be identifying around 10 or so classes in this data.

I'm looking to identify when an inputted value is really far off from the groups. Something along the lines of having a class 0 which would be unidentified and then having classes 1 to 10 only being outputted when the SVM has a high degree of confidence it is in the group.

In essence I am looking to go from the top to the bottom of this image:
this image showing SVM classification

Is something like this possible in accord.net?

Thanks!

答:
I answered my own question!

This can be accomplished by using the Probability function to get an estimate of how accurate the guess is from the SupportVectorMachine class, and then using that as a threshold to reject guesses with a low probability.


问:
Cascading delete on table that references itself
I have a table (say 'MyTable') that can reference itself, ie. it has a ParentId that can point to another record in the same table (so you can store a tree of related nodes).

The problem is that when I try to delete all records that are children of a specific parent, I get the following exception (using EF 6):

The DELETE statement conflicted with the SAME TABLE REFERENCE constraint "FK_dbo.MyTable_dbo.MyTable_ParentId". The conflict occurred in database "foo", table "dbo.MyTable", column 'ParentId'.
  The statement has been terminated.

(I'm executing a Sql command like this context.Database.ExecuteSqlCommand("DELETE FROM [MyTable] WHERE ParentId = {0}", parentId);

I  tried to fix it by adding a Children property and use fluent api to set cascading delete like this:

```<code>modelBuilder.Entity<MyTable>()
.HasMany(t => t.Children)
.WithOptional(t => t.Parent)
.WillCascadeOnDelete(true);
</code>```

But that gives the following error:

Introducing FOREIGN KEY constraint 'FK_dbo.MyTable_dbo.MyTable_ParentId' on table 'MyTable' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

Also when I manually remove the FK and recreate it with ON CASCADE DELETE I get the same error.

I'm a bit lost now on how to fix this.. so any ideas are welcome :)

答:
USE tempdb;
GO

IF OBJECT_ID('tempdb..#Employees') IS NOT NULL
  DROP TABLE #Employees;
GO

CREATE TABLE #Employees
(
  empid   INT          PRIMARY KEY,
  mgrid   INT          NULL REFERENCES #Employees,
  empname VARCHAR(25)  NOT NULL
);
CREATE UNIQUE INDEX idx_unc_mgrid_empid ON #Employees(mgrid, empid);

INSERT INTO #Employees(empid, mgrid, empname) VALUES
  (1,  NULL, 'David'),
  (2,  1,    'Eitan'),
  (3,  1,    'Ina'),
  (4,  2,    'Seraph'),
  (5,  2,    'Jiru'),
  (6,  2,    'Steve'),
  (7,  3,    'Aaron'),
  (8,  5,    'Lilach'),
  (9,  7,    'Rita'),
  (10, 5,    'Sean'),
  (11, 7,    'Gabriel'),
  (12, 9,    'Emilia'),
  (13, 9,    'Michael'),
  (14, 9,    'Didi');
GO

DELETE FROM #Employees WHERE mgrid = 9
SELECT * FROM #Employees;

Body:
I have a table (say 'MyTable') that can reference itself, ie. it has a ParentId that can point to another record in the same table (so you can store a tree of related nodes).

The problem is that when I try to delete all records that are children of a specific parent, I get the following exception (using EF 6):

The DELETE statement conflicted with the SAME TABLE REFERENCE constraint "FK_dbo.MyTable_dbo.MyTable_ParentId". The conflict occurred in database "foo", table "dbo.MyTable", column 'ParentId'.
  The statement has been terminated.

(I'm executing a Sql command like this context.Database.ExecuteSqlCommand("DELETE FROM [MyTable] WHERE ParentId = {0}", parentId);

I  tried to fix it by adding a Children property and use fluent api to set cascading delete like this:

modelBuilder.Entity<MyTable>()
.HasMany(t => t.Children)
.WithOptional(t => t.Parent)
.WillCascadeOnDelete(true);

But that gives the following error:

Introducing FOREIGN KEY constraint 'FK_dbo.MyTable_dbo.MyTable_ParentId' on table 'MyTable' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

Also when I manually remove the FK and recreate it with ON CASCADE DELETE I get the same error.

I'm a bit lost now on how to fix this.. so any ideas are welcome :)


问:
How to make textbox resize as the window resize
Any property to set to make textbox to resize according to the window size?</p>

答:
Layout in WPF is heavily influenced by the parent container. For example, if you are creating a form with labels and input fields, consider using a Grid panel. Controls in WPF by default resize according to the layout behavior of their parent. Here is an example of a window with two labeled text boxes and two buttons that resize along with the window.

```<code><Window>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Label Content="Contact Name" Grid.Row="0" Grid.Column="0" />
        <TextBox Grid.Row="0" Grid.Column="1" />

        <Label Content="Contact Location" Grid.Row="1" Grid.Column="0" />
        <TextBox Grid.Row="1" Grid.Column="1" />

        <StackPanel Orientation="Horizontal" HorizontalAlignment="Right"
                    VerticalAlignment="Bottom" Grid.Row="2" Grid.Column="1">
            <Button Content="OK" Width="75" Height="24" Margin="3" />
            <Button Content="Cancel" Width="75" Height="24" Margin="3" />
        </StackPanel>

    </Grid>
</Window>
</code>```

Or if you wanted something similar to the address bar layout of a browser, you could do something like:

```<code><Window>
    <DockPanel>
        <DockPanel DockPanel.Dock="Top">
            <Button Content="Back" DockPanel.Dock="Left" />
            <Button Content="Forward" DockPanel.Dock="Left" />
            <Button Content="Refresh" DockPanel.Dock="Right" />
            <TextBox /> <!-- fill is assumed for last child -->
        <DockPanel>
        <StatusBar DockPanel.Dock="Bottom" />
        <WebBrowser /> <!-- fill is assumed for last child -->
    </DockPanel>
</Window>
</code>```

Note that in the above example, I nested two DockPanel's. It could also have been achieved with a Grid but the markup would have been much more cluttered. If you are new to WPF, I'd highly suggest playing around with the various panels available to you. Once you learn when to apply a particular panel to a particular layout, it makes WPF much easier to work with.

Body:
Layout in WPF is heavily influenced by the parent container. For example, if you are creating a form with labels and input fields, consider using a Grid panel. Controls in WPF by default resize according to the layout behavior of their parent. Here is an example of a window with two labeled text boxes and two buttons that resize along with the window.

<Window>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Label Content="Contact Name" Grid.Row="0" Grid.Column="0" />
        <TextBox Grid.Row="0" Grid.Column="1" />

        <Label Content="Contact Location" Grid.Row="1" Grid.Column="0" />
        <TextBox Grid.Row="1" Grid.Column="1" />

        <StackPanel Orientation="Horizontal" HorizontalAlignment="Right"
                    VerticalAlignment="Bottom" Grid.Row="2" Grid.Column="1">
            <Button Content="OK" Width="75" Height="24" Margin="3" />
            <Button Content="Cancel" Width="75" Height="24" Margin="3" />
        </StackPanel>

    </Grid>
</Window>

Or if you wanted something similar to the address bar layout of a browser, you could do something like:

<Window>
    <DockPanel>
        <DockPanel DockPanel.Dock="Top">
            <Button Content="Back" DockPanel.Dock="Left" />
            <Button Content="Forward" DockPanel.Dock="Left" />
            <Button Content="Refresh" DockPanel.Dock="Right" />
            <TextBox /> <!-- fill is assumed for last child -->
        <DockPanel>
        <StatusBar DockPanel.Dock="Bottom" />
        <WebBrowser /> <!-- fill is assumed for last child -->
    </DockPanel>
</Window>

Note that in the above example, I nested two DockPanel's. It could also have been achieved with a Grid but the markup would have been much more cluttered. If you are new to WPF, I'd highly suggest playing around with the various panels available to you. Once you learn when to apply a particular panel to a particular layout, it makes WPF much easier to work with.


问:
How to list all calls of a function at runtime?
Is there any way to list (show in VS, write to file) all callers (objects, functions) of a function while the program is running? Possibly using the debugger?

I need to record all calls (including callers) of a function from the launch of the program to its termination.

A simple scan of the source code or the binary does not do the job because the program could operate as a server which receives requests to call the desired function.

If Visual Studio does not provide this feature, are there any other solutions to this problem?

答:
IMO, your best solution is to add logging capabilities.

Find all calls to your function.  Print some kind of information to a log file before the function is called.  This will give you an annotated history of the function calls.

Another idea is to use a documentation tool, like Doxygen, which can print a "caller" and "callee" diagram.  However, this is not during your program's execution.


问:
Functions and random integers
I want to first say this is my homework, so I do not want it done for me I just need some guidance as my teacher is not providing it for me nor can I find my answer online. Here is my problem

Write a program that displays a table of distance equivalents in miles and kilometers. You must generate the table by running a function inside a loop in main. Generate a random integer from 10 to 60, inclusive, in each loop cycle. Use this latter value as the miles argument to the function. The function must then print a line in the table. Repeat: The function prints the table.

I am able to get the top part of the table to print correctly. When I run my code at the top it gives me the calculation for the kilometers but then just prints the same number 10 times.

How do I get it to print out the 10 random numbers for the miles and the calculations in the right spot for the kilometers?

Example output:

```<code>  MILES   KILOMETERS
52.00     83.68568
11.00     17.70274
40.00     64.37360
21.00     33.79614
14.00     22.53076
23.00     37.01482
48.00     77.24832
22.00     35.40548
15.00     24.14010
16.00     25.74944
</code>```

obviously the sample output is supposed to be in two different columns for the miles and the kilometers but I couldn't figure out how to set that up on here.

my code

```<code>import random
  def main():
      print('Miles\tKilometers')
      miles = random.randint(10, 60)
      find_kilometers(miles)
      for number in range(10):
      print(miles)

 def find_kilometers(miles):
         kilometers = miles * 1.60934
         print(format(kilometers, '.5f'))

main()
</code>```

答:
Probably a bit late for your homework, but I'll answer anyway.

You're assigning the value for miles outside of your for loop, so it's going to use that single value 10 times.

Also I'm assuming that it's just a typo in your post but the print(miles) line should be indented so it's within the for loop.

Title: Functions and random integers

Body:
I want to first say this is my homework, so I do not want it done for me I just need some guidance as my teacher is not providing it for me nor can I find my answer online. Here is my problem

Write a program that displays a table of distance equivalents in miles and kilometers. You must generate the table by running a function inside a loop in main. Generate a random integer from 10 to 60, inclusive, in each loop cycle. Use this latter value as the miles argument to the function. The function must then print a line in the table. Repeat: The function prints the table.

I am able to get the top part of the table to print correctly. When I run my code at the top it gives me the calculation for the kilometers but then just prints the same number 10 times.

How do I get it to print out the 10 random numbers for the miles and the calculations in the right spot for the kilometers?

Example output:

  MILES   KILOMETERS
52.00     83.68568
11.00     17.70274
40.00     64.37360
21.00     33.79614
14.00     22.53076
23.00     37.01482
48.00     77.24832
22.00     35.40548
15.00     24.14010
16.00     25.74944

obviously the sample output is supposed to be in two different columns for the miles and the kilometers but I couldn't figure out how to set that up on here.

my code

import random
  def main():
      print('Miles\tKilometers')
      miles = random.randint(10, 60)
      find_kilometers(miles)
      for number in range(10):
      print(miles)

 def find_kilometers(miles):
         kilometers = miles * 1.60934
         print(format(kilometers, '.5f'))

main()


问:
Is it possible to cancel a SqlBulkCopy.WriteToServer (c#)?
I am using SqlBulkCopy.WriteToServer (C#) to copy billions of rows, and which takes hours to complete. Sometimes I need to stop the operation for some urgent tasks, but I don't know how to do so. Can I do something on the arriving of the notification event (with SqlBulkCopy.NotifyAfter and SqlBulkCopy.SqlRowsCopied)?</p>

答:
Can I do something on the arriving of the notification event

As a SQL administrator you can always find the session running the bulk load and KILL it, like this:

```<code>declare @spid int = (
select session_id
from sys.dm_exec_requests
where command = 'BULK INSERT')

if @spid is not null
begin
    declare @sql varchar(200) = concat('kill ',@spid)

    exec ( @sql )

end
</code>```

If you want to do this in your code, use the Async version of WriteToServer which accepts a Cancelation Token.  eg

```<code>  static void Main(string[] args)
    {
        using (var src = new SqlConnection("server=.;database=tempdb;integrated security=true"))
        using (var dest = new SqlConnection("server=.;database=tempdb;integrated security=true"))
        {
            src.Open();
            dest.Open();
            var cmd = new SqlCommand("create table #t(id int)", dest);
            cmd.ExecuteNonQuery();

            bool cancel = false;
            var cancelationTokenSource = new CancellationTokenSource();
            var srcCmd = new SqlCommand("select row_number() over (order by (select null)) id from sys.objects o, sys.columns c, sys.columns c2", src);
            using (var rdr = srcCmd.ExecuteReader())
            {
                var bc = new SqlBulkCopy(dest);
                bc.NotifyAfter = 10000;
                bc.SqlRowsCopied += (s, a) =>
                {
                    Console.WriteLine($"{a.RowsCopied} rows copied");
                    if (cancel)
                    {
                        dest.Close();
                    }
                };

                bc.DestinationTableName = "#t";
                bc.ColumnMappings.Add(new SqlBulkCopyColumnMapping("id", "id"));

                var task = bc.WriteToServerAsync(rdr, cancelationTokenSource.Token);

                Console.WriteLine("Hit any key to cancel the bulk load");
                while (!task.Wait(1000))
                {
                    if (Console.KeyAvailable)
                    {

                        cancelationTokenSource.Cancel();
                        try
                        {
                            task.Wait();
                        }
                        catch (AggregateException ex)
                        {
                            Console.WriteLine(ex.InnerException.Message);
                            Console.WriteLine("WriteToServer Canceled");
                            break;
                        }
                    }
                }

                Console.WriteLine("Hit any key to exit");
                return;
            }

        }
    }
</code>```

Body:
Can I do something on the arriving of the notification event

As a SQL administrator you can always find the session running the bulk load and KILL it, like this:

declare @spid int = (
select session_id
from sys.dm_exec_requests
where command = 'BULK INSERT')

if @spid is not null
begin
    declare @sql varchar(200) = concat('kill ',@spid)

    exec ( @sql )

end

If you want to do this in your code, use the Async version of WriteToServer which accepts a Cancelation Token.  eg

  static void Main(string[] args)
    {
        using (var src = new SqlConnection("server=.;database=tempdb;integrated security=true"))
        using (var dest = new SqlConnection("server=.;database=tempdb;integrated security=true"))
        {
            src.Open();
            dest.Open();
            var cmd = new SqlCommand("create table #t(id int)", dest);
            cmd.ExecuteNonQuery();

            bool cancel = false;
            var cancelationTokenSource = new CancellationTokenSource();
            var srcCmd = new SqlCommand("select row_number() over (order by (select null)) id from sys.objects o, sys.columns c, sys.columns c2", src);
            using (var rdr = srcCmd.ExecuteReader())
            {
                var bc = new SqlBulkCopy(dest);
                bc.NotifyAfter = 10000;
                bc.SqlRowsCopied += (s, a) =>
                {
                    Console.WriteLine($"{a.RowsCopied} rows copied");
                    if (cancel)
                    {
                        dest.Close();
                    }
                };

                bc.DestinationTableName = "#t";
                bc.ColumnMappings.Add(new SqlBulkCopyColumnMapping("id", "id"));

                var task = bc.WriteToServerAsync(rdr, cancelationTokenSource.Token);

                Console.WriteLine("Hit any key to cancel the bulk load");
                while (!task.Wait(1000))
                {
                    if (Console.KeyAvailable)
                    {

                        cancelationTokenSource.Cancel();
                        try
                        {
                            task.Wait();
                        }
                        catch (AggregateException ex)
                        {
                            Console.WriteLine(ex.InnerException.Message);
                            Console.WriteLine("WriteToServer Canceled");
                            break;
                        }
                    }
                }

                Console.WriteLine("Hit any key to exit");
                return;
            }

        }
    }


问:
Looking to iterate over JSON in a Sequelize / Postgres DB query to find a matching value
This is my first post here so please be gentle.
I am using Sequelize w/ PostgresDB in Node and trying to search for a contact by email using findOrCreate. The email entry is in JSON format (see structure below)...

I want to find a contact by email and iterate over each email address in the JSON array for each contact entry.

I am passing in an email address and a name in the POST payload.

If I cannot find the contact by email I want to create a new contact (this part is easy).

```<code>router.post('/gmail/fetchcontact', function (req, res, next){

    Contacts.findOrCreate({
        where: {
          email:  // this is where I am stuck. How do I access this array and loop over?
        },
        defaults: {
          name: req.body.name //
        }
      })
      .then(response => {
        if (response[1] === true) {
          console.log('RESPONSE!!!', response[1])
        }

      })
</code>```

// THIS IS THE STRUCTURE OF THE JSON I AM LOOKING TO ITERATE OVER

```<code>[{
          address: 'your.name@gmail.com',
          primary: true,
          rel: 'http://schemas.google.com/g/2005#home'
        },{
          address: 'work@work.com',
          primary: false,
          labels: ['work'],
        },{
          address: 'play@play.com',
          primary: false,
          labels: ['play'],
        }]
</code>```

Any ideas? Any help would be greatly appreciated. Thanks!

答:
I would create an array of just the emails and then do an $in search.

```<code>const emails = [{
      address: 'your.name@gmail.com',
      primary: true,
      rel: 'http://schemas.google.com/g/2005#home'
    },{
      address: 'work@work.com',
      primary: false,
      labels: ['work'],
    },{
      address: 'play@play.com',
      primary: false,
      labels: ['play'],
    }].map(email => email.address);
</code>```

Search:

```<code>Contacts.findOrCreate({
    where: {
      email: { $in: emails }
    },
    defaults: {
      name: req.body.name //
    }
  })
  .then(response => {
    if (response[1] === true) {
      console.log('RESPONSE!!!', response[1])
    }
  });
</code>```

Documentation on $in is here: http://docs.sequelizejs.com/manual/tutorial/models-usage.html#-findall-search-for-multiple-elements-in-the-database

Body:
This is my first post here so please be gentle.
I am using Sequelize w/ PostgresDB in Node and trying to search for a contact by email using findOrCreate. The email entry is in JSON format (see structure below)...

I want to find a contact by email and iterate over each email address in the JSON array for each contact entry.

I am passing in an email address and a name in the POST payload.

If I cannot find the contact by email I want to create a new contact (this part is easy).

router.post('/gmail/fetchcontact', function (req, res, next){

    Contacts.findOrCreate({
        where: {
          email:  // this is where I am stuck. How do I access this array and loop over?
        },
        defaults: {
          name: req.body.name //
        }
      })
      .then(response => {
        if (response[1] === true) {
          console.log('RESPONSE!!!', response[1])
        }

      })

// THIS IS THE STRUCTURE OF THE JSON I AM LOOKING TO ITERATE OVER

[{
          address: 'your.name@gmail.com',
          primary: true,
          rel: 'http://schemas.google.com/g/2005#home'
        },{
          address: 'work@work.com',
          primary: false,
          labels: ['work'],
        },{
          address: 'play@play.com',
          primary: false,
          labels: ['play'],
        }]

Any ideas? Any help would be greatly appreciated. Thanks!

Body:
I would create an array of just the emails and then do an $in search.

const emails = [{
      address: 'your.name@gmail.com',
      primary: true,
      rel: 'http://schemas.google.com/g/2005#home'
    },{
      address: 'work@work.com',
      primary: false,
      labels: ['work'],
    },{
      address: 'play@play.com',
      primary: false,
      labels: ['play'],
    }].map(email => email.address);

Search:

Contacts.findOrCreate({
    where: {
      email: { $in: emails }
    },
    defaults: {
      name: req.body.name //
    }
  })
  .then(response => {
    if (response[1] === true) {
      console.log('RESPONSE!!!', response[1])
    }
  });

Documentation on $in is here: http://docs.sequelizejs.com/manual/tutorial/models-usage.html#-findall-search-for-multiple-elements-in-the-database


问:
Why is the size of this struct 32?
This is the struct.

```<code>//Structure pour communiquer les paramètres de traitement à travers le MMF
struct params_traitement_mmf
{
    int brilliance;
    double contraste;
    char convolution[9];
};
</code>```

This is my code to display the size of this struct :

```<code>    char valeur[10];
    sprintf(valeur, "%d", sizeof(params_traitement_mmf));
    MessageBoxA(NULL, valeur, "rien", MB_OK);
</code>```

The MessageBox displays 32.
Thank you!

答:
You're getting

```<code>int - 4 bytes
padding - 4 bytes (So the double is aligned)
double 8 - bytes
char array - 9 bytes
padding - 7 bytes
</code>```

Why the padding at the end? Not certain, but suppose you had an array of these; you'll need it 8 byte aligned for the double.

Title: Why is the size of this struct 32?

Body:
This is the struct.

//Structure pour communiquer les paramètres de traitement à travers le MMF
struct params_traitement_mmf
{
    int brilliance;
    double contraste;
    char convolution[9];
};

This is my code to display the size of this struct :

    char valeur[10];
    sprintf(valeur, "%d", sizeof(params_traitement_mmf));
    MessageBoxA(NULL, valeur, "rien", MB_OK);

The MessageBox displays 32.
Thank you!

Body:
You're getting

int - 4 bytes
padding - 4 bytes (So the double is aligned)
double 8 - bytes
char array - 9 bytes
padding - 7 bytes

Why the padding at the end? Not certain, but suppose you had an array of these; you'll need it 8 byte aligned for the double.


问:
Unexpected behaviour when previewing images before uploading
I have been working on previewing multiple images before they are uploaded and tried using @ratan-paul response to the "Preview an image before it is uploaded" quite useful. However when I tried to tweak the code a bit I got a rather unexpected result. What I did was to create a  tag for each <image> to add some styling options. Here's the jQuery code I ended up with:

```<code>$(function () {
    var span_id = "";
    function readURL(input) {
        for(var i =0; i< input.files.length; i++){
            var span = $('<span>');
            span_id = "span"+i;
            span.attr('id',span_id);
            span.appendTo('#img-previews');
            if (input.files[i]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    var img = $('<img id="dynamic">');
                    img.attr('src', e.target.result);
                    img.attr('height','150px');
                    img.attr('width','200px');
                    img.appendTo("#"+span_id);
                };
                reader.readAsDataURL(input.files[i]);
            }
        }
    }

    $("#imgUpload").change(function(){
        readURL(this);
    });
});
</code>```

Now the strange thing is that when I run the code above I create a  tag for each image but all the images get crammed into the last  created. On the other hand if i debug the script I get the wanted result where each image is inserted into its own  tag. I'm kinda baffled by this so if anyone has any ideas as to why this is happening or how to avoid it would appreciate the assistance.

Here is a screen grab of when I run the script without debugging:

And here is a screen grab of the result when stepped through with the js debugger

答:
Short story:

Change your loop to

```<code>for(let i =0; i< input.files.length; i++){
</code>```

let keyword in the for loop

Note, let in the for loop may not work as one would expect for IE11 and Edge. You could move the creation of your span into the reader.onload event to adjust for those browsers (your generation of id's will have to change though).

Long story:

using var i =0 instantiates i over the entire loop, whereas let i =0 binds it to the current iteration.

What's happening is that the for loop fires off the async call reader.onload which is added to the JS event loop for future resolution, and the for loop proceeds to its next iteration. Important bit: At the next iteration, the previous reader.onload had not resolved yet.

Sometime later, the reader.onload async calls return after the for loop is completed (where i is at the max value for the loop), and appends the resultant imgs to #span_(max i).

Update: OK, so let may not be supported everywhere, caniuse puts it at 80% as of July 2017.

For consistent results, move the creation of the span element into the onload event:

```<code>function readURL(input) {
    for(var i =0; i< input.files.length; i++){
        if (input.files[i]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                var span = $('<span>');
                var uniqueId;
                do {  //simple loop to generate a unique id
                  uniqueId = 'img-' + (Math.random()+1).toString(36).substring(2, 7);
                } while ($('#' + uniqueId).length > 0); //redo loop if id not unique
                span.attr('id', uniqueId);
                span.appendTo('#img-previews');

                var img = $('<img>');
                img.attr('src', e.target.result);
                img.attr('height','150px');
                img.attr('width','200px');
                span.append(img);
            };
            reader.readAsDataURL(input.files[i]);
        }
    }
}
</code>```

Note that the creation of these span elements may end up being out of order; if you'd want them in the order as they were added, have a look at using Promise.all (or the jQuery version).

Also note, I haven't tested the above so some massaging may be needed.

Body:
I have been working on previewing multiple images before they are uploaded and tried using @ratan-paul response to the "Preview an image before it is uploaded" quite useful. However when I tried to tweak the code a bit I got a rather unexpected result. What I did was to create a  tag for each <image> to add some styling options. Here's the jQuery code I ended up with:

$(function () {
    var span_id = "";
    function readURL(input) {
        for(var i =0; i< input.files.length; i++){
            var span = $('');
            span_id = "span"+i;
            span.attr('id',span_id);
            span.appendTo('#img-previews');
            if (input.files[i]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    var img = $('');
                    img.attr('src', e.target.result);
                    img.attr('height','150px');
                    img.attr('width','200px');
                    img.appendTo("#"+span_id);
                };
                reader.readAsDataURL(input.files[i]);
            }
        }
    }

    $("#imgUpload").change(function(){
        readURL(this);
    });
});

Now the strange thing is that when I run the code above I create a  tag for each image but all the images get crammed into the last  created. On the other hand if i debug the script I get the wanted result where each image is inserted into its own  tag. I'm kinda baffled by this so if anyone has any ideas as to why this is happening or how to avoid it would appreciate the assistance.

Here is a screen grab of when I run the script without debugging:

And here is a screen grab of the result when stepped through with the js debugger

Body:
Short story:

Change your loop to

for(let i =0; i< input.files.length; i++){

let keyword in the for loop

Note, let in the for loop may not work as one would expect for IE11 and Edge. You could move the creation of your span into the reader.onload event to adjust for those browsers (your generation of id's will have to change though).

Long story:

using var i =0 instantiates i over the entire loop, whereas let i =0 binds it to the current iteration.

What's happening is that the for loop fires off the async call reader.onload which is added to the JS event loop for future resolution, and the for loop proceeds to its next iteration. Important bit: At the next iteration, the previous reader.onload had not resolved yet.

Sometime later, the reader.onload async calls return after the for loop is completed (where i is at the max value for the loop), and appends the resultant imgs to #span_(max i).

Update: OK, so let may not be supported everywhere, caniuse puts it at 80% as of July 2017.

For consistent results, move the creation of the span element into the onload event:

function readURL(input) {
    for(var i =0; i< input.files.length; i++){
        if (input.files[i]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                var span = $('<span>');
                var uniqueId;
                do {  //simple loop to generate a unique id
                  uniqueId = 'img-' + (Math.random()+1).toString(36).substring(2, 7);
                } while ($('#' + uniqueId).length > 0); //redo loop if id not unique
                span.attr('id', uniqueId);
                span.appendTo('#img-previews');

                var img = $('<img>');
                img.attr('src', e.target.result);
                img.attr('height','150px');
                img.attr('width','200px');
                span.append(img);
            };
            reader.readAsDataURL(input.files[i]);
        }
    }
}

Note that the creation of these span elements may end up being out of order; if you'd want them in the order as they were added, have a look at using Promise.all (or the jQuery version).

Also note, I haven't tested the above so some massaging may be needed.


问:
Override a Method from a Stateless Spring Service with Additional Parameter
I'm trying to improve the structure of some code I wrote. I want to override a method of a service, but need another parameter/object for the new functionality. In plain Java, I would solve this by making the needed object an attribute of the class and initialized in the constructor. But because this is a bean, the constructor has no arguments.

```<code>@Service("testService")
public class TestService extends AbstractService {
    @Override
    public String perform(String original) {
        return original + extra; //<-- What's the best way to get
                                 //    'extra' here from the controller
                                 //    without going stateful?
    }
}

######

public abstract class AbstractService {
    public String perform(String original);
}
</code>```

I think my problem is best described by the code and comments above. How would I get the object to be accessible from that method without adding attributes to the class?

I'm very new to Spring, so feel free to tell me I'm way off track.

答:
Bean can have constructor argument and the values can be injected into constructor using constructor dependency injection.
example

If the extra value is just a property you can inject the value from the property file using @Value or @Autowire Environment and get the value form it.
example

Body:
I'm trying to improve the structure of some code I wrote. I want to override a method of a service, but need another parameter/object for the new functionality. In plain Java, I would solve this by making the needed object an attribute of the class and initialized in the constructor. But because this is a bean, the constructor has no arguments.

@Service("testService")
public class TestService extends AbstractService {
    @Override
    public String perform(String original) {
        return original + extra; //<-- What's the best way to get
                                 //    'extra' here from the controller
                                 //    without going stateful?
    }
}

######

public abstract class AbstractService {
    public String perform(String original);
}

I think my problem is best described by the code and comments above. How would I get the object to be accessible from that method without adding attributes to the class?

I'm very new to Spring, so feel free to tell me I'm way off track.


问:
R : Error in Axis && box : invalid 'y' type in ' x && y'
I'm trying to use the package "scatterplot3d" with R. when I try it like this :

```<code>data<-read.table("C:\\Users\\Firas\\Desktop\\southafrica.txt",header=TRUE,sep="")
View(data)
colnames(data)
colnames(data) = c("performance","croissance","inflation","balance")

library(scatterplot3d)
scatterplot3d(data$inflation,data$croissance,data$performance,highlight.3d = TRUE, col.axis="blue",col.grid="lightblue",box="False",pch=20,type="h",main="Performance macroeconomique en Afrique du Sud")
</code>```

I get the error : Error in axis && box : invalid 'y' type in 'x && y'
can someone help me please?

答:
Change your code on line 4 to

```<code>colnames(data) <- c("performance","croissance","inflation","balance")
</code>```

I had the same problem and this way it worked.

Body:
I'm trying to use the package "scatterplot3d" with R. when I try it like this :

data<-read.table("C:\\Users\\Firas\\Desktop\\southafrica.txt",header=TRUE,sep="")
View(data)
colnames(data)
colnames(data) = c("performance","croissance","inflation","balance")

library(scatterplot3d)
scatterplot3d(data$inflation,data$croissance,data$performance,highlight.3d = TRUE, col.axis="blue",col.grid="lightblue",box="False",pch=20,type="h",main="Performance macroeconomique en Afrique du Sud")

I get the error : Error in axis && box : invalid 'y' type in 'x && y'
can someone help me please?

Body:
Change your code on line 4 to

colnames(data) <- c("performance","croissance","inflation","balance")

I had the same problem and this way it worked.


问:
Use Font Awesome Icons in CSS
I have some CSS that looks like this:

#content h2 {
   background: url(../images/tContent.jpg) no-repeat 0 6px;
}
```

I would like to replace the image with an icon from Font Awesome.

I do not see anyway to use the icon in CSS as a background image. Is this possible to do assuming the Font Awesome stylesheets/fonts are loaded before my CSS?

答:
For this you just need to add content attribute and font-family attribute to the required element via :before or :after wherever applicable.

For example: I wanted to attach an attachment icon after all the a element inside my post. So, first I need to search if such icon exists in fontawesome. Like in the case I found it here, i.e. fa fa-paperclip. Then I would right click the icon there, and go the ::before pseudo property to fetch out the content tag it is using, which in my case I found to be \f0c6. Then I would use that in my css like this:

```<code>   .post a:after {
     font-family: FontAwesome,
     content: " \f0c6" /* I added a space before \ for better UI */
    }
</code>```

Title: Use Font Awesome Icons in CSS

Body:
I have some CSS that looks like this:

#content h2 {
   background: url(../images/tContent.jpg) no-repeat 0 6px;
}

I would like to replace the image with an icon from Font Awesome.

I do not see anyway to use the icon in CSS as a background image. Is this possible to do assuming the Font Awesome stylesheets/fonts are loaded before my CSS?

Body:
For this you just need to add content attribute and font-family attribute to the required element via :before or :after wherever applicable.

For example: I wanted to attach an attachment icon after all the a element inside my post. So, first I need to search if such icon exists in fontawesome. Like in the case I found it here, i.e. fa fa-paperclip. Then I would right click the icon there, and go the ::before pseudo property to fetch out the content tag it is using, which in my case I found to be \f0c6. Then I would use that in my css like this:

   .post a:after {
     font-family: FontAwesome,
     content: " \f0c6" /* I added a space before \ for better UI */
    }


问:
jquery - Using Lightbox plugin with blob from mysql database
So I am trying to incorporate the LightBox plugin in order to have pop up images: LightBox Info

However my php code code uses an img tag rather than an a tag as Lightbox so requires. It seems the href and src conflicts when I try it. The images and everything display correctly and it is just a matter of using LightBox with my code. I was wondering if any of guys know how to do it.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <title>Greeting Cards</title>

  <link rel="icon" type="image/png" href="../../favicon-32x32.png" sizes="32x32" />
  <link rel="icon" type="image/png" href="../../favicon-16x16.png" sizes="16x16" />
  <link rel="icon" type="image/x-icon" href="../../chromevers.ico" />

  <link rel="stylesheet" type="text/css" href="../../styles/catbar.css">
  <link rel="stylesheet" href="/var/www/lightbox2-master/dist/css/lightbox.css">

<?php
include '/var/db_file.php';
include '/var/www/WideImage/lib/WideImage.php';

$con = mysqli_connect($theDb,$usr, $pass, "images");
mysqli_select_db($con, "images");

$query = "SELECT * FROM Greeting_Cards";
$result = mysqli_query($con, $query);
$images = array();

while($row = mysqli_fetch_assoc($result)){
  $images[] = $row['image'];
}

echo '
';

foreach ($images as $image) {
  $image = WideImage::loadFromString($image)->resize(300, 300);
  echo '';
}
echo '
';

mysqli_close($con);

?>

```

Thank you!

答:
I managed to display my images another way. I uploaded the images to the server and stored the image path on the database. This way would make your website faster since you wouldn't be pulling a BLOB for lots of images and just would reference them on your server. Here is the line of code:

echo '';

The $image variable is the $row = mysqli_fetch_assoc() call storing the image path. And $reimage is using the php library WideImage to  load an image from path. That library also has lots of other very useful image manipulation functions that you can use. Hope this helped!

Body:
So I am trying to incorporate the LightBox plugin in order to have pop up images: LightBox Info

However my php code code uses an img tag rather than an a tag as Lightbox so requires. It seems the href and src conflicts when I try it. The images and everything display correctly and it is just a matter of using LightBox with my code. I was wondering if any of guys know how to do it.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <title>Greeting Cards</title>

  <link rel="icon" type="image/png" href="../../favicon-32x32.png" sizes="32x32" />
  <link rel="icon" type="image/png" href="../../favicon-16x16.png" sizes="16x16" />
  <link rel="icon" type="image/x-icon" href="../../chromevers.ico" />

  <link rel="stylesheet" type="text/css" href="../../styles/catbar.css">
  <link rel="stylesheet" href="/var/www/lightbox2-master/dist/css/lightbox.css">

<?php
include '/var/db_file.php';
include '/var/www/WideImage/lib/WideImage.php';

$con = mysqli_connect($theDb,$usr, $pass, "images");
mysqli_select_db($con, "images");

$query = "SELECT * FROM Greeting_Cards";
$result = mysqli_query($con, $query);
$images = array();

while($row = mysqli_fetch_assoc($result)){
  $images[] = $row['image'];
}

echo '
';

foreach ($images as $image) {
  $image = WideImage::loadFromString($image)->resize(300, 300);
  echo '';
}
echo '
';

mysqli_close($con);

?>

Thank you!

Body:
I managed to display my images another way. I uploaded the images to the server and stored the image path on the database. This way would make your website faster since you wouldn't be pulling a BLOB for lots of images and just would reference them on your server. Here is the line of code:

echo '<a href="'. $image.'" data-lightbox="roadtrip"><img id="dbImages" src="data:image/jpg;base64,'.base64_encode($reimage).'"/></a>';

The $image variable is the $row = mysqli_fetch_assoc() call storing the image path. And $reimage is using the php library WideImage to  load an image from path. That library also has lots of other very useful image manipulation functions that you can use. Hope this helped!


问:
How to fetch data about current user in ASP .NET MVC?
So, I added a new Parameter to my ApplicationUser class, which is called SocialName. I would like to display it when user is logged in, at the top right corner. There, we have this piece of code:

```<code>@Html.ActionLink("Hello, " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</code>```

Now the thing is, I would like to display parameter other than Current user's username. I found passing the model to the Partial View problematic because I need to do it for every single action, otherwise I will have Null Reference. Do you have any ideas how to do this?

答:
You can get the user from this code:

ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

You can have this in your controller or view then user with all properties will be available for you.

Body:
So, I added a new Parameter to my ApplicationUser class, which is called SocialName. I would like to display it when user is logged in, at the top right corner. There, we have this piece of code:

@Html.ActionLink("Hello, " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

Now the thing is, I would like to display parameter other than Current user's username. I found passing the model to the Partial View problematic because I need to do it for every single action, otherwise I will have Null Reference. Do you have any ideas how to do this?


问:
IIS 7 unable to find Microsoft.CodDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider DLL
So when deploying our web service using a customized build configuration, after deploying I get the error:

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, could not be located.

when trying to browse the site. Looking in the bin\~configurationName~ folder, I can find the specified DLL just fine though. The error is referencing these lines in my web.config:

```<code>  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
</code>```

Odd thing is when building/deploying for Debug on the same server, I don't run into this issue and everything seems to work fine (which leads me to believe this error exists with my project configuration, not the deployment server). The configuration I'm building for when getting this error is our custom defined QA config, which outputs to bin\QA, so I'm wondering if there's something special I need to do to get the ASP.NET compiler to look at special output folders?

答:
So this was caused because I had nested all the assemblies for the site under a folder with the configurations name like you would do in a console/windows app (e.g. 'bin\Debug'). For web applications, the assemblies do not get nested under a config folder (e.g. they should go in 'bin\').

Hope this helps others!

Body:
So when deploying our web service using a customized build configuration, after deploying I get the error:

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, could not be located.

when trying to browse the site. Looking in the bin\~configurationName~ folder, I can find the specified DLL just fine though. The error is referencing these lines in my web.config:

  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>

Odd thing is when building/deploying for Debug on the same server, I don't run into this issue and everything seems to work fine (which leads me to believe this error exists with my project configuration, not the deployment server). The configuration I'm building for when getting this error is our custom defined QA config, which outputs to bin\QA, so I'm wondering if there's something special I need to do to get the ASP.NET compiler to look at special output folders?


问:
Custom UIbutton inside a nested UICollectionView cell does not get fired
I have a main UICollectionView which contains a custom header and a custom cell. Inside the custom cell I have another UICollectionView with a custom cell in which there are three buttons (inside a stackView) that has added target as a selector function to it for .touchUpInside but when I touch the button it does not fire the selector function at all. didSelectItemAt function gets called on parent UICollectionView but not the nested one. If I comment out the parent didSelectItemAt nothing is called.

I have also set the nested collectionView delegate. Any idea what I should do to make it work would be much appreciated.

(I don't use storyboard)

答: Check that view.isUserInteractionEnabled is true for the parent view.


问:
Gradient from non-trainable weights function
I'm trying to implement a self-written loss function. My pipeline is as follows

x -> {constant computation} = x_feature -> machine learning training -> y_feature -> {constant computation} = y_produced

These "constant computations" are necessary to bring out the differences between the desired o/p and produced o/p.

So if I take the L2 norm of the y_produced and y_original, how should I incorporate this loss in the original loss.

Please Note that y_produced has a different dimension than y_feature.

答:
As long as you are using differentiable operations there is no difference between "constant transformations" and "learnable ones". There is no such distinction, look even at the linear layer of a neural net

```<code>f(x) = sigmoid( W * x + b )
</code>```

is it constant or learnable? W and b are trained, but "sigmoid" is not, yet gradient flows the same way, no matter if something is a variable or not. In particular gradient wrt. to x is the same for

```<code>g(x) = sigmoid( A * x + c )
</code>```

where A and c are constants.

The only problem you will encounter is using non-differentiable operations, such as: argmax, sorting, indexing, sampling etc. these operations do not have a well defined gradient thus you cannot directly use first order optimisers with them. As long as you stick with the differentiable ones - the problem described does not really exist - there is no difference between "constant transromations" and any other transformations - no matter change of the size etc.

Body:
As long as you are using differentiable operations there is no difference between "constant transformations" and "learnable ones". There is no such distinction, look even at the linear layer of a neural net

f(x) = sigmoid( W * x + b )

is it constant or learnable? W and b are trained, but "sigmoid" is not, yet gradient flows the same way, no matter if something is a variable or not. In particular gradient wrt. to x is the same for

g(x) = sigmoid( A * x + c )

where A and c are constants.

The only problem you will encounter is using non-differentiable operations, such as: argmax, sorting, indexing, sampling etc. these operations do not have a well defined gradient thus you cannot directly use first order optimisers with them. As long as you stick with the differentiable ones - the problem described does not really exist - there is no difference between "constant transromations" and any other transformations - no matter change of the size etc.


问:
NLTK: Get word from Synset ID
Using NLTK is there a way of getting the word and its POS given the Synset ID?

I have a set if Synset ID and their corresponding domains, I need a way to extract label using the SynsetID
Thanks

Ankit

答:
Now with nltk 3.2.4 (and probably already a bit before), you can simply use the method synset_from_pos_and_offset(pos, offset) from the nltk.corpus.reader.wordnet module</p>

```<code>import nltk
from nltk.corpus import wordnet
wordnet.synset_from_pos_and_offset('n',2403454)
</code>```

Title: NLTK: Get word from Synset ID

Body:
Now with nltk 3.2.4 (and probably already a bit before), you can simply use the method synset_from_pos_and_offset(pos, offset) from the nltk.corpus.reader.wordnet module

import nltk
from nltk.corpus import wordnet
wordnet.synset_from_pos_and_offset('n',2403454)


问:
How to send a Status Code 500 in ASP.Net and still write to the response?
I have an ASP.Net single-file web service (a .ashx file containing an IHttpHandler implementation) which needs to be able to return errors as responses with 500 Internal Server Error status codes. This is a relatively straightforward thing to do in PHP:

```<code>header("HTTP/1.1 500 Internal Server Error");
header("Content-Type: text/plain");
echo "Unable to connect to database on $dbHost";
</code>```

The ASP.Net (C#) equivalent should be:

```<code>Context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
Context.Response.ContentType = "text/plain";
Context.Response.Write("Unable to connect to database on " + dbHost);
</code>```

Of course, this doesn't work as expected; instead, IIS intercepts the 500 status code, trashes whatever I've written to the Response object, and sends either debug info or a custom error page, depending on how the app is configured.

My question - how can I suppress this IIS behaviour and send error information directly from my IHttpHandler implementation?

This app is a port from PHP; the client-side is already written, so I'm essentially stuck with this spec. Sending errors with a 200 status code sadly doesn't fit the mould.

Ideally, I need to control the behaviour programmatically, because this is part of an SDK we want to distribute without any "edit this file" and "change this IIS setting" supplementary instructions.

Thanks!

Edit: Sorted. Context.Response.TrySkipIisCustomErrors = true was the ticket. Wow.

答:
I have used the following in the past and been able to throw a 503 error with a custom message using the code shown below in the Page_Load method. I use this page behind a load balancer as the ping page for the load balancer to know if a server is in service or not.

Hope this helps.

```<code>        protected void Page_Load(object sender, System.EventArgs e)
    {
        if (Common.CheckDatabaseConnection())
        {
            this.LiteralMachineName.Text = Environment.MachineName;
        }
        else
        {
            Response.ClearHeaders();
            Response.ClearContent();
            Response.Status = "503 ServiceUnavailable";
            Response.StatusCode = 503;
            Response.StatusDescription= "An error has occurred";
            Response.Flush();
            throw new HttpException(503,string.Format("An internal error occurred in the Application on {0}",Environment.MachineName));
        }
    }
</code>```

Body:
I have an ASP.Net single-file web service (a .ashx file containing an IHttpHandler implementation) which needs to be able to return errors as responses with 500 Internal Server Error status codes. This is a relatively straightforward thing to do in PHP:

header("HTTP/1.1 500 Internal Server Error");
header("Content-Type: text/plain");
echo "Unable to connect to database on $dbHost";

The ASP.Net (C#) equivalent should be:

Context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
Context.Response.ContentType = "text/plain";
Context.Response.Write("Unable to connect to database on " + dbHost);

Of course, this doesn't work as expected; instead, IIS intercepts the 500 status code, trashes whatever I've written to the Response object, and sends either debug info or a custom error page, depending on how the app is configured.

My question - how can I suppress this IIS behaviour and send error information directly from my IHttpHandler implementation?

This app is a port from PHP; the client-side is already written, so I'm essentially stuck with this spec. Sending errors with a 200 status code sadly doesn't fit the mould.

Ideally, I need to control the behaviour programmatically, because this is part of an SDK we want to distribute without any "edit this file" and "change this IIS setting" supplementary instructions.

Thanks!

Edit: Sorted. Context.Response.TrySkipIisCustomErrors = true was the ticket. Wow.

Body:
I have used the following in the past and been able to throw a 503 error with a custom message using the code shown below in the Page_Load method. I use this page behind a load balancer as the ping page for the load balancer to know if a server is in service or not.

Hope this helps.

        protected void Page_Load(object sender, System.EventArgs e)
    {
        if (Common.CheckDatabaseConnection())
        {
            this.LiteralMachineName.Text = Environment.MachineName;
        }
        else
        {
            Response.ClearHeaders();
            Response.ClearContent();
            Response.Status = "503 ServiceUnavailable";
            Response.StatusCode = 503;
            Response.StatusDescription= "An error has occurred";
            Response.Flush();
            throw new HttpException(503,string.Format("An internal error occurred in the Application on {0}",Environment.MachineName));
        }
    }


问:
Neo4j: Copy folder to /data Directory via Shell-Script in Dockerfile
I want to build a Docker image based on the official Neo4j image.

In the Dockerfile, I am adding a shell script to the image, which I execute in the next step in the Dockerfile.

In this shell script, I want to copy a folder into the data directory (/var/lib/neo4j/data which is linked to /data). However, this does not work. There is no error statement, but the folder does not exist in the data-directory.

cp -r wikipediadb /var/lib/neo4j/data/databases/wikipediadb

答:
OK, if anybody should ever have the same problem: I figured out, that removing the directory and newly creating it works. Then you can copy the folder without any problems:

RUN rm -r /var/lib/neo4j/data
RUN mkdir /var/lib/neo4j/data
RUN mkdir /var/lib/neo4j/data/databases
RUN cp -r wikipediadb /var/lib/neo4j/data/databases/wikipediadb