问:
Issue with fgets() inside of a do-while loop in C

Hello. I have a problem with a code I have created to decide if an input string is a palindrome or not (word is the same if read in wrong direction). The actual code in itself works as intended, however when I tried to put a loop on the whole code it started acting weird.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define STRING_MAX 100

int isPalindrome();
char* removeNonAlpha();
char* strLowerCase();

int main()
{
    int x = 0;
    char inputString[STRING_MAX];
    char cont='y';

    do
    {
        printf("Hello. Please enter a word or sentence: ");
        fgets(inputString, STRING_MAX, stdin);

        printf("You entered: %s\n", inputString);

        //Remove all non alphabetical symbols from the string
        removeNonAlpha(inputString);
        printf("First we have to remove everything non-alphabetical: %s\n", inputString);

        //Make sure all the alphabetical symbols are lower case
        strLowerCase(inputString);
        printf("Then we have to make everything lower-case: %s\n", inputString);

        //After that, check if the string is a palindrome
        x = isPalindrome(inputString);

        if(x)
        {
            printf("The string you entered is a palindrome! :D\n");
        }
        else
        {
            printf("The string you entered is not a palindrome... :|\n");
        }
        printf("Would you like to enter another word or sentence? (y/n): ");
        cont = getchar();

        inputString[strlen(inputString)-1] = '\0';

    } while (cont == 'y');

    return 0;
}

int isPalindrome(char inputString[])
{
    int l = 0, r = strlen(inputString) - 1;

    if (l == r)
        return 1;

    while (r > l)
    {
        if (inputString[l++] != inputString[r--])
            return 0;
    }
    return 1;
}

char* removeNonAlpha(char inputString[])
{
    int i, j;

    for(i=0,j=0; i<strlen(inputString); i++,j++)
    {
        if (isalpha(inputString[i]))
            inputString[j] = inputString[i];
        else
            j--;
    }
    inputString[j] = '\0';

    return inputString;

}

char* strLowerCase(char inputString[])
{
    int i;

    for(i=0; i<strlen(inputString); i++)
        inputString[i] = tolower(inputString[i]);

    return inputString;
}
</code>```

So what I expected was the code to run again and ask for another string to be entered, however it doesn't. I read around a bit about this and it looks like what is happening is what a newline (\n) is still in the input buffer and the fgets is skipped. I tried using a getchar() after the fgets to consume eventual newlines but it did not solve my problem. This is the output I am getting:

Any ideas on how to solve this? I am new to programming and I would love to hear on how I could improve my code generally, although my main concern right now is fixing this loop issue.

EDIT: The only function from string.h that I am allowed to use is strlen().

答:
Where the newline is getting left in the buffer is after the getchar call at the bottom of the loop.  It only reads one character, so the newline (and any extra characters you may have entered) are still left.  So when fgets is called on the next iteration, it reads just the newline.

You need to flush out the input buffer at the bottom of the loop by repeatedly calling getchar until you see a newline:

```<code>cont = getchar();

int nextchar;
do {
    nextchar = getchar();
} while (nextchar != '\n' && nextchar != EOF);
</code>```

Body:
Hello. I have a problem with a code I have created to decide if an input string is a palindrome or not (word is the same if read in wrong direction). The actual code in itself works as intended, however when I tried to put a loop on the whole code it started acting weird.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define STRING_MAX 100

int isPalindrome();
char* removeNonAlpha();
char* strLowerCase();

int main()
{
    int x = 0;
    char inputString[STRING_MAX];
    char cont='y';

    do
    {
        printf("Hello. Please enter a word or sentence: ");
        fgets(inputString, STRING_MAX, stdin);

        printf("You entered: %s\n", inputString);

        //Remove all non alphabetical symbols from the string
        removeNonAlpha(inputString);
        printf("First we have to remove everything non-alphabetical: %s\n", inputString);

        //Make sure all the alphabetical symbols are lower case
        strLowerCase(inputString);
        printf("Then we have to make everything lower-case: %s\n", inputString);

        //After that, check if the string is a palindrome
        x = isPalindrome(inputString);

        if(x)
        {
            printf("The string you entered is a palindrome! :D\n");
        }
        else
        {
            printf("The string you entered is not a palindrome... :|\n");
        }
        printf("Would you like to enter another word or sentence? (y/n): ");
        cont = getchar();

        inputString[strlen(inputString)-1] = '\0';

    } while (cont == 'y');

    return 0;
}

int isPalindrome(char inputString[])
{
    int l = 0, r = strlen(inputString) - 1;

    if (l == r)
        return 1;

    while (r > l)
    {
        if (inputString[l++] != inputString[r--])
            return 0;
    }
    return 1;
}

char* removeNonAlpha(char inputString[])
{
    int i, j;

    for(i=0,j=0; i<strlen(inputString); i++,j++)
    {
        if (isalpha(inputString[i]))
            inputString[j] = inputString[i];
        else
            j--;
    }
    inputString[j] = '\0';

    return inputString;

}

char* strLowerCase(char inputString[])
{
    int i;

    for(i=0; i<strlen(inputString); i++)
        inputString[i] = tolower(inputString[i]);

    return inputString;
}

So what I expected was the code to run again and ask for another string to be entered, however it doesn't. I read around a bit about this and it looks like what is happening is what a newline (\n) is still in the input buffer and the fgets is skipped. I tried using a getchar() after the fgets to consume eventual newlines but it did not solve my problem. This is the output I am getting:

Any ideas on how to solve this? I am new to programming and I would love to hear on how I could improve my code generally, although my main concern right now is fixing this loop issue.

EDIT: The only function from string.h that I am allowed to use is strlen().

Body:
Where the newline is getting left in the buffer is after the getchar call at the bottom of the loop.  It only reads one character, so the newline (and any extra characters you may have entered) are still left.  So when fgets is called on the next iteration, it reads just the newline.

You need to flush out the input buffer at the bottom of the loop by repeatedly calling getchar until you see a newline:

cont = getchar();

int nextchar;
do {
    nextchar = getchar();
} while (nextchar != '\n' && nextchar != EOF);


来源: stackexchange

问:
Using for loop and if statement side by side C++
Can someone explain this syntax of using for and if side by side?    </p>

```<code>int min_dist = huge;
int v = -1;

for (int i = 0; i < N; ++i) if (!done[i]) {
    if (d[i] >= min_dist) continue;
    min_dist = d[i];
    v = i;
}
</code>```

答: If you intend about the loop without parenthesis, it can be used to execute a single block of statements. In this case the ifstatement groups all other statements in a pair of parenthesis, making them a single block.

ContentLicense: CC BY-SA 3.0

Body:
Can someone explain this syntax of using for and if side by side?

int min_dist = huge;
int v = -1;

for (int i = 0; i < N; ++i) if (!done[i]) {
    if (d[i] >= min_dist) continue;
    min_dist = d[i];
    v = i;
}


问:
CLI to convert SVG file to AI (Adobe Illustrator)
Looking for a command line utility or ruby gem that can convert a SVG file to a AI file. I've searched around quite a bit, and can't seem to find anything.

Does this not exists because AI is proprietary?

答: There is a reason for such a converter. Illustrator CS6 and earlier versions don't open SVG files correctly, so things like color, gradients and transparency are lost. </p>


问:
Disassembler Visual Studio C++
I am using debugging in Visual Studio and disassembler window to get the instruction code in hex, but when the main call a function (as Fig.1), the function instructions appear in a sperate section (as Fig. 2)
Is there any way to show the function instructions appears as a part of the main?

main section in dissasembler window

function section in dissasembler window

Thanks,

答:
Based on mov eax, 0CCCCCCCCh it seems you're working with a Debug build.

In Debug mode Visual Studio does not inline any function by default.

You can switch to Release mode or enable function inlining in compiler settings (C/C++ - Optimization - Inline Function Expansion) and the call to fun() will probably get inlined.

Title: Disassembler Visual Studio C++


问:
1/1 NotFoundHttpException in RouteCollection.php line 179:
Router file

```<code>Route::get('index',[
        'as'=>'home',
        'uses'=>'PageController@getIndex'
]);
</code>```

P age Controller

```<code>namespace App\Http\Controllers;
use Illuminate\Http\Request;
class `PageController` extends Controller
{
    public function getIndex(){
        return view('master');
    }
}
</code>```

please help me,i tried but there was a problem :NotFoundHttpException in RouteCollection.php line 179:
thank so much

答: Just a kind reminder another possible reason causes the issue is that you should put your Route::get(..) into "web.php" not other php files like "api.php" in the routes folder.</p>

Body:
Router file

Route::get('index',[
        'as'=>'home',
        'uses'=>'PageController@getIndex'
]);

P age Controller

namespace App\Http\Controllers;
use Illuminate\Http\Request;
class `PageController` extends Controller
{
    public function getIndex(){
        return view('master');
    }
}

please help me,i tried but there was a problem :NotFoundHttpException in RouteCollection.php line 179:
thank so much


问:
Client Server TCP in Python 'bytes' object has no attribute 'encode'
Im trying to create a client server, where server stores list of strings and client keeps asking if user wants another one till they indicate no. Im trying to figure out how to send the whole list over and how to iterate it properly. In my client I get the error 'bytes' object has no attribute 'encode' which is the "clientSocket.send(msg.encode())" part.

Server

```<code>from random import choice
import socket
Port =13000
Server= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Server.bind((socket.gethostname(),Port))
Server.listen(1)
print ("The server is ready to recieve ")

quotes = ["Not my circus, not my monkeys",
         "Don't eat yellow snow",
         "Where's Waldo?"]

while True:
    connectionSocket, addr = Server.accept()
    sentence = connectionSocket.recv(2048)
    for i in range (len(quotes)):
        connectionSocket.sendall(quotes.encode())
    **new edit**
    for i in quotes:
        connectionSocket.sendall(i.encode())

Server.close()
</code>```

Client

```<code>from random import choice
import socket

serverName = socket.gethostname()
Port=13000
clientSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientSocket.connect((serverName,Port))
msg = "Quote is: "
while True:
    clientSocket.send(msg.encode())
    msg = clientSocket.recv(2048)
    print(msg.decode())

    x = input(("Would you like another quote? Type 'yes' or 'no' "))
    if x =='yes':
       pass
    elif x == 'no':
        print ("Thanks for using me, bye! ")
        quit()
    else:
        print("Invalid input try again")

