问:
scanf prematurely terminating while loop (I think)
I am making a simple program to calculate the required exam mark based on your current mark, the % total worth of the exam on the course, and your desired mark. I was having no problems with it until I wanted a simple while loop to redo the proses if the user wanted to do so. The problem that arose was that when I have the scanf to get a char response from the user, it terminates the while loop and then the program. When I comment out the scanf line and leave the code as is (an infinite while loop) it works properly looping forever but with it, it will terminate with no errors. Any thoughts?</p>

```<code>    #include <stdio.h>

    #define TRUE 1
    #define FALSE 0

    int main()
    {
        int continueProgram = TRUE;
        float currentMark = 0.0, examPercent = 0.0, desiredMark = 0.0, requiredMark = 0.0;
        char response  = 'y';

        while (continueProgram == TRUE)
        {
            printf("What is your current mark in your class: ");
            scanf("%f", &currentMark);
            printf("How much is you exam worth: ");
            scanf("%f", &examPercent);
            examPercent /= 100.0;
            printf("What is your desiered mark: ");
            scanf("%f", &desiredMark);

            // Simple math to get mark
            requiredMark = (desiredMark - currentMark * examPercent) / examPercent;

            if (requiredMark > 100.0)
            {
                printf("\nI'm sorry but you need above 100%% to get to your required mark\nHere is a list of all the marks you can get:\n\n");

                for (requiredMark = 0.0; requiredMark <= 100.0; requiredMark += 5.0)
                {
                    desiredMark = currentMark * examPercent + requiredMark * examPercent;
                    printf("Exam Mark: %.2f, Final Mark: %.2f\n", requiredMark, desiredMark);
                }
            }
            else
            {
                printf("\nThe mark that you need to get on the exam is: %.2f\nHere is a list of all the marks you can get:\n\n", requiredMark);

                for (requiredMark = 0.0; requiredMark <= 100.0; requiredMark += 5.0)
                {
                    desiredMark = currentMark * examPercent + requiredMark * examPercent;
                    printf("Exam Mark: %.2f, Final Mark: %.2f\n", requiredMark, desiredMark);
                }
            }

            printf("\nDid you want to continue with a new grade (y or n): ");

            // THIS IS WHERE I AM HAVING THE ISSUE
            scanf("%c", &response );

            if (response  == 'y')
            {
                printf("\n\nResetting  terminal...\n\n");
                currentMark = 0.0;
                examPercent = 0.0;
                desiredMark = 0.0;
                requiredMark = 0.0;
            }
            else
                continueProgram = FALSE;
        }
    }
</code>```

答:
The problem that arose was that when I have the scanf to get a char response from the user, it terminates the while loop and then the program.

This is happening because the scanf() is reading the stray \n (newline character) from the input buffer.

To resolve this, add a space before % character in scanf() like this:

```<code>scanf(" %c", &responce);
</code>```

This will skip the leading whitespace characters (including newline character) and read the input given by the user.

Body:
I am making a simple program to calculate the required exam mark based on your current mark, the % total worth of the exam on the course, and your desired mark. I was having no problems with it until I wanted a simple while loop to redo the proses if the user wanted to do so. The problem that arose was that when I have the scanf to get a char response from the user, it terminates the while loop and then the program. When I comment out the scanf line and leave the code as is (an infinite while loop) it works properly looping forever but with it, it will terminate with no errors. Any thoughts?

    #include <stdio.h>

    #define TRUE 1
    #define FALSE 0

    int main()
    {
        int continueProgram = TRUE;
        float currentMark = 0.0, examPercent = 0.0, desiredMark = 0.0, requiredMark = 0.0;
        char response  = 'y';

        while (continueProgram == TRUE)
        {
            printf("What is your current mark in your class: ");
            scanf("%f", &currentMark);
            printf("How much is you exam worth: ");
            scanf("%f", &examPercent);
            examPercent /= 100.0;
            printf("What is your desiered mark: ");
            scanf("%f", &desiredMark);

            // Simple math to get mark
            requiredMark = (desiredMark - currentMark * examPercent) / examPercent;

            if (requiredMark > 100.0)
            {
                printf("\nI'm sorry but you need above 100%% to get to your required mark\nHere is a list of all the marks you can get:\n\n");

                for (requiredMark = 0.0; requiredMark <= 100.0; requiredMark += 5.0)
                {
                    desiredMark = currentMark * examPercent + requiredMark * examPercent;
                    printf("Exam Mark: %.2f, Final Mark: %.2f\n", requiredMark, desiredMark);
                }
            }
            else
            {
                printf("\nThe mark that you need to get on the exam is: %.2f\nHere is a list of all the marks you can get:\n\n", requiredMark);

                for (requiredMark = 0.0; requiredMark <= 100.0; requiredMark += 5.0)
                {
                    desiredMark = currentMark * examPercent + requiredMark * examPercent;
                    printf("Exam Mark: %.2f, Final Mark: %.2f\n", requiredMark, desiredMark);
                }
            }

            printf("\nDid you want to continue with a new grade (y or n): ");

            // THIS IS WHERE I AM HAVING THE ISSUE
            scanf("%c", &response );

            if (response  == 'y')
            {
                printf("\n\nResetting  terminal...\n\n");
                currentMark = 0.0;
                examPercent = 0.0;
                desiredMark = 0.0;
                requiredMark = 0.0;
            }
            else
                continueProgram = FALSE;
        }
    }

Body:
The problem that arose was that when I have the scanf to get a char response from the user, it terminates the while loop and then the program.

This is happening because the scanf() is reading the stray \n (newline character) from the input buffer.

To resolve this, add a space before % character in scanf() like this:

scanf(" %c", &responce);

This will skip the leading whitespace characters (including newline character) and read the input given by the user.


来源: stackexchange

问:
Can't parse DialogFlow json response
I know this question has been asked multiple times... but I can't figure out what happens
I've an issue while trying to parse a json response.
Here is the json (extract)

```<code>{"result":{"fulfillment":{"speech":"[{\"name\":\"Pallet truck\",\"object_type\":\"machine\",\"object_id\":3279}, ...
</code>```

I'm applying JSON parse on it like this

```<code> var obj = JSON.parse(response);
</code>```

Then I have something like this

```<code>"result":{
  "fulfillment":{
     "speech":"[
{"name":"Pallet truck","object_type":"machine","object_id":3279},
{"name":"CollaborativeRobot","object_type":"machine","object_id":3273},
{"name":"Bender","object_type":"machine","object_id":3997},...
</code>```

I want only display it like that at the end :

```<code>Name : Pallet Truck
Name : CollaborativeRobot
Name : Bender
</code>```

I've tried things like this

```<code>for (var key in obj.result.fulfillment.speech) {
      if (obj.result.fulfillment.speech.hasOwnProperty(key)) {
            console.log(obj.result.fulfillment.speech[key].name.val());
      }
}
</code>```

But I only got undefined results... I think I'm missing something while accessing the array (it's been a while without coding anything in php/js )

EDIT

EDIT 2

It seams that the issue is on server side, while double encoding
here is an extract :

```<code>    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://api.mephisto.optimdata.io/search?object_type=machine');
    curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'authorization: JWT '.$accessToken));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);

    $fulfillment = new stdClass();
    $fulfillment->speech = $result;
    $result = new stdClass();
    $result->fulfillment = $fulfillment;
    $result->requete = "machines actives";
    $responseQueryAPI = new stdClass();
    $responseQueryAPI->result = $result;
    echo json_encode($responseQueryAPI);
</code>```

Maybe this is because the curl response is already json?
The curl response looks like this :

```<code>[
    {
        "name": "Pallet truck",
        "object_type": "machine",
        "object_id": 3279
    },
    {
        "name": "Collaborative Robot",
        "object_type": "machine",
        "object_id": 3273
    },
    {
        "name": "Bender",
        "object_type": "machine",
        "object_id": 3997
    },
</code>```

答:
name is just a string, so try to replace

```<code>for (var key in obj.result.fulfillment.speech) {
    if (obj.result.fulfillment.speech.hasOwnProperty(key)) {
        console.log(obj.result.fulfillment.speech[key].name.val());
    }
}
</code>```

to

```<code>for (var i = 0; i < obj.result.fulfillment.speech.length; ++i) {
    console.log(obj.result.fulfillment.speech[i].name);
}
</code>```

Edit:

The response data looks wrong.

I got syntax error with JSON.parse('{"result":{"fulfillment":{"speech":"[{\"name\":\"Pallet truck\",\"object_type\":\"machine\",\"object_id\":3279}]"}}}');.

Try to use
JSON.parse('{"result":{"fulfillment":{"speech":[{"name":"Pallet truck","object_type":"machine","object_id":3279}]}}}');.

ContentLicense: CC BY-SA 3.0

Title: Can't parse DialogFlow json response

Body:
I know this question has been asked multiple times... but I can't figure out what happens
I've an issue while trying to parse a json response.
Here is the json (extract)

