问:
Sum a range for a specific column
I want to build a dynamic reporting, and for that, if the header is equal to a specific text then sum the entire column below the header. This is the code that I have.

```<code>Sub FindIfSumColumn()
    Dim LastRow As Long
    Dim rgFound As Range
    Dim mFound As Range
    Dim bd As Worksheet: Set bd = Sheets("BDD")
    Dim dt As Worksheet: Set dt = Sheets("DICT")

    LastCol = bd.Cells(1, Columns.Count).End(xlToLeft).Column

    Set mFound = dt.Range("B2")

    Set rgFound = bd.Range("A1:XFD" & LastCol).Find(What:=mFound, _
    LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns)

    If rgFound Is Nothing Then
        MsgBox "Nothing"
    Else
        LastRow = rgFound.Cells(Rows.Count, 1).End(xlUp).Row
        dt.Range("B4") = Application.WorksheetFunction.Sum(LastRow)
    End If
End Sub
</code>```

答:
Replace, please, your code row

```<code>dt.Range("B4") = Application.WorksheetFunction.Sum(LastRow)
</code>```

with

```<code>dt.Range("B4") = Application.WorksheetFunction.Sum(bd.Range(rgFound.Offset(1, 0), rgFound.Offset(lastRow, 0)))
</code>```

Title: Sum a range for a specific column

Body:
I want to build a dynamic reporting, and for that, if the header is equal to a specific text then sum the entire column below the header. This is the code that I have.

Sub FindIfSumColumn()
    Dim LastRow As Long
    Dim rgFound As Range
    Dim mFound As Range
    Dim bd As Worksheet: Set bd = Sheets("BDD")
    Dim dt As Worksheet: Set dt = Sheets("DICT")

    LastCol = bd.Cells(1, Columns.Count).End(xlToLeft).Column

    Set mFound = dt.Range("B2")

    Set rgFound = bd.Range("A1:XFD" & LastCol).Find(What:=mFound, _
    LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns)

    If rgFound Is Nothing Then
        MsgBox "Nothing"
    Else
        LastRow = rgFound.Cells(Rows.Count, 1).End(xlUp).Row
        dt.Range("B4") = Application.WorksheetFunction.Sum(LastRow)
    End If
End Sub

Body:
Replace, please, your code row

dt.Range("B4") = Application.WorksheetFunction.Sum(LastRow)

with

dt.Range("B4") = Application.WorksheetFunction.Sum(bd.Range(rgFound.Offset(1, 0), rgFound.Offset(lastRow, 0)))


来源: stackexchange

答:
Logic:

Find the header

Get the row below the header

Get the last row under that header

Create your range to sum

Find sum

TIP: It will be easier if you give meaningful names to your variables. That way it will be easier to understand what they are for

Is this what you are trying?

```<code>Option Explicit

Sub FindIfSumColumn()
    Dim StartRow As Long, LastRow As Long
    Dim FoundColumn As String
    Dim StringToFind As String
    Dim ResultRange As Range
    Dim sumRng As Range

    Dim bd As Worksheet: Set bd = Sheets("BDD")
    Dim dt As Worksheet: Set dt = Sheets("DICT")

    StringToFind = dt.Range("B2").Value

    Set ResultRange = bd.Cells.Find(What:=StringToFind, LookIn:=xlValues, _
                                    LookAt:=xlWhole, SearchOrder:=xlByColumns)

    If ResultRange Is Nothing Then
        MsgBox "Nothing"
    Else
        '~~> Get the row after the header
        StartRow = ResultRange.Row + 1
        '~~> Column of the header
        FoundColumn = Split(Cells(, ResultRange.Column).Address, "$")(1)
        '~~> Last row under that header
        LastRow = bd.Range(FoundColumn & bd.Rows.Count).End(xlUp).Row

        '~~> The range that we need to sum
        Set sumRng = bd.Range(FoundColumn & StartRow & ":" & FoundColumn & LastRow)

        '~~> Output
        dt.Range("B4") = Application.WorksheetFunction.Sum(sumRng)
    End If
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Title: Sum a range for a specific column

Body:
Logic:

Find the header

Get the row below the header

Get the last row under that header

Create your range to sum

Find sum

TIP: It will be easier if you give meaningful names to your variables. That way it will be easier to understand what they are for

Is this what you are trying?

Option Explicit

Sub FindIfSumColumn()
    Dim StartRow As Long, LastRow As Long
    Dim FoundColumn As String
    Dim StringToFind As String
    Dim ResultRange As Range
    Dim sumRng As Range

    Dim bd As Worksheet: Set bd = Sheets("BDD")
    Dim dt As Worksheet: Set dt = Sheets("DICT")

    StringToFind = dt.Range("B2").Value

    Set ResultRange = bd.Cells.Find(What:=StringToFind, LookIn:=xlValues, _
                                    LookAt:=xlWhole, SearchOrder:=xlByColumns)

    If ResultRange Is Nothing Then
        MsgBox "Nothing"
    Else
        '~~> Get the row after the header
        StartRow = ResultRange.Row + 1
        '~~> Column of the header
        FoundColumn = Split(Cells(, ResultRange.Column).Address, "$")(1)
        '~~> Last row under that header
        LastRow = bd.Range(FoundColumn & bd.Rows.Count).End(xlUp).Row

        '~~> The range that we need to sum
        Set sumRng = bd.Range(FoundColumn & StartRow & ":" & FoundColumn & LastRow)

        '~~> Output
        dt.Range("B4") = Application.WorksheetFunction.Sum(sumRng)
    End If
End Sub


问:
Writing a simple class with accessors and mutators
I am very much a newbie to Java.  I have been asked to Write a java class for a very simple Course class, named Course, that has the data members name and credit hours (e.g. "Programming and Logic I", 4). Your class needs to include the accessor (i.e. get) and mutator (i.e. set) methods for each attribute and at least one overloaded constructor which initializes the data members name and credit hours.

This is what I have so far, but I believe I am so far off and my brain just doesn't want to work right now.

```<code>public class Course {

public String courseName;
public int creditHours;

public Course(String courseName, int creditHours) {

    this.courseName = courseName;
    this.creditHours = creditHours;

    public String getCourseName() {
        return courseName;
    }
    public int getCreditHours(){
        return creditHours
    }

   public void setCourse(String course)
   {
     this.course = course;
   }

   public void setHours(String hours)
   {
     this.hours = hours;
    }

}
}
</code>```

答:
First of all, your constructor should end after you initialize your variables. Then you have your method implementations after that, within the class brackets. You should also make your variable declarations private. Only the methods will be public or available externally.

Secondly, your setter methods should be setting your variable names. In other words

```<code>this.courseName = course;
</code>```

instead of

```<code>   this.course = course;
</code>```

you don't have a this.course.

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I am very much a newbie to Java.  I have been asked to Write a java class for a very simple Course class, named Course, that has the data members name and credit hours (e.g. "Programming and Logic I", 4). Your class needs to include the accessor (i.e. get) and mutator (i.e. set) methods for each attribute and at least one overloaded constructor which initializes the data members name and credit hours.

This is what I have so far, but I believe I am so far off and my brain just doesn't want to work right now.

public class Course {

public String courseName;
public int creditHours;

public Course(String courseName, int creditHours) {

    this.courseName = courseName;
    this.creditHours = creditHours;

    public String getCourseName() {
        return courseName;
    }
    public int getCreditHours(){
        return creditHours
    }

   public void setCourse(String course)
   {
     this.course = course;
   }

   public void setHours(String hours)
   {
     this.hours = hours;
    }

}
}

Body:
First of all, your constructor should end after you initialize your variables. Then you have your method implementations after that, within the class brackets. You should also make your variable declarations private. Only the methods will be public or available externally.

Secondly, your setter methods should be setting your variable names. In other words

this.courseName = course;

instead of

   this.course = course;

you don't have a this.course.

Hope this helps.


问:
How to skip the first row of data in SQL Query?
I have this code:

select DOLFUT from [DATABASE $]

How do I get it to get data from the 2nd line? (skip only the first line of data and collect all the rest)

答:
Data in tables have no inherent order.

To get  data from the 2nd line

, you have to set up some sort sequence and then bypass the first record of the set - as Gustav has shown.


问:
Issues to upload and rename multiple files from the same form
I am currently working on a form that has multiple file uploads (one image and multiple pdfs) with PHP/Mysqli. When I fill it out information are recorded into the database but the name of the files are not renamed and the destination folder called "uploads" remains empty. I have tried many php scripts but it still doesn't work. Any assistance will be appreciated. Please find below the code. Thank you.

Code of the form

```<code><form method="post" enctype="multipart/form-data" name="form1" id="form1">
  <table align="center">
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Email:</td>
      <td><input type="text" name="email" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Nom:</td>
      <td><input type="text" name="nom" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Prenom:</td>
      <td><input type="text" name="prenom" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Localisation:</td>
      <td><select name="localisation" id="localisation">
                                        <option value=""></option>
                                          <option value="Luxembourg - Luxembourg" >Luxembourg - Luxembourg</option>
                                          <option value="Lituanie - Lithuania" >Lituanie - Lithuania</option>
                                          <option value="Liechtenstein - Liechtenstein" >Liechtenstein - Liechtenstein</option>
                                          <option value="Libye - Libyan Arab Jamahiriya" >Libye - Libyan Arab Jamahiriya</option>
                                          <option value="Liberia - Liberia" >Liberia - Liberia</option>
                                          <option value="Liban - Lebanon" >Liban - Lebanon</option>
                                          <option value="Lettonie - Latvia" >Lettonie - Latvia</option>
                                          <option value="Lesotho - Lesotho" >Lesotho - Lesotho</option>
                                          <option value="Albanie - Albania" >Albanie - Albania</option>
                                          <option value="Afrique du Sud - South Africa" >Afrique du Sud - South Africa</option>
                                          <option value="Afghanistan - Afghanistan" >Afghanistan - Afghanistan</option>
                                          <option value="" ></option>
      </select></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Pays d'Origine:</td>
      <td><select name="pays" id="pays">
                                            <option value=""></option>
                                              <option value="Togo - Togo" >Togo - Togo</option>
                                          <option value="Sénégal - Senegal" >Sénégal - Senegal</option>
                                          <option value="Niger - Niger" >Niger - Niger</option>
                                          <option value="Mali - Mali" >Mali - Mali</option>
                                          <option value="Guinée - Guinea" >Guinée - Guinea</option>
                                          <option value="Côte d'Ivoire - Ivory Coast" >Côte d'Ivoire - Ivory Coast</option>
                                          <option value="Burkina Faso - Burkina Faso" >Burkina Faso - Burkina Faso</option>
                                          <option value="Bénin - Benin" >Bénin - Benin</option>
      </select></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Secteur de travail 1:</td>
      <td><select name="secteur1" id="secteur1">
                                            <option value=""></option>
                                              <option value="Autres - Others" >Autres - Others</option>
                                          <option value="Sécurité  - Security " >Sécurité  - Security </option>
                                          <option value="Sciences - Sciences " >Sciences - Sciences </option>
                                          <option value="Vente - Sales " >Vente - Sales </option>
                                          <option value="Commerce de détail  - Retail " >Commerce de détail  - Retail </option>
                                          <option value="Impression et édition  - Printing and publishing  " >Impression et édition  - Printing and publishing  </option>
                                          <option value="Marketing et communications - Marketing and communications " >Marketing et communications - Marketing and communications </option>
                                          <option value="" ></option>
      </select></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Photo:</td>
      <td><input name="photo" type="file" id="photo" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Titre CV/Competences:</td>
      <td><input type="text" name="titre_cv1" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Fichier CV:</td>
      <td><input type="file" name="cv1" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Langue CV:</td>
      <td><input type="text" name="langue_cv1" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Diplôme 1:</td>
      <td><input type="text" name="dip1" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Université d'obtention:</td>
      <td><input type="text" name="obtention1" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Fichier diplôme 1:</td>
      <td><input type="file" name="fichier1" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right"> </td>
      <td><input type="submit" value="Insert record" name="submit"/></td>
    </tr>
  </table>
  <input type="hidden" name="id" value="" />
  <input type="hidden" name="todays_date" value="<?php echo date("Y-m-d");  ?>" />
  <input type="hidden" name="MM_insert" value="form1" />