clientSocket.close()
</code>```

答: Aside from the first iteration, your msg variable is already encoded, because recv returns type bytes. The best solution is to declare msg = b"Quote is: " before the while loop, and then change msg.encode() to simply msg

Body:
Im trying to create a client server, where server stores list of strings and client keeps asking if user wants another one till they indicate no. Im trying to figure out how to send the whole list over and how to iterate it properly. In my client I get the error 'bytes' object has no attribute 'encode' which is the "clientSocket.send(msg.encode())" part.

Server

from random import choice
import socket
Port =13000
Server= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Server.bind((socket.gethostname(),Port))
Server.listen(1)
print ("The server is ready to recieve ")

quotes = ["Not my circus, not my monkeys",
         "Don't eat yellow snow",
         "Where's Waldo?"]

while True:
    connectionSocket, addr = Server.accept()
    sentence = connectionSocket.recv(2048)
    for i in range (len(quotes)):
        connectionSocket.sendall(quotes.encode())
    **new edit**
    for i in quotes:
        connectionSocket.sendall(i.encode())

Server.close()

Client

from random import choice
import socket

serverName = socket.gethostname()
Port=13000
clientSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientSocket.connect((serverName,Port))
msg = "Quote is: "
while True:
    clientSocket.send(msg.encode())
    msg = clientSocket.recv(2048)
    print(msg.decode())

    x = input(("Would you like another quote? Type 'yes' or 'no' "))
    if x =='yes':
       pass
    elif x == 'no':
        print ("Thanks for using me, bye! ")
        quit()
    else:
        print("Invalid input try again")

clientSocket.close()


答:
This is exactly the same:

```<code>int min_dist = huge;
int v = -1;

for (int i = 0; i < N; ++i){
    if (!done[i]) {
        if (d[i] >= min_dist) continue;
        min_dist = d[i];
        v = i;
    }
}
</code>```

As an explanation, when you only have one statement inside a for or if, you don't need the brackets.

Title: Using for loop and if statement side by side C++

Body:
This is exactly the same:

int min_dist = huge;
int v = -1;

for (int i = 0; i < N; ++i){
    if (!done[i]) {
        if (d[i] >= min_dist) continue;
        min_dist = d[i];
        v = i;
    }
}

As an explanation, when you only have one statement inside a for or if, you don't need the brackets.


答:
The layout may fool you. It's just a for-loop with a single if-statement:

for each item indexed by i

if item i not done already, then proces item i in if-body

else next item (in for-loop)


答:
It's not side by side. It's an if inside a for. The syntax of a for is

```<code>for(...)
  statement
</code>```

And it just so happens that an if is also a statement. So your code is equivalent to this:

```<code>for(...)
  if() {
  }
</code>```

Because white-spaces are pretty much ignored by the compilation process. It doesn't matter if there's a new line or not. It's still a statement. Just like it doesn't matter for the one-liner

```<code>if (d[i] >= min_dist) continue;
</code>```

And if we don't omit those obviously crucial braces:

```<code>for(...) {
  if() {
  }
}
</code>```

We'll be far less likely to be confused in the future.

Body:
It's not side by side. It's an if inside a for. The syntax of a for is

for(...)
  statement

And it just so happens that an if is also a statement. So your code is equivalent to this:

for(...)
  if() {
  }

Because white-spaces are pretty much ignored by the compilation process. It doesn't matter if there's a new line or not. It's still a statement. Just like it doesn't matter for the one-liner

if (d[i] >= min_dist) continue;

And if we don't omit those obviously crucial braces:

for(...) {
  if() {
  }
}

We'll be far less likely to be confused in the future.


问:
SQL: Optional Foreign Keys
I have the following tables....

"Floor" (which has many) "Area" (which has many) "Asset",

then I have a "Task" table.

A "Task" can be assigned to either an "Area" or an "Asset"; so I have two columns in the "Task" table named areaId and assetId, one of which must have a value.

1st question: How do I query all tasks which have occurred on a given floor?

2nd question: How do I enforce referential integrity?

3rd question: Is this approach recommended? Any suggestions welcome if not.

Many thanks for any answers given,

ETFairfax

答:
Let's start with question 3, is this a valid approach?  It is if it models reality.  If floors, areas, and assets are unlike things, with more distinct properties than properties in common, and if the operations on them tend to be different, then your 3 table approach is fine.

For the second question, simply put foreign keys onto both areaId and assetId.  Null values are ok in foreign keys.

But you need a table level constraint that will not allow both of them to be null, nor allow both of them to be populated.

Finally, having settled the issue of schema and constraints, we can do the query, which is pretty straightforward.  The idea is that some tasks join through asset through area to floor, while others join through area straight to floor.  For that you need to union two queries together:

```<code>-- First query is the three level
select task.*
  from task
  join asset on task.assetid = asset.id
  join area  on asset.areaid = area.id
  join floor on area.floorid = floor.id
 where floor = xxxx
UNION ALL
-- Second query is the two level
select task.*
  from task
  join area  on task.areaid  = area.id
  join floor on area.floorid = floor.id
 where floor = xxxx
</code>```

This will return the correct results but may not be the fastest.  Putting a WHERE clause on each subquery to filter out NULL/NOT NULL may speed it up, that you would have to investigate.

ContentLicense: CC BY-SA 2.5

Title: SQL: Optional Foreign Keys

Body:
Let's start with question 3, is this a valid approach?  It is if it models reality.  If floors, areas, and assets are unlike things, with more distinct properties than properties in common, and if the operations on them tend to be different, then your 3 table approach is fine.

For the second question, simply put foreign keys onto both areaId and assetId.  Null values are ok in foreign keys.

But you need a table level constraint that will not allow both of them to be null, nor allow both of them to be populated.

Finally, having settled the issue of schema and constraints, we can do the query, which is pretty straightforward.  The idea is that some tasks join through asset through area to floor, while others join through area straight to floor.  For that you need to union two queries together:

-- First query is the three level
select task.*
  from task
  join asset on task.assetid = asset.id
  join area  on asset.areaid = area.id
  join floor on area.floorid = floor.id
 where floor = xxxx
UNION ALL
-- Second query is the two level
select task.*
  from task
  join area  on task.areaid  = area.id
  join floor on area.floorid = floor.id
 where floor = xxxx

This will return the correct results but may not be the fastest.  Putting a WHERE clause on each subquery to filter out NULL/NOT NULL may speed it up, that you would have to investigate.


问:
Allow a user to login/signin between actions
I have a requirement, where we allow a user to access a URL without logging in until a certain point.
For example:

OnlineBooking/Services.  They can select the services, this populates the viewmodel and then brings up a confirm view OnlineBooking/Confirm allowing a user to add an email address etc.  Which then generates a ViewModel.

My question is, how can I check the user exists, if it does.  Redirect to the login view (Account Controller - Login Action), allow them to login, then redirect back to this action without losing the viewmodel in this action?  This may not even be possible, if not how can I achieve this?
Thanks for any advice.

Example:

```<code>     public async Task<IActionResult> Confirm(BookingViewModel bookingViewModel)
    {
        try
        {
            var matchedUser = await _userManager.FindByEmailAsync(bookingViewModel.Email);
            if (matchedUser == null) //User does not have an existing account, so register them.
            {
              //This is fine
            }
            else
            {
              //Need to redirect to login, then back to here without losing the viewmodel
            }
     }
</code>```

答:
Not sure if it's the best practice, but what about storing the View Model in the session before you redirect to the login page?  Then at the beginning of the confirm action, check if that session variable exists.

Session variables can be set like this:

```<code>Session["MyViewModel"] = viewModel;
</code>```

and retrieved like so:

```<code>MyViewModel viewModel = (MyViewModel)Session["MyViewModel"]
</code>```

Body:
I have a requirement, where we allow a user to access a URL without logging in until a certain point.
For example:

OnlineBooking/Services.  They can select the services, this populates the viewmodel and then brings up a confirm view OnlineBooking/Confirm allowing a user to add an email address etc.  Which then generates a ViewModel.

My question is, how can I check the user exists, if it does.  Redirect to the login view (Account Controller - Login Action), allow them to login, then redirect back to this action without losing the viewmodel in this action?  This may not even be possible, if not how can I achieve this?
Thanks for any advice.

Example:

     public async Task<IActionResult> Confirm(BookingViewModel bookingViewModel)
    {
        try
        {
            var matchedUser = await _userManager.FindByEmailAsync(bookingViewModel.Email);
            if (matchedUser == null) //User does not have an existing account, so register them.
            {
              //This is fine
            }
            else
            {
              //Need to redirect to login, then back to here without losing the viewmodel
            }
     }

Body:
Not sure if it's the best practice, but what about storing the View Model in the session before you redirect to the login page?  Then at the beginning of the confirm action, check if that session variable exists.

Session variables can be set like this:

Session["MyViewModel"] = viewModel;

and retrieved like so:

MyViewModel viewModel = (MyViewModel)Session["MyViewModel"]


问:
Floating a div to the right causes undesirable results
I've got my code structure in the JSfiddle link below.  Problem is when I add float:right to the "Add" text it causes extra space above the "Quick Links" & "Top 20 Sites" sections.

#home-content {
 padding: 5px;
}

#home-content .css-table #row1-col3 .col-body {
 padding: 5px 5px;
    /* border: 1px solid #000; */
}

/* Home page Quick Links column */
#home-content .css-table #row1-col1 .col-body > div {
    max-height: 232px;
    overflow: auto;
}

/* Home page MyShortcuts column */
#home-content .css-table #row1-col3 .col-body > div {
    max-height: 215px;
    overflow: auto;
}

.css-table {
 display: table;
 border-spacing: 9px 5px;
 margin-left: auto;
 margin-right: auto;
 width: 980px;
}

.css-table #row1-col1 {
 display: table-cell;
 width: 170px;
 border: 1px solid #cccccc;
 background-color: White;
}

.css-table #row1-col2 {
 display: table-cell;
 width: 540px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.css-table #row1-col3 {
 display: table-cell;
 width: 255px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.css-table #row2 {
 display: table-cell;
 width: 906px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.css-table #row2-col1 {
 display: table-cell;
 width: 490px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.css-table #row2-col2 {
 display: table-cell;
 width: 490px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.col-header {
 border-bottom: 1px dotted #cccccc;
 position: relative;
 height: 24px;
 padding: 7px 7px 1px 7px;
 font-family: verdana;
 font-size: 13px;
 background-color:#cccccc;
}

.col-body {
 padding: 0px 0px 0px 0px;
 border-spacing: 1px 1px;
  font-family: verdana;
 font-size:12px;
}

.col-newsfeeds {
 padding: 5px 5px 5px 5px;
 border-spacing: 1px 1px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="home-content">
  <div class="css-table">
   <div id="row1-col1">
    <div class="col-header">
     Quick Links
   </div>
   <div class="col-body">
        Test 1
   </div>
  </div>
  <div id="row1-col2">
    <div class="col-header">
    Top 20 Sites
   </div>
   <div class="col-body">
        Test 2
   </div>
  </div>
  <div id="row1-col3">
    <div class="col-header">
     <div style="float:left;">My Shortcuts</div>
    <div style="float:right;">Add</div>
   </div>
   <div class="col-body">
     Item 1<br/>
     Item 2<br/>
     Item 3<br/>
     Item 4<br/>
     Item 5<br/>
     Item 6<br/>
     Item 7<br/>
     Item 8<br/>
     Item 9<br/>
     Item 10<br/>
   </div>
  </div>
 </div>
 <div class="css-table">
  <div id="row2-col1">
   <div class="col-header">
    In the News
   </div>
   <div class="col-body">
     Test 3
      </div>
  </div>
  <div id="row2-col2">
   <div class="col-header">
    Announcements
   </div>
   <div class="col-body">
      Test 4
   </div>
  </div>
 </div>
</div></code>```

How can I float the "Add" text to the right of the "My Shortcuts" text without it affecting the others?

Thank you.

答:
Set the "My Shortcuts" header to be inline-block instead of float left

#home-content {
 padding: 5px;
}