{"result":{"fulfillment":{"speech":"[{\"name\":\"Pallet truck\",\"object_type\":\"machine\",\"object_id\":3279}, ...

I'm applying JSON parse on it like this

 var obj = JSON.parse(response);

Then I have something like this

"result":{
  "fulfillment":{
     "speech":"[
{"name":"Pallet truck","object_type":"machine","object_id":3279},
{"name":"CollaborativeRobot","object_type":"machine","object_id":3273},
{"name":"Bender","object_type":"machine","object_id":3997},...

I want only display it like that at the end :

Name : Pallet Truck
Name : CollaborativeRobot
Name : Bender

I've tried things like this

for (var key in obj.result.fulfillment.speech) {
      if (obj.result.fulfillment.speech.hasOwnProperty(key)) {
            console.log(obj.result.fulfillment.speech[key].name.val());
      }
}

But I only got undefined results... I think I'm missing something while accessing the array (it's been a while without coding anything in php/js )

EDIT

EDIT 2

It seams that the issue is on server side, while double encoding
here is an extract :

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://api.mephisto.optimdata.io/search?object_type=machine');
    curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'authorization: JWT '.$accessToken));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);

    $fulfillment = new stdClass();
    $fulfillment->speech = $result;
    $result = new stdClass();
    $result->fulfillment = $fulfillment;
    $result->requete = "machines actives";
    $responseQueryAPI = new stdClass();
    $responseQueryAPI->result = $result;
    echo json_encode($responseQueryAPI);

Maybe this is because the curl response is already json?
The curl response looks like this :

[
    {
        "name": "Pallet truck",
        "object_type": "machine",
        "object_id": 3279
    },
    {
        "name": "Collaborative Robot",
        "object_type": "machine",
        "object_id": 3273
    },
    {
        "name": "Bender",
        "object_type": "machine",
        "object_id": 3997
    },

Body:
name is just a string, so try to replace

for (var key in obj.result.fulfillment.speech) {
    if (obj.result.fulfillment.speech.hasOwnProperty(key)) {
        console.log(obj.result.fulfillment.speech[key].name.val());
    }
}

to

for (var i = 0; i < obj.result.fulfillment.speech.length; ++i) {
    console.log(obj.result.fulfillment.speech[i].name);
}

Edit:

The response data looks wrong.

I got syntax error with JSON.parse('{"result":{"fulfillment":{"speech":"[{\"name\":\"Pallet truck\",\"object_type\":\"machine\",\"object_id\":3279}]"}}}');.

Try to use
JSON.parse('{"result":{"fulfillment":{"speech":[{"name":"Pallet truck","object_type":"machine","object_id":3279}]}}}');.


问:
Docker cannot login to azurecr.io
On Docker version 17.09.0-ce, build afdb6d4 (running on Mac OS 10.12.5) I'm having the following error when I run docker login <proj>.azurecr.io:

Warning: failed to get default registry endpoint from daemon (Cannot
  connect to the Docker daemon at unix:///var/run/docker.sock. Is the
  docker daemon running?). Using system default:
  https://index.docker.io/v1/

This is after I input the username and password that I retrived using az acr. I've done this same process in the past and now it's not working anymore.

How can I debug this and login/pull images again?

答:
Summary: I believe I just needed to restart Docker.

First, I turned on debugging by adding { "debug": true } to /etc/docker/daemon.json. Resource here. This probably wasn't needed

Second, I restarted docker from the mac terminal with osascript -e 'quit app "Docker"' followed by open -a Docker, details found here.

Title: Docker cannot login to azurecr.io


问:
Two PDO sql statements/Using fetched data for the second statement
So I'm new to PHP/PDO and I'm having some problems with passing the fetched variable on to the second statement. I'm also having problems with exceptions i don't know how the right structure for this situation.

```<code>try {
$connection->beginTransaction();
$stmt = $connection->prepare("CALL sproc_patient_profile_physical_exam_hdr(?,?,?)");
$stmt->bindValue(1,$casenumber_fetch,PDO::PARAM_INT);
$stmt->bindValue(2,$patientid_val,PDO::PARAM_INT);
$stmt->bindValue(3,$enteredby,PDO::PARAM_STR);

while($row = $stmt->fetch()){
    echo $physicalexamid_insert=$row['physicalexamid'];
    /* I need to use this data for another try and catch or sql statements for example*/

    $count_physical_exam_id = count($physical_exam_id);
    for ($x=0; $x < $count_physical_exam_id; $x++) {
        if (!(empty($physical_exam_id[$x]))) {
           try {
            $connection->beginTransaction();
            $stmt = $connection->prepare("CALL sproc_patient_profile_physical_exam_dtl(?,?,?,?,?,?,?)");
            $stmt->bindValue(1,$casenumber_fetch,PDO::PARAM_INT);
            $stmt->bindValue(2,1,PDO::PARAM_INT);
            $stmt->bindValue(3,$physical_exam_id[$x],PDO::PARAM_INT);
            $stmt->bindValue(4,$physical_exam_desc[$x],PDO::PARAM_STR);
            $stmt->bindValue(5,$normal[$x],PDO::PARAM_INT);
            $stmt->bindValue(6,$undone[$x],PDO::PARAM_INT);
            $stmt->bindValue(7,$specific[$x],PDO::PARAM_INT);

            $stmt->execute();
            $connection->commit();

            } catch(PDOException $ex) {
            //$connection->rollBack();
            echo $ex->getMessage();

        }

        }
    }

}
$stmt->execute();
$connection->commit();
} catch(PDOException $ex) {
$connection->rollBack();
echo $ex->getMessage();
</code>```

Can someone help me with this? Thanks.

答:
There's a couple of issues with your code:

You're not executing the first statement before you call fetch on it.

You're over-writing the $stmt variable in your loop.

The opening section of your code should be like this:

```<code>$stmt = $connection->prepare("CALL sproc_patient_profile_physical_exam_hdr(?,?,?)");
$stmt->bindValue(1,$casenumber_fetch,PDO::PARAM_INT);
$stmt->bindValue(2,$patientid_val,PDO::PARAM_INT);
$stmt->bindValue(3,$enteredby,PDO::PARAM_STR);
$stmt->execute();
</code>```

Once you've done that you can loop through with a control statement like you're doing (e.g. while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { ... }).

Inside that control structure, instead of using the variable $stmt for a new (second) statement, use something like $stmt2 or $inner_stmt, so that you don't over-write the outer variable.

Body:
So I'm new to PHP/PDO and I'm having some problems with passing the fetched variable on to the second statement. I'm also having problems with exceptions i don't know how the right structure for this situation.

try {
$connection->beginTransaction();
$stmt = $connection->prepare("CALL sproc_patient_profile_physical_exam_hdr(?,?,?)");
$stmt->bindValue(1,$casenumber_fetch,PDO::PARAM_INT);
$stmt->bindValue(2,$patientid_val,PDO::PARAM_INT);
$stmt->bindValue(3,$enteredby,PDO::PARAM_STR);

while($row = $stmt->fetch()){
    echo $physicalexamid_insert=$row['physicalexamid'];
    /* I need to use this data for another try and catch or sql statements for example*/

    $count_physical_exam_id = count($physical_exam_id);
    for ($x=0; $x < $count_physical_exam_id; $x++) {
        if (!(empty($physical_exam_id[$x]))) {
           try {
            $connection->beginTransaction();
            $stmt = $connection->prepare("CALL sproc_patient_profile_physical_exam_dtl(?,?,?,?,?,?,?)");
            $stmt->bindValue(1,$casenumber_fetch,PDO::PARAM_INT);
            $stmt->bindValue(2,1,PDO::PARAM_INT);
            $stmt->bindValue(3,$physical_exam_id[$x],PDO::PARAM_INT);
            $stmt->bindValue(4,$physical_exam_desc[$x],PDO::PARAM_STR);
            $stmt->bindValue(5,$normal[$x],PDO::PARAM_INT);
            $stmt->bindValue(6,$undone[$x],PDO::PARAM_INT);
            $stmt->bindValue(7,$specific[$x],PDO::PARAM_INT);

            $stmt->execute();
            $connection->commit();

            } catch(PDOException $ex) {
            //$connection->rollBack();
            echo $ex->getMessage();

        }

        }
    }

}
$stmt->execute();
$connection->commit();
} catch(PDOException $ex) {
$connection->rollBack();
echo $ex->getMessage();

Can someone help me with this? Thanks.

Body:
There's a couple of issues with your code:

You're not executing the first statement before you call fetch on it.

You're over-writing the $stmt variable in your loop.

The opening section of your code should be like this:

$stmt = $connection->prepare("CALL sproc_patient_profile_physical_exam_hdr(?,?,?)");
$stmt->bindValue(1,$casenumber_fetch,PDO::PARAM_INT);
$stmt->bindValue(2,$patientid_val,PDO::PARAM_INT);
$stmt->bindValue(3,$enteredby,PDO::PARAM_STR);
$stmt->execute();

Once you've done that you can loop through with a control statement like you're doing (e.g. while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { ... }).

Inside that control structure, instead of using the variable $stmt for a new (second) statement, use something like $stmt2 or $inner_stmt, so that you don't over-write the outer variable.


问:
Undefined index: uploadimage UPDATE: UPLOADS BUT DOESN'T ADD DIRECTORY TO COLUMN
So i've been trying to make a form with an IMG uploader.
The db is working and i can send the information to the database.
When I tried to implement the image uploader it gives me this print:
So in the form I only added the buttom to upload image, added name and on the post method i tried to upload the image before adding the data.

I did a print, and this is what it came out:
Field 'imgdire' doesn't have a default value

Can someone tell me what's wrong?

PHP

```<code> **if($_SERVER["REQUEST_METHOD"] == "POST"){
  // Validate album

   $UploadedFileName=$_FILES['uploadimage']['name'];
   if($UploadedFileName!='')
   {
   $upload_directory = "uploads/";
   $TargetPath=time().$UploadedFileName;
    if(move_uploaded_file($_FILES['files']['tmp_name'],
  $upload_directory.$TargetPath)){
     $QueryInsertFile="INSERT INTO album SET imgdire='$TargetPath'";

   }
}
</code>```

Send Information to database

```<code>// Check input errors before inserting in database
if(empty($artist_err) && empty($album_err) && empty($stock_err) &&
 empty($price_err) && empty($genre_err)){

    // Prepare an insert statement
    $sql = "INSERT INTO album (nomealbum, stock, price, genero, nomeinter) VALUES (?, ?, ?, ?, ?)";

    if($stmt = mysqli_prepare($link, $sql)){
        // Bind variables to the prepared statement as parameters
        mysqli_stmt_bind_param($stmt, "sssss", $param_album, $param_stock, $param_price, $param_genre, $param_artist);

        // Set parameters
        $param_album = $album;
        $param_stock = $stock;
        $param_price = $price;
        $param_genre = $genre;
        $param_artist = $artist;

        // Attempt to execute the prepared statement
        if(mysqli_stmt_execute($stmt)){

            // Redirect to admin page
            header("location: admin.php");
        } else{
           print mysqli_error($link);
            echo "Algo não correu bem, por favor tente mais uma vez";
        }
    }

    // Close statement
    mysqli_stmt_close($stmt);
}

// Close connection
mysqli_close($link);
}
</code>```

FORM

```<code>  <form method="POST" action="admin.php" enctype="multipart/form-data">

  <div class="form-group <?php echo (!empty($artist_err)) ? 'has-error' :
  ''; ?>">
  <label>Intérprete</label>
  <input  type="text" name="inter" class="form-control" placeholder="Nome do
  Artista" value="<?php echo $artist; ?>">
  <span class="help-block"><?php echo $artist_err; ?></span>
</div>

 <div class="form-group <?php echo (!empty($album_err)) ? 'has-error' : '';
  ?
 >">
  <label>Nome do Albúm:</label>
  <input  type="text" name="aname" class="form-control" placeholder="Album"
  value="<?php echo $album; ?>">
  <span class="help-block"><?php echo $album_err; ?></span>
  </div>

    <div class="form-group <?php echo (!empty($stock_err)) ? 'has-error' :
    ''; ?>">
  <label>Stock</label>
  <input  type="text" name="stocks" class="form-control"  placeholder=""
  value="<?php echo $stock; ?>">
  <span class="help-block"><?php echo $stock_err; ?></span>
</div>

<div class="form-group <?php echo (!empty($price_err)) ? 'has-error' : ''; ?
>">
  <label>Preço</label>
  <input  type="text"  name="prices" class="form-control"  placeholder=""
value="<?php echo $price; ?>">
  <span class="help-block"><?php echo $price_err; ?></span>
</div>

<div class="form-group <?php echo (!empty($genre_err)) ? 'has-error' : ''; ?
>">
  <label>Género</label>
  <input type="text" name="genres"  class="form-control" placeholder=""
 value="<?php echo $genre; ?>">
  <span class="help-block"><?php echo $genre_err; ?></span>
</div>
<div class="form-group">
<input type="file" name="uploadimage">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">

 </div>
 </form>

</div>
</code>```

答:
```<code>move_uploaded_file($_FILES["image"]["tmp_name"],
    "uploads/" . $_FILES["image"]["name"]);
$location1 = $_FILES["image"]["name"];
</code>```

Body:
So i've been trying to make a form with an IMG uploader.
The db is working and i can send the information to the database.
When I tried to implement the image uploader it gives me this print:
So in the form I only added the buttom to upload image, added name and on the post method i tried to upload the image before adding the data.

I did a print, and this is what it came out:
Field 'imgdire' doesn't have a default value

Can someone tell me what's wrong?

PHP

 **if($_SERVER["REQUEST_METHOD"] == "POST"){
  // Validate album

   $UploadedFileName=$_FILES['uploadimage']['name'];
   if($UploadedFileName!='')
   {
   $upload_directory = "uploads/";
   $TargetPath=time().$UploadedFileName;
    if(move_uploaded_file($_FILES['files']['tmp_name'],
  $upload_directory.$TargetPath)){
     $QueryInsertFile="INSERT INTO album SET imgdire='$TargetPath'";

   }
}

Send Information to database

// Check input errors before inserting in database
if(empty($artist_err) && empty($album_err) && empty($stock_err) &&
 empty($price_err) && empty($genre_err)){

    // Prepare an insert statement
    $sql = "INSERT INTO album (nomealbum, stock, price, genero, nomeinter) VALUES (?, ?, ?, ?, ?)";

    if($stmt = mysqli_prepare($link, $sql)){
        // Bind variables to the prepared statement as parameters
        mysqli_stmt_bind_param($stmt, "sssss", $param_album, $param_stock, $param_price, $param_genre, $param_artist);

        // Set parameters
        $param_album = $album;
        $param_stock = $stock;
        $param_price = $price;
        $param_genre = $genre;
        $param_artist = $artist;

        // Attempt to execute the prepared statement
        if(mysqli_stmt_execute($stmt)){

            // Redirect to admin page
            header("location: admin.php");
        } else{
           print mysqli_error($link);
            echo "Algo não correu bem, por favor tente mais uma vez";
        }
    }

    // Close statement
    mysqli_stmt_close($stmt);
}

// Close connection
mysqli_close($link);
}

FORM

  <form method="POST" action="admin.php" enctype="multipart/form-data">

  <div class="form-group <?php echo (!empty($artist_err)) ? 'has-error' :
  ''; ?>">
  Intérprete
  <input  type="text" name="inter" class="form-control" placeholder="Nome do
  Artista" value="<?php echo $artist; ?>">
  <?php echo $artist_err; ?>

 <div class="form-group <?php echo (!empty($album_err)) ? 'has-error' : '';
  ?
 >">
  Nome do Albúm:
  <input  type="text" name="aname" class="form-control" placeholder="Album"
  value="<?php echo $album; ?>">
  <?php echo $album_err; ?>

    <div class="form-group <?php echo (!empty($stock_err)) ? 'has-error' :
    ''; ?>">
  Stock
  <input  type="text" name="stocks" class="form-control"  placeholder=""
  value="<?php echo $stock; ?>">
  <?php echo $stock_err; ?>

<div class="form-group <?php echo (!empty($price_err)) ? 'has-error' : ''; ?
>">
  Preço
  <input  type="text"  name="prices" class="form-control"  placeholder=""
value="<?php echo $price; ?>">
  <?php echo $price_err; ?>

<div class="form-group <?php echo (!empty($genre_err)) ? 'has-error' : ''; ?
>">
  Género
  <input type="text" name="genres"  class="form-control" placeholder=""
 value="<?php echo $genre; ?>">
  <?php echo $genre_err; ?>

<input type="file" name="uploadimage">

<input type="submit" class="btn btn-primary" value="Submit">

 </form>


问:
How to initialize an array in private class without using a constant array size?
I have a header and .cpp file. I am having difficulty initializing the array. The problem is that I can't specify the array size. The size depends on the number of elements the user inputs. When I make a new dynamicArray, I believe I have to use the "new" like dynamicArray = new string[sizeof(array)] (because I have to delete the memory later according to the assignment) but when I run it through Linux, it says that it cannot appear in a constant - expression.

I'm still a little unfamiliar with C++. Any feedback is appreciated.

What the error looks like:

I also had issues with the header redefinition and I think the #pragma once helped.
I know #include "stdafx.h" is bad for linux. I remove it every time I run it on linux.

DynamaicStringArray.cpp

```<code>// DynamicStringArray.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "DynamicStringArray.h"
#include "Assignment9Test_V1.cpp"

// copy constructor that copies the array
DynamicStringArray::DynamicStringArray(string array[]) {
    // string *dynamicArray = new string[sizeof(array)]; // without pointer, error with conversion between types
    dynamicArray = new string[sizeof(array)];

    for (int i = 0; i < sizeof(array); i++) {
        dynamicArray[i] = array[i];
    }
}

// default constructor
DynamicStringArray::DynamicStringArray() {
    size = 0;

    dynamicArray = NULL;
    // dynamicArray = new string[size];
}

// frees up dynamic array memory
void DynamicStringArray::destructor(string array[]) {
    delete[] array;
    array = NULL;
}

// return number of entries in array
int DynamicStringArray::getSize() {
    return size;
}

// creates a new dynamic array one element larger than dynamicArray
// copies all elements of dynamicArray to new array and
// add new string to end of new array
// increment size
// delete old dynamicArray
// set new array as dynamicArray
void DynamicStringArray::addEntry(string newString) {
    string *newArray;
    newArray = new string[size + 1];

    for (int i = 0; i < size; i++) {
        newArray[i] == dynamicArray[i];
    }

    int endIndex = sizeof(newArray);
    newArray[endIndex] = newString;

    destructor(dynamicArray);
    dynamicArray = newArray;
}

// searches for dynamicArray for specific string,
// if string not found, return false
// if string is found, create new one size smaller dynamic array
// than dynamicArray
// copy elements of old dynamicArray to new array without the string
// delete old dynamicArray
// decrement size
// return true
bool DynamicStringArray::deleteEntry(string deleteMe) {
    string *newArray;
    newArray = new string[size - 1];

    bool isFound = false;

    for (int i = 0; i < size; i++) {
        if (dynamicArray[i] == deleteMe) {
            i++;
            isFound = true;
        }
        else if (dynamicArray[i] != deleteMe) {
            newArray[i] == dynamicArray[i];
        }
    }

    if (isFound) {
        return true;
        destructor(dynamicArray);

        dynamicArray = newArray;
    }
    else if (!isFound) {
        return false;
    }
}

// returns the string at that index
string DynamicStringArray::getEntry(int findMe) {
    return dynamicArray[findMe];
}
</code>```

DynamicStringArray.h

```<code>#pragma once
#include <string>
#include <iostream>

using namespace std;

class DynamicStringArray {
public:
    DynamicStringArray();

    DynamicStringArray(string array[]);

    // overloading the assignment operator

    void destructor(string array[]);
    int getSize();
    void addEntry(string);
    bool deleteEntry(string);
    string getEntry(int);

private:
    int size; // holds number of entries in the array
    string *dynamicArray; // references a dynamic array of type string
};
</code>```

答:
Your instinct to use new (specifically, new[] and delete[]) to solve this issue is correct.  You must dynamically allocate the array at runtime since you don't know the number of elements at compile-time.  However, you are not using new[]/delete[] correctly, which is why you are getting errors (amongst many other problems with your code).

Try something more like this instead:

DynamicStringArray.h

```<code>#pragma once
#include <string>

class DynamicStringArray {
public:
    DynamicStringArray();
    DynamicStringArray(const std::string *array, int arraySize);
    DynamicStringArray(const DynamicStringArray &array);
    ~DynamicStringArray();

    DynamicStringArray& operator=(const DynamicStringArray &array);

    int getSize() const;
    void addEntry(const std::string &newString);
    bool deleteEntry(const std::string &deleteMe);
    std::string getEntry(int findMe) const;

private:
    int size; // holds number of entries in the array
    string *dynamicArray; // references a dynamic array of type string
};
</code>```

DynamicStringArray.cpp

```<code>// DynamicStringArray.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "DynamicStringArray.h"

// default constructor
DynamicStringArray::DynamicStringArray() {
    size = 0;
    dynamicArray = NULL;
}

// constructor that copies an array
DynamicStringArray::DynamicStringArray(const std::string *array, int arraySize) {
    size = arraySize;
    dynamicArray = new std::string[size];

    for (int i = 0; i < size; i++) {
        dynamicArray[i] = array[i];
    }
}

// copy constructor that copies the array
DynamicStringArray::DynamicStringArray(const DynamicStringArray &array) {
    size = array.size;
    dynamicArray = new std::string[size];

    for (int i = 0; i < size; i++) {
        dynamicArray[i] = array.dynamicArray[i];
    }
}

// frees up dynamic array memory
DynamicStringArray::~DynamicStringArray() {
    delete[] array;
}

// copy assignment operator that copies the array
DynamicStringArray& DynamicStringArray::operator=(const DynamicStringArray &array) {
    if (&array != this) {
        DynamicStringArray copied(array);
        std::string *temp = copied.dynamicArray;
        copied.dynamicArray = dynamicArray;
        dynamicArray = temp;
        size = array.size;
    }
    return *this;
}

// return number of entries in array
int DynamicStringArray::getSize() const {
    return size;
}

// creates a new dynamic array one element larger than dynamicArray
// copies all elements of dynamicArray to new array and
// add new string to end of new array
// increment size
// delete old dynamicArray
// set new array as dynamicArray
void DynamicStringArray::addEntry(const std::string &newString) {
    std::string *newArray = new std::string[size + 1];
    for (int i = 0; i < size; i++) {
        newArray[i] = dynamicArray[i];
    }
    newArray[size] = newString;
    delete[] dynamicArray;
    dynamicArray = newArray;
    ++size;
}

// searches the dynamic array for a specific string,
// if string not found, return false
// if string is found, create new array one size smaller than dynamicArray
// copy elements of old dynamicArray to new array without the string
// delete old dynamicArray and replace with new array
// decrement size
// return true
bool DynamicStringArray::deleteEntry(const string &deleteMe) {
    for (int i = 0; i < size; i++) {
        if (dynamicArray[i] == deleteMe) {
            std::string *newArray = new std::string[size - 1];
            for (int j = 0; j < i; ++j) {
                newArray[j] = dynamicArray[j];
            }
            for (int j = i+1; j < size; ++j) {
                newArray[j-1] = dynamicArray[j];
            }
            delete[] dynamicArray;
            dynamicArray = newArray;
            --size;
            return true;
        }
    }
    return false;
}

// returns the string at that index
std::string DynamicStringArray::getEntry(int findMe) const {
    return dynamicArray[findMe];
}
</code>```

That being said, using a std::vector is the preferred solution.  It is a dynamic-sized array that wraps new[]/delete[] for you.  It is simpler and safer to use than using new[]/delete[] directly, eg:

DynamicStringArray.h

```<code>#pragma once
#include <string>
#include <vector>

class DynamicStringArray {
public:
    DynamicStringArray();
    DynamicStringArray(const std::string *array, int arraySize);

    int getSize() const;
    void addEntry(const std::string &newString);
    bool deleteEntry(const std::string &deleteMe);
    std::string getEntry(int findMe) const;

private:
    std::vector<std::string> dynamicArray; // dynamic array of type string
};
</code>```

DynamicStringArray.cpp

```<code>// DynamicStringArray.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "DynamicStringArray.h"
#include <algorithm>

// default constructor
DynamicStringArray::DynamicStringArray() {
}

// copy constructor that copies the array
DynamicStringArray::DynamicStringArray(const std::string *array, int arraySize) :
    dynamicArray(array, array + arraySize) {
}

// return number of entries in array
int DynamicStringArray::getSize() const {
    return dynamicArray.size();
}

// appends a new element to the end of the dynamic array
void DynamicStringArray::addEntry(const std::string &newString) {
    dynamicArray.push_back(newString);
}

// searches the dynamic array for a specific string,
// if string not found, return false
// if string is found, remove it and return true
bool DynamicStringArray::deleteEntry(const std::string &deleteMe) {
    std::vector<std::string>::iterator iter = std::find(dynamicArray.begin(), dynamicArray.end(), deleteMe);
    if (iter != dynamicArray.end())
    {
        dynamicArray.erase(iter);
        return true;
    }
    return false;
}

// returns the string at that index
std::string DynamicStringArray::getEntry(int findMe) const {
    return dynamicArray[findMe];
}
</code>```

Body:
I have a header and .cpp file. I am having difficulty initializing the array. The problem is that I can't specify the array size. The size depends on the number of elements the user inputs. When I make a new dynamicArray, I believe I have to use the "new" like dynamicArray = new string[sizeof(array)] (because I have to delete the memory later according to the assignment) but when I run it through Linux, it says that it cannot appear in a constant - expression.

I'm still a little unfamiliar with C++. Any feedback is appreciated.

What the error looks like:

I also had issues with the header redefinition and I think the #pragma once helped.
I know #include "stdafx.h" is bad for linux. I remove it every time I run it on linux.

DynamaicStringArray.cpp

// DynamicStringArray.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "DynamicStringArray.h"
#include "Assignment9Test_V1.cpp"

// copy constructor that copies the array
DynamicStringArray::DynamicStringArray(string array[]) {
    // string *dynamicArray = new string[sizeof(array)]; // without pointer, error with conversion between types
    dynamicArray = new string[sizeof(array)];

    for (int i = 0; i < sizeof(array); i++) {
        dynamicArray[i] = array[i];
    }
}

// default constructor
DynamicStringArray::DynamicStringArray() {
    size = 0;

    dynamicArray = NULL;
    // dynamicArray = new string[size];
}

// frees up dynamic array memory
void DynamicStringArray::destructor(string array[]) {
    delete[] array;
    array = NULL;
}

// return number of entries in array
int DynamicStringArray::getSize() {
    return size;
}

// creates a new dynamic array one element larger than dynamicArray
// copies all elements of dynamicArray to new array and
// add new string to end of new array
// increment size
// delete old dynamicArray
// set new array as dynamicArray
void DynamicStringArray::addEntry(string newString) {
    string *newArray;
    newArray = new string[size + 1];

    for (int i = 0; i < size; i++) {
        newArray[i] == dynamicArray[i];
    }

    int endIndex = sizeof(newArray);
    newArray[endIndex] = newString;

    destructor(dynamicArray);
    dynamicArray = newArray;
}

// searches for dynamicArray for specific string,
// if string not found, return false
// if string is found, create new one size smaller dynamic array
// than dynamicArray
// copy elements of old dynamicArray to new array without the string
// delete old dynamicArray
// decrement size
// return true
bool DynamicStringArray::deleteEntry(string deleteMe) {
    string *newArray;
    newArray = new string[size - 1];

    bool isFound = false;

    for (int i = 0; i < size; i++) {
        if (dynamicArray[i] == deleteMe) {
            i++;
            isFound = true;
        }
        else if (dynamicArray[i] != deleteMe) {
            newArray[i] == dynamicArray[i];
        }
    }

    if (isFound) {
        return true;
        destructor(dynamicArray);

        dynamicArray = newArray;
    }
    else if (!isFound) {
        return false;
    }
}

// returns the string at that index
string DynamicStringArray::getEntry(int findMe) {
    return dynamicArray[findMe];
}

DynamicStringArray.h

#pragma once
#include <string>
#include <iostream>

using namespace std;

class DynamicStringArray {
public:
    DynamicStringArray();

    DynamicStringArray(string array[]);

    // overloading the assignment operator

    void destructor(string array[]);
    int getSize();
    void addEntry(string);
    bool deleteEntry(string);
    string getEntry(int);

private:
    int size; // holds number of entries in the array
    string *dynamicArray; // references a dynamic array of type string
};

Body:
Your instinct to use new (specifically, new[] and delete[]) to solve this issue is correct.  You must dynamically allocate the array at runtime since you don't know the number of elements at compile-time.  However, you are not using new[]/delete[] correctly, which is why you are getting errors (amongst many other problems with your code).

Try something more like this instead:

DynamicStringArray.h

#pragma once
#include <string>

class DynamicStringArray {
public:
    DynamicStringArray();
    DynamicStringArray(const std::string *array, int arraySize);
    DynamicStringArray(const DynamicStringArray &array);
    ~DynamicStringArray();

    DynamicStringArray& operator=(const DynamicStringArray &array);

    int getSize() const;
    void addEntry(const std::string &newString);
    bool deleteEntry(const std::string &deleteMe);
    std::string getEntry(int findMe) const;

private:
    int size; // holds number of entries in the array
    string *dynamicArray; // references a dynamic array of type string
};

DynamicStringArray.cpp

// DynamicStringArray.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "DynamicStringArray.h"

// default constructor
DynamicStringArray::DynamicStringArray() {
    size = 0;
    dynamicArray = NULL;
}

// constructor that copies an array
DynamicStringArray::DynamicStringArray(const std::string *array, int arraySize) {
    size = arraySize;
    dynamicArray = new std::string[size];

    for (int i = 0; i < size; i++) {
        dynamicArray[i] = array[i];
    }
}

// copy constructor that copies the array
DynamicStringArray::DynamicStringArray(const DynamicStringArray &array) {
    size = array.size;
    dynamicArray = new std::string[size];

    for (int i = 0; i < size; i++) {
        dynamicArray[i] = array.dynamicArray[i];
    }
}

// frees up dynamic array memory
DynamicStringArray::~DynamicStringArray() {
    delete[] array;
}

// copy assignment operator that copies the array
DynamicStringArray& DynamicStringArray::operator=(const DynamicStringArray &array) {
    if (&array != this) {
        DynamicStringArray copied(array);
        std::string *temp = copied.dynamicArray;
        copied.dynamicArray = dynamicArray;
        dynamicArray = temp;
        size = array.size;
    }
    return *this;
}

// return number of entries in array
int DynamicStringArray::getSize() const {
    return size;
}

// creates a new dynamic array one element larger than dynamicArray
// copies all elements of dynamicArray to new array and
// add new string to end of new array
// increment size
// delete old dynamicArray
// set new array as dynamicArray
void DynamicStringArray::addEntry(const std::string &newString) {
    std::string *newArray = new std::string[size + 1];
    for (int i = 0; i < size; i++) {
        newArray[i] = dynamicArray[i];
    }
    newArray[size] = newString;
    delete[] dynamicArray;
    dynamicArray = newArray;
    ++size;
}

// searches the dynamic array for a specific string,
// if string not found, return false
// if string is found, create new array one size smaller than dynamicArray
// copy elements of old dynamicArray to new array without the string
// delete old dynamicArray and replace with new array
// decrement size
// return true
bool DynamicStringArray::deleteEntry(const string &deleteMe) {
    for (int i = 0; i < size; i++) {
        if (dynamicArray[i] == deleteMe) {
            std::string *newArray = new std::string[size - 1];
            for (int j = 0; j < i; ++j) {
                newArray[j] = dynamicArray[j];
            }
            for (int j = i+1; j < size; ++j) {
                newArray[j-1] = dynamicArray[j];
            }
            delete[] dynamicArray;
            dynamicArray = newArray;
            --size;
            return true;
        }
    }
    return false;
}

// returns the string at that index
std::string DynamicStringArray::getEntry(int findMe) const {
    return dynamicArray[findMe];
}

That being said, using a std::vector is the preferred solution.  It is a dynamic-sized array that wraps new[]/delete[] for you.  It is simpler and safer to use than using new[]/delete[] directly, eg:

DynamicStringArray.h

#pragma once
#include <string>
#include <vector>

class DynamicStringArray {
public:
    DynamicStringArray();
    DynamicStringArray(const std::string *array, int arraySize);

    int getSize() const;
    void addEntry(const std::string &newString);
    bool deleteEntry(const std::string &deleteMe);
    std::string getEntry(int findMe) const;

private:
    std::vector<std::string> dynamicArray; // dynamic array of type string
};

DynamicStringArray.cpp

// DynamicStringArray.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "DynamicStringArray.h"
#include <algorithm>

// default constructor
DynamicStringArray::DynamicStringArray() {
}

// copy constructor that copies the array
DynamicStringArray::DynamicStringArray(const std::string *array, int arraySize) :
    dynamicArray(array, array + arraySize) {
}

// return number of entries in array
int DynamicStringArray::getSize() const {
    return dynamicArray.size();
}

// appends a new element to the end of the dynamic array
void DynamicStringArray::addEntry(const std::string &newString) {
    dynamicArray.push_back(newString);
}

// searches the dynamic array for a specific string,
// if string not found, return false
// if string is found, remove it and return true
bool DynamicStringArray::deleteEntry(const std::string &deleteMe) {
    std::vector<std::string>::iterator iter = std::find(dynamicArray.begin(), dynamicArray.end(), deleteMe);
    if (iter != dynamicArray.end())
    {
        dynamicArray.erase(iter);
        return true;
    }
    return false;
}

// returns the string at that index
std::string DynamicStringArray::getEntry(int findMe) const {
    return dynamicArray[findMe];
}


问:
Google Datastore multiple parents?
Can an entity have multiple parents that don't go in a single line like son->father->grandfather?

Examples:

Family tree: Mom & Dad are both parents of all their children.

答:
No, an entity can only have a single parent. From Ancestor paths:

Entities in Cloud Datastore form a hierarchically structured space
  similar to the directory structure of a file system. When you create
  an entity, you can optionally designate another entity as its
  parent; the new entity is a child of the parent entity (note that unlike in a file system, the parent entity need not actually exist).
  An entity without a parent is a root entity. The association between
  an entity and its parent is permanent, and cannot be changed once the
  entity is created. Cloud Datastore will never assign the same numeric
  ID to two entities with the same parent, or to two root entities
  (those without a parent).

An entity's parent, parent's parent, and so on recursively, are its
  ancestors; its children, children's children, and so on, are its descendants. The sequence of entities beginning with a root entity and proceeding from parent to child, leading to a given entity,
  constitute that entity's ancestor path. The complete key identifying
  the entity consists of a sequence of kind-identifier pairs specifying
  its ancestor path and terminating with those of the entity itself:

```<code>[User:alice, TaskList:default, Task:sampleTask]
</code>```

For a root entity, the ancestor path is empty and the key consists
  solely of the entity's own kind and identifier:

```<code>[User:alice]
</code>```

Following the directory structure comparison: a file can only exist in one directory, not in two or more.

Title: Google Datastore multiple parents?

Body:
No, an entity can only have a single parent. From Ancestor paths:

Entities in Cloud Datastore form a hierarchically structured space
  similar to the directory structure of a file system. When you create
  an entity, you can optionally designate another entity as its
  parent; the new entity is a child of the parent entity (note that unlike in a file system, the parent entity need not actually exist).
  An entity without a parent is a root entity. The association between
  an entity and its parent is permanent, and cannot be changed once the
  entity is created. Cloud Datastore will never assign the same numeric
  ID to two entities with the same parent, or to two root entities
  (those without a parent).

An entity's parent, parent's parent, and so on recursively, are its
  ancestors; its children, children's children, and so on, are its descendants. The sequence of entities beginning with a root entity and proceeding from parent to child, leading to a given entity,
  constitute that entity's ancestor path. The complete key identifying
  the entity consists of a sequence of kind-identifier pairs specifying
  its ancestor path and terminating with those of the entity itself:

[User:alice, TaskList:default, Task:sampleTask]

For a root entity, the ancestor path is empty and the key consists
  solely of the entity's own kind and identifier:

[User:alice]

Following the directory structure comparison: a file can only exist in one directory, not in two or more.


问:
How to add vmware tag to a virtual machine if it has spaces in the tag name
I am trying to create a script that adds "Tags" to my virtual machine.  I am using Powershell/PowerCLI to do this.  I am able to add the names if there are no spaces in the tag name. For example, Application tag is name "Test" and it adds it to the server fine.  But if the owner name is "John Doe" it will not take because of the space.  Here is myscript thus far:</p>

```<code>$vCenter = "test.com"
$ServerName = "test1"

Add-PSSnapin VMware.VimAutomation.Core
Connect-ViServer -server $vCenter -ErrorAction Stop

$AppTag = Read-Host "What is the Application tag name for $ServerName"
$myTag1 = Get-Tag $AppTag
$myVM = Get-VM "$ServerName"
New-TagAssignment -Tag $myTag1 -Entity $myVM

$AppOwnerTag = Read-Host "What is the Application Owner tag name for $ServerName"
$myTag2 = Get-Tag $AppOwnerTag
$myVM = Get-VM $ServerName
New-TagAssignment -Tag $myTag2 -Entity $myVM

$CreatedByTag = Read-Host "What is the Created By tag name for $ServerName"
$myTag3 = Get-Tag $CreatedByTag
$myVM = Get-VM $ServerName
New-TagAssignment -Tag $myTag3 -Entity $myVM
</code>```

答:
Yes, you may use spaces in your tag names.  The problem you are running into may be due to the version of PowerShell, or an issue if you have multiple tags with the same name or the same tag across vCenters:

First confirm your PowerShell VMware PowerCLI version is at least 6.5.3 with the command Get-PowerCLIVersion, or if you like to be fancy Get-Module -Name VMware.* | Select Name,Version.  According to VMware PowerCLI Blog for version 6.5.3, New-TagAssignment has a related issue and has been fixed.  If you are unsure how to upgrade or install VMware PowerCLI, you can Import-Module VMware.PowerCLI as Administrator as described in this other VMware PowerCLI Installation Blog if you have the PackageManager installed as described in this 4sysops article.

Another thing is to confirm that the correct and only one vCenter is active if your query.  For example, you may need to modify your command to New-TagAssignment -Tag $myTag3 -Entity $myVM  -Server $vCenter.  The $vCenter is the same name you use when you Connect-VIServer $vCenter, which in your case I assume is "test.com".  If you logged into, and not out of, other vCenters before performing this query, this may be your fix. For example, I do not see Disconnect-VIServer $vCenter at the bottom of your script which is why I suggest this.

The last thing to try is you may have the same tag name in multiple tag categories.  The recommendation in VMware Communities is to get the tag explicitly by specifying the category in the command, such as $myTag1 = Get-Tag $AppTag -Category $myCategory.  Another less desirable option may be to rename your tags in those categories so they do not overlap.

Body:
I am trying to create a script that adds "Tags" to my virtual machine.  I am using Powershell/PowerCLI to do this.  I am able to add the names if there are no spaces in the tag name. For example, Application tag is name "Test" and it adds it to the server fine.  But if the owner name is "John Doe" it will not take because of the space.  Here is myscript thus far:

$vCenter = "test.com"
$ServerName = "test1"

Add-PSSnapin VMware.VimAutomation.Core
Connect-ViServer -server $vCenter -ErrorAction Stop

$AppTag = Read-Host "What is the Application tag name for $ServerName"
$myTag1 = Get-Tag $AppTag
$myVM = Get-VM "$ServerName"
New-TagAssignment -Tag $myTag1 -Entity $myVM

$AppOwnerTag = Read-Host "What is the Application Owner tag name for $ServerName"
$myTag2 = Get-Tag $AppOwnerTag
$myVM = Get-VM $ServerName
New-TagAssignment -Tag $myTag2 -Entity $myVM

$CreatedByTag = Read-Host "What is the Created By tag name for $ServerName"
$myTag3 = Get-Tag $CreatedByTag
$myVM = Get-VM $ServerName
New-TagAssignment -Tag $myTag3 -Entity $myVM


问:
reg expression replace not replacing space-dash-space
I am trying to strip out any non-alphanumeric characters and also replace any whitespace with an underscore.

myString = myString.replace(/[^a-zA-Z 0-9]+/g, '').replace(" ", "_");

This almost it, but it still fails in one case:

```<code>12th Madison - 100
</code>```

Becomes

```<code>12th_Madison  100
</code>```

What I would like is this:

```<code>12th_Madison_100
</code>```

答:
I would suggest:

```<code>result = subject.replace(/[^\w]+/g, "_");
</code>```

[^\w] ...  Match a single character that is not a word character (ASCII letter, digit, or underscore only)

Body:
I am trying to strip out any non-alphanumeric characters and also replace any whitespace with an underscore.

myString = myString.replace(/[^a-zA-Z 0-9]+/g, '').replace(" ", "_");

This almost it, but it still fails in one case:

12th Madison - 100

Becomes

12th_Madison  100

What I would like is this:

12th_Madison_100

Body:
I would suggest:

result = subject.replace(/[^\w]+/g, "_");

[^\w] ...  Match a single character that is not a word character (ASCII letter, digit, or underscore only)


问:
Java StringTemplate Using File From Outside Directory
I have a directory structure like this:

```<code>Templates/
├── Foo/
│   ├── Foo.st
├── Signature.st
</code>```

Here's what the Foo.st looks like:

```<code><?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
</head>
<body>
    <div id="body">
        <p> Some Text </p>
    </div>
    $Signature()$
</body>
</html>
</code>```

Here's my Java code with StringTemplate:

```<code>STRawGroupDir dir = new STRawGroupDir("Templates", '$', '$');
ST st = dir.getInstanceOf("Foo/Foo");
System.out.println(st.render());
</code>```

But the output is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
</head>
<body>
    <div id="body">
        <p> Some Text </p>
    </div>
</body>
</html>
</code>```

How do I get the Foo template to be able to properly reference the signature template?

If I put Signature.st inside the Foo directory then the above code works just fine, but I can't do that as I'll have many templates that will reference the Signature template.

答:
I figured out a really easy way to do this. I have now the following directory structure:

```<code>Templates/
├── Foo/
│   ├── Foo.st
├── Main.st
├── Signature.st
</code>```

Here's my Main.st

```<code>$ templates : { template |
$(template)()$
}$

$Signature()$
</code>```

And here's my java code:

```<code>STRawGroupDir dir = new STRawGroupDir("Templates", '$', '$');
ST st = dir.getInstanceOf("Main");
st.add("templates", Arrays.asList("/Foo/Foo.st"));
st.render();
</code>```

Now I can pass in any number of templates and this works perfectly.

Body:
I have a directory structure like this:

Templates/
├── Foo/
│   ├── Foo.st
├── Signature.st

Here's what the Foo.st looks like:

<?xml version="1.0" encoding="UTF-8"?>

 Some Text

    $Signature()$

Here's my Java code with StringTemplate:

STRawGroupDir dir = new STRawGroupDir("Templates", '$', '$');
ST st = dir.getInstanceOf("Foo/Foo");
System.out.println(st.render());

But the output is:

<?xml version="1.0" encoding="UTF-8"?>

 Some Text

How do I get the Foo template to be able to properly reference the signature template?

If I put Signature.st inside the Foo directory then the above code works just fine, but I can't do that as I'll have many templates that will reference the Signature template.

Body:
I figured out a really easy way to do this. I have now the following directory structure:

Templates/
├── Foo/
│   ├── Foo.st
├── Main.st
├── Signature.st

Here's my Main.st

$ templates : { template |
$(template)()$
}$

$Signature()$

And here's my java code:

STRawGroupDir dir = new STRawGroupDir("Templates", '$', '$');
ST st = dir.getInstanceOf("Main");
st.add("templates", Arrays.asList("/Foo/Foo.st"));
st.render();

Now I can pass in any number of templates and this works perfectly.


问:
Card not pushing onto to the Navigation stack, why not? Is there a limit?
There is one root card and one other card on the stack.  I'm doing data validation.  If there is no file value selected in the drop-down box, this is the error handler to create a new error card.  The originating function throws an error and the catch calls my error handler.  When the error is triggered, it does nothing, but log the error message.  It seems to create the new card in the execution transcript, the header, and section, however, it doesn't show.  I don't see an error in the execution transcript.  Everything succeeds, but there is no new card.

```<code>function error(e){
try{
 // create new card, header, and section
 var header = CardService.newCardHeader().setTitle('Error')
  .setImageUrl('http://www.pvhc.net/img55/waclmgwigxuizcqbxjdx.jpg')
  .setImageStyle(CardService.ImageStyle.SQUARE);

 var section = CardService.newCardSection()
  .setHeader('<b>Error Message:</b>')
  .addWidget(CardService.newTextParagraph().setText(e));

 var card = CardService.newCardBuilder()
  .setHeader(header).addSection(section).build();

 // Create Nav object
 var nav = CardService.newNavigation().pushCard(card);

 // Check if my function is being called and the error message is correct.
 Logger.log(e);

 // push card onto stack.
 return CardService.newActionResponseBuilder().setNavigation(nav);
}catch(e){Logger.log(e.message);}
}
</code>```

Update: In my catch statement, I didn't have a return statement before calling the error function.  Now I'm getting a run time error: 'Missing required fields in markup: '.  Not sure why.

答:
Don't forget to build the Card!. You have to build the card.</p>

```<code>return CardService.newActionResponseBuilder().setNavigation(nav).build();
</code>```

Body:
There is one root card and one other card on the stack.  I'm doing data validation.  If there is no file value selected in the drop-down box, this is the error handler to create a new error card.  The originating function throws an error and the catch calls my error handler.  When the error is triggered, it does nothing, but log the error message.  It seems to create the new card in the execution transcript, the header, and section, however, it doesn't show.  I don't see an error in the execution transcript.  Everything succeeds, but there is no new card.

function error(e){
try{
 // create new card, header, and section
 var header = CardService.newCardHeader().setTitle('Error')
  .setImageUrl('http://www.pvhc.net/img55/waclmgwigxuizcqbxjdx.jpg')
  .setImageStyle(CardService.ImageStyle.SQUARE);

 var section = CardService.newCardSection()
  .setHeader('Error Message:')
  .addWidget(CardService.newTextParagraph().setText(e));

 var card = CardService.newCardBuilder()
  .setHeader(header).addSection(section).build();

 // Create Nav object
 var nav = CardService.newNavigation().pushCard(card);

 // Check if my function is being called and the error message is correct.
 Logger.log(e);

 // push card onto stack.
 return CardService.newActionResponseBuilder().setNavigation(nav);
}catch(e){Logger.log(e.message);}
}

Update: In my catch statement, I didn't have a return statement before calling the error function.  Now I'm getting a run time error: 'Missing required fields in markup: '.  Not sure why.

Body:
Don't forget to build the Card!. You have to build the card.

return CardService.newActionResponseBuilder().setNavigation(nav).build();


问:
Python Dataframe: Fill in Row as 1 or 0 Based on If Column Name is Contained in String Row of Another Column in Dataframe
Let's say hypothetically I have a dataframe with one column called "Col_Strings".  This column has 30k rows.  I am only showing the first three rows in my table

Next I am going to add a bunch of additional columns to my dataframe.

I want to use logic that says: If my column name is contained in the row of "Col_Strings" then I want the value to say 1 ... otherwise 0.

Below is a sample table (first row is the column names):

```<code>Col_Strings       2C    GAD D2  6F  ABCDE
2C 1B D2 6F ABC    1    0   1   1   0
Act Dog House GAD  0    1   0   0   0
D2 6F Ant          0    0   1   1   0
</code>```

Based on someone's else help I can do the following by creating a dataframe from scratch.  But my question is how do I employ the above python logic when I already have a dataframe and need to reference the "Col_Strings" to determine 1 or 0?

答:
map a function on the database column Col_Strings, checking if the word is contained in each element. Assign the results to the column

```<code>df['Act'] = df['Col_Strings'].map(lambda x: int('Act' in x.split())
</code>```

If you have a list of words to create columns for, then execute the above logic in a loop:

```<code>for word in ['Act', 'Now', 'Buy', 'MORE']:
    df[word] = df['Col_Strings'].map(lambda x: int(word in x.split())
</code>```

Body:
Let's say hypothetically I have a dataframe with one column called "Col_Strings".  This column has 30k rows.  I am only showing the first three rows in my table

Next I am going to add a bunch of additional columns to my dataframe.

I want to use logic that says: If my column name is contained in the row of "Col_Strings" then I want the value to say 1 ... otherwise 0.

Below is a sample table (first row is the column names):

Col_Strings       2C    GAD D2  6F  ABCDE
2C 1B D2 6F ABC    1    0   1   1   0
Act Dog House GAD  0    1   0   0   0
D2 6F Ant          0    0   1   1   0

Based on someone's else help I can do the following by creating a dataframe from scratch.  But my question is how do I employ the above python logic when I already have a dataframe and need to reference the "Col_Strings" to determine 1 or 0?

Body:
map a function on the database column Col_Strings, checking if the word is contained in each element. Assign the results to the column

df['Act'] = df['Col_Strings'].map(lambda x: int('Act' in x.split())

If you have a list of words to create columns for, then execute the above logic in a loop:

for word in ['Act', 'Now', 'Buy', 'MORE']:
    df[word] = df['Col_Strings'].map(lambda x: int(word in x.split())


答:
The reason you face this has to do with leading whitespaces

Change your scanf line to this:

```<code>scanf(" %c", &responce);
</code>```

Here's a link for the explanation

How to do scanf for single char in C

Title: scanf prematurely terminating while loop (I think)

Body:
I am making a simple program to calculate the required exam mark based on your current mark, the % total worth of the exam on the course, and your desired mark. I was having no problems with it until I wanted a simple while loop to redo the proses if the user wanted to do so. The problem that arose was that when I have the scanf to get a char response from the user, it terminates the while loop and then the program. When I comment out the scanf line and leave the code as is (an infinite while loop) it works properly looping forever but with it, it will terminate with no errors. Any thoughts?

    #include <stdio.h>

    #define TRUE 1
    #define FALSE 0

    int main()
    {
        int continueProgram = TRUE;
        float currentMark = 0.0, examPercent = 0.0, desiredMark = 0.0, requiredMark = 0.0;
        char response  = 'y';

        while (continueProgram == TRUE)
        {
            printf("What is your current mark in your class: ");
            scanf("%f", &currentMark);
            printf("How much is you exam worth: ");
            scanf("%f", &examPercent);
            examPercent /= 100.0;
            printf("What is your desiered mark: ");
            scanf("%f", &desiredMark);

            // Simple math to get mark
            requiredMark = (desiredMark - currentMark * examPercent) / examPercent;

            if (requiredMark > 100.0)
            {
                printf("\nI'm sorry but you need above 100%% to get to your required mark\nHere is a list of all the marks you can get:\n\n");

                for (requiredMark = 0.0; requiredMark <= 100.0; requiredMark += 5.0)
                {
                    desiredMark = currentMark * examPercent + requiredMark * examPercent;
                    printf("Exam Mark: %.2f, Final Mark: %.2f\n", requiredMark, desiredMark);
                }
            }
            else
            {
                printf("\nThe mark that you need to get on the exam is: %.2f\nHere is a list of all the marks you can get:\n\n", requiredMark);

                for (requiredMark = 0.0; requiredMark <= 100.0; requiredMark += 5.0)
                {
                    desiredMark = currentMark * examPercent + requiredMark * examPercent;
                    printf("Exam Mark: %.2f, Final Mark: %.2f\n", requiredMark, desiredMark);
                }
            }

            printf("\nDid you want to continue with a new grade (y or n): ");

            // THIS IS WHERE I AM HAVING THE ISSUE
            scanf("%c", &response );

            if (response  == 'y')
            {
                printf("\n\nResetting  terminal...\n\n");
                currentMark = 0.0;
                examPercent = 0.0;
                desiredMark = 0.0;
                requiredMark = 0.0;
            }
            else
                continueProgram = FALSE;
        }
    }

Body:
The reason you face this has to do with leading whitespaces

Change your scanf line to this:

scanf(" %c", &responce);

Here's a link for the explanation

How to do scanf for single char in C


问:
Valgrind not showing line numbers when compiled with cmake
I am compiling my project with the command cmake .. -G "CodeBlocks - Ninja, which works fine, but when I run valgrind it does not display any lines numbers.
This is the valgrind command I am using: valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes  --log-file="log.txt" ./pony_gpExe.

Here is an example of the output:

```<code>==5402== Use of uninitialised value of size 8
==5402==    at 0x40447B: get_double_arr_length (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x405184: get_test_and_train_data (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x4027B3: setup (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x402861: main (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==  Uninitialised value was created by a stack allocation
==5402==    at 0x405149: get_test_and_train_data (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
</code>```

Not sure if this is helpful but here is my main CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.4.3)
project (pony_gp)
set(DIR ${pony_gp_SOURCE_DIR})

file(GLOB_RECURSE pony_gp_SOURCES "${DIR}/src/*.c")
file(GLOB_RECURSE pony_gp_HEADERS "${DIR}/include/*.h")

foreach (_headerFile ${pony_gp_HEADERS})
    get_filename_component(_dir ${_headerFile} PATH)
    list (APPEND pony_gp_INCLUDE_DIRS ${_dir})
endforeach()
list(REMOVE_DUPLICATES pony_gp_INCLUDE_DIRS)

include("${DIR}/include/CMakeLists.txt")
include_directories(${pony_gp_INCLUDE_DIRS})
add_executable (pony_gpExe ${pony_gp_SOURCES})

if (CMAKE_COMPILER_IS_GNUCC)

    target_link_libraries(pony_gpExe m)

    find_program(MEMORYCHECK_COMMAND valgrind)
    set(MEMORYCHECK_COMMAND_OPTIONS "--trace-children=yes --leak-check=full")
    set(MEMORYCHECK_SUPPRESSIONS_FILE "${DIR}/valgrind_suppress.txt")
endif()

include(CTest)
add_test(test pony_gpExe)
</code>```

答:
You need to tell cmake to produce a debug executable. Without seeing your cmake config, it's hard to tell you how to do this, but by default/convention, it should be:

```<code>cmake -DCMAKE_BUILD_TYPE=Debug
</code>```

See this answer on Debug vs Release in CMAKE for additional infomation.

ContentLicense: CC BY-SA 4.0

Body:
I am compiling my project with the command cmake .. -G "CodeBlocks - Ninja, which works fine, but when I run valgrind it does not display any lines numbers.
This is the valgrind command I am using: valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes  --log-file="log.txt" ./pony_gpExe.

Here is an example of the output:

==5402== Use of uninitialised value of size 8
==5402==    at 0x40447B: get_double_arr_length (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x405184: get_test_and_train_data (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x4027B3: setup (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==    by 0x402861: main (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)
==5402==  Uninitialised value was created by a stack allocation
==5402==    at 0x405149: get_test_and_train_data (in /home/robbie/Dropbox/MIT/pony_gp_ubuntu/build/pony_gpExe)

Not sure if this is helpful but here is my main CMakeLists.txt:

cmake_minimum_required(VERSION 3.4.3)
project (pony_gp)
set(DIR ${pony_gp_SOURCE_DIR})

file(GLOB_RECURSE pony_gp_SOURCES "${DIR}/src/*.c")
file(GLOB_RECURSE pony_gp_HEADERS "${DIR}/include/*.h")

foreach (_headerFile ${pony_gp_HEADERS})
    get_filename_component(_dir ${_headerFile} PATH)
    list (APPEND pony_gp_INCLUDE_DIRS ${_dir})
endforeach()
list(REMOVE_DUPLICATES pony_gp_INCLUDE_DIRS)

include("${DIR}/include/CMakeLists.txt")
include_directories(${pony_gp_INCLUDE_DIRS})
add_executable (pony_gpExe ${pony_gp_SOURCES})

if (CMAKE_COMPILER_IS_GNUCC)

    target_link_libraries(pony_gpExe m)

    find_program(MEMORYCHECK_COMMAND valgrind)
    set(MEMORYCHECK_COMMAND_OPTIONS "--trace-children=yes --leak-check=full")
    set(MEMORYCHECK_SUPPRESSIONS_FILE "${DIR}/valgrind_suppress.txt")
endif()

include(CTest)
add_test(test pony_gpExe)

Body:
You need to tell cmake to produce a debug executable. Without seeing your cmake config, it's hard to tell you how to do this, but by default/convention, it should be:

cmake -DCMAKE_BUILD_TYPE=Debug

See this answer on Debug vs Release in CMAKE for additional infomation.


问:
Apache Spark on Mesos: Initial job has not accepted any resources
I am running Apache Spark on cluster mode using Apache Mesos. But, when I start Spark-Shell to run a simple test command (sc.parallelize(0 to 10, 8).count) I receive the following warning message:

16/03/10 11:50:55 WARN TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources

If I check on Mesos WebUI I can see that Spark-Shell is listed as a framework and I have listed one slave (my own machine). Any help how to troubleshoot it?

答:
While most of other answers focuses on resource allocation (cores, memory) on spark slaves, I would like to highlight that firewall could cause exactly the same issue, especially when you are running spark on cloud platforms.

If you can find spark slaves in the web UI, you have probably opened the standard ports 8080, 8081, 7077, 4040. Nonetheless, when you actually run a job, it uses SPARK_WORKER_PORT, spark.driver.port and spark.blockManager.port which by default are randomly assigned. If your firewall is blocking these ports, the master could not retrieve any job-specific response from slaves and return the error.

You can run a quick test by opening all the ports and see whether the slave accepts jobs.


问:
Logging and Exception handling in a micro-service in Java
I am working on a microservice which does some calculation based on certain configurations stored in its own data store. The calculations apis are stored via REST APIs. The application is a spring boot application.
Now there are mainly 3 layers in the application :

REST Controller

Service layer

DAO layer - it used spring data.

I am planning to handle the logging and exception handling using below points:

Log each request that the service receives and response or at least
the response if the status is not in 2xx series.

If there are any    checked exception in either DAO layer or Service
layer then log them    and throw a custom exception derived from
RuntimeException.

Have Several custom exception which    should be thrown from Service
layer mainly if we come across    scenarios like invalid values, null
values etc.

Have a try catch    block in the REST Controller and log the
exception i.e. message along    with stacktrace and return the
response accordingly.

So overall idea is to let the RuntimeExceptions propagate all the way to REST Controller where they should be logged and accordingly the response should be sent. Incase of checked exceptions log them in the same method and throw custom exceptions instead.

Please suggest what should be the correct or a good approach for logging exception in such applications.

答:
Write controller advice which will catch all the exceptions & logs the required contents. You may catch exceptions here. I implemented same what you asked here.

```<code>*/
/**
 * Uncaught exception handler
 * @param e - Exception
 */
@ExceptionHandler(Exception.class)
@ResponseStatus(code=HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public void handleError(Exception e,HttpServletRequest request, HttpServletResponse response){
    logger.error("Exception occured : {}",e);
        //logs request & response here
}
</code>```

Also please check AbstractRequestLoggingFilter described here.

For all custom application specific exeptions create your own custom exception type & handle it with the help of @ExceptionHandler as specified in above code block.

Body:
Write controller advice which will catch all the exceptions & logs the required contents. You may catch exceptions here. I implemented same what you asked here.

*/
/**
 * Uncaught exception handler
 * @param e - Exception
 */
@ExceptionHandler(Exception.class)
@ResponseStatus(code=HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public void handleError(Exception e,HttpServletRequest request, HttpServletResponse response){
    logger.error("Exception occured : {}",e);
        //logs request & response here
}

Also please check AbstractRequestLoggingFilter described here.

For all custom application specific exeptions create your own custom exception type & handle it with the help of @ExceptionHandler as specified in above code block.


问:
Implementing this with CSS and HTMl
This is my css -

```<code>#nav {
    position: relative;
    background-color: #292929;
    float: left;
    width:960px;
    margin-left:auto;
    margin-right:auto;

}
#nav li {
    float: left;
    list-style: none;

    width:auto;

}
#nav li a {
    color: #e3e3e3;
    position: relative;
    z-index: 2;
    float: left;

}
ul, li {
  margin:0;
    padding: 0;

}

#blob {

    position: absolute;
    top: 0;
    z-index : 1;
    background: #0b2b61;

    background-repeat:repeat;

}
</code>```

I want to place this object in the center. How do i do that. I also want the background to fit the page. I tried a lot, but it isn't working.

```<code><ul id="nav">
        <li><a href="home.php">Home</a></li>
</ul>
</code>```

答:
Place an object in the center:
CSS:

```<code>.Center1
    {
    position:relative;
    text-align:center;
    }

.Center2
{
position:relative;
margin-left:auto;
margin-right:auto;
width:1024px;
height:800px;
text-align:left;
}
</code>```

Markup:

```<code><body class="body">
<div class="Center1">
    <div class="Center2">
                 <!-- Your content -->
</code>```

ContentLicense: CC BY-SA 2.5

Title: Implementing this with CSS and HTMl

Body:
This is my css -

#nav {
    position: relative;
    background-color: #292929;
    float: left;
    width:960px;
    margin-left:auto;
    margin-right:auto;

}
#nav li {
    float: left;
    list-style: none;

    width:auto;

}
#nav li a {
    color: #e3e3e3;
    position: relative;
    z-index: 2;
    float: left;

}
ul, li {
  margin:0;
    padding: 0;

}

#blob {

    position: absolute;
    top: 0;
    z-index : 1;
    background: #0b2b61;

    background-repeat:repeat;

}

I want to place this object in the center. How do i do that. I also want the background to fit the page. I tried a lot, but it isn't working.

Home

Body:
Place an object in the center:
CSS:

.Center1
    {
    position:relative;
    text-align:center;
    }

.Center2
{
position:relative;
margin-left:auto;
margin-right:auto;
width:1024px;
height:800px;
text-align:left;
}

Markup:

<body class="body">
<div class="Center1">
    <div class="Center2">
                 <!-- Your content -->


问:
Display border line in <ol> without duplicating css

Currently, i am trying to use  to create a grid view. I am able to have my desire output that display border only on the inside of the outer box. But this is achieve using duplicated style rules. So i hope someone could advice me a better way to achieve the same result. Here is the image of the result
Grid selector</p>

<p>       </p>

```<code>    .ui-draggable, .ui-droppable {
        background-position: top;
    }
    .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default, .ui-button, html .ui-button.ui-state-disabled:hover, html .ui-button.ui-state-disabled:active
    {
        border-bottom: 1px solid red;
        border-left: 1px solid red;
        background: #fff;
        font-weight: normal;

    }

    .ui-state-default-left, html .ui-button.ui-state-disabled:active
    {
        border-left: none;
        border-bottom: 1px solid red;
        background: #fff;
        font-weight: normal;
    }

    .ui-state-default-bottom, html .ui-button.ui-state-disabled:active
    {
        border-left: 1px solid red;
        border-bottom: none;
        background: #fff;
        font-weight: normal;
    }

    .ui-state-default-left-bottom, html .ui-button.ui-state-disabled:active
    {
        border-left: none;
        border-bottom: none;
        background: #fff;
        font-weight: normal;
    }

    #selectable .ui-selecting { background: #FECA40; }
    #selectable .ui-selected { background: #F39814; color: white; }
    #selectable { list-style-type: none; margin: 0; padding: 0; width: 20rem; }
    #selectable li { padding: 0.3rem; float: left; width: 2rem; height: 2rem; font-size: 1.5rem; text-align: center; }

    </style>

    <ol id="selectable">
              <li class="ui-state-default-left">01</li>
              <li class="ui-state-default">02</li>
              <li class="ui-state-default">03</li>
              <li class="ui-state-default">04</li>
              <li class="ui-state-default">05</li>
              <li class="ui-state-default">06</li>
              <li class="ui-state-default">07</li>
              <li class="ui-state-default-left">08</li>
              <li class="ui-state-default">09</li>
              <li class="ui-state-default">10</li>
              <li class="ui-state-default">11</li>
              <li class="ui-state-default">12</li>
              <li class="ui-state-default">13</li>
              <li class="ui-state-default">14</li>
              <li class="ui-state-default-left">15</li>
              <li class="ui-state-default">16</li>
              <li class="ui-state-default">17</li>
              <li class="ui-state-default">18</li>
              <li class="ui-state-default">19</li>
              <li class="ui-state-default">20</li>
              <li class="ui-state-default">21</li>
              <li class="ui-state-default-left">22</li>
              <li class="ui-state-default">23</li>
              <li class="ui-state-default">24</li>
              <li class="ui-state-default">25</li>
              <li class="ui-state-default">26</li>
              <li class="ui-state-default">27</li>
              <li class="ui-state-default">28</li>
              <li class="ui-state-default-left">29</li>
              <li class="ui-state-default">30</li>
              <li class="ui-state-default">31</li>
              <li class="ui-state-default">32</li>
              <li class="ui-state-default">33</li>
              <li class="ui-state-default">34</li>
              <li class="ui-state-default">35</li>
              <li class="ui-state-default-left">36</li>
              <li class="ui-state-default">37</li>
              <li class="ui-state-default">38</li>
              <li class="ui-state-default">39</li>
              <li class="ui-state-default">40</li>
              <li class="ui-state-default">41</li>
              <li class="ui-state-default">42</li>
              <li class="ui-state-default-left-bottom">43</li>
              <li class="ui-state-default-bottom">44</li>
              <li class="ui-state-default-bottom">45</li>
              <li class="ui-state-default-bottom">46</li>
              <li class="ui-state-default-bottom">47</li>
              <li class="ui-state-default-bottom">48</li>
              <li class="ui-state-default-bottom">49</li>
    </ol>
</code>```

答:
You can refactor your css in many ways specially when they shares same properties:

1: Use comma

```<code>.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default, html .ui-button.ui-state-disabled:hover, html .ui-button.ui-state-disabled:active,
.ui-state-default-left-bottom, html .ui-button.ui-state-disabled:active,
.ui-state-default-left, html .ui-button.ui-state-disabled:active,
.ui-state-default-bottom, html .ui-button.ui-state-disabled:active {
    background: #fff;
    font-weight: normal;
}
</code>```

2: Use css selector

```<code>div[class^="ui-state"] {
    font-weight: normal;
    background: #fff;
}
</code>```

With this 2 ways you can reduce your total css file size significantly and final result would be the same.
With doing a little more refactoring, you will be able to achieve this:

```<code>.ui-draggable,
.ui-droppable {
    background-position: top;
}
.ui-state-default,
.ui-widget-content .ui-state-default,
.ui-widget-header .ui-state-default,
html .ui-button.ui-state-disabled:hover,
html .ui-button.ui-state-disabled:active,
.ui-state-default-left,
html .ui-button.ui-state-disabled:active,
.ui-state-default-bottom, html .ui-button.ui-state-disabled:active {
    border-bottom: 1px solid red;
    border-left: 1px solid red;

}

.ui-state-default-left,
html .ui-button.ui-state-disabled:active,
.ui-state-default-left-bottom, html .ui-button.ui-state-disabled:active {
    border-left: none;
}

.ui-state-default-bottom, html .ui-button.ui-state-disabled:active,
.ui-state-default-left-bottom, html .ui-button.ui-state-disabled:active {
    border-bottom: none;
}

div[class^="ui-state"] {
    font-weight: normal;
    background: #fff;
}
</code>```

Edit:

For your element you just need this minified version of css

```<code>#selectable {list-style-type: none;margin: 0;padding: 0;width: 20rem;}
#selectable li {padding: 0.3rem;float: left;width: 2rem;height: 2rem;font-size: 1.5rem;text-align: center;font-weight: normal;background: #fff;border-bottom: 1px solid red;border-left: 1px solid red;}
#selectable li.ui-state-default-bottom,
#selectable li.ui-state-default-left-bottom {border-bottom: none;}
#selectable li.ui-state-default-left,
#selectable li.ui-state-default-left-bottom {border-left: none;}
</code>```

BUT if javascript will manipulate the classes you will need to add these classes as well:

```<code>#selectable .ui-selecting { background: #FECA40; }
#selectable .ui-selected { background: #F39814; color: white; }
.ui-draggable, .ui-droppable {background-position: top;}
</code>```

Body:
Currently, i am trying to use  to create a grid view. I am able to have my desire output that display border only on the inside of the outer box. But this is achieve using duplicated style rules. So i hope someone could advice me a better way to achieve the same result. Here is the image of the result
Grid selector

    .ui-draggable, .ui-droppable {
        background-position: top;
    }
    .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default, .ui-button, html .ui-button.ui-state-disabled:hover, html .ui-button.ui-state-disabled:active
    {
        border-bottom: 1px solid red;
        border-left: 1px solid red;
        background: #fff;
        font-weight: normal;

    }

    .ui-state-default-left, html .ui-button.ui-state-disabled:active
    {
        border-left: none;
        border-bottom: 1px solid red;
        background: #fff;
        font-weight: normal;
    }

    .ui-state-default-bottom, html .ui-button.ui-state-disabled:active
    {
        border-left: 1px solid red;
        border-bottom: none;
        background: #fff;
        font-weight: normal;
    }

    .ui-state-default-left-bottom, html .ui-button.ui-state-disabled:active
    {
        border-left: none;
        border-bottom: none;
        background: #fff;
        font-weight: normal;
    }

    #selectable .ui-selecting { background: #FECA40; }
    #selectable .ui-selected { background: #F39814; color: white; }
    #selectable { list-style-type: none; margin: 0; padding: 0; width: 20rem; }
    #selectable li { padding: 0.3rem; float: left; width: 2rem; height: 2rem; font-size: 1.5rem; text-align: center; }

    </style>

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

Body:
You can refactor your css in many ways specially when they shares same properties:

1: Use comma

.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default, html .ui-button.ui-state-disabled:hover, html .ui-button.ui-state-disabled:active,
.ui-state-default-left-bottom, html .ui-button.ui-state-disabled:active,
.ui-state-default-left, html .ui-button.ui-state-disabled:active,
.ui-state-default-bottom, html .ui-button.ui-state-disabled:active {
    background: #fff;
    font-weight: normal;
}

2: Use css selector

div[class^="ui-state"] {
    font-weight: normal;
    background: #fff;
}

With this 2 ways you can reduce your total css file size significantly and final result would be the same.
With doing a little more refactoring, you will be able to achieve this:

.ui-draggable,
.ui-droppable {
    background-position: top;
}
.ui-state-default,
.ui-widget-content .ui-state-default,
.ui-widget-header .ui-state-default,
html .ui-button.ui-state-disabled:hover,
html .ui-button.ui-state-disabled:active,
.ui-state-default-left,
html .ui-button.ui-state-disabled:active,
.ui-state-default-bottom, html .ui-button.ui-state-disabled:active {
    border-bottom: 1px solid red;
    border-left: 1px solid red;

}

.ui-state-default-left,
html .ui-button.ui-state-disabled:active,
.ui-state-default-left-bottom, html .ui-button.ui-state-disabled:active {
    border-left: none;
}

.ui-state-default-bottom, html .ui-button.ui-state-disabled:active,
.ui-state-default-left-bottom, html .ui-button.ui-state-disabled:active {
    border-bottom: none;
}

div[class^="ui-state"] {
    font-weight: normal;
    background: #fff;
}

Edit:

For your element you just need this minified version of css

#selectable {list-style-type: none;margin: 0;padding: 0;width: 20rem;}
#selectable li {padding: 0.3rem;float: left;width: 2rem;height: 2rem;font-size: 1.5rem;text-align: center;font-weight: normal;background: #fff;border-bottom: 1px solid red;border-left: 1px solid red;}
#selectable li.ui-state-default-bottom,
#selectable li.ui-state-default-left-bottom {border-bottom: none;}
#selectable li.ui-state-default-left,
#selectable li.ui-state-default-left-bottom {border-left: none;}

BUT if javascript will manipulate the classes you will need to add these classes as well:

#selectable .ui-selecting { background: #FECA40; }
#selectable .ui-selected { background: #F39814; color: white; }
.ui-draggable, .ui-droppable {background-position: top;}


答:
I suggest you need restart your docker service, please refer to this similar issue.

https://github.com/yegor256/rultor/issues/1041

Title: Docker cannot login to azurecr.io

Body:
On Docker version 17.09.0-ce, build afdb6d4 (running on Mac OS 10.12.5) I'm having the following error when I run docker login <proj>.azurecr.io:

Warning: failed to get default registry endpoint from daemon (Cannot
  connect to the Docker daemon at unix:///var/run/docker.sock. Is the
  docker daemon running?). Using system default:
  https://index.docker.io/v1/

This is after I input the username and password that I retrived using az acr. I've done this same process in the past and now it's not working anymore.

How can I debug this and login/pull images again?


问:
putExtra from activity then getExtra in fragment
i tried to put and get extra from activity to fragment . but something is wrong! anybody have idea? my case is diffrent because i wanna do it in fragment

myActivity :

```<code>if(email.matches(users.user1)&&password.matches(users.pass1)){
        Intent intent = new Intent(LoginActivity.this,MainActivity.class);
        Intent i = new Intent(LoginActivity.this,ProfileFragment.class);
        i.putExtra("pn", users.pn1);
        i.putExtra("name", users.name1);
        i.putExtra("family", users.family1);
        i.putExtra("rank", users.rank1);
        startActivity(intent);
        finish();
    }
</code>```

myfragment

```<code>@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_profile2, container, false);

    final TextView pn =getActivity().findViewById(R.id.pn);
    final TextView name =getActivity().findViewById(R.id.name);
    final TextView family =getActivity().findViewById(R.id.family);
    final TextView user =getActivity().findViewById(R.id.user);
    final TextView rank =getActivity().findViewById(R.id.rank);

    String pnget = getActivity().getIntent().getStringExtra("pn");
    String nameget = getActivity().getIntent().getStringExtra("name");
    String familyget = getActivity().getIntent().getStringExtra("family");
    String userget = getActivity().getIntent().getStringExtra("user");
    String rankget = getActivity().getIntent().getStringExtra("rank");

    pn.setText(pnget);
    name.setText(nameget);
    family.setText(familyget);
    user.setText(userget);
    rank.setText(rankget);
}
</code>```

Hi . i tried to put and get extra from activity to fragment . but something is wrong! anybody have idea?

答:
You start an intent call intent. But the intent have data is i, and it have't started yet.

You can use setArgument and getArgument to send and receive data from activity to fragment or from fragment to fragment:

In YourReceiveFragment:

```<code>public static Fragment newInstance(String data1, String data2, ...) {
    Fragment f = new YourReceiveFragment();
    Bundle bundle = new Bundle();
    bundle.putString(DATA_RECEIVE1, data1);
    bundle.putString(DATA_RECEIVE2, data2);
    f.setArguments(bundle);
    return f;
}
</code>```

In your activity: Just call it:

```<code>Fragment f = YourReceiveFragment.newInstance(yourString1, yourString2);

                            FragmentTransaction ft = getFragmentManager().beginTransaction();
                            ft.add(R.id.main_container, f).commit();
</code>```

Then in YourReceiveFragment:

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null){
        String dataReceive1 = getArguments().getString(DATA_RECEIVE1);
        String dataReceive2 = getArguments().getString(DATA_RECEIVE2);
    }
}
</code>```

In case you want to send data from an activity to a fragment in another activity,  use interface or an easier way is just pass the data to the activity which contains fragment and from that, send data to fragment.

Body:
i tried to put and get extra from activity to fragment . but something is wrong! anybody have idea? my case is diffrent because i wanna do it in fragment

myActivity :

if(email.matches(users.user1)&&password.matches(users.pass1)){
        Intent intent = new Intent(LoginActivity.this,MainActivity.class);
        Intent i = new Intent(LoginActivity.this,ProfileFragment.class);
        i.putExtra("pn", users.pn1);
        i.putExtra("name", users.name1);
        i.putExtra("family", users.family1);
        i.putExtra("rank", users.rank1);
        startActivity(intent);
        finish();
    }

myfragment

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_profile2, container, false);

    final TextView pn =getActivity().findViewById(R.id.pn);
    final TextView name =getActivity().findViewById(R.id.name);
    final TextView family =getActivity().findViewById(R.id.family);
    final TextView user =getActivity().findViewById(R.id.user);
    final TextView rank =getActivity().findViewById(R.id.rank);

    String pnget = getActivity().getIntent().getStringExtra("pn");
    String nameget = getActivity().getIntent().getStringExtra("name");
    String familyget = getActivity().getIntent().getStringExtra("family");
    String userget = getActivity().getIntent().getStringExtra("user");
    String rankget = getActivity().getIntent().getStringExtra("rank");

    pn.setText(pnget);
    name.setText(nameget);
    family.setText(familyget);
    user.setText(userget);
    rank.setText(rankget);
}

Hi . i tried to put and get extra from activity to fragment . but something is wrong! anybody have idea?

Body:
You start an intent call intent. But the intent have data is i, and it have't started yet.

You can use setArgument and getArgument to send and receive data from activity to fragment or from fragment to fragment:

In YourReceiveFragment:

public static Fragment newInstance(String data1, String data2, ...) {
    Fragment f = new YourReceiveFragment();
    Bundle bundle = new Bundle();
    bundle.putString(DATA_RECEIVE1, data1);
    bundle.putString(DATA_RECEIVE2, data2);
    f.setArguments(bundle);
    return f;
}

In your activity: Just call it:

Fragment f = YourReceiveFragment.newInstance(yourString1, yourString2);

                            FragmentTransaction ft = getFragmentManager().beginTransaction();
                            ft.add(R.id.main_container, f).commit();

Then in YourReceiveFragment:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null){
        String dataReceive1 = getArguments().getString(DATA_RECEIVE1);
        String dataReceive2 = getArguments().getString(DATA_RECEIVE2);
    }
}

In case you want to send data from an activity to a fragment in another activity,  use interface or an easier way is just pass the data to the activity which contains fragment and from that, send data to fragment.


问:
scanf prematurely terminating while loop (I think)
I am making a simple program to calculate the required exam mark based on your current mark, the % total worth of the exam on the course, and your desired mark. I was having no problems with it until I wanted a simple while loop to redo the proses if the user wanted to do so. The problem that arose was that when I have the scanf to get a char response from the user, it terminates the while loop and then the program. When I comment out the scanf line and leave the code as is (an infinite while loop) it works properly looping forever but with it, it will terminate with no errors. Any thoughts?</p>

```<code>    #include <stdio.h>

    #define TRUE 1
    #define FALSE 0

    int main()
    {
        int continueProgram = TRUE;
        float currentMark = 0.0, examPercent = 0.0, desiredMark = 0.0, requiredMark = 0.0;
        char response  = 'y';

        while (continueProgram == TRUE)
        {
            printf("What is your current mark in your class: ");
            scanf("%f", &currentMark);
            printf("How much is you exam worth: ");
            scanf("%f", &examPercent);
            examPercent /= 100.0;
            printf("What is your desiered mark: ");
            scanf("%f", &desiredMark);

            // Simple math to get mark
            requiredMark = (desiredMark - currentMark * examPercent) / examPercent;

            if (requiredMark > 100.0)
            {
                printf("\nI'm sorry but you need above 100%% to get to your required mark\nHere is a list of all the marks you can get:\n\n");

                for (requiredMark = 0.0; requiredMark <= 100.0; requiredMark += 5.0)
                {
                    desiredMark = currentMark * examPercent + requiredMark * examPercent;
                    printf("Exam Mark: %.2f, Final Mark: %.2f\n", requiredMark, desiredMark);
                }
            }
            else
            {
                printf("\nThe mark that you need to get on the exam is: %.2f\nHere is a list of all the marks you can get:\n\n", requiredMark);

                for (requiredMark = 0.0; requiredMark <= 100.0; requiredMark += 5.0)
                {
                    desiredMark = currentMark * examPercent + requiredMark * examPercent;
                    printf("Exam Mark: %.2f, Final Mark: %.2f\n", requiredMark, desiredMark);
                }
            }

            printf("\nDid you want to continue with a new grade (y or n): ");

            // THIS IS WHERE I AM HAVING THE ISSUE
            scanf("%c", &response );

            if (response  == 'y')
            {
                printf("\n\nResetting  terminal...\n\n");
                currentMark = 0.0;
                examPercent = 0.0;
                desiredMark = 0.0;
                requiredMark = 0.0;
            }
            else
                continueProgram = FALSE;
        }
    }
</code>```

答:
Try this, which works as you expected.

Original :

scanf("%c", &responce);

Replace:

responce=fgetc(stdin);