</form>

</code>```

The PHP code that inserts inputs into the database

```<code>    <?php require_once('Connections/conn_i.php'); ?>
<?php
if ((((isset($_POST["MM_insert"]))?$_POST["MM_insert"]:"") != "")) {
  $InsertQuery = new WA_MySQLi_Query($conn_i);
  $InsertQuery->Action = "insert";
  $InsertQuery->Table = "infos";
  $InsertQuery->bindColumn("id", "d", "".((isset($_POST["id"]))?$_POST["id"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("email", "s", "".((isset($_POST["email"]))?$_POST["email"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("nom", "s", "".((isset($_POST["nom"]))?$_POST["nom"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("prenom", "s", "".((isset($_POST["prenom"]))?$_POST["prenom"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("localisation", "s", "".((isset($_POST["localisation"]))?$_POST["localisation"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("pays", "s", "".((isset($_POST["pays"]))?$_POST["pays"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("secteur1", "s", "".((isset($_POST["secteur1"]))?$_POST["secteur1"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("photo", "s", "".((isset($_FILES["photo"]))?$_FILES["photo"]["name"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("titre_cv1", "s", "".((isset($_POST["titre_cv1"]))?$_POST["titre_cv1"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("cv1", "s", "".((isset($_FILES["cv1"]))?$_FILES["cv1"]["name"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("langue_cv1", "s", "".((isset($_POST["langue_cv1"]))?$_POST["langue_cv1"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("dip1", "s", "".((isset($_POST["dip1"]))?$_POST["dip1"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("obtention1", "s", "".((isset($_POST["obtention1"]))?$_POST["obtention1"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("fichier1", "s", "".((isset($_FILES["fichier1"]))?$_FILES["fichier1"]["name"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("todays_date", "t", "".((isset($_POST["todays_date"]))?$_POST["todays_date"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->saveInSession("");
  $InsertQuery->execute();
  $InsertGoTo = "Success.php";
  if (function_exists("rel2abs")) $InsertGoTo = $InsertGoTo?rel2abs($InsertGoTo,dirname(__FILE__)):"";
  $InsertQuery->redirect($InsertGoTo);
}
?>
</code>```

The code that renames and saves the file that doesn't work!

```<code>    <?php
if (isset($_POST['photo'])) {
    $upload_error_codes=array("",
        "The uploaded file exceeds the upload_max_filesize directive in php.ini.","",
        "The uploaded file was only partially uploaded.",
        "No file was uploaded.","Missing a temporary folder.",
        "Failed to write file to disk.","File upload stopped by extension.");
    $allowed_ext_string="jpeg,jpg";
    $allowed_extensions=explode(",",$allowed_ext_string);
    $upload_status = "";
    $allowed_size =  2+0;
    $success_page = "Success.php";
    $thumbs_dir = "";
    $resize_image = "yes";
    $resize_width = 150+0;
    $resize_height = 200+0;
    $thumb_width = +0;
    $thumb_height = +0;
    $make_thumbs = "";
    $thumb_prefix = "";
    $thumb_suffix = "";
    $file_prefix = "";
    $file_suffix = "";
    $append_date_stamp = "1";
    $date_stamp=($append_date_stamp=="1")?date(time()):"";
    $haulted = false;
    $upload_folder="uploads/";
    //Check for restrictions
    //Check if upload folder exists
    if(!file_exists($upload_folder)){die("Upload folder doesn't exist");}
    if(!is_writable($upload_folder)){die("Upload folder is not writable");}
    if($make_thumbs == "yes" && !file_exists($thumbs_dir)){die("Thumbnails folder doesn't exist");}
    if($make_thumbs == "yes" && !is_writable($thumbs_dir)){die("Thumbnails folder is not writable");}
    foreach($_FILES as $files => $_file){
        //Check if it's not empty
        if($_file['name']!=""){
            $pathinfo = pathinfo($_file['name']);
            //If allowed extension or no extension restriction
            if(!in_array(strtolower($pathinfo['extension']),$allowed_extensions) && $allowed_ext_string!=""){
                die(strtoupper($pathinfo['extension'])." files are not allowed.
                <br>No files have been uploaded.");
            }
            if($_file['size']>$allowed_size*1048576 && $allowed_size!=0){
                die("The file size of ".basename($_file['name'])." is ".round($_file['size']/1048576,2)."MB,
                which is larger than allowed ".$allowed_size."MB.<br>No files have been uploaded.");
            }
        }
    }
    //All checks passed, attempt to upload
    foreach($_FILES as $files => $_file){
        //Check if it's not empty
        if($_file['name']!=""){
            $pathinfo = pathinfo($_file['name']);
            $file_name_array = explode(".", basename($_file['name']));
            $filename = $file_name_array[count($file_name_array)-2];
            $target = $upload_folder;
            $file_uploaded = false;
            $target = $target."/".$file_prefix.$filename.$file_suffix.$date_stamp.".".$pathinfo['extension'];
            //if image
            if(strtolower($pathinfo['extension'])=="jpeg" || strtolower($pathinfo['extension'])=="jpg"){
                //if needs resizing or a thumbnail
                if(($resize_image == "yes" && ($resize_width!="" || $resize_height!="")) || ($make_thumbs == "yes" && ($thumb_width!="" || $thumb_height!=""))){
                    $src = imagecreatefromjpeg($_file['tmp_name']);
                    list($width,$height)=getimagesize($_file['tmp_name']);
                    //if needs thumbnail
                    if ($make_thumbs == "yes" && ($thumb_width!="" || $thumb_height!="")){
                        $thumb_newwidth=($thumb_width!=0)?$thumb_width:(($width/$height)*$thumb_height);
                        $thumb_newheight=($thumb_height!=0)?$thumb_height:(($height/$width)*$thumb_width);
                        $tmp=imagecreatetruecolor($thumb_newwidth,$thumb_newheight);
                        imagecopyresampled($tmp,$src,0,0,0,0,$thumb_newwidth,$thumb_newheight,$width,$height);
                        $thumb_name=$thumb_prefix.$filename.$thumb_suffix.$date_stamp.".".$pathinfo['extension'];
                        if(imagejpeg($tmp,$thumbs_dir."/".$thumb_name,100)){
                            $upload_status=$upload_status."Thumbnail for ".basename($_file['name'])." was created successfully.<br>";
                        }else{
                            die($upload_status."There was a problem creating a thumbnail for ". basename($_file['name']).".
                            Upload was interrupted.<br>");
                        }
                    }
                    //if needs resizing
                    if($resize_image == "yes" && ($resize_width!="" || $resize_height!="")){
                        $newwidth=($resize_width!=0)?$resize_width:(($width/$height)*$resize_height);
                        $newheight=($resize_height!=0)?$resize_height:(($height/$width)*$resize_width);
                        $tmp=imagecreatetruecolor($newwidth,$newheight);
                        imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
                        if(imagejpeg($tmp,$target,100)){
                            $upload_status=$upload_status.basename($_file['name'])." was successfully resized.<br>";
                            $file_uploaded=true;
                        }else{
                            die($upload_status.basename($_file['name'])." could not be resized. Upload was interrupted.<br>");
                        }
                    }
                }
            }
            if(!$file_uploaded){
                if(move_uploaded_file($_file['tmp_name'], $target)){
                    $upload_status=$upload_status.basename($_file['name'])." was uploaded successfully.<br>";
                }else{
                    $haulted=true;
                }
            }
            //Cleanup
            if(isset($src)){imagedestroy($src);unset($src);}
            if(isset($tmp)){imagedestroy($tmp);unset($tmp);}
            if($haulted){die($upload_status."There was a problem uploading ". basename($_file['name']).".
                        Error: ".$upload_error_codes[basename($_file['error'])].". Upload was interrupted.<br>");}
        }
    }
    if($success_page!="" && $upload_status!=""){
        header("Location: ".$success_page);
    }
}
?>
</code>```

答:
I have finally found the answer.
Here are the code to upload an image and a pdf file. Thank you again.</p>

```<code>// Script to upload photo
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Check if file was uploaded without errors
    if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
        $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
        $filename = $filename = time(). '_' . $_FILES["photo"]["name"]; //$_FILES["photo"]["name"];
        $filetype = $_FILES["photo"]["type"];
        $filesize = $_FILES["photo"]["size"];

        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");

        // Verify file size - 2MB maximum
        $maxsize = 2 * 1024 * 1024;
        if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");

        // Verify MYME type of the file
        if(in_array($filetype, $allowed)){
            // Check whether file exists before uploading it
            if(file_exists("uploads/" . $filename)){
                echo $filename . " is already exists.";
            } else{
                move_uploaded_file($_FILES["photo"]["tmp_name"], "uploads/" . $filename);
                echo "Your file was uploaded successfully.";
            }
        } else{
            echo "Error: There was a problem uploading your file. Please try again.";
        }
    } else{
        echo "Error: " . $_FILES["photo"]["error"];
    }
}
?>
</code>```

```<code><?php
// Script to upload fichier1
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Check if file was uploaded without errors
    if(isset($_FILES["fichier1"]) && $_FILES["fichier1"]["error"] == 0){
        $allowed = array("pdf" => "application/pdf");
        $filename = $filename = time(). '_' . $_FILES["fichier1"]["name"]; //$_FILES["photo"]["name"];
        $filetype = $_FILES["fichier1"]["type"];
        $filesize = $_FILES["fichier1"]["size"];

        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");

        // Verify file size - 2MB maximum
        $maxsize = 2097152;
        if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");

        // Verify MYME type of the file
        if(in_array($filetype, $allowed)){
            // Check whether file exists before uploading it
            if(file_exists("uploads/" . $filename)){
                echo $filename . " is already exists.";
            } else{
                move_uploaded_file($_FILES["fichier1"]["tmp_name"], "uploads/" . $filename);
                echo "Your file was uploaded successfully.";
            }
        } else{
            echo "Error: There was a problem uploading your file. Please try again.";
        }
    } else{
        echo "Error: " . $_FILES["fichier1"]["error"];
    }
}
?>
</code>```

Body:
I am currently working on a form that has multiple file uploads (one image and multiple pdfs) with PHP/Mysqli. When I fill it out information are recorded into the database but the name of the files are not renamed and the destination folder called "uploads" remains empty. I have tried many php scripts but it still doesn't work. Any assistance will be appreciated. Please find below the code. Thank you.

Code of the form

<form method="post" enctype="multipart/form-data" name="form1" id="form1">

      Email:
      <input type="text" name="email" value="" size="32" />

      Nom:
      <input type="text" name="nom" value="" size="32" />

      Prenom:
      <input type="text" name="prenom" value="" size="32" />

      Localisation:
      <select name="localisation" id="localisation">
                                        <option value=""></option>
                                          <option value="Luxembourg - Luxembourg" >Luxembourg - Luxembourg</option>
                                          <option value="Lituanie - Lithuania" >Lituanie - Lithuania</option>
                                          <option value="Liechtenstein - Liechtenstein" >Liechtenstein - Liechtenstein</option>
                                          <option value="Libye - Libyan Arab Jamahiriya" >Libye - Libyan Arab Jamahiriya</option>
                                          <option value="Liberia - Liberia" >Liberia - Liberia</option>
                                          <option value="Liban - Lebanon" >Liban - Lebanon</option>
                                          <option value="Lettonie - Latvia" >Lettonie - Latvia</option>
                                          <option value="Lesotho - Lesotho" >Lesotho - Lesotho</option>
                                          <option value="Albanie - Albania" >Albanie - Albania</option>
                                          <option value="Afrique du Sud - South Africa" >Afrique du Sud - South Africa</option>
                                          <option value="Afghanistan - Afghanistan" >Afghanistan - Afghanistan</option>
                                          <option value="" ></option>
      </select>

      Pays d'Origine:
      <select name="pays" id="pays">
                                            <option value=""></option>
                                              <option value="Togo - Togo" >Togo - Togo</option>
                                          <option value="Sénégal - Senegal" >Sénégal - Senegal</option>
                                          <option value="Niger - Niger" >Niger - Niger</option>
                                          <option value="Mali - Mali" >Mali - Mali</option>
                                          <option value="Guinée - Guinea" >Guinée - Guinea</option>
                                          <option value="Côte d'Ivoire - Ivory Coast" >Côte d'Ivoire - Ivory Coast</option>
                                          <option value="Burkina Faso - Burkina Faso" >Burkina Faso - Burkina Faso</option>
                                          <option value="Bénin - Benin" >Bénin - Benin</option>
      </select>

      Secteur de travail 1:
      <select name="secteur1" id="secteur1">
                                            <option value=""></option>
                                              <option value="Autres - Others" >Autres - Others</option>
                                          <option value="Sécurité  - Security " >Sécurité  - Security </option>
                                          <option value="Sciences - Sciences " >Sciences - Sciences </option>
                                          <option value="Vente - Sales " >Vente - Sales </option>
                                          <option value="Commerce de détail  - Retail " >Commerce de détail  - Retail </option>
                                          <option value="Impression et édition  - Printing and publishing  " >Impression et édition  - Printing and publishing  </option>
                                          <option value="Marketing et communications - Marketing and communications " >Marketing et communications - Marketing and communications </option>
                                          <option value="" ></option>
      </select>

      Photo:
      <input name="photo" type="file" id="photo" value="" size="32" />

      Titre CV/Competences:
      <input type="text" name="titre_cv1" value="" size="32" />

      Fichier CV:
      <input type="file" name="cv1" value="" size="32" />

      Langue CV:
      <input type="text" name="langue_cv1" value="" size="32" />

      Diplôme 1:
      <input type="text" name="dip1" value="" size="32" />

      Université d'obtention:
      <input type="text" name="obtention1" value="" size="32" />

      Fichier diplôme 1:
      <input type="file" name="fichier1" value="" size="32" />

      <input type="submit" value="Insert record" name="submit"/>

  <input type="hidden" name="id" value="" />
  <input type="hidden" name="todays_date" value="<?php echo date("Y-m-d");  ?>" />
  <input type="hidden" name="MM_insert" value="form1" />
</form>

The PHP code that inserts inputs into the database

    <?php require_once('Connections/conn_i.php'); ?>
<?php
if ((((isset($_POST["MM_insert"]))?$_POST["MM_insert"]:"") != "")) {
  $InsertQuery = new WA_MySQLi_Query($conn_i);
  $InsertQuery->Action = "insert";
  $InsertQuery->Table = "infos";
  $InsertQuery->bindColumn("id", "d", "".((isset($_POST["id"]))?$_POST["id"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("email", "s", "".((isset($_POST["email"]))?$_POST["email"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("nom", "s", "".((isset($_POST["nom"]))?$_POST["nom"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("prenom", "s", "".((isset($_POST["prenom"]))?$_POST["prenom"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("localisation", "s", "".((isset($_POST["localisation"]))?$_POST["localisation"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("pays", "s", "".((isset($_POST["pays"]))?$_POST["pays"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("secteur1", "s", "".((isset($_POST["secteur1"]))?$_POST["secteur1"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("photo", "s", "".((isset($_FILES["photo"]))?$_FILES["photo"]["name"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("titre_cv1", "s", "".((isset($_POST["titre_cv1"]))?$_POST["titre_cv1"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("cv1", "s", "".((isset($_FILES["cv1"]))?$_FILES["cv1"]["name"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("langue_cv1", "s", "".((isset($_POST["langue_cv1"]))?$_POST["langue_cv1"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("dip1", "s", "".((isset($_POST["dip1"]))?$_POST["dip1"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("obtention1", "s", "".((isset($_POST["obtention1"]))?$_POST["obtention1"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("fichier1", "s", "".((isset($_FILES["fichier1"]))?$_FILES["fichier1"]["name"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("todays_date", "t", "".((isset($_POST["todays_date"]))?$_POST["todays_date"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->saveInSession("");
  $InsertQuery->execute();
  $InsertGoTo = "Success.php";
  if (function_exists("rel2abs")) $InsertGoTo = $InsertGoTo?rel2abs($InsertGoTo,dirname(__FILE__)):"";
  $InsertQuery->redirect($InsertGoTo);
}
?>

The code that renames and saves the file that doesn't work!

    <?php
if (isset($_POST['photo'])) {
    $upload_error_codes=array("",
        "The uploaded file exceeds the upload_max_filesize directive in php.ini.","",
        "The uploaded file was only partially uploaded.",
        "No file was uploaded.","Missing a temporary folder.",
        "Failed to write file to disk.","File upload stopped by extension.");
    $allowed_ext_string="jpeg,jpg";
    $allowed_extensions=explode(",",$allowed_ext_string);
    $upload_status = "";
    $allowed_size =  2+0;
    $success_page = "Success.php";
    $thumbs_dir = "";
    $resize_image = "yes";
    $resize_width = 150+0;
    $resize_height = 200+0;
    $thumb_width = +0;
    $thumb_height = +0;
    $make_thumbs = "";
    $thumb_prefix = "";
    $thumb_suffix = "";
    $file_prefix = "";
    $file_suffix = "";
    $append_date_stamp = "1";
    $date_stamp=($append_date_stamp=="1")?date(time()):"";
    $haulted = false;
    $upload_folder="uploads/";
    //Check for restrictions
    //Check if upload folder exists
    if(!file_exists($upload_folder)){die("Upload folder doesn't exist");}
    if(!is_writable($upload_folder)){die("Upload folder is not writable");}
    if($make_thumbs == "yes" && !file_exists($thumbs_dir)){die("Thumbnails folder doesn't exist");}
    if($make_thumbs == "yes" && !is_writable($thumbs_dir)){die("Thumbnails folder is not writable");}
    foreach($_FILES as $files => $_file){
        //Check if it's not empty
        if($_file['name']!=""){
            $pathinfo = pathinfo($_file['name']);
            //If allowed extension or no extension restriction
            if(!in_array(strtolower($pathinfo['extension']),$allowed_extensions) && $allowed_ext_string!=""){
                die(strtoupper($pathinfo['extension'])." files are not allowed.

No files have been uploaded.");
            }
            if($_file['size']>$allowed_size*1048576 && $allowed_size!=0){
                die("The file size of ".basename($_file['name'])." is ".round($_file['size']/1048576,2)."MB,
                which is larger than allowed ".$allowed_size."MB.
No files have been uploaded.");
            }
        }
    }
    //All checks passed, attempt to upload
    foreach($_FILES as $files => $_file){
        //Check if it's not empty
        if($_file['name']!=""){
            $pathinfo = pathinfo($_file['name']);
            $file_name_array = explode(".", basename($_file['name']));
            $filename = $file_name_array[count($file_name_array)-2];
            $target = $upload_folder;
            $file_uploaded = false;
            $target = $target."/".$file_prefix.$filename.$file_suffix.$date_stamp.".".$pathinfo['extension'];
            //if image
            if(strtolower($pathinfo['extension'])=="jpeg" || strtolower($pathinfo['extension'])=="jpg"){
                //if needs resizing or a thumbnail
                if(($resize_image == "yes" && ($resize_width!="" || $resize_height!="")) || ($make_thumbs == "yes" && ($thumb_width!="" || $thumb_height!=""))){
                    $src = imagecreatefromjpeg($_file['tmp_name']);
                    list($width,$height)=getimagesize($_file['tmp_name']);
                    //if needs thumbnail
                    if ($make_thumbs == "yes" && ($thumb_width!="" || $thumb_height!="")){
                        $thumb_newwidth=($thumb_width!=0)?$thumb_width:(($width/$height)*$thumb_height);
                        $thumb_newheight=($thumb_height!=0)?$thumb_height:(($height/$width)*$thumb_width);
                        $tmp=imagecreatetruecolor($thumb_newwidth,$thumb_newheight);
                        imagecopyresampled($tmp,$src,0,0,0,0,$thumb_newwidth,$thumb_newheight,$width,$height);
                        $thumb_name=$thumb_prefix.$filename.$thumb_suffix.$date_stamp.".".$pathinfo['extension'];
                        if(imagejpeg($tmp,$thumbs_dir."/".$thumb_name,100)){
                            $upload_status=$upload_status."Thumbnail for ".basename($_file['name'])." was created successfully.
";
                        }else{
                            die($upload_status."There was a problem creating a thumbnail for ". basename($_file['name']).".
                            Upload was interrupted.
");
                        }
                    }
                    //if needs resizing
                    if($resize_image == "yes" && ($resize_width!="" || $resize_height!="")){
                        $newwidth=($resize_width!=0)?$resize_width:(($width/$height)*$resize_height);
                        $newheight=($resize_height!=0)?$resize_height:(($height/$width)*$resize_width);
                        $tmp=imagecreatetruecolor($newwidth,$newheight);
                        imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
                        if(imagejpeg($tmp,$target,100)){
                            $upload_status=$upload_status.basename($_file['name'])." was successfully resized.
";
                            $file_uploaded=true;
                        }else{
                            die($upload_status.basename($_file['name'])." could not be resized. Upload was interrupted.
");
                        }
                    }
                }
            }
            if(!$file_uploaded){
                if(move_uploaded_file($_file['tmp_name'], $target)){
                    $upload_status=$upload_status.basename($_file['name'])." was uploaded successfully.
";
                }else{
                    $haulted=true;
                }
            }
            //Cleanup
            if(isset($src)){imagedestroy($src);unset($src);}
            if(isset($tmp)){imagedestroy($tmp);unset($tmp);}
            if($haulted){die($upload_status."There was a problem uploading ". basename($_file['name']).".
                        Error: ".$upload_error_codes[basename($_file['error'])].". Upload was interrupted.
");}
        }
    }
    if($success_page!="" && $upload_status!=""){
        header("Location: ".$success_page);
    }
}
?>

Body:
I have finally found the answer.
Here are the code to upload an image and a pdf file. Thank you again.

// Script to upload photo
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Check if file was uploaded without errors
    if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
        $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
        $filename = $filename = time(). '_' . $_FILES["photo"]["name"]; //$_FILES["photo"]["name"];
        $filetype = $_FILES["photo"]["type"];
        $filesize = $_FILES["photo"]["size"];

        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");

        // Verify file size - 2MB maximum
        $maxsize = 2 * 1024 * 1024;
        if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");

        // Verify MYME type of the file
        if(in_array($filetype, $allowed)){
            // Check whether file exists before uploading it
            if(file_exists("uploads/" . $filename)){
                echo $filename . " is already exists.";
            } else{
                move_uploaded_file($_FILES["photo"]["tmp_name"], "uploads/" . $filename);
                echo "Your file was uploaded successfully.";
            }
        } else{
            echo "Error: There was a problem uploading your file. Please try again.";
        }
    } else{
        echo "Error: " . $_FILES["photo"]["error"];
    }
}
?>

<?php
// Script to upload fichier1
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Check if file was uploaded without errors
    if(isset($_FILES["fichier1"]) && $_FILES["fichier1"]["error"] == 0){
        $allowed = array("pdf" => "application/pdf");
        $filename = $filename = time(). '_' . $_FILES["fichier1"]["name"]; //$_FILES["photo"]["name"];
        $filetype = $_FILES["fichier1"]["type"];
        $filesize = $_FILES["fichier1"]["size"];

        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");

        // Verify file size - 2MB maximum
        $maxsize = 2097152;
        if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");

        // Verify MYME type of the file
        if(in_array($filetype, $allowed)){
            // Check whether file exists before uploading it
            if(file_exists("uploads/" . $filename)){
                echo $filename . " is already exists.";
            } else{
                move_uploaded_file($_FILES["fichier1"]["tmp_name"], "uploads/" . $filename);
                echo "Your file was uploaded successfully.";
            }
        } else{
            echo "Error: There was a problem uploading your file. Please try again.";
        }
    } else{
        echo "Error: " . $_FILES["fichier1"]["error"];
    }
}
?>


问:
How to check which condition was true in an if statement where the order matters?
I know there are similar questions to this one but mine is sort of specific so I need some advice.

I am making a game in JS in which there are 4 divs racing, and the finish line is -70vw (racing right to left). They randomly increment their vw from 0 to 100 by 5-15 vw on button click. Right now what I have in my code to check the order of the winners is this:

```<code> if (this.state.winnersArr.length < 4) {

  if (
    changePlayerArr[0].speed <= -70 &&
    !this.state.winnersArr.includes(changePlayerArr[0].name)
  ) {
    this.state.winnersArr.push(changePlayerArr[0].name);
  }
  if (
    changePlayerArr[1].speed <= -70 &&
    !this.state.winnersArr.includes(changePlayerArr[1].name)
  ) {
    this.state.winnersArr.push(changePlayerArr[1].name);
  }
  if (
    changePlayerArr[2].speed <= -70 &&
    !this.state.winnersArr.includes(changePlayerArr[2].name)
  ) {
    this.state.winnersArr.push(changePlayerArr[2].name);
  }
  if (
    changePlayerArr[3].speed <= -70 &&
    !this.state.winnersArr.includes(changePlayerArr[3].name)
  ) {
    this.state.winnersArr.push(changePlayerArr[3].name);
  }
  return changePlayerArr;
</code>```

Here I have an array which pushes the div which passes -70vw which is the finish line. However since the checks for the div speed (changePlayerArr[0].speed) go from first div [0] to last div [3] if lets say the last div is at -69vw and the first at -65vw and on button click they both go to -70vw, the first div still ends up being first since the if check pushes it first to the winning array.

So I was wondering can I do something like this:

```<code>if(div[0].speed <= -70 || div[1].speed <= -70 || div[2].speed <= -70 || div[3].speed <= -70)
 { // Check which statement was true in order and push to array}
</code>```

But in this case the checks still go from left to right so I guess it wouldn't work either even if it was possible. Any suggestions? (Sorry if the explanation was a bit sucky i'm still new to this) :)

EDIT: Perhaps it's not the way that I check the winners but the order in which I increment their speeds. Their increment should probably happen at the same time rather than from first div to last div, but the question still remains, how can I do that :/

答:
Instead of having an if statement with a lot of conditions you could iterate the changePlayerArr like so:

```<code>this.state.winnersArr = changePlayerArr.map(player => {
  if(player.speed <= -70) {
    return player;
  }
});
</code>```

With map() you can go through each player and return a new array with only the winners.
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Later you can then check which players are in the winners array.

If it's according to the speed property then you can sort the array like this:

```<code>this.state.winnersArr.sort((firstEl, secondEl) => {
 return firstEl.speed > secondEl.speed;
});
</code>```

I hope that answers your question!

Body:
I know there are similar questions to this one but mine is sort of specific so I need some advice.

I am making a game in JS in which there are 4 divs racing, and the finish line is -70vw (racing right to left). They randomly increment their vw from 0 to 100 by 5-15 vw on button click. Right now what I have in my code to check the order of the winners is this:

 if (this.state.winnersArr.length < 4) {

  if (
    changePlayerArr[0].speed <= -70 &&
    !this.state.winnersArr.includes(changePlayerArr[0].name)
  ) {
    this.state.winnersArr.push(changePlayerArr[0].name);
  }
  if (
    changePlayerArr[1].speed <= -70 &&
    !this.state.winnersArr.includes(changePlayerArr[1].name)
  ) {
    this.state.winnersArr.push(changePlayerArr[1].name);
  }
  if (
    changePlayerArr[2].speed <= -70 &&
    !this.state.winnersArr.includes(changePlayerArr[2].name)
  ) {
    this.state.winnersArr.push(changePlayerArr[2].name);
  }
  if (
    changePlayerArr[3].speed <= -70 &&
    !this.state.winnersArr.includes(changePlayerArr[3].name)
  ) {
    this.state.winnersArr.push(changePlayerArr[3].name);
  }
  return changePlayerArr;

Here I have an array which pushes the div which passes -70vw which is the finish line. However since the checks for the div speed (changePlayerArr[0].speed) go from first div [0] to last div [3] if lets say the last div is at -69vw and the first at -65vw and on button click they both go to -70vw, the first div still ends up being first since the if check pushes it first to the winning array.

So I was wondering can I do something like this:

if(div[0].speed <= -70 || div[1].speed <= -70 || div[2].speed <= -70 || div[3].speed <= -70)
 { // Check which statement was true in order and push to array}

But in this case the checks still go from left to right so I guess it wouldn't work either even if it was possible. Any suggestions? (Sorry if the explanation was a bit sucky i'm still new to this) :)

EDIT: Perhaps it's not the way that I check the winners but the order in which I increment their speeds. Their increment should probably happen at the same time rather than from first div to last div, but the question still remains, how can I do that :/

Body:
Instead of having an if statement with a lot of conditions you could iterate the changePlayerArr like so:

this.state.winnersArr = changePlayerArr.map(player => {
  if(player.speed <= -70) {
    return player;
  }
});

With map() you can go through each player and return a new array with only the winners.
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Later you can then check which players are in the winners array.

If it's according to the speed property then you can sort the array like this:

this.state.winnersArr.sort((firstEl, secondEl) => {
 return firstEl.speed > secondEl.speed;
});

I hope that answers your question!


问:
sourceloader - No configuration found in the configured sources
when I run the command sudo bin/logstash -f logstash.conf it appears this error

```<code>[ERROR] 2018-04-05 10:22:32.872 [Ruby-0-Thread-1: /usr/share/logstash/vendor/bundle/jruby/2.3.0/gems/stud-0.0.23/lib/stud/task.rb:22] sourceloader - No configuration found in the configured sources.
</code>```

I don't know what to do anymore. Logstash reinstalled did not help. Changing the logstash config also did not help.

Who can tell me how to fix this problem?

Here is my current config:

```<code>input {
  file {
    type => "rails logs"
    path => "/home/user/apps/demo/log/logstash_development.log"
    codec =>   json {
      charset => "UTF-8"
    }
  }
}

output {
  # Print each event to stdout.
  stdout {
    codec => rubydebug
  }

  elasticsearch {
    # Setting 'embedded' will run  a real elasticsearch server inside logstash.
    # This option below saves you from having to run a separate process just
    # for ElasticSearch, so you can get started quicker!
    embedded => true
  }
}
</code>```

答:
The logstash.conf file is inside the config folder, not in bin.

Use a command like W:\logstash\bin>logstash -f .\..\config\logstash.conf.

Body:
when I run the command sudo bin/logstash -f logstash.conf it appears this error

[ERROR] 2018-04-05 10:22:32.872 [Ruby-0-Thread-1: /usr/share/logstash/vendor/bundle/jruby/2.3.0/gems/stud-0.0.23/lib/stud/task.rb:22] sourceloader - No configuration found in the configured sources.

I don't know what to do anymore. Logstash reinstalled did not help. Changing the logstash config also did not help.

Who can tell me how to fix this problem?

Here is my current config:

input {
  file {
    type => "rails logs"
    path => "/home/user/apps/demo/log/logstash_development.log"
    codec =>   json {
      charset => "UTF-8"
    }
  }
}

output {
  # Print each event to stdout.
  stdout {
    codec => rubydebug
  }

  elasticsearch {
    # Setting 'embedded' will run  a real elasticsearch server inside logstash.
    # This option below saves you from having to run a separate process just
    # for ElasticSearch, so you can get started quicker!
    embedded => true
  }
}


问:
How to generate a list with only two 1s and other 0s of the given length?
I have to generate lists that consist of 2 '1's and other elements are '0's. I tried the following code but it does not work:

```<code>count([], _, 0).
count([X|T], X, Y) :- count(T, X, Z), Y is 1+Z.
count([X1|T],X,Z):- X1\=X,count(T,X,Z).

two(X) :- count(X, 1, Counter), Counter =:= 2.
</code>```

Querying length(Vs, 4), Vs ins 0..1, two(Vs). gives nothing.

How to generate such lists properly?
I expect to get something like [1, 1, 0, 0], [1, 0, 1, 0] ... [0, 0, 1, 1].

答:
These are excellent answers.

Here is another one. nth0 comes from library(lists).

SWI Prolog nth0

SICStus nth0

The two 1 have been replaced by a and b for illustration purposes.

findall(0, between(1, Zlen, _), Zlist) creates a list of 0 (Zlist) of length Zlen. See between.

```<code>gimme(List,Len) :- Len >= 2,
                   Zlen is Len-2,
                   findall(0, between(1, Zlen, _), Zlist),
                   between(0, Zlen, Pos1),                 % we will insert 'a' at Pos1
                   Pos1n is Pos1+1,
                   between(Pos1n,Len,Pos2),                % we will insert 'b' at Pos2, always after 'a'
                   nth0(Pos1, Tlist, a, Zlist),            % Zlist -morph-> Tlist
                   nth0(Pos2, List, b, Tlist).             % Tlist -morph-> List
</code>```

```<code>?- gimme(L,2).
L = [a, b] ;
false.

?- gimme(L,3).
L = [a, b, 0] ;
L = [a, 0, b] ;
L = [0, a, b] ;
false.

?- gimme(L,4).
L = [a, b, 0, 0] ;
L = [a, 0, b, 0] ;
L = [a, 0, 0, b] ;
L = [0, a, b, 0] ;
L = [0, a, 0, b] ;
L = [0, 0, a, b] ;
false.

?- gimme(L,5).
L = [a, b, 0, 0, 0] ;
L = [a, 0, b, 0, 0] ;
L = [a, 0, 0, b, 0] ;
L = [a, 0, 0, 0, b] ;
L = [0, a, b, 0, 0] ;
L = [0, a, 0, b, 0] ;
L = [0, a, 0, 0, b] ;
L = [0, 0, a, b, 0] ;
L = [0, 0, a, 0, b] ;
L = [0, 0, 0, a, b] ;
</code>```

Body:
I have to generate lists that consist of 2 '1's and other elements are '0's. I tried the following code but it does not work:

count([], _, 0).
count([X|T], X, Y) :- count(T, X, Z), Y is 1+Z.
count([X1|T],X,Z):- X1\=X,count(T,X,Z).

two(X) :- count(X, 1, Counter), Counter =:= 2.

Querying length(Vs, 4), Vs ins 0..1, two(Vs). gives nothing.

How to generate such lists properly?
I expect to get something like [1, 1, 0, 0], [1, 0, 1, 0] ... [0, 0, 1, 1].

Body:
These are excellent answers.

Here is another one. nth0 comes from library(lists).

SWI Prolog nth0

SICStus nth0

The two 1 have been replaced by a and b for illustration purposes.

findall(0, between(1, Zlen, _), Zlist) creates a list of 0 (Zlist) of length Zlen. See between.

gimme(List,Len) :- Len >= 2,
                   Zlen is Len-2,
                   findall(0, between(1, Zlen, _), Zlist),
                   between(0, Zlen, Pos1),                 % we will insert 'a' at Pos1
                   Pos1n is Pos1+1,
                   between(Pos1n,Len,Pos2),                % we will insert 'b' at Pos2, always after 'a'
                   nth0(Pos1, Tlist, a, Zlist),            % Zlist -morph-> Tlist
                   nth0(Pos2, List, b, Tlist).             % Tlist -morph-> List

?- gimme(L,2).
L = [a, b] ;
false.

?- gimme(L,3).
L = [a, b, 0] ;
L = [a, 0, b] ;
L = [0, a, b] ;
false.

?- gimme(L,4).
L = [a, b, 0, 0] ;
L = [a, 0, b, 0] ;
L = [a, 0, 0, b] ;
L = [0, a, b, 0] ;
L = [0, a, 0, b] ;
L = [0, 0, a, b] ;
false.

?- gimme(L,5).
L = [a, b, 0, 0, 0] ;
L = [a, 0, b, 0, 0] ;
L = [a, 0, 0, b, 0] ;
L = [a, 0, 0, 0, b] ;
L = [0, a, b, 0, 0] ;
L = [0, a, 0, b, 0] ;
L = [0, a, 0, 0, b] ;
L = [0, 0, a, b, 0] ;
L = [0, 0, a, 0, b] ;
L = [0, 0, 0, a, b] ;


问:
How to distinguish output panel from other activeTextEditor?
It is known that vscode.window.activeTextEditor may return output panel.

Is there any way to determine the returned value is a real document or not?

答:
Alex's solution will produce false positives, for instance for .log files or files where you manually switch the language mode to Log. I've been using the following in an extension, which seems safer:

activeEditor.document.uri.scheme == "output"
```


问:
css problem in action on Zend Framework
Not sure what I'm doing wrong here, but it seems that the framework is only able to find the style.css on my index actions on every controller. I'm calling it from the layout.phtml like this:

```<code>$this->headLink()->appendStylesheet('css/styles.css');
</code>```

So when I go to project.local/account, I find the styles. If I go to project.local/account/action there are no styles...and actually if I go to project.local/account/index...there are no styles. So... it's a bit of a weird error, or at least it is for a n00b

Edit: When I open the code console on firefox and try to follow the css/styles.css I find the following error message:

```<code>```#0 /home/fiodorovich/library/ZendFramework/library/Zend/Controller/Action.php(515): Zend_Controller_Action->__call('cssAction', Array)
#1/home/fiodorovich/library/ZendFramework/library/Zend/Controller/Dispatcher/Standard.php(295): Zend_Controller_Action->dispatch('cssAction')
#2 /home/fiodorovich/library/ZendFramework/library/Zend/Controller/Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#3 /home/fiodorovich/library/ZendFramework/library/Zend/Application/Bootstrap/Bootstrap.php(97): Zend_Controller_Front->dispatch()
#4 /home/fiodorovich/library/ZendFramework/library/Zend/Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#5 /home/fiodorovich/public_html/gisele/public/index.php(26): Zend_Application->run()
#6 {main}  ```

  <h3>Request Parameters:</h3>
  ```array (
  'controller' => 'gisele',
  'action' => 'css',
  'module' => 'default',
)  ```
</code>```

答:
The parameter you pass to appendStylesheet is just being blindly output in your HTML, the framework's not actually looking for that file.

The reason this is working on some pages and not others is that you've given appendStylesheet a relative link. Basically, when a browser encounters a relative link, it strips off the current URL at the last slash and then adds on the link.

So, on project.local/account, the browser is looking for the CSS at project.local/css/styles.css, but on project.local/account/action, the browser is looking for the CSS at project.local/account/css/styles.css.

Long story short, add a leading slash to your parameter, which will make it into a root-relative link that will resolve to the same location on all pages:

```<code>$this->headLink()->appendStylesheet('/css/styles.css');
</code>```

As pointed out by Phil in a comment, the above example only works as long as your ZF application is installed in the root of the site (as in this case). Using the BaseUrl helper will output the correct path regardless of where the site is located in the site hierarchy.

```<code>$this->headLink()->appendStylesheet($this->baseUrl('css/styles.css'));
</code>```

Title: css problem in action on Zend Framework

Body:
Not sure what I'm doing wrong here, but it seems that the framework is only able to find the style.css on my index actions on every controller. I'm calling it from the layout.phtml like this:

$this->headLink()->appendStylesheet('css/styles.css');

So when I go to project.local/account, I find the styles. If I go to project.local/account/action there are no styles...and actually if I go to project.local/account/index...there are no styles. So... it's a bit of a weird error, or at least it is for a n00b

Edit: When I open the code console on firefox and try to follow the css/styles.css I find the following error message:

#0 /home/fiodorovich/library/ZendFramework/library/Zend/Controller/Action.php(515): Zend_Controller_Action->__call('cssAction', Array)
#1/home/fiodorovich/library/ZendFramework/library/Zend/Controller/Dispatcher/Standard.php(295): Zend_Controller_Action->dispatch('cssAction')
#2 /home/fiodorovich/library/ZendFramework/library/Zend/Controller/Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#3 /home/fiodorovich/library/ZendFramework/library/Zend/Application/Bootstrap/Bootstrap.php(97): Zend_Controller_Front->dispatch()
#4 /home/fiodorovich/library/ZendFramework/library/Zend/Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#5 /home/fiodorovich/public_html/gisele/public/index.php(26): Zend_Application->run()
#6 {main}

Request Parameters:

array (
  'controller' => 'gisele',
  'action' => 'css',
  'module' => 'default',
)

Body:
The parameter you pass to appendStylesheet is just being blindly output in your HTML, the framework's not actually looking for that file.

The reason this is working on some pages and not others is that you've given appendStylesheet a relative link. Basically, when a browser encounters a relative link, it strips off the current URL at the last slash and then adds on the link.

So, on project.local/account, the browser is looking for the CSS at project.local/css/styles.css, but on project.local/account/action, the browser is looking for the CSS at project.local/account/css/styles.css.

Long story short, add a leading slash to your parameter, which will make it into a root-relative link that will resolve to the same location on all pages:

$this->headLink()->appendStylesheet('/css/styles.css');

As pointed out by Phil in a comment, the above example only works as long as your ZF application is installed in the root of the site (as in this case). Using the BaseUrl helper will output the correct path regardless of where the site is located in the site hierarchy.

$this->headLink()->appendStylesheet($this->baseUrl('css/styles.css'));


问:
REPLACEMENT SELECTION SORT:
I am working on Replacement Selection sort project but i keep getting the error Exception in thread main Java.lang.ArrayIndexOutOfBoundsException:10 at ReplacementSelection.swap(ReplacementSelection.java:42) at ReplacementSelection.siftDown(ReplacementSelection.java:69) at Replacement..</p>

```<code>class ReplacementSelection {
    static int[] array = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

    public static void sort() {

        System.out.println("before:" + Arrays.toString(array));

        for (int i = array.length/2; i >= 0; i--) {
            siftDown(i);
        }

        int count = array.length-1;
        while (count > 0)
        {
            swap(array[0], array[count]);
            --count;
            siftDown(0);
        }

        System.out.println("after:" + Arrays.toString(array));
    }

    public static void swap(int i, int j)
    {
        int tmp;
        tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }

    public static void siftDown(int index)
    {
        int count = array.length;
        // Left child is at index*2+1. Right child is at index*2+2;
        while (true)
        {
            // first find the largest child
            int largestChild = index*2+1;
            // if left child is larger than count, then done
            if (largestChild >= count)
            {
                break;
            }
            // compare with right child
            if (largestChild+1 < count && array[largestChild] < array[largestChild+1])
            {
                ++largestChild;
            }

            // If item is smaller than the largest child, then swap and continue.
            if (array[index] < array[largestChild])
            {
                swap(array[index], array[largestChild]);
                index = largestChild;
            }
            else
            {
                break;
            }
        }
    }

    public static void main(String[] args){
        ReplacementSelection a = new ReplacementSelection();
        a.sort();
    }
}
</code>```

答:
You have written a swap method which takes indices as arguments. However, you pass it the values in the array at those indices instead of the indices themselves:

```<code>swap(array[0], array[count]);
</code>```

and

```<code>swap(array[index], array[largestChild]);
</code>```

To fix the exception error just pass the indices to the method:

```<code>swap(0, count);
</code>```

and

```<code>swap(index, largestChild);
</code>```

Title: REPLACEMENT SELECTION SORT:

Body:
I am working on Replacement Selection sort project but i keep getting the error Exception in thread main Java.lang.ArrayIndexOutOfBoundsException:10 at ReplacementSelection.swap(ReplacementSelection.java:42) at ReplacementSelection.siftDown(ReplacementSelection.java:69) at Replacement..

class ReplacementSelection {
    static int[] array = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

    public static void sort() {

        System.out.println("before:" + Arrays.toString(array));

        for (int i = array.length/2; i >= 0; i--) {
            siftDown(i);
        }

        int count = array.length-1;
        while (count > 0)
        {
            swap(array[0], array[count]);
            --count;
            siftDown(0);
        }

        System.out.println("after:" + Arrays.toString(array));
    }

    public static void swap(int i, int j)
    {
        int tmp;
        tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }

    public static void siftDown(int index)
    {
        int count = array.length;
        // Left child is at index*2+1. Right child is at index*2+2;
        while (true)
        {
            // first find the largest child
            int largestChild = index*2+1;
            // if left child is larger than count, then done
            if (largestChild >= count)
            {
                break;
            }
            // compare with right child
            if (largestChild+1 < count && array[largestChild] < array[largestChild+1])
            {
                ++largestChild;
            }

            // If item is smaller than the largest child, then swap and continue.
            if (array[index] < array[largestChild])
            {
                swap(array[index], array[largestChild]);
                index = largestChild;
            }
            else
            {
                break;
            }
        }
    }

    public static void main(String[] args){
        ReplacementSelection a = new ReplacementSelection();
        a.sort();
    }
}

Body:
You have written a swap method which takes indices as arguments. However, you pass it the values in the array at those indices instead of the indices themselves:

swap(array[0], array[count]);

and

swap(array[index], array[largestChild]);

To fix the exception error just pass the indices to the method:

swap(0, count);

and

swap(index, largestChild);


问:
MvvmLight : How to unsubscribe "RaisePropertychanged" Event
I have a problem in my WPF application with MvvmLight.

My application :

I have a MainView with a menu, each MenuItem will open a new view (different for each menuitem).

Each MenuItem is bound to a RelayCommand of my MainViewModel

In my MainViewModel, the RelayCommand just do Messenger.Default.Send(this, "ShowMyView") to the MainView.

In my MainView, I'm registered on the message "ShowMyView" and actions are :

var v = new MyView();
v.Owner = this;
v.ShowDialog();
Messenger.Default.Unregister(v);

This new view (MyView) is bound on a viewmodel (MyViewModel) that contains properties.
Elements of this view (textbox, radiobutton, etc) are bound to these properties.

When I close "MyView", It's disposed and I come back to my mainview but the "MyViewModel" still exist.

Problem :

When I first open "MyView", binding works properly, if "MyViewModel" set a property, the RaisePropertyChanged is called, then the "get" of this property is call once.

But If I open and close my view 20 times, at the 20th times, when a RaisePropertyChanged is called, the get of this property is call 20 times !

Question :

So how can I unsubscribe these "RaisePropertyChanged" when I close a view ?

Hopping it's clear for you, and sorry for my bad english.

EDIT : With code

EDIT BIS

Instead of putting some part of code, please found on my github a complete project where the problem occured.

https://github.com/damgot/MvvmLightProblemExample

When I run the application, the MainWindow start :

You can see in Debug Output :

```<code>Starting
Creating NewViewModel
</code>```

Then, when I click on NewView Menu, the newview open :

And you can see in Debug output :

```<code>Initialize NewViewModel and set MyBool to true
MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call
</code>```

Seems Ok as I have 2 radio button bound on "MyBool"

Now if I select the "MyBool is false" Radio button :

and in output :

```<code>MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call
</code>```

Still good.

Now, If I close the NewView, and open it again, and select "MyBool is false" Radio button, the output is :

```<code>MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
</code>```

Then once again, output is  :

```<code>MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
</code>```

and once again :

```<code>MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
</code>```

And so on...

As You can see, "Get" call on my property, increase each team I re-open the view

答:
I've found a solution, but it's an ugly one.

As I said in comment, I'm not alone in my project, and the solution involved other project that I can not edit. So I can not simply suppress the "ViewModelLocator".

So to fix my problem, in my ViewModelLocator, in my ViewModels properties, instead of doing this :

```<code>public NewViewModel NewView
{
    get
    {
        var vm = ServiceLocator.Current.GetInstance<NewViewModel>();
        vm.Initialize();
        return vm;
    }
}
</code>```

I do this :

```<code>public NewViewModel NewView
{
    get
    {
        SimpleIoc.Default.Unregister<NewViewModel>();
        SimpleIoc.Default.Register<NewViewModel>(true);
        var vm = ServiceLocator.Current.GetInstance<NewViewModel>();
        vm.Initialize();
        return vm;
    }
}
</code>```

Each time I call a ViewModel (so when I open a view), the model is Unregistered then Registered. It force to recreate a ViewModel, so all subscriptions to PropertyChanged are reset.

I will not set this solution as the good one because I think this solution is not very pretty. But it works and the used memory seems not raising.

Body:
I have a problem in my WPF application with MvvmLight.

My application :

I have a MainView with a menu, each MenuItem will open a new view (different for each menuitem).

Each MenuItem is bound to a RelayCommand of my MainViewModel

In my MainViewModel, the RelayCommand just do Messenger.Default.Send(this, "ShowMyView") to the MainView.

In my MainView, I'm registered on the message "ShowMyView" and actions are :

var v = new MyView();
v.Owner = this;
v.ShowDialog();
Messenger.Default.Unregister(v);

This new view (MyView) is bound on a viewmodel (MyViewModel) that contains properties.
Elements of this view (textbox, radiobutton, etc) are bound to these properties.

When I close "MyView", It's disposed and I come back to my mainview but the "MyViewModel" still exist.

Problem :

When I first open "MyView", binding works properly, if "MyViewModel" set a property, the RaisePropertyChanged is called, then the "get" of this property is call once.

But If I open and close my view 20 times, at the 20th times, when a RaisePropertyChanged is called, the get of this property is call 20 times !

Question :

So how can I unsubscribe these "RaisePropertyChanged" when I close a view ?

Hopping it's clear for you, and sorry for my bad english.

EDIT : With code

EDIT BIS

Instead of putting some part of code, please found on my github a complete project where the problem occured.

https://github.com/damgot/MvvmLightProblemExample

When I run the application, the MainWindow start :

You can see in Debug Output :

Starting
Creating NewViewModel

Then, when I click on NewView Menu, the newview open :

And you can see in Debug output :

Initialize NewViewModel and set MyBool to true
MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call

Seems Ok as I have 2 radio button bound on "MyBool"

Now if I select the "MyBool is false" Radio button :

and in output :

MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call

Still good.

Now, If I close the NewView, and open it again, and select "MyBool is false" Radio button, the output is :

MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call

Then once again, output is  :

MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call

and once again :

MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call

And so on...

As You can see, "Get" call on my property, increase each team I re-open the view

Body:
I've found a solution, but it's an ugly one.

As I said in comment, I'm not alone in my project, and the solution involved other project that I can not edit. So I can not simply suppress the "ViewModelLocator".

So to fix my problem, in my ViewModelLocator, in my ViewModels properties, instead of doing this :

public NewViewModel NewView
{
    get
    {
        var vm = ServiceLocator.Current.GetInstance<NewViewModel>();
        vm.Initialize();
        return vm;
    }
}

I do this :

public NewViewModel NewView
{
    get
    {
        SimpleIoc.Default.Unregister<NewViewModel>();
        SimpleIoc.Default.Register<NewViewModel>(true);
        var vm = ServiceLocator.Current.GetInstance<NewViewModel>();
        vm.Initialize();
        return vm;
    }
}

Each time I call a ViewModel (so when I open a view), the model is Unregistered then Registered. It force to recreate a ViewModel, so all subscriptions to PropertyChanged are reset.

I will not set this solution as the good one because I think this solution is not very pretty. But it works and the used memory seems not raising.


问:
What should basically public folder contain in React
I was learning React and came across public folder which contains html file, favicon and the others. The question is for what public folder is actually created? and what should it contain?</p>

答:
Just static contents that do not need to compile (.html, .svg, .jpg, ...).

Just like www folder for ASP.net Core projects.

But It is your desition to put them there or somewhere else.

Documentation


问:
NSWindow contentView not cover full window size - macOS & SwiftUI
I'm starting a new macOS app with SwiftUI but I have a big problem.
The app needs a full size contentView (underneath titleBar) but I can't accomplish. On a new project using Storyboards works fine, but with SwiftUI not.

My code:

Result:

And it should look like this:

Any ideas?
Thanks!

答:
The safe area does not extend underneath a transparent title bar. You can use edgesIgnoringSafeArea to tell your content view edges to ignore the safe area. Something that resembles your example:

```<code>struct ContentView: View {
  var body: some View {
    HStack(spacing: 0) {
      Text("Hello, World!")
        .frame(maxWidth: 200, maxHeight: .infinity)
        .background(Color.red)
      Text("Hello, World!")
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.black)
    }.edgesIgnoringSafeArea(.all)
  }
}
</code>```

Update:
If you want to use a NavigationView, you have to add edgesIgnoringSafeArea to its contents as well:

```<code>struct ContentView: View {
  var body: some View {
    NavigationView {
      Text("Hello, World!")
        .frame(maxWidth: 200, maxHeight: .infinity)
        .background(Color.red)
        .edgesIgnoringSafeArea(.all)

      Text("Hello, World!")
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.black)
        .edgesIgnoringSafeArea(.all)

    }.edgesIgnoringSafeArea(.all)
  }
}
</code>```

Unfortunately, this will initially show a title bar at the moment, apparently until you force a full window redraw. Once you move the window to a different display or hide and show it again, the title bar disappears. So, my guess is that this will be fixed at some point.

Right now, you can programmatically force a hide & show by adding

```<code>DispatchQueue.main.async {
  self.window.orderOut(nil)
  self.window.makeKeyAndOrderFront(nil)
}
</code>```

after window.makeKeyAndOrderFront(nil) in applicationDidFinishLaunching. It will add a very short animation however. If it bothers you, you may be able to turn that off with NSWindow.animationBehavior or something like that.

Update 2: Apparently, if you remove the initial window.makeKeyAndOrderFront(nil) and replace it with the dispatch queue logic above it won't animate. So in the end you'll have

```<code>func applicationDidFinishLaunching(_ aNotification: Notification) {
  let contentView = ContentView()

  window = NSWindow(
      contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
      styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView, .texturedBackground],
      backing: .buffered, defer: false)
  window.titlebarAppearsTransparent = true
  window.center()
  window.setFrameAutosaveName("Main Window")
  window.contentView = NSHostingView(rootView: contentView)
  // window.makeKeyAndOrderFront(self) <- don't call it here
  DispatchQueue.main.async {
    self.window.orderOut(nil)
    self.window.makeKeyAndOrderFront(nil)
  }
}
</code>```

Body:
The safe area does not extend underneath a transparent title bar. You can use edgesIgnoringSafeArea to tell your content view edges to ignore the safe area. Something that resembles your example:

struct ContentView: View {
  var body: some View {
    HStack(spacing: 0) {
      Text("Hello, World!")
        .frame(maxWidth: 200, maxHeight: .infinity)
        .background(Color.red)
      Text("Hello, World!")
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.black)
    }.edgesIgnoringSafeArea(.all)
  }
}

Update:
If you want to use a NavigationView, you have to add edgesIgnoringSafeArea to its contents as well:

struct ContentView: View {
  var body: some View {
    NavigationView {
      Text("Hello, World!")
        .frame(maxWidth: 200, maxHeight: .infinity)
        .background(Color.red)
        .edgesIgnoringSafeArea(.all)

      Text("Hello, World!")
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.black)
        .edgesIgnoringSafeArea(.all)

    }.edgesIgnoringSafeArea(.all)
  }
}

Unfortunately, this will initially show a title bar at the moment, apparently until you force a full window redraw. Once you move the window to a different display or hide and show it again, the title bar disappears. So, my guess is that this will be fixed at some point.

Right now, you can programmatically force a hide & show by adding

DispatchQueue.main.async {
  self.window.orderOut(nil)
  self.window.makeKeyAndOrderFront(nil)
}

after window.makeKeyAndOrderFront(nil) in applicationDidFinishLaunching. It will add a very short animation however. If it bothers you, you may be able to turn that off with NSWindow.animationBehavior or something like that.

Update 2: Apparently, if you remove the initial window.makeKeyAndOrderFront(nil) and replace it with the dispatch queue logic above it won't animate. So in the end you'll have

func applicationDidFinishLaunching(_ aNotification: Notification) {
  let contentView = ContentView()

  window = NSWindow(
      contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
      styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView, .texturedBackground],
      backing: .buffered, defer: false)
  window.titlebarAppearsTransparent = true
  window.center()
  window.setFrameAutosaveName("Main Window")
  window.contentView = NSHostingView(rootView: contentView)
  // window.makeKeyAndOrderFront(self) <- don't call it here
  DispatchQueue.main.async {
    self.window.orderOut(nil)
    self.window.makeKeyAndOrderFront(nil)
  }
}


问:
What should I know about C# before walking into an interview for a .NET job?
Sure, we all have written tons of C# code. So walking into an interview for a .NET job should be a no-brainer, right? And then you read some stackoverflow posts and it hits you: You don't know squat!

Remember that site with the cram sessions to go through, before taking an exam? I think stackoverflow could be used to make a sorted (voting) list of topics to know about.

Please only put one topic per post.
Please also add some information about the topic. Links, reference material etc.

EDIT: I guess some of you misunderstood the reason for the post - I'm hoping to generate a list of stuff to know about .NET, a sort of cram session that can be reviewed by everyone on the planet to regularly review. This should help us all remember arcane stuff we never really use.

答:
I don't see how this question is valuable to your situation.  The result of this question is going to be 30 posts listing features of the C# language.

I think you need to refine your question by giving us a hint about what type of job you are applying for. Or your skill set level or what areas your familiar with.  Otherwise this post won't really contain a valuable answer.

EDIT

[OP] That (30 posts listing features of the C# language) is precisely what I am after

Then I suggest the C# language spec.  http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx

OwnerDisplayName: Daren Thomas

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Daren Thomas

OwnerDisplayName: JaredPar

LastEditorDisplayName: JaredPar


问:
How to create a join query between two entities in FIWARE orion?
I have two entites A (postings) and B (users) with a many to one relationship and I want to do an SQL like join to list posts and users together.
I tried the following query, but it only returns an empty array.
I could not find any other documentation regarding this, all tutorials only refer to one id.

```<code>https://{{orion}}/v2/entities?q=Post.createdBy==User.id&options=count,keyValues&limit=100
</code>```

I also tried this variant, but the same result:

```<code>https://{{orion}}/v2/entities?q=createdBy==id&options=count,keyValues&limit=100
</code>```

And I checked that there is at least one entity which matches I manually checked

```<code>https://{{orion}}/v2/entities?q=createdBy==urn:ngsi-ld:User:78bc5cac26d1b3abe27cb2cf94b1015a3710958f
</code>```

This query above returns an entity.

```<code>|      Post        |     |     User     |
|------------------|     |--------------|
| ID               |     | ID           |
| Type             |     | Type         |
| Message          |     | Username     |
| CreatedBy: UserId|
</code>```

In orion the datatype:

```<code>   "createdBy": {
            "type": "Relationship",
            "value": "urn:ngsi-ld:User:78bc5cac26d1b3abe27cb2cf94b1015a3710958f",
            "metadata": {}
        },
</code>```

答:
The short answer is that you cannot do that kind of join operations using the NGSI API provided by Orion.

The NGSI API is oriented to context management, that is, retrieving and updating context information in the form of entities and their attributes. It is not designed to be a SQL-style language, which would involve a lot of complexity. Orion is a context broker, not a relational database ;)

Fortunately, that kind of join operations can be done by the client, doing several queries to Orion.

Body:
I have two entites A (postings) and B (users) with a many to one relationship and I want to do an SQL like join to list posts and users together.
I tried the following query, but it only returns an empty array.
I could not find any other documentation regarding this, all tutorials only refer to one id.

https://{{orion}}/v2/entities?q=Post.createdBy==User.id&options=count,keyValues&limit=100

I also tried this variant, but the same result:

https://{{orion}}/v2/entities?q=createdBy==id&options=count,keyValues&limit=100

And I checked that there is at least one entity which matches I manually checked

https://{{orion}}/v2/entities?q=createdBy==urn:ngsi-ld:User:78bc5cac26d1b3abe27cb2cf94b1015a3710958f

This query above returns an entity.

|      Post        |     |     User     |
|------------------|     |--------------|
| ID               |     | ID           |
| Type             |     | Type         |
| Message          |     | Username     |
| CreatedBy: UserId|

In orion the datatype:

   "createdBy": {
            "type": "Relationship",
            "value": "urn:ngsi-ld:User:78bc5cac26d1b3abe27cb2cf94b1015a3710958f",
            "metadata": {}
        },


问:
Roboto 'Thin' with Google Fonts
So I'm trying to get Roboto Thin working in my CSS through Google Fonts

```<code><link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto:bold&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto:thin&display=swap" rel="stylesheet">
</code>```

I can get the normal Roboto working just fine, but not when I try to specify the thin weight like so:

```<code>body {
    font: 16px/21px Roboto, "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
}

h1, h2, h3, h4, h5, h6 {
    font-weight: thin;
}
</code>```

It just gives me the regular weight... can anyone see what I'm doing wrong?

答:
If you look at the font source by going to the link in the CSS you can see the light font is weight 100, so you can just do this:

body{
    font-family: 'Roboto', sans-serif;
}

.normal{
  font-weight: 400;
}

.light{
  font-weight: 100;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?family=Roboto:100,400&display=swap" rel="stylesheet">
<!-- 100 is light, 400 is normal -->

<p class="normal">Lorem ipsum</p>
<p class="light">Lorem ipsum</p></code>```

You can get the link by selecting the font in Google Fonts, clicking on the font name in the bottom right hand corner, going to customize and checking all the font weight boxes you need. Then go back to embed and copy the link. Don't just use the weight though - import the link too or you'll get font scaling and spacing problems on Firefox on Ubuntu.

Title: Roboto 'Thin' with Google Fonts

Body:
So I'm trying to get Roboto Thin working in my CSS through Google Fonts

<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto:bold&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto:thin&display=swap" rel="stylesheet">

I can get the normal Roboto working just fine, but not when I try to specify the thin weight like so:

body {
    font: 16px/21px Roboto, "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
}

h1, h2, h3, h4, h5, h6 {
    font-weight: thin;
}

It just gives me the regular weight... can anyone see what I'm doing wrong?

Body:
If you look at the font source by going to the link in the CSS you can see the light font is weight 100, so you can just do this:

body{
    font-family: 'Roboto', sans-serif;
}

.normal{
  font-weight: 400;
}

.light{
  font-weight: 100;
}

<link href="https://fonts.googleapis.com/css?family=Roboto:100,400&display=swap" rel="stylesheet">
<!-- 100 is light, 400 is normal -->

<p class="normal">Lorem ipsum</p>
<p class="light">Lorem ipsum</p>

You can get the link by selecting the font in Google Fonts, clicking on the font name in the bottom right hand corner, going to customize and checking all the font weight boxes you need. Then go back to embed and copy the link. Don't just use the weight though - import the link too or you'll get font scaling and spacing problems on Firefox on Ubuntu.


问:
Why HtmlUnit code doesn't match Chrome code?
I am trying to web router page scraping to search for connected devices and information about them.
I  written this code:

```<code>String searchUrl="http://192.168.1.1";
HtmlPage page=client.getPage(searchUrl);
System.out.println(page.asXml());
</code>```

The problem is that the code returns by HtmlUnit is different from the code in Chrome. In HtmlUnit I don't have the section of code that lists connected devices.

答:
try something like this

```<code>try (final WebClient webClient = new WebClient()) {
    // do not stop at js errors
    webClient.getOptions().setThrowExceptionOnScriptError(false);

    webClient.getPage(searchUrl);
    // now wait for the js starting async (you can play with the timing)
    webClient.waitForBackgroundJavaScript(10000);

    // maybe the page was replaced from the async js
    HtmlPage page = (HtmlPage) webClient.getCurrentWindow().getEnclosedPage();

    System.out.println(page.asXml());
}
</code>```

Usually that helps.
If you still facing problems you have to open an issue on github (https://github.com/HtmlUnit/htmlunit).

But keep in mind i can only really help if i can run/and debug your code here - means you web app has to be public.

Body:
I am trying to web router page scraping to search for connected devices and information about them.
I  written this code:

String searchUrl="http://192.168.1.1";
HtmlPage page=client.getPage(searchUrl);
System.out.println(page.asXml());

The problem is that the code returns by HtmlUnit is different from the code in Chrome. In HtmlUnit I don't have the section of code that lists connected devices.

Body:
try something like this

try (final WebClient webClient = new WebClient()) {
    // do not stop at js errors
    webClient.getOptions().setThrowExceptionOnScriptError(false);

    webClient.getPage(searchUrl);
    // now wait for the js starting async (you can play with the timing)
    webClient.waitForBackgroundJavaScript(10000);

    // maybe the page was replaced from the async js
    HtmlPage page = (HtmlPage) webClient.getCurrentWindow().getEnclosedPage();

    System.out.println(page.asXml());
}

Usually that helps.
If you still facing problems you have to open an issue on github (https://github.com/HtmlUnit/htmlunit).

But keep in mind i can only really help if i can run/and debug your code here - means you web app has to be public.


问:
Help debugging this multiplication algorithm
I'm implementing the simple multiplication algorithm to compare its performance to a divide and conquer approach.

I ditched my original idea to do this thing with byte arithmetic and opted to convert the numbers via char arrays.

Well, everything works fine on simple cases like 33 x 33, where the debugging method prints, correctly:

```<code>0 9 9
0 9 9
</code>```

yet on 34 x 33, I get

```<code>1 0 3
1 0 2
</code>```

where it should be

```<code>1 0 2
1 0 2
</code>```

Where is that 3 coming from?

```<code>public static BigInteger simpleMultiply(BigInteger x, BigInteger y){

    char [] longerNum;
    char [] shorterNum;

    if(x.compareTo(y)>=0){ // x is a longer/equal num

        longerNum = x.toString().toCharArray();
        shorterNum = y.toString().toCharArray();

    }

   else { //y is a longer num

       longerNum = y.toString().toCharArray();
       shorterNum = x.toString().toCharArray();

   }

   //shorter num equals the number of rows in partial result
   // longer num + 1 equals the number of columns in partial result

    int [][] partialResult = new int [shorterNum.length][longerNum.length+1];

    int pastCarry=0;
    int result=0;
    int carry=0;

    for (int sIndex=(shorterNum.length-1); sIndex>=0; sIndex--)
        for (int lIndex = (longerNum.length-1); lIndex>=0; lIndex--)
        {
            int sInt = Integer.parseInt(""+shorterNum[sIndex]+"");
            int lInt = Integer.parseInt(""+longerNum[lIndex]+"");

            int product = sInt*lInt;

            if (lIndex==0){

             result  =  (pastCarry+product)% 10;
             carry   = (pastCarry+product) /  10;

             pastCarry = carry;

             partialResult [sIndex][lIndex+1] = result; //one more column element in partialResult

             partialResult[sIndex][lIndex] = carry;

           }

            else {

             result  = (pastCarry+product)% 10;
             carry   = (pastCarry+product) /  10;

             pastCarry = carry;

             partialResult [sIndex][lIndex+1] = result;//one more column element in partialResult

            }

        }

        for (int i=0; i<partialResult.length;i++)
            for (int j=0; j<partialResult[0].length;j++)
            {

                  System.out.print(partialResult[i][j] + " ");
                  if (j==partialResult[0].length-1){System.out.println();}
            }

    return null;
 }
</code>```

答:
It's because you're not zeroing out pastCarry between iterations of the outer loop.

Change

```<code>for (int sIndex=(shorterNum.length-1); sIndex>=0; sIndex--)
    for (int lIndex = (longerNum.length-1); lIndex>=0; lIndex--)
    {
        [snip]
    }
</code>```

to

```<code>for (int sIndex=(shorterNum.length-1); sIndex>=0; sIndex--)
{
    pastCarry = 0;
    for (int lIndex = (longerNum.length-1); lIndex>=0; lIndex--)
    {
        [snip]
    }
}
</code>```

And by the way, the int sInt = .... line should also be moved outside the inner loop since it doesn't depend on anything inside the inner loop.

Body:
I'm implementing the simple multiplication algorithm to compare its performance to a divide and conquer approach.

I ditched my original idea to do this thing with byte arithmetic and opted to convert the numbers via char arrays.

Well, everything works fine on simple cases like 33 x 33, where the debugging method prints, correctly:

0 9 9
0 9 9

yet on 34 x 33, I get

1 0 3
1 0 2

where it should be

1 0 2
1 0 2

Where is that 3 coming from?

public static BigInteger simpleMultiply(BigInteger x, BigInteger y){

    char [] longerNum;
    char [] shorterNum;

    if(x.compareTo(y)>=0){ // x is a longer/equal num

        longerNum = x.toString().toCharArray();
        shorterNum = y.toString().toCharArray();

    }

   else { //y is a longer num

       longerNum = y.toString().toCharArray();
       shorterNum = x.toString().toCharArray();

   }

   //shorter num equals the number of rows in partial result
   // longer num + 1 equals the number of columns in partial result

    int [][] partialResult = new int [shorterNum.length][longerNum.length+1];

    int pastCarry=0;
    int result=0;
    int carry=0;

    for (int sIndex=(shorterNum.length-1); sIndex>=0; sIndex--)
        for (int lIndex = (longerNum.length-1); lIndex>=0; lIndex--)
        {
            int sInt = Integer.parseInt(""+shorterNum[sIndex]+"");
            int lInt = Integer.parseInt(""+longerNum[lIndex]+"");

            int product = sInt*lInt;

            if (lIndex==0){

             result  =  (pastCarry+product)% 10;
             carry   = (pastCarry+product) /  10;

             pastCarry = carry;

             partialResult [sIndex][lIndex+1] = result; //one more column element in partialResult

             partialResult[sIndex][lIndex] = carry;

           }

            else {

             result  = (pastCarry+product)% 10;
             carry   = (pastCarry+product) /  10;

             pastCarry = carry;

             partialResult [sIndex][lIndex+1] = result;//one more column element in partialResult

            }

        }

        for (int i=0; i<partialResult.length;i++)
            for (int j=0; j<partialResult[0].length;j++)
            {

                  System.out.print(partialResult[i][j] + " ");
                  if (j==partialResult[0].length-1){System.out.println();}
            }

    return null;
 }

Body:
It's because you're not zeroing out pastCarry between iterations of the outer loop.

Change

for (int sIndex=(shorterNum.length-1); sIndex>=0; sIndex--)
    for (int lIndex = (longerNum.length-1); lIndex>=0; lIndex--)
    {
        [snip]
    }

to

for (int sIndex=(shorterNum.length-1); sIndex>=0; sIndex--)
{
    pastCarry = 0;
    for (int lIndex = (longerNum.length-1); lIndex>=0; lIndex--)
    {
        [snip]
    }
}

And by the way, the int sInt = .... line should also be moved outside the inner loop since it doesn't depend on anything inside the inner loop.