#home-content .css-table #row1-col3 .col-body {
 padding: 5px 5px;
    /* border: 1px solid #000; */
}

/* Home page Quick Links column */
#home-content .css-table #row1-col1 .col-body > div {
    max-height: 232px;
    overflow: auto;
}

/* Home page MyShortcuts column */
#home-content .css-table #row1-col3 .col-body > div {
    max-height: 215px;
    overflow: auto;
}

.css-table {
 display: table;
 border-spacing: 9px 5px;
 margin-left: auto;
 margin-right: auto;
 width: 980px;
}

.css-table #row1-col1 {
 display: table-cell;
 width: 170px;
 border: 1px solid #cccccc;
 background-color: White;
}

.css-table #row1-col2 {
 display: table-cell;
 width: 540px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.css-table #row1-col3 {
 display: table-cell;
 width: 255px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.css-table #row2 {
 display: table-cell;
 width: 906px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.css-table #row2-col1 {
 display: table-cell;
 width: 490px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.css-table #row2-col2 {
 display: table-cell;
 width: 490px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.col-header {
 border-bottom: 1px dotted #cccccc;
 position: relative;
 height: 24px;
 padding: 7px 7px 1px 7px;
 font-family: verdana;
 font-size: 13px;
 background-color:#cccccc;
}

.col-body {
 padding: 0px 0px 0px 0px;
 border-spacing: 1px 1px;
  font-family: verdana;
 font-size:12px;
}

.col-newsfeeds {
 padding: 5px 5px 5px 5px;
 border-spacing: 1px 1px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="home-content">
  <div class="css-table">
   <div id="row1-col1">
    <div class="col-header">
     Quick Links
   </div>
   <div class="col-body">
        Test 1
   </div>
  </div>
  <div id="row1-col2">
    <div class="col-header">
    Top 20 Sites
   </div>
   <div class="col-body">
        Test 2
   </div>
  </div>
  <div id="row1-col3">
    <div class="col-header">
     <div style="display:inline-block">My Shortcuts</div>
    <div style="float:right;">Add</div>
   </div>
   <div class="col-body">
     Item 1<br/>
     Item 2<br/>
     Item 3<br/>
     Item 4<br/>
     Item 5<br/>
     Item 6<br/>
     Item 7<br/>
     Item 8<br/>
     Item 9<br/>
     Item 10<br/>
   </div>
  </div>
 </div>
 <div class="css-table">
  <div id="row2-col1">
   <div class="col-header">
    In the News
   </div>
   <div class="col-body">
     Test 3
      </div>
  </div>
  <div id="row2-col2">
   <div class="col-header">
    Announcements
   </div>
   <div class="col-body">
      Test 4
   </div>
  </div>
 </div>
</div></code>```

Body:
I've got my code structure in the JSfiddle link below.  Problem is when I add float:right to the "Add" text it causes extra space above the "Quick Links" & "Top 20 Sites" sections.

#home-content {
 padding: 5px;
}

#home-content .css-table #row1-col3 .col-body {
 padding: 5px 5px;
    /* border: 1px solid #000; */
}

/* Home page Quick Links column */
#home-content .css-table #row1-col1 .col-body > div {
    max-height: 232px;
    overflow: auto;
}

/* Home page MyShortcuts column */
#home-content .css-table #row1-col3 .col-body > div {
    max-height: 215px;
    overflow: auto;
}

.css-table {
 display: table;
 border-spacing: 9px 5px;
 margin-left: auto;
 margin-right: auto;
 width: 980px;
}

.css-table #row1-col1 {
 display: table-cell;
 width: 170px;
 border: 1px solid #cccccc;
 background-color: White;
}

.css-table #row1-col2 {
 display: table-cell;
 width: 540px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.css-table #row1-col3 {
 display: table-cell;
 width: 255px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.css-table #row2 {
 display: table-cell;
 width: 906px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.css-table #row2-col1 {
 display: table-cell;
 width: 490px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.css-table #row2-col2 {
 display: table-cell;
 width: 490px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.col-header {
 border-bottom: 1px dotted #cccccc;
 position: relative;
 height: 24px;
 padding: 7px 7px 1px 7px;
 font-family: verdana;
 font-size: 13px;
 background-color:#cccccc;
}

.col-body {
 padding: 0px 0px 0px 0px;
 border-spacing: 1px 1px;
  font-family: verdana;
 font-size:12px;
}

.col-newsfeeds {
 padding: 5px 5px 5px 5px;
 border-spacing: 1px 1px;
}

     Quick Links

        Test 1

    Top 20 Sites

        Test 2

My Shortcuts

Add

     Item 1

     Item 2

     Item 3

     Item 4

     Item 5

     Item 6

     Item 7

     Item 8

     Item 9

     Item 10

    In the News

     Test 3

    Announcements

      Test 4

How can I float the "Add" text to the right of the "My Shortcuts" text without it affecting the others?

Thank you.

Body:
Set the "My Shortcuts" header to be inline-block instead of float left

#home-content {
 padding: 5px;
}

#home-content .css-table #row1-col3 .col-body {
 padding: 5px 5px;
    /* border: 1px solid #000; */
}

/* Home page Quick Links column */
#home-content .css-table #row1-col1 .col-body > div {
    max-height: 232px;
    overflow: auto;
}

/* Home page MyShortcuts column */
#home-content .css-table #row1-col3 .col-body > div {
    max-height: 215px;
    overflow: auto;
}

.css-table {
 display: table;
 border-spacing: 9px 5px;
 margin-left: auto;
 margin-right: auto;
 width: 980px;
}

.css-table #row1-col1 {
 display: table-cell;
 width: 170px;
 border: 1px solid #cccccc;
 background-color: White;
}

.css-table #row1-col2 {
 display: table-cell;
 width: 540px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.css-table #row1-col3 {
 display: table-cell;
 width: 255px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.css-table #row2 {
 display: table-cell;
 width: 906px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.css-table #row2-col1 {
 display: table-cell;
 width: 490px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.css-table #row2-col2 {
 display: table-cell;
 width: 490px;
 border: 1px solid #cccccc;
 padding: 0;
 background-color: White;
}

.col-header {
 border-bottom: 1px dotted #cccccc;
 position: relative;
 height: 24px;
 padding: 7px 7px 1px 7px;
 font-family: verdana;
 font-size: 13px;
 background-color:#cccccc;
}

.col-body {
 padding: 0px 0px 0px 0px;
 border-spacing: 1px 1px;
  font-family: verdana;
 font-size:12px;
}

.col-newsfeeds {
 padding: 5px 5px 5px 5px;
 border-spacing: 1px 1px;
}

<div id="home-content">
  <div class="css-table">
   <div id="row1-col1">
    <div class="col-header">
     Quick Links
   </div>
   <div class="col-body">
        Test 1
   </div>
  </div>
  <div id="row1-col2">
    <div class="col-header">
    Top 20 Sites
   </div>
   <div class="col-body">
        Test 2
   </div>
  </div>
  <div id="row1-col3">
    <div class="col-header">
     <div style="display:inline-block">My Shortcuts</div>
    <div style="float:right;">Add</div>
   </div>
   <div class="col-body">
     Item 1<br/>
     Item 2<br/>
     Item 3<br/>
     Item 4<br/>
     Item 5<br/>
     Item 6<br/>
     Item 7<br/>
     Item 8<br/>
     Item 9<br/>
     Item 10<br/>
   </div>
  </div>
 </div>
 <div class="css-table">
  <div id="row2-col1">
   <div class="col-header">
    In the News
   </div>
   <div class="col-body">
     Test 3
      </div>
  </div>
  <div id="row2-col2">
   <div class="col-header">
    Announcements
   </div>
   <div class="col-body">
      Test 4
   </div>
  </div>
 </div>
</div>


问:
Can I send a message to a customer on facebook messenger once he completes an order?
I saw the following screenshot on this page.

From the look of it, it sent order details to a customer upon completion of her order to her facebook messenger. I can't find any of the facebook messenger plugins capable of doing this. Can you please help me find out how did they actually did it? I want to replicate it for my site. Thanks

答: Send to messenger plugin and checkbox plugin could be used to create this type of functionality.</p>


问:
CSS not centering
I have the following html and css.

  .divOuter {
  width: 50%;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 150px;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="logo">
  <img src="http://i.cubeupload.com/jmdKlW.png"></img>
</div>
<div id="title">
  <h3>Who's watching</h3>
</div>
<div class="divOuter">
  <div class="divInner1">First DIV</div>
  <div class="divInner2">Second DIV</div>
  <div class="divInner3">Third DIV</div>
</div></code>```

I used the outer div to try and center everything inside. but i get the following image:

The squares in the middle are not centered. A working example is on xat.me/madses1996

I would like the squares next to eachtother.

答:
Using Chrome's Inspect, I got the results I think you are looking for with these updates to the .divInner1, 2 & 3 CSS classes.

remove: "float: left;"

add: "display: inline-block;

Title: CSS not centering

Body:
I have the following html and css.

  .divOuter {
  width: 50%;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 150px;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;

Who's watching

First DIV

Second DIV

Third DIV

I used the outer div to try and center everything inside. but i get the following image:

The squares in the middle are not centered. A working example is on xat.me/madses1996

I would like the squares next to eachtother.


问:
Why React setState is not triggering re-render?
I am trying to use react and update properties with setState, however, it doesnt seem to re-render.

In the following code, you will see that the onStart and onComplete use setState to update the style property.

The property gets updated, but the style does not get changed in the dom, despite my render function appearing to be set up in the correct way?

```<code>export default class FirstScene extends React.Component {
    constructor() {
        super();
        let self=this;
        this.state = {
            style:{display:'hidden'}
        };
        this.mainTimeline= new TimelineMax({repeat:0,paused:true,
            onStart:function(){
                self.setState({style:{display:'block'}})
            }.bind(self),
            onComplete:function(){
                self.setState({style:{display:'hidden'}})
                console.log(this.state);
            }.bind(self)
        });
    }

    render() {
        return (
            <div style={this.state.style} >test hey</div>
        )
    }

};
</code>```

答: Try to create TimelineMax in componentDidMount lifecycle method. It might be that callbacks are executed before component is mounted.

Body:
I am trying to use react and update properties with setState, however, it doesnt seem to re-render.

In the following code, you will see that the onStart and onComplete use setState to update the style property.

The property gets updated, but the style does not get changed in the dom, despite my render function appearing to be set up in the correct way?

export default class FirstScene extends React.Component {
    constructor() {
        super();
        let self=this;
        this.state = {
            style:{display:'hidden'}
        };
        this.mainTimeline= new TimelineMax({repeat:0,paused:true,
            onStart:function(){
                self.setState({style:{display:'block'}})
            }.bind(self),
            onComplete:function(){
                self.setState({style:{display:'hidden'}})
                console.log(this.state);
            }.bind(self)
        });
    }

    render() {
        return (

test hey

        )
    }

};


问:
how to add new item to firebase
I want to add a new item to my list, I use firebase without user(email,password)

I want to add new items like this:-

```<code>list
-vdjs43ndjufd87
         "name" : Jak
         "university" : Harvard

list
-vdjs43ndjufd87
          "name" : Jak
          "university" : Harvard
          "age" : 23
</code>```

this code is not working with me:-

```<code>let key = ref.child("posts").childByAutoId().key

let post = ["uid": userID,
        "author": username,
        "title": title,
        "body": body]
let childUpdates = ["/posts/\(key)": post,
                "/user-posts/\(userID)/\(key)/": post]
ref.updateChildValues(childUpdates)`h
</code>```

答:
All you need to do is this:   </p>

```<code>let post = ["uid": userID,
    "author": username,
    "title": title,
    "body": body]

ref.child("posts").childByAutoId().setValue(post)
</code>```

Title: how to add new item to firebase

Body:
I want to add a new item to my list, I use firebase without user(email,password)

I want to add new items like this:-

list
-vdjs43ndjufd87
         "name" : Jak
         "university" : Harvard

list
-vdjs43ndjufd87
          "name" : Jak
          "university" : Harvard
          "age" : 23

this code is not working with me:-

let key = ref.child("posts").childByAutoId().key

let post = ["uid": userID,
        "author": username,
        "title": title,
        "body": body]
let childUpdates = ["/posts/\(key)": post,
                "/user-posts/\(userID)/\(key)/": post]
ref.updateChildValues(childUpdates)`h

Body:
All you need to do is this:

let post = ["uid": userID,
    "author": username,
    "title": title,
    "body": body]

ref.child("posts").childByAutoId().setValue(post)


问:
don't get expected results using dplyr and group_by in R
Trying to summarize a data set, but it does not group the variables specified

Sample from the data set, test2

```<code>  newClientID   Month      newApp          count    app
  100           November    R              51       Other
  100           November    Tableau        58       Other
  100           October     R              12       Other
  100           October     Tableau        212      Other
  100           September   R              72       Other
  100           September   Tableau        74       Other
  100           October     SQL Assistant  11       Other
  100           September   SQL Assistant  396      Other
</code>```

This should summarize the data

```<code>test3 <- test2 %>%
   group_by(newClientID, Month, app) %>%
   summarise(total = sum(count))
</code>```

It should be like this

```<code>newClientID Month        app    total
100         November     Other  109
100         October      Other  235
100         September    Other  542
</code>```

But I am getting

```<code>newClientID Month        app    total
100         November     Other  109
100         October      Other  224
100         September    Other  146
100         October      Other  11
100         September    Other  396
</code>```

Why is it nor grouping the Month variable?

答:
Thank you. The newClientID had white spaces. I did the following to fix all the columns in the data set: </p>

```<code>test2<- data.frame(lapply(test2, function(x) if(class(x)=="character") trimws(x) else(x)), stringsAsFactors=F)
</code>```

Body:
Trying to summarize a data set, but it does not group the variables specified

Sample from the data set, test2

  newClientID   Month      newApp          count    app
  100           November    R              51       Other
  100           November    Tableau        58       Other
  100           October     R              12       Other
  100           October     Tableau        212      Other
  100           September   R              72       Other
  100           September   Tableau        74       Other
  100           October     SQL Assistant  11       Other
  100           September   SQL Assistant  396      Other

This should summarize the data

test3 <- test2 %>%
   group_by(newClientID, Month, app) %>%
   summarise(total = sum(count))

It should be like this

newClientID Month        app    total
100         November     Other  109
100         October      Other  235
100         September    Other  542

But I am getting

newClientID Month        app    total
100         November     Other  109
100         October      Other  224
100         September    Other  146
100         October      Other  11
100         September    Other  396

Why is it nor grouping the Month variable?

Body:
Thank you. The newClientID had white spaces. I did the following to fix all the columns in the data set:

test2<- data.frame(lapply(test2, function(x) if(class(x)=="character") trimws(x) else(x)), stringsAsFactors=F)


答:
I always find when looking at code I don't understand the best method is to rewrite it in a format which I find easier to read, in this case:

```<code>for (int i = 0; i < N; ++i) {
    if (!done[i]) {
        if (d[i] >= min_dist) {
            continue;
        }
        min_dist = d[i];
        v = i;
    }
}
</code>```

The fact that the if statement is beside the loop merely means that that is the expression to be resolved as the loop body (note this is always the case, blocks {} are also used). This if then has a body as well, by putting in the omitted blocks explicitly it is easier to see what is going on.

Body:
I always find when looking at code I don't understand the best method is to rewrite it in a format which I find easier to read, in this case:

for (int i = 0; i < N; ++i) {
    if (!done[i]) {
        if (d[i] >= min_dist) {
            continue;
        }
        min_dist = d[i];
        v = i;
    }
}

The fact that the if statement is beside the loop merely means that that is the expression to be resolved as the loop body (note this is always the case, blocks {} are also used). This if then has a body as well, by putting in the omitted blocks explicitly it is easier to see what is going on.


问:
Convert an Array of Bytes to IPAddress
.Net IPAddress class GetAddressBytes method can be used to convert an IPAddress to an array of bytes.

My problem is one I have these array of bytes, how do I convert them back to an IPAddress object, or an IP string??
(Its important to have a solution working for both IPv4 and IPv6).

答:
What andrey said</p>

```<code>    Dim ipv4Addr As Net.IPAddress = Net.IPAddress.Parse("224.0.0.1")
    Dim ipv6Addr As Net.IPAddress = Net.IPAddress.Parse("ff00:0:0:0:0:0:e000:1")

    Debug.WriteLine(ipv4Addr.ToString)
    Debug.WriteLine(ipv6Addr.ToString)

    Dim b() As Byte = ipv4Addr.GetAddressBytes
    ipv4Addr = New Net.IPAddress(b)

    b = ipv6Addr.GetAddressBytes
    ipv6Addr = New Net.IPAddress(b)

    Debug.WriteLine(ipv4Addr.ToString)
    Debug.WriteLine(ipv6Addr.ToString)
</code>```

Title: Convert an Array of Bytes to IPAddress

Body:
What andrey said

    Dim ipv4Addr As Net.IPAddress = Net.IPAddress.Parse("224.0.0.1")
    Dim ipv6Addr As Net.IPAddress = Net.IPAddress.Parse("ff00:0:0:0:0:0:e000:1")

    Debug.WriteLine(ipv4Addr.ToString)
    Debug.WriteLine(ipv6Addr.ToString)

    Dim b() As Byte = ipv4Addr.GetAddressBytes
    ipv4Addr = New Net.IPAddress(b)

    b = ipv6Addr.GetAddressBytes
    ipv6Addr = New Net.IPAddress(b)

    Debug.WriteLine(ipv4Addr.ToString)
    Debug.WriteLine(ipv6Addr.ToString)


问:
Jquery get content not working properly
So, my problem is I am using Jquery for a slider and whenever my slide changes I want to get some attribute data using Jquery. So, I am using this HTML code:

```<code>      <a href="#" data-caption="Nepal"><img src="img/01.jpg"></a>
      <a href="#" data-caption="Ghandruk"><img src="img/01.jpg"></a>
      <a href="#" data-caption="thriller!"><img src="img/01.jpg"></a>
      <a href="#" data-caption="Himalayas!"><img src="img/01.jpg"></a>
      <a href="#" data-caption="Beautiful"><img src="img/01.jpg"></a>
      <a href="#" data-caption="Chhomrong"><img src="img/01.jpg"></a>
</code>```

So, when any one of these images is active it automatically gets a class named active so, I am trying to use this Jquery to get that active class so, that I can do some work according to the current slide

```<code>      var x = (($("a.active").data("data-caption")));
</code>```

:

答:
Take the 'data-' off of the key. data() puts it on there for you when it looks it up.

```<code>$("a.active").data("caption")
</code>```

console.log($('a.active').data('caption'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="img/01.jpg"></code>```

ContentLicense: CC BY-SA 4.0

Title: Jquery get content not working properly

Body:
So, my problem is I am using Jquery for a slider and whenever my slide changes I want to get some attribute data using Jquery. So, I am using this HTML code:

So, when any one of these images is active it automatically gets a class named active so, I am trying to use this Jquery to get that active class so, that I can do some work according to the current slide

      var x = (($("a.active").data("data-caption")));

:

Body:
Take the 'data-' off of the key. data() puts it on there for you when it looks it up.

$("a.active").data("caption")

console.log($('a.active').data('caption'));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" data-caption="Himalayas!" class="active"><img src="img/01.jpg"></a>


问:
Adding Values to a List Separately
I am a beginner to Python and just programming in general so this will probably have a very obvious answer to everyone here.

So - I am currently trying to make hangman however I have run into an issue with the display. I am trying to add underscores to a list, with each underscore being in it's own string. I am doing this with

```<code>targetWord = ["_ " * len(answer)]
</code>```

answer is the word being searched for

targetWord is what the user sees (e.g. app_e)

However instead of adding say, 5 strings with each string containing 1 underscore, 1 string is being added with 5 underscores.

The output is ["_ _ _ _ _ "]

The output should be ["_ ","_ ","_ ","_ ","_ "]

All help is appreciated :)

答:
Move the multiplication outside of the list:</p>

```<code>targetWord = ["_ " * len(answer)]  # no
targetWord = ["_ "] * len(answer)  # yes
</code>```

Title: Adding Values to a List Separately

Body:
I am a beginner to Python and just programming in general so this will probably have a very obvious answer to everyone here.

So - I am currently trying to make hangman however I have run into an issue with the display. I am trying to add underscores to a list, with each underscore being in it's own string. I am doing this with

targetWord = ["_ " * len(answer)]

answer is the word being searched for

targetWord is what the user sees (e.g. app_e)

However instead of adding say, 5 strings with each string containing 1 underscore, 1 string is being added with 5 underscores.

The output is ["_ _ _ _ _ "]

The output should be ["_ ","_ ","_ ","_ ","_ "]

All help is appreciated :)

Body:
Move the multiplication outside of the list:

targetWord = ["_ " * len(answer)]  # no
targetWord = ["_ "] * len(answer)  # yes


问:
Inserting values to an empty multidim. numpy array
I need to create an empty numpy array of a shape (?, 10, 10, 3). ? means I don't know how many elements will be inserted. Then I have many numpy arrays of a shape (1, 10, 10, 3) which I want to be inserted to the prepared array one by one, so the ? mark will be increasing with inserted elements.

I'm trying all variations of numpy array methods like empty, insert, concatenate, append... but I'm not able to achieve this. Could you please give me a hand with this?

答:
Using np.append works:

```<code>import numpy as np

mat = np.empty((0,10,10,3))

array = np.random.rand(1,10,10,3)

mat = np.append(mat, array, axis=0)
mat = np.append(mat, array, axis=0)

print(mat.shape)

>>>(2,10,10,3)
</code>```

Body:
Using np.append works:

import numpy as np

mat = np.empty((0,10,10,3))

array = np.random.rand(1,10,10,3)

mat = np.append(mat, array, axis=0)
mat = np.append(mat, array, axis=0)

print(mat.shape)

>>>(2,10,10,3)


问:
Is it possible to install ipa from my site without udid?
I am going to build website where users can download my ipa without asking udid.

I saw that TestFlight App can implement this feature. but I don't want installing "testflight" app to users.

I heard that enterprise developer program or  B-2-B App Store is the way.
But I don't know it is exact.

It's possible? Is there any other method? How can I do this?

Please help.

答:
This depends whether you're making an internal app for your organization and its employees, or if you want to distribute an app to anyone in the general public.

For Android distribution you can post the file publicly online & anyone, anywhere can download and install it if they allow their device to do so. This is not possible with iOS apps for security.

Your options for apps aimed at the general public are:

The public App Store

Test Flight w/user emails
--  (up to 10K users; 90 days per build; minimal internal testing of a few dozen users; external test builds must pass App Store review first)

"Hockey App" which will soon become Microsoft's "App Center" allows for test builds and distribution as well.

Collect and manage individual UDIDs for manual testing (the "old school approach", also limited # of devices per category).

If your app is for internal, organizational use by a restricted group of employees, you can publish to an internal "App Store" setup w/your Mobile Device Management system (Citrix SecureHub, XenMobile), or post the .ipa file to a company web server as detailed in this article. No Apple/App Store review is required.

This requires being a member of Apple's Enterprise Developer Program and signing your apps with the Enterprise Developer Certificate. This program is a separate, more expensve ($299/yr) cost/subscription designed for organizations to publish/distribute "in-house" apps solely for use by their employees.

Users who then install your app from the company web server must "Manually Trust an Enterprise Developer" as explained in Apple's docs on distributing in-house/ad-hoc apps.

EDIT:
As you mentioned, there's also the "B2B" route for, it seems, a regular non-enterprise developer, but this also requires that your end user be a business with a MDM setup or redemption codes purchased as part of a corporate "Volume Purchase Program." Still doesn't work to just post the .ipa online as you're hoping.
See this description & WWDC video if you're interested in this route.
Also, this question is essentially a duplicate of this earlier question...


问:
InputStream read(byte[] b, int off, int len) - Drop the rest of the file?
This is an extension of a question I asked on here this morning so please don't disregard if you think you've seen this code before :D

```<code>for (String name : filenames) {
FileInputStream in = new FileInputStream(input.readUTF());
    int byteCounter = 0;
    int rowCounter = 0;
    long bufferCounter = 0;
    byte[] b = new byte[10];
    int read;

    //in.skip(10);
    //while((read = in.read()) != -1){
    while((read = in.read(b, 0, 10)) != -1){
        byteCounter ++;
        if (byteCounter != 1000){
            if (rowCounter == 1){
                System.out.println("\n");
                rowCounter = 0;
            }
        System.out.print(org.apache.commons.codec.binary.Hex.encodeHexString(b));
            bufferCounter ++;
            rowCounter ++;
        }else{
                byteCounter = 0;
                try{
                    Thread.sleep(200);
                }catch(InterruptedException e) {
                }
        }
    }
    System.out.println("\n"+"================"+"\n");
}
</code>```

Hi there, after hours of struggling to get this code to how it is, I've almost finished the particular component that I am working on. The program takes in a specified file and is supposed to convert the first 10 bytes of that file into Hex. Once it has acquired the first 10 bytes of that file, it should stop and move onto the next specified file. Currently, it takes the entirety of the file and divides it into multiple 10 byte 'chunks' which it then prints out. In other words, it isn't stopping after the first 10 bytes which  I thought read(byte[] b, int off, int len) did

Example output:

74656173676173677361

67616773617367616773

61676173617367616773

but instead it should produce

74656173676173677361

Any advice would be hugely appreciated it and I really do mean that :)

答:
You have a while loop inside your outer for loop (  while((read = in.read(b, 0, 10)) != -1)  ) that is cycling through all of the bytes in the whole file.

Try a simple for(int i = 0; i < 10; i++)  that reads a single byte from in, and converts those to hex.

And don't forget to close your files and input streams in a finally{} clause!

Body:
This is an extension of a question I asked on here this morning so please don't disregard if you think you've seen this code before :D

for (String name : filenames) {
FileInputStream in = new FileInputStream(input.readUTF());
    int byteCounter = 0;
    int rowCounter = 0;
    long bufferCounter = 0;
    byte[] b = new byte[10];
    int read;

    //in.skip(10);
    //while((read = in.read()) != -1){
    while((read = in.read(b, 0, 10)) != -1){
        byteCounter ++;
        if (byteCounter != 1000){
            if (rowCounter == 1){
                System.out.println("\n");
                rowCounter = 0;
            }
        System.out.print(org.apache.commons.codec.binary.Hex.encodeHexString(b));
            bufferCounter ++;
            rowCounter ++;
        }else{
                byteCounter = 0;
                try{
                    Thread.sleep(200);
                }catch(InterruptedException e) {
                }
        }
    }
    System.out.println("\n"+"================"+"\n");
}

Hi there, after hours of struggling to get this code to how it is, I've almost finished the particular component that I am working on. The program takes in a specified file and is supposed to convert the first 10 bytes of that file into Hex. Once it has acquired the first 10 bytes of that file, it should stop and move onto the next specified file. Currently, it takes the entirety of the file and divides it into multiple 10 byte 'chunks' which it then prints out. In other words, it isn't stopping after the first 10 bytes which  I thought read(byte[] b, int off, int len) did

Example output:

74656173676173677361

67616773617367616773

61676173617367616773

but instead it should produce

74656173676173677361

Any advice would be hugely appreciated it and I really do mean that :)


问:
How do I Scroll parent page to top when child page is click within iframe?
When someone clicks on a link within an iframe (child page), how do I get the parent page to scroll to the top? The issue is the child page will remain in the same spot of the page, because the iframe has a lot of height larger than the parent page.

Please note: the parent and child pages are on different sub domains.

I created a demo to show this:
http://www.apus.edu/_test/iframe/index.htm

答:
If you have cross origins (the iframe and the parent have different domains), then just calling window.scrollTo(0,0) won't work.

One solution to cross-origin is to send a trusted message from the iframe to the parent.

Code inside the iframe:

```<code>var parent_origin = 'http://your/iframe/domain/here'
parent.postMessage({'task': 'scroll_top'}, parent_origin);
</code>```

Then code in the parent:

```<code>function handleMessage(event) {
    var accepted_origin = 'http://your/iframe/domain/here';
    if (event.origin == accepted_origin){
        if (event.data['task'] == 'scroll_top'){
           window.scrollTo(0,0);
        }
        // you can have more tasks
    } else{
        console.error('Unknown origin', event.origin);
    }
}

window.onload = function() {
    window.addEventListener("message", handleMessage, false);
}
</code>```

Body:
If you have cross origins (the iframe and the parent have different domains), then just calling window.scrollTo(0,0) won't work.

One solution to cross-origin is to send a trusted message from the iframe to the parent.

Code inside the iframe:

var parent_origin = 'http://your/iframe/domain/here'
parent.postMessage({'task': 'scroll_top'}, parent_origin);

Then code in the parent:

function handleMessage(event) {
    var accepted_origin = 'http://your/iframe/domain/here';
    if (event.origin == accepted_origin){
        if (event.data['task'] == 'scroll_top'){
           window.scrollTo(0,0);
        }
        // you can have more tasks
    } else{
        console.error('Unknown origin', event.origin);
    }
}

window.onload = function() {
    window.addEventListener("message", handleMessage, false);
}


问:
Is it possible to display numeric keyboard for Messenger Platform?
I am developing a bot using the Messenger Platform with Node.js. Sometimes the user need to provide an information based only on numbers. Is there a way to display the numeric keyboard in this situation?</p>

答: Specifying the keyboard type is not supported.</p>


问:
How can I convert char pointer to __uint8_t array in C?
I need to convert a string (char*) to an array of __uint8_t. I know the latter is an alias of unsigned char but I can't figure it out how to proper convert it.

Example:

```<code>char *ssid = "XXXXX";
</code>```

This is need cause I have to call an API that accepts only an array of __uint8_t and not char*.

```<code>struct WifiConfig {
    uint8_t ssid[32];
    uint8_t password[64];
};

struct WifiConfig wifi_config;
wifi_config.ssid = ???
</code>```

If I try to cast:

```<code>wifi_config.ssid = (__uint8_t *) ssid;
</code>```

I get the follow error:

```<code>error: assignment to expression with array type
     wifi_config.ssid = (__uint8_t *) ssid;
</code>```

Sorry if that's a silly question, last time I've played with C I was a teen.

Thanks in advance!

答:
I need to convert a string (char*) to an array of __uint8_t. I know
  the latter is an alias of unsigned char but I can't figure it out how
  to proper convert it.

Being pedantic -- because it matters here -- a C string is not a char *.  Rather, it is a null-terminated array of char.  These are accessed and handled primarily via pointers of type char *, largely because that's how one works with arrays in C.

Thus, no, you do not want to convert a char * to an array.  It appears that what you want to do is copy the contents of the array to which it points.  For your particular purpose I would use the strncpy() function:

```<code>strncpy((char *) wifi_config.ssid, ssid, sizeof(wifi_config.ssid));
</code>```

Note well that with that code, if ssid is longer than wifi_config.ssid can accommodate then the latter will end up being unterminated, and that otherwise its tail will be filled out with null bytes.  Given the type of that array, such behavior may be precisely what is needed.  If you want to ensure null termination, however, then simply overwrite the last byte of the array with a 0 after the strncpy().

Body:
I need to convert a string (char*) to an array of __uint8_t. I know the latter is an alias of unsigned char but I can't figure it out how to proper convert it.

Example:

char *ssid = "XXXXX";

This is need cause I have to call an API that accepts only an array of __uint8_t and not char*.

struct WifiConfig {
    uint8_t ssid[32];
    uint8_t password[64];
};

struct WifiConfig wifi_config;
wifi_config.ssid = ???

If I try to cast:

wifi_config.ssid = (__uint8_t *) ssid;

I get the follow error:

error: assignment to expression with array type
     wifi_config.ssid = (__uint8_t *) ssid;

Sorry if that's a silly question, last time I've played with C I was a teen.

Thanks in advance!

Body:
I need to convert a string (char*) to an array of __uint8_t. I know
  the latter is an alias of unsigned char but I can't figure it out how
  to proper convert it.

Being pedantic -- because it matters here -- a C string is not a char *.  Rather, it is a null-terminated array of char.  These are accessed and handled primarily via pointers of type char *, largely because that's how one works with arrays in C.

Thus, no, you do not want to convert a char * to an array.  It appears that what you want to do is copy the contents of the array to which it points.  For your particular purpose I would use the strncpy() function:

strncpy((char *) wifi_config.ssid, ssid, sizeof(wifi_config.ssid));

Note well that with that code, if ssid is longer than wifi_config.ssid can accommodate then the latter will end up being unterminated, and that otherwise its tail will be filled out with null bytes.  Given the type of that array, such behavior may be precisely what is needed.  If you want to ensure null termination, however, then simply overwrite the last byte of the array with a 0 after the strncpy().


问:
Angular 4 string parameters
I'm a touch stumped on why my input parameters are being turned into numbers.
I have this component:

```<code>import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-tile',
  templateUrl: './tile.component.html',
  styleUrls: ['./tile.component.css']
})
export class TileComponent implements OnInit {
  @Input() icon1: string;
  @Input() headerText1: string;
  @Input() mainText: string;
  @Input() footerText: string;

  constructor() { }

  ngOnInit() {
  }

}
</code>```

and the template:

```<code><div class="widget widget-stats bg-green">
  <div *ngIf="icon1" class="stats-icon"><i class="fa {{icon1}}"></i></div>
  <div class="stats-info">
      <h4>Header - {{headerText1}}</h4>
      <p>Icon - {{icon1}}</p>
      <p>Main - {{mainText}}</p>
      <p>Footer - {{footerText}}</p>
  </div>
</div>
</code>```

Passing these this from another component works:

```<code><app-tile [headerText1]="43543" [mainText]="123456" [footerText]="243542354235" [icon1]="999"></app-tile>
</code>```

But I want this:

```<code><app-tile [headerText1]="TOTAL VISITORS" [mainText]="93%" [footerText]="243542354235" [icon1]="fa-users"></app-tile>
</code>```

headerText1 fails at compile time because there's a space and if I remove it the value is never displayed and icon1 show NaN.

Why would these be treated as numbers when I've clearly defined them as strings?

答:
If I understand your question correctly, to pass string literals try adding single quotes within the double quotes, an expression, like this:

```<code><app-tile [headerText1]="'TOTAL VISITORS'" [mainText]="'93%'"
</code>```

Title: Angular 4 string parameters

Body:
I'm a touch stumped on why my input parameters are being turned into numbers.
I have this component:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-tile',
  templateUrl: './tile.component.html',
  styleUrls: ['./tile.component.css']
})
export class TileComponent implements OnInit {
  @Input() icon1: string;
  @Input() headerText1: string;
  @Input() mainText: string;
  @Input() footerText: string;

  constructor() { }

  ngOnInit() {
  }

}

and the template:

Header - {{headerText1}}

Icon - {{icon1}}

Main - {{mainText}}

Footer - {{footerText}}

Passing these this from another component works:

<app-tile [headerText1]="43543" [mainText]="123456" [footerText]="243542354235" [icon1]="999"></app-tile>

But I want this:

<app-tile [headerText1]="TOTAL VISITORS" [mainText]="93%" [footerText]="243542354235" [icon1]="fa-users"></app-tile>

headerText1 fails at compile time because there's a space and if I remove it the value is never displayed and icon1 show NaN.

Why would these be treated as numbers when I've clearly defined them as strings?

Body:
If I understand your question correctly, to pass string literals try adding single quotes within the double quotes, an expression, like this:

<app-tile [headerText1]="'TOTAL VISITORS'" [mainText]="'93%'"


问:
MsgBox within an If statement not working
I'm trying to use the following code to open a password protected file if the Windows user is "bhope" or "jdean" and display a message box if the user is anyone else. It opens the file as needed when the user is "bhope" or "jdean" but if another user clicks the button, nothing happens/no error. What am I missing?

```<code>Sub Button1_Click()

Dim wb As Workbook
Dim strUser As String
strUser = Environ("USERNAME")

  Application.ScreenUpdating = False

  Select Case strUser

    ' Full Workbook Access
    Case Is = "bhope", "jdean"
       If ActiveWorkbook.ReadOnly Then _
          Set wb = Workbooks.Open(Filename:="M:\...", Password:="TEST")

    ' Limit Access
    Case Is = "mjackson" 'also tried "Case Is <> "bhope", "jdean"
       If Not ActiveWorkbook.ReadOnly Then _
          MsgBox ("This button is reserved for SAMs")
  End Select

  Application.ScreenUpdating = True
End Sub
</code>```

If it helps, I used this link to start the base of the code and tried to modify it from there. Thanks and cheers!

答:
Your use of IS here may be the culprit. At best it's superfluous, at worse it's masking this issue. Instead try:

```<code>Sub Button1_Click()

Dim wb As Workbook
Dim strUser As String
strUser = Environ("USERNAME")

  Application.ScreenUpdating = False

  Select Case strUser

    ' Full Workbook Access
    Case "bhope", "jdean"
       If ActiveWorkbook.ReadOnly Then _
          Set wb = Workbooks.Open(Filename:="M:\...", Password:="TEST")

    ' Limit Access
    Case "mjackson"
       If Not ActiveWorkbook.ReadOnly Then _
          MsgBox ("This button is reserved for SAMs")
  End Select

  Application.ScreenUpdating = True
End Sub
</code>```

Also consider changing that second CASE to CASE ELSE.

The other thing is that your msgbox is inside of your IF condition. strUser must be uqual to mjackson AND the ActiveWorkbook (whatever that might be at the time this code executes) must NOT be ReadOnly for that msgbox to fire.

Consider changing "ActiveWorkbook" to be more specific. Perhaps ThisWorkbook.ReadOnly?

Consider an Else for your if statement to see if the mjackson is hitting but the readonly is not:

```<code>Case "mjackson"
   If Not ActiveWorkbook.ReadOnly Then
      MsgBox ("This button is reserved for SAMs")
   Else
      MsgBox ("ActiveWorkbook is not Read Only so yo get this message")
   End If
</code>```

Lastly, put a breakpoint (F9) on SELECT and see what your value of strUser as while the code is running (hover over strUSer on that line or check your Locals pane). You may also want to see what ActiveWorkbook is at this point of time too, just in case. The answer will, again, be in your Locals pane, so make sure that is turned on in the view drop down of VBE.

Body:
I'm trying to use the following code to open a password protected file if the Windows user is "bhope" or "jdean" and display a message box if the user is anyone else. It opens the file as needed when the user is "bhope" or "jdean" but if another user clicks the button, nothing happens/no error. What am I missing?

Sub Button1_Click()

Dim wb As Workbook
Dim strUser As String
strUser = Environ("USERNAME")

  Application.ScreenUpdating = False

  Select Case strUser

    ' Full Workbook Access
    Case Is = "bhope", "jdean"
       If ActiveWorkbook.ReadOnly Then _
          Set wb = Workbooks.Open(Filename:="M:\...", Password:="TEST")

    ' Limit Access
    Case Is = "mjackson" 'also tried "Case Is <> "bhope", "jdean"
       If Not ActiveWorkbook.ReadOnly Then _
          MsgBox ("This button is reserved for SAMs")
  End Select

  Application.ScreenUpdating = True
End Sub

If it helps, I used this link to start the base of the code and tried to modify it from there. Thanks and cheers!

Body:
Your use of IS here may be the culprit. At best it's superfluous, at worse it's masking this issue. Instead try:

Sub Button1_Click()

Dim wb As Workbook
Dim strUser As String
strUser = Environ("USERNAME")

  Application.ScreenUpdating = False

  Select Case strUser

    ' Full Workbook Access
    Case "bhope", "jdean"
       If ActiveWorkbook.ReadOnly Then _
          Set wb = Workbooks.Open(Filename:="M:\...", Password:="TEST")

    ' Limit Access
    Case "mjackson"
       If Not ActiveWorkbook.ReadOnly Then _
          MsgBox ("This button is reserved for SAMs")
  End Select

  Application.ScreenUpdating = True
End Sub

Also consider changing that second CASE to CASE ELSE.

The other thing is that your msgbox is inside of your IF condition. strUser must be uqual to mjackson AND the ActiveWorkbook (whatever that might be at the time this code executes) must NOT be ReadOnly for that msgbox to fire.

Consider changing "ActiveWorkbook" to be more specific. Perhaps ThisWorkbook.ReadOnly?

Consider an Else for your if statement to see if the mjackson is hitting but the readonly is not:

Case "mjackson"
   If Not ActiveWorkbook.ReadOnly Then
      MsgBox ("This button is reserved for SAMs")
   Else
      MsgBox ("ActiveWorkbook is not Read Only so yo get this message")
   End If

Lastly, put a breakpoint (F9) on SELECT and see what your value of strUser as while the code is running (hover over strUSer on that line or check your Locals pane). You may also want to see what ActiveWorkbook is at this point of time too, just in case. The answer will, again, be in your Locals pane, so make sure that is turned on in the view drop down of VBE.


问:
NotSupportedException get_HasShutdownStarted - "This icall is not supported by il2cpp
I'm getting the following exception from my iOS App (Which was build with Unity3d):

```<code>NotSupportedException: /Users/builduser/buildslave/unity/build/External/il2cpp/il2cpp/libil2cpp/icalls/mscorlib/System/Environment.cpp(166) : Unsupported internal call for IL2CPP:Environment::get_HasShutdownStarted - "This icall is not supported by il2cpp
</code>```

This is the C# stackstrace that I have:

```<code>System.Threading.ThreadPoolWorkQueueThreadLocals.Finalize () (at <00000000000000000000000000000000>:0)
System.UnhandledExceptionEventHandler:Invoke(Object, UnhandledExceptionEventArgs)
</code>```

Anything I can do?

答:
this bug is still present in 2017.2.0p3.

NotSupportedException: /Users/builduser/buildslave/unity/build/External/il2cpp/il2cpp/libil2cpp/icalls/mscorlib/System/Environment.cpp(166) : Unsupported internal call for IL2CPP:Environment::get_HasShutdownStarted - "This icall is not supported by il2cpp

Body:
I'm getting the following exception from my iOS App (Which was build with Unity3d):

NotSupportedException: /Users/builduser/buildslave/unity/build/External/il2cpp/il2cpp/libil2cpp/icalls/mscorlib/System/Environment.cpp(166) : Unsupported internal call for IL2CPP:Environment::get_HasShutdownStarted - "This icall is not supported by il2cpp

This is the C# stackstrace that I have:

System.Threading.ThreadPoolWorkQueueThreadLocals.Finalize () (at <00000000000000000000000000000000>:0)
System.UnhandledExceptionEventHandler:Invoke(Object, UnhandledExceptionEventArgs)

Anything I can do?


问:
Does -XX:+CMSClassUnloadingEnabled work with the -XX:+UseSerialGC option in Java 8?
It's all in the question. The more information on the matter, the better. I'm having issues in an application where it seems like my class space is never being GC'd, hence running me out of memory on a 512m Heroku dyno.</p>

答: CMSClassUnloadingEnabled refers to CMS, the ConcurrentMarkSweep collector, which is not the serial collector which you select via UseSerialGC. There is a more general setting ClassUnloading, which defaults to true and thus does not need to be set explicitly.


问:
Comparing two integers without any comparison
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

```<code>if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";
</code>```

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

答:
Not one of the samples presented in the question or any of the answers thus far protects from division by zero.  Why on earth are you trying to avoid an 'if' statement?  I suspect homework question about ?: operators.

```<code>cout << "Maximum is: " << ((a>b)?a:b)
</code>```

There we go.

It's not possible to compare two numbers without a comparison.  You can fudge it and do an indirect operation, but at the end of the day you're comparing something.  Trust the compiler to optimize the code and select the best operations.

OwnerDisplayName: kvphxga

Body:
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

LastEditorDisplayName: kvphxga

Body:
Not one of the samples presented in the question or any of the answers thus far protects from division by zero.  Why on earth are you trying to avoid an 'if' statement?  I suspect homework question about ?: operators.

cout << "Maximum is: " << ((a>b)?a:b)

There we go.

It's not possible to compare two numbers without a comparison.  You can fudge it and do an indirect operation, but at the end of the day you're comparing something.  Trust the compiler to optimize the code and select the best operations.

OwnerDisplayName: Adam Hawes


问:
strncpy documentation question
At the following regarding strncpy: http://www.cplusplus.com/reference/clibrary/cstring/strncpy/, it mentions the following:

No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num.

What is meant by this sentence?

答:
It means that only num bytes will be copied from the source buffer to the destination buffer; so if the source string length if upper or equal to num, the terminating NULL byte will not be copied, and the result will not have a NULL terminating byte, which is dangerous.

It is recommended to use strlcpy instead.

Title: strncpy documentation question


问:
Circleci deployment to Google Container Engine
I manage to push my image to Google cloud registry but when I try to rolling upgrade my cluster nothing happen.

I check my pods and they are not restarted.

I think I'm missing a command to force the rolling upgrade but I can't found help into the circle ci documentation which is really low: https://circleci.com/docs/2.0/google-container-engine/

my circle.yml:

```<code>version: 2

jobs:
   build:
     docker:
       - image: google/cloud-sdk:latest
     steps:

        - checkout

        - run:
            name: Install Docker client
            command: |
              set -x
              VER="17.03.0-ce"
              curl -L -o /tmp/docker-$VER.tgz https://get.docker.com/builds/Linux/x86_64/docker-$VER.tgz
              tar -xz -C /tmp -f /tmp/docker-$VER.tgz
              mv -f /tmp/docker/* /usr/bin

        - run:
            name: Install Docker Compose
            command: |
              set -x
              curl -L https://github.com/docker/compose/releases/download/1.11.2/docker-compose-`uname -s`-`uname -m` > /tmp/docker-compose
              mv -f /tmp/docker-compose /usr/local/bin/docker-compose
              chmod +x /usr/local/bin/docker-compose

        - type: setup-docker-engine

        - run:
            name: Build Docker image
            command: |
              docker build -t eu.gcr.io/${GOOGLE_PROJECT_ID}/gcp-test:latest .

        - run:
            name: Dump Google Cloud Credentials to file
            command: |
              echo ${GOOGLE_AUTH} > ${HOME}/gcp-key.json
              gcloud auth activate-service-account --key-file ${HOME}/gcp-key.json
              gcloud --quiet config set project ${GOOGLE_PROJECT_ID}
              gcloud --quiet config set compute/zone ${GOOGLE_COMPUTE_ZONE}
              gcloud --quiet container clusters get-credentials ${GOOGLE_CLUSTER_NAME}

        - run:
            name: Push the image to google registry
            command: |
              gcloud docker -- push eu.gcr.io/${GOOGLE_PROJECT_ID}/gcp-test:latest

        - run:
            name: Deploy image to the gc cluster
            command: |
              kubectl apply -f deployment.yml
              kubectl apply -f service.yml
              kubectl set image deployment/solive-deployment node-app=eu.gcr.io/${GOOGLE_PROJECT_ID}/gcp-test:latest
              kubectl get deployments
              kubectl get pods
</code>```

答:
Pods do not restart when you do kubectl apply -f deployment.yml, but the image they are running on will be updated (the container will be stopped and started with the new image).

In my experience it is not necessary to update the service or to set image.

Note that my answer shouldn't be taken for granted as I am far from an expert in Kubernetes.

Body:
I manage to push my image to Google cloud registry but when I try to rolling upgrade my cluster nothing happen.

I check my pods and they are not restarted.

I think I'm missing a command to force the rolling upgrade but I can't found help into the circle ci documentation which is really low: https://circleci.com/docs/2.0/google-container-engine/

my circle.yml:

version: 2

jobs:
   build:
     docker:
       - image: google/cloud-sdk:latest
     steps:

        - checkout

        - run:
            name: Install Docker client
            command: |
              set -x
              VER="17.03.0-ce"
              curl -L -o /tmp/docker-$VER.tgz https://get.docker.com/builds/Linux/x86_64/docker-$VER.tgz
              tar -xz -C /tmp -f /tmp/docker-$VER.tgz
              mv -f /tmp/docker/* /usr/bin

        - run:
            name: Install Docker Compose
            command: |
              set -x
              curl -L https://github.com/docker/compose/releases/download/1.11.2/docker-compose-`uname -s`-`uname -m` > /tmp/docker-compose
              mv -f /tmp/docker-compose /usr/local/bin/docker-compose
              chmod +x /usr/local/bin/docker-compose

        - type: setup-docker-engine

        - run:
            name: Build Docker image
            command: |
              docker build -t eu.gcr.io/${GOOGLE_PROJECT_ID}/gcp-test:latest .

        - run:
            name: Dump Google Cloud Credentials to file
            command: |
              echo ${GOOGLE_AUTH} > ${HOME}/gcp-key.json
              gcloud auth activate-service-account --key-file ${HOME}/gcp-key.json
              gcloud --quiet config set project ${GOOGLE_PROJECT_ID}
              gcloud --quiet config set compute/zone ${GOOGLE_COMPUTE_ZONE}
              gcloud --quiet container clusters get-credentials ${GOOGLE_CLUSTER_NAME}

        - run:
            name: Push the image to google registry
            command: |
              gcloud docker -- push eu.gcr.io/${GOOGLE_PROJECT_ID}/gcp-test:latest

        - run:
            name: Deploy image to the gc cluster
            command: |
              kubectl apply -f deployment.yml
              kubectl apply -f service.yml
              kubectl set image deployment/solive-deployment node-app=eu.gcr.io/${GOOGLE_PROJECT_ID}/gcp-test:latest
              kubectl get deployments
              kubectl get pods


问:
@ControllerAdvice Spring - Return type as a custom object and not ModelAndView
I've been tasked to expose the exceptions thrown from the @RequestMapping methods in controllers to the UI as JSON objects. While googling, I found out about ControllerAdvice and I guess I need something similar to that. The only problem that I see in all the examples is the return type - they are returning ModelAndView whereas I need to return a custom object as return type. Here is my sample code:

Controller class:

```<code>@RequestMapping(value="/abc", method=RequestMethod.GET)
@ResponseBody
public MyModel getResponse(@RequestParam String id,
                            HttpServletRequest request) throws SQLException
   {
    boolean exceptionFlag = true;
         if (exceptionFlag){
        throw new SQLException();
    }
     return myModel;
  }
</code>```

ExceptionHandlerClass:

```<code>@ControllerAdvice
public class ExceptionHandler {
        @ExceptionHandler(SQLException.class)
        public MyCustomException handleSQLException(SQLException exception)
        {
            MyCustomException ex = new MyCustomException();
            ex.setExceptionCode("MyCode");
            ex.setExceptionDescription(exception.getMessage());
            return ex;
        }
</code>```

It complains that it couldn't find the JSP (WARN:org.apache.jasper.servlet.JspServlet:PWC6117: File "rest\support\abc.jsp" not foundnull)

答:
You probably want to wrap your exception inside of a ResponseEntity<T>, so that you can also return an HttpStatus code along with the json body.

```<code>@ControllerAdvice
@RequestMapping(produces = "application/json")
@ResponseBody
public class RestControllerAdvice {

    @ExceptionHandler(EntityNotFoundException .class)
    public ResponseEntity<Map<String,Object>> notFoundException(final EntityNotFoundException e) {

        Map<String,Object> errorInfo = new HashMap<>();
        errorInfo.put("error message",e.getMessage());
        errorInfo.put("timestamp", new Date());
        return new ResponseEntity<Map<String,Object>>(errorInfo, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(QueryParameterNotSupportedException.class)
    public ResponseEntity<Map<String,Object>> unrecognizedParameter(final QueryParameterNotSupportedException e) {

        Map<String,Object> errorInfo = new LinkedHashMap<>();
        errorInfo.put("timestamp", new Date());
        errorInfo.put("errorMessage",e.getMessage());
        errorInfo.put("allowableParameters",e.getValidArgs());

        return new ResponseEntity<Map<String,Object>>(errorInfo, HttpStatus.BAD_REQUEST);

    }
</code>```

In the example above the type "T"  is a Map<String,Object> , but it can be any type that is serializable by Jackson.  Also, notice there is a class level @ResponseBody annotation present, which instructs spring to convert the return methods of every method in the class to json before returning.

Body:
I've been tasked to expose the exceptions thrown from the @RequestMapping methods in controllers to the UI as JSON objects. While googling, I found out about ControllerAdvice and I guess I need something similar to that. The only problem that I see in all the examples is the return type - they are returning ModelAndView whereas I need to return a custom object as return type. Here is my sample code:

Controller class:

@RequestMapping(value="/abc", method=RequestMethod.GET)
@ResponseBody
public MyModel getResponse(@RequestParam String id,
                            HttpServletRequest request) throws SQLException
   {
    boolean exceptionFlag = true;
         if (exceptionFlag){
        throw new SQLException();
    }
     return myModel;
  }

ExceptionHandlerClass:

@ControllerAdvice
public class ExceptionHandler {
        @ExceptionHandler(SQLException.class)
        public MyCustomException handleSQLException(SQLException exception)
        {
            MyCustomException ex = new MyCustomException();
            ex.setExceptionCode("MyCode");
            ex.setExceptionDescription(exception.getMessage());
            return ex;
        }

It complains that it couldn't find the JSP (WARN:org.apache.jasper.servlet.JspServlet:PWC6117: File "rest\support\abc.jsp" not foundnull)

Body:
You probably want to wrap your exception inside of a ResponseEntity<T>, so that you can also return an HttpStatus code along with the json body.

@ControllerAdvice
@RequestMapping(produces = "application/json")
@ResponseBody
public class RestControllerAdvice {

    @ExceptionHandler(EntityNotFoundException .class)
    public ResponseEntity<Map<String,Object>> notFoundException(final EntityNotFoundException e) {

        Map<String,Object> errorInfo = new HashMap<>();
        errorInfo.put("error message",e.getMessage());
        errorInfo.put("timestamp", new Date());
        return new ResponseEntity<Map<String,Object>>(errorInfo, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(QueryParameterNotSupportedException.class)
    public ResponseEntity<Map<String,Object>> unrecognizedParameter(final QueryParameterNotSupportedException e) {

        Map<String,Object> errorInfo = new LinkedHashMap<>();
        errorInfo.put("timestamp", new Date());
        errorInfo.put("errorMessage",e.getMessage());
        errorInfo.put("allowableParameters",e.getValidArgs());

        return new ResponseEntity<Map<String,Object>>(errorInfo, HttpStatus.BAD_REQUEST);

    }

In the example above the type "T"  is a Map<String,Object> , but it can be any type that is serializable by Jackson.  Also, notice there is a class level @ResponseBody annotation present, which instructs spring to convert the return methods of every method in the class to json before returning.


问:
JSON object from Stringified value
Here is my very simple C# class object that I am trying to turn into a JSON string and stringifying:

```<code>public class rTestObject
{
    public rTestObject()
    {
        Name = "Hello";
        State = 7;
    }

    public string Name { get; set; }
    public int State { get; set; }
}
</code>```

I call the following static method:

```<code>    // Json.net
    // from Newtonsoft.Json.dll
    // version 8.0.2.19309
    //

    using Newtonsoft.Json;
    public static string ConvertToJSON<T>(T obj)
    {
        return JsonConvert.SerializeObject(obj);
    }
</code>```

Which produces the following (expected) output:

```<code>    {"Name":"Hello","State":7}
</code>```

I call the following static method to stringify my JSON string

```<code>    public static string Stringify(string json)
    {
        return JsonConvert.ToString(json);
    }
</code>```

Which produces the following (I think this is expected ??) output:

```<code>    "{\"Name\":\"Hello\",\"State\":7}"
</code>```

My question how do I get from:

```<code>    "{\"Name\":\"Hello\",\"State\":7}"
</code>```

back to rTestObject?

Here is what I have tried:

TRY 1

```<code>    public static T ConvertFromStringifiedJSON<T>(string stringifiedJSON)
    {
        Newtonsoft.Json.Linq.JObject j = Newtonsoft.Json.Linq.JObject.Parse(stringifiedJSON);
        return ConvertFromJSON<T>(j.ToString());
    }
</code>```

Here is the exception:

```<code>    {"Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 34."}
</code>```

TRY 2

```<code>    public static T ConvertFromJSON<T>(string jsonNotation)
    {
        return JsonConvert.DeserializeObject<T>(jsonNotation, NoNullStrings);
    }
</code>```

Here is the exception:

```<code>    {"Error converting value \"{\"Name\":\"Hello\",\"State\":7}\" to type 'RestApi.Objects.rTestObject'. Path '', line 1, position 34."}
</code>```

Solution:

Thank you Alexander I. !

```<code>    public static T ConvertFromStringifiedJSON<T>(string stringifiedJSON)
    {
        var json = JsonConvert.DeserializeObject<string>(stringifiedJSON);
        return ConvertFromJSON<T>(json);
    }
</code>```

答:
Like @ne1410 writes, use:
JsonConvert.DeserializeObject<rTestObject>(myJsonString);

You don't have to stringify you Json, It is already a string as seen by the return type of JsonConvert.SerializeObject(obj)

You don't need any of the other methods IMO.

Title: JSON object from Stringified value

Body:
Here is my very simple C# class object that I am trying to turn into a JSON string and stringifying:

public class rTestObject
{
    public rTestObject()
    {
        Name = "Hello";
        State = 7;
    }

    public string Name { get; set; }
    public int State { get; set; }
}

I call the following static method:

    // Json.net
    // from Newtonsoft.Json.dll
    // version 8.0.2.19309
    //

    using Newtonsoft.Json;
    public static string ConvertToJSON<T>(T obj)
    {
        return JsonConvert.SerializeObject(obj);
    }

Which produces the following (expected) output:

    {"Name":"Hello","State":7}

I call the following static method to stringify my JSON string

    public static string Stringify(string json)
    {
        return JsonConvert.ToString(json);
    }

Which produces the following (I think this is expected ??) output:

    "{\"Name\":\"Hello\",\"State\":7}"

My question how do I get from:

    "{\"Name\":\"Hello\",\"State\":7}"

back to rTestObject?

Here is what I have tried:

TRY 1

    public static T ConvertFromStringifiedJSON<T>(string stringifiedJSON)
    {
        Newtonsoft.Json.Linq.JObject j = Newtonsoft.Json.Linq.JObject.Parse(stringifiedJSON);
        return ConvertFromJSON<T>(j.ToString());
    }

Here is the exception:

    {"Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 34."}

TRY 2

    public static T ConvertFromJSON<T>(string jsonNotation)
    {
        return JsonConvert.DeserializeObject<T>(jsonNotation, NoNullStrings);
    }

Here is the exception:

    {"Error converting value \"{\"Name\":\"Hello\",\"State\":7}\" to type 'RestApi.Objects.rTestObject'. Path '', line 1, position 34."}

Solution:

Thank you Alexander I. !

    public static T ConvertFromStringifiedJSON<T>(string stringifiedJSON)
    {
        var json = JsonConvert.DeserializeObject<string>(stringifiedJSON);
        return ConvertFromJSON<T>(json);
    }


问:
SQL: Optional Foreign Keys
I have the following tables....

"Floor" (which has many) "Area" (which has many) "Asset",

then I have a "Task" table.

A "Task" can be assigned to either an "Area" or an "Asset"; so I have two columns in the "Task" table named areaId and assetId, one of which must have a value.

1st question: How do I query all tasks which have occurred on a given floor?

2nd question: How do I enforce referential integrity?

3rd question: Is this approach recommended? Any suggestions welcome if not.

Many thanks for any answers given,

ETFairfax

答:
1st question:

```<code>SELECT
    distinct t.TaskID
FROM
    Floor f
        inner join
    Area a
        on
            f.FloorID = a.FloorID
        left join
    Asset ast
        on
            a.AreaID = ast.AreaID
        inner join
    Task t
        on
            t.AreaID = a.AreaID or
            t.AssetID = ast.AssetID
 WHERE
     f.FloorID = @FloorID
</code>```

should give you the shape of the query you're trying to build. (Of course, you don't actually need to query the Floor table if you already have a FloorID)

2nd question:

```<code> CREATE TABLE Task (
     TaskID int not null,
     AreaID int null,
     AssetID int null,
     constraint PK_Task PRIMARY KEY (TaskID),
     constraint FK_Task_Area FOREIGN KEY (AreaID) references Area (AreaID),
     constraint FK_Task_Asset FOREIGN KEY (AssetID) references Asset (AssetID),
     constraint CK_Task_OneNonNull CHECK (
         (AreaID is null and AssetID is not null) or
         (AssetID is null and AreaID is not null))
 )
</code>```

Or, alternatively, you can make AreaID not null, add a unique constraint on the Asset table across (AreaID,AssetID), and then make the foreign key to the Asset table reference both columns - this ensures that if an AssetID is supplied, it's linking to an Asset that belongs to the correct AreaID. This would also simplify the answer to Q1, if there's always an AreaID in Task

3rd question:

difficult to say without knowing how this is all going to be used. I don't think it's an un-reasonable approach.

Title: SQL: Optional Foreign Keys

Body:
1st question:

SELECT
    distinct t.TaskID
FROM
    Floor f
        inner join
    Area a
        on
            f.FloorID = a.FloorID
        left join
    Asset ast
        on
            a.AreaID = ast.AreaID
        inner join
    Task t
        on
            t.AreaID = a.AreaID or
            t.AssetID = ast.AssetID
 WHERE
     f.FloorID = @FloorID

should give you the shape of the query you're trying to build. (Of course, you don't actually need to query the Floor table if you already have a FloorID)

2nd question:

 CREATE TABLE Task (
     TaskID int not null,
     AreaID int null,
     AssetID int null,
     constraint PK_Task PRIMARY KEY (TaskID),
     constraint FK_Task_Area FOREIGN KEY (AreaID) references Area (AreaID),
     constraint FK_Task_Asset FOREIGN KEY (AssetID) references Asset (AssetID),
     constraint CK_Task_OneNonNull CHECK (
         (AreaID is null and AssetID is not null) or
         (AssetID is null and AreaID is not null))
 )

Or, alternatively, you can make AreaID not null, add a unique constraint on the Asset table across (AreaID,AssetID), and then make the foreign key to the Asset table reference both columns - this ensures that if an AssetID is supplied, it's linking to an Asset that belongs to the correct AreaID. This would also simplify the answer to Q1, if there's always an AreaID in Task

3rd question:

difficult to say without knowing how this is all going to be used. I don't think it's an un-reasonable approach.


问:
Copy element within copy element in Azure ARM deployment template to create multiple instances of a resource
I'm trying to create do a "nested for loop" in my Azure ARM deployment template via the copy element feature to create multiple instance of the same resource type (Microsoft.Web/sites/hostnameBindings in my case)

More specifically I'm trying to bind multiple hostnames to multiple apps (azure app service websites).

Is this possible? Or would I need to go down the linked templates path?

Here is my attempt so far but I can't get it to work.

parameters.json

```<code>{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "appList": {
      "value": [
        { "appName": "app1", "hostNames": [ "app1.qqq.example.com", "app1.ttt.example.com" ] },
        { "appName": "app2", "hostNames": [ "app2.qqq.example.com" , "app2.ttt.example.com" ] },
        { "appName": "app3", "hostNames": [ "app3.qqq.example.com", "app3.ttt.example.com" ] }
      ]
    }
  }
}
</code>```

template.json

```<code>{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "appList": { "type": "array"  }
  },
  "resources": [
    {
      "type": "Microsoft.Web/sites/hostnameBindings",
      "name": "parameters('appList')[copyIndex('webAppCopy')]/parameters('appList')[copyIndex('webAppCopy')].hostNames",
      "copy": [
        {
          "name": "webAppCopy",
          "count": "[length(parameters('appList'))]"
        }
      ],
      "apiVersion": "2016-03-01",
      "location": "[resourceGroup().location]"
    }
  ],
  "outputs": {}
}
</code>```

答:
I've never seen anything in the docs about direct support for nested
loops. But you could probably solve this with the numeric functions as follows:

define a template variable that is number-of-apps * number-of-addresses-per-app.  Let's call this variable bindingCount

Use bindingCount as the count for your "copy"

When constructing the resource name, use the div and mod functions to take copyIndex and turn it back into an "app index" and a "hostname" index.  I
think you'll have to do the math inline, in the formula that constructs the name.

Body:
I'm trying to create do a "nested for loop" in my Azure ARM deployment template via the copy element feature to create multiple instance of the same resource type (Microsoft.Web/sites/hostnameBindings in my case)

More specifically I'm trying to bind multiple hostnames to multiple apps (azure app service websites).

Is this possible? Or would I need to go down the linked templates path?

Here is my attempt so far but I can't get it to work.

parameters.json

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "appList": {
      "value": [
        { "appName": "app1", "hostNames": [ "app1.qqq.example.com", "app1.ttt.example.com" ] },
        { "appName": "app2", "hostNames": [ "app2.qqq.example.com" , "app2.ttt.example.com" ] },
        { "appName": "app3", "hostNames": [ "app3.qqq.example.com", "app3.ttt.example.com" ] }
      ]
    }
  }
}

template.json

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "appList": { "type": "array"  }
  },
  "resources": [
    {
      "type": "Microsoft.Web/sites/hostnameBindings",
      "name": "parameters('appList')[copyIndex('webAppCopy')]/parameters('appList')[copyIndex('webAppCopy')].hostNames",
      "copy": [
        {
          "name": "webAppCopy",
          "count": "[length(parameters('appList'))]"
        }
      ],
      "apiVersion": "2016-03-01",
      "location": "[resourceGroup().location]"
    }
  ],
  "outputs": {}
}