问:
Elegant way to validate scala map
My program receives a scala map, the requirements is to validate this map (key-value pairs). Ex: validate a key value, change its value to an acceptable format etc. In a rare case, we update the key as well before passing the map to the down layer. Its not always required to update this map , but only when we detect that there are any unsupported keys or values. However, we have to check all key/value pairs. I'm doing some thing like this:

```<code>private def updateMap ( parameters: Map[String, String]): Map[String, String] = {

parameters.map{

  case(k,v) => k match { case "checkPool" =>

    (k, (if (k.contains("checkPool"))
      v match {
        case "1" => "true"
        case _ => "false"
      }
    else v))

  case "Newheader" => (k.replace("Newheader","header"),v)
  case _ =>(k,v)
  }

  case _ => ("","")
}

}
</code>```

Like this the code increases for doing the validation and converting the keys/values to supported ones. Is there a cleaner way of doing this validation in Scala for a map?

Thanks

答:
It will be clearer if you put all your patterns above one another:

```<code>parameters.map{
  case (k@"checkPool", "1") => k -> "true"
  case (k@"checkPool", _") => k -> "false"
  case ("Newheader", v) => "header" -> v
  // put here all your other cases
  case (k, v) => k -> v  //last possible case, if nothing other matches
}
</code>```

For clarity, you can also put different validators in partial functions:

```<code>type Validator = PartialFunction[(String, String), (String, String)
val checkPool: Validator = {
  case (k@"checkPool", "1") => k -> "true"
  case (k@"checkPool", _") => k -> "false"
}
val headers: Validator = {
  case ("Newheader", v) => "header" -> v
}
</code>```

And then put all your validators one after the other in your map:

```<code>parameters.map(
  checkPool orElse
   headers orElse
   ... orElse
   PartialFunction(identity[(String, String)]) //this is the same as case (k, v) => k -> v
)
</code>```

Title: Elegant way to validate scala map

Body:
My program receives a scala map, the requirements is to validate this map (key-value pairs). Ex: validate a key value, change its value to an acceptable format etc. In a rare case, we update the key as well before passing the map to the down layer. Its not always required to update this map , but only when we detect that there are any unsupported keys or values. However, we have to check all key/value pairs. I'm doing some thing like this:

private def updateMap ( parameters: Map[String, String]): Map[String, String] = {

parameters.map{

  case(k,v) => k match { case "checkPool" =>

    (k, (if (k.contains("checkPool"))
      v match {
        case "1" => "true"
        case _ => "false"
      }
    else v))

  case "Newheader" => (k.replace("Newheader","header"),v)
  case _ =>(k,v)
  }

  case _ => ("","")
}

}

Like this the code increases for doing the validation and converting the keys/values to supported ones. Is there a cleaner way of doing this validation in Scala for a map?

Thanks

Body:
It will be clearer if you put all your patterns above one another:

parameters.map{
  case (k@"checkPool", "1") => k -> "true"
  case (k@"checkPool", _") => k -> "false"
  case ("Newheader", v) => "header" -> v
  // put here all your other cases
  case (k, v) => k -> v  //last possible case, if nothing other matches
}

For clarity, you can also put different validators in partial functions:

type Validator = PartialFunction[(String, String), (String, String)
val checkPool: Validator = {
  case (k@"checkPool", "1") => k -> "true"
  case (k@"checkPool", _") => k -> "false"
}
val headers: Validator = {
  case ("Newheader", v) => "header" -> v
}

And then put all your validators one after the other in your map:

parameters.map(
  checkPool orElse
   headers orElse
   ... orElse
   PartialFunction(identity[(String, String)]) //this is the same as case (k, v) => k -> v
)


来源: stackexchange

问:
Finding difference of two columns with where clause - MySQL
I'm trying to get the difference of two columns(OTHER AND SENIOR) with WHERE clause along with the Sum of their amount. The formulas are working fine, however, I'm not getting the result I want.

I tried to do it using INNER JOIN and unfortunately its not the result that I expected

Here's my query:

```<code>select a.ID as EMPLOYEE,
sum(a.amount) as other,
sum(b.amount) as senior,
(sum(a.amount) - sum(b.amount)) as result
from gndsale a
INNER join gndsale
b ON a.ID= b.ID
where a.TYPE = "5" and b.seniortype = "10"
group by a.ID
</code>```

Result:

What I want to do is get the difference of Column (Other) where type = 5 and Column (Senior)  where seniortype = 10

Here is my query for Senior:

```<code> select ID as EMPLOYEE, sum(amount)
 from gndsale
 where seniortype = "10"
 group by ID
</code>```

Result:

Here is my query for Other:

```<code>select ID as employee, sum(amount)
from gndsale
where type = "5"
group by ID
</code>```

The result should be

9907 = 530

9912 = 63.71

Anyone can help me with this? :(

Sample/Expected output:

答:
Please try this query</p>

```<code>select employee, other, senior, (other-senior) AS result
From (
    select ID as employee,
           sum(if(type=5,amount,0)) AS other,
           sum(if(seniortype =10,amount,0)) AS senior
           from gndsale group by ID
) a
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get the difference of two columns(OTHER AND SENIOR) with WHERE clause along with the Sum of their amount. The formulas are working fine, however, I'm not getting the result I want.

I tried to do it using INNER JOIN and unfortunately its not the result that I expected

Here's my query:

select a.ID as EMPLOYEE,
sum(a.amount) as other,
sum(b.amount) as senior,
(sum(a.amount) - sum(b.amount)) as result
from gndsale a
INNER join gndsale
b ON a.ID= b.ID
where a.TYPE = "5" and b.seniortype = "10"
group by a.ID

Result:

What I want to do is get the difference of Column (Other) where type = 5 and Column (Senior)  where seniortype = 10

Here is my query for Senior:

 select ID as EMPLOYEE, sum(amount)
 from gndsale
 where seniortype = "10"
 group by ID

Result:

Here is my query for Other:

select ID as employee, sum(amount)
from gndsale
where type = "5"
group by ID

The result should be

9907 = 530

9912 = 63.71

Anyone can help me with this? :(

Sample/Expected output:

Body:
Please try this query

select employee, other, senior, (other-senior) AS result
From (
    select ID as employee,
           sum(if(type=5,amount,0)) AS other,
           sum(if(seniortype =10,amount,0)) AS senior
           from gndsale group by ID
) a


问:
how many times does the user want to play a game c language
I am learning how to write a game I have been given the following rules for the game.

Rule 1: Players must define a minimum number to stop the turn this has to be greater than 10

Rule 2: all point from round are added to the total

Rule 3: If the dice lands on 1 then all points for that round are forfeited

Rule 4: First player to get to 101 points WINS!

I am trying to get the number of games to be inputted in after the user enters how many players there are.

My problem is it ask the user every time I enter the players names depending on how many players I have inputted

Example

How many Players: 3

How many games: 15

Enter Players name: John

How many games: 15 (I input this number again) I dont need this line here

Enter Players name: Mary

How many games: 15 (I input this number again) I dont need this line here

Enter Players name: Barry

How many games: 15 (I input this number again) I dont need this line here

This is my code for the problem:

```<code>//user inputs value of player_num, here, as you have now//

printf_s("Please type in the number of players: ");
scanf_s("%d", &player_num, sizeof(int));
for (i = 0; i < player_num; i++) {
    //user inputs value of num_game, here, as you have now//
    printf_s("Please type in the number of games: ");
    scanf_s("%d", &num_games, sizeof(int));
    num_games = (j = 1, num_games);

    printf_s("Enter the player's first name: ");
    scanf_s("%s", names[i], 25);
    getchar();
}
printf_s("\n");
for (i = 0; i < player_num; i++)
    printf_s("\n%s", names[i]);
</code>```

答:
The reason why it keeps asking you to "input the number of games" again and again is because you've put the printf and scanf statement in the loop.

```<code>for (i = 0; i < player_num; i++) {
printf_s("Please type in the number of games: ");//this
scanf_s("%d", &num_games, sizeof(int));//this
num_games = (j = 1, num_games); //including this

printf_s("Enter the player's first name: ");// also this
scanf_s("%s", names[i], 25);  // and this
getchar();
}
</code>```

Due to this each time the loop is executed, it asks you to enter the value.

instead if you want it to ask you once, you must put it outside the loop if you want the statements to be executed once only.

You can do this if you want to :

get the number of games to be inputted in after the user enters how
  many players there are.

```<code>printf_s("Please type in the number of players: ");
scanf_s("%d", &player_num, sizeof(int));
printf_s("Please type in the number of games: ");
scanf_s("%d", &num_games, sizeof(int));
num_games = (j = 1, num_games);
</code>```

and it is

asking the user every time you enter the players names depending on how
  many players you have inputted
  because you've entered those lines "inside the loop";

Body:
I am learning how to write a game I have been given the following rules for the game.

Rule 1: Players must define a minimum number to stop the turn this has to be greater than 10

Rule 2: all point from round are added to the total

Rule 3: If the dice lands on 1 then all points for that round are forfeited

Rule 4: First player to get to 101 points WINS!

I am trying to get the number of games to be inputted in after the user enters how many players there are.

My problem is it ask the user every time I enter the players names depending on how many players I have inputted

Example

How many Players: 3

How many games: 15

Enter Players name: John

How many games: 15 (I input this number again) I dont need this line here

Enter Players name: Mary

How many games: 15 (I input this number again) I dont need this line here

Enter Players name: Barry

How many games: 15 (I input this number again) I dont need this line here

This is my code for the problem:

//user inputs value of player_num, here, as you have now//

printf_s("Please type in the number of players: ");
scanf_s("%d", &player_num, sizeof(int));
for (i = 0; i < player_num; i++) {
    //user inputs value of num_game, here, as you have now//
    printf_s("Please type in the number of games: ");
    scanf_s("%d", &num_games, sizeof(int));
    num_games = (j = 1, num_games);

    printf_s("Enter the player's first name: ");
    scanf_s("%s", names[i], 25);
    getchar();
}
printf_s("\n");
for (i = 0; i < player_num; i++)
    printf_s("\n%s", names[i]);

Body:
The reason why it keeps asking you to "input the number of games" again and again is because you've put the printf and scanf statement in the loop.

for (i = 0; i < player_num; i++) {
printf_s("Please type in the number of games: ");//this
scanf_s("%d", &num_games, sizeof(int));//this
num_games = (j = 1, num_games); //including this

printf_s("Enter the player's first name: ");// also this
scanf_s("%s", names[i], 25);  // and this
getchar();
}

Due to this each time the loop is executed, it asks you to enter the value.

instead if you want it to ask you once, you must put it outside the loop if you want the statements to be executed once only.

You can do this if you want to :

get the number of games to be inputted in after the user enters how
  many players there are.

printf_s("Please type in the number of players: ");
scanf_s("%d", &player_num, sizeof(int));
printf_s("Please type in the number of games: ");
scanf_s("%d", &num_games, sizeof(int));
num_games = (j = 1, num_games);

and it is

asking the user every time you enter the players names depending on how
  many players you have inputted
  because you've entered those lines "inside the loop";


问:
Badly designed application: should we rewrite?
When you work on an application that has a bad architecture and you definitely know it won't support well a scale up, what would be the best solution to improve the app?

The app I work on has been built in a very bad way, is difficult to understand and took about 6 months to develop. Although I just arrived on this project and we need to take decisions.

Would you rewrite everything?

Would you refactor piece per piece?

Would you keep it as it and add new features with a better design?

Considering time is money how would you argue about the right solution?

Thanks

答:
The answer depends from person to person. For me, I would leave the rest as it is. But I would start developing the new activities or features in the right designed way.
And once you finish everything, then make it a little better by refactoring the old ones.</p>


问:
Google Drive Auth: Creating JWT signature from JSON version of private key
I am having trouble creating a JWT for Google Drive authorization.
The instruction is given in this link.

```<code><?php
//helper function
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

//Google's Documentation of Creating a JWT https://developers.google.com/identity/protocols/OAuth2ServiceAccount#authorizingrequests

$raw_key_data="-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkWhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCLJN7B2USp0bTH\n7aVt1K/pAJa9rgUEkebbRQUPEopManZHgJK8SMzq5nUM3OOVlTdyDyuzxUZW65Y+\nR1xajNHSidE+rJJ3MWwuevXBuUws5oiA+DXJBB6FsTtHDvUPT7sePbJx8Y80S1Jr\nB3apJNdohjSef4UihgjJ93A0PgeSVz7CeUKxrBHdGiK2Ikf7wTCzcRzz/15I6QLu\ncsNbWxo0+koXo9D0+wT3RN+riSyTa2WwYn//B8v6VmDPVrcjxETEXraAIMpqURtK\n4BuK4Qp2pSd1u2zrGc58BVGuT6+nPVpmX6wiZ21sqOulTzgIOXKIuc4zdKvZ+jz/\n1jst3ertAgMBAAECggEADRGn+IYbLGYdeD/Kb2/wG87p2aP8Jas8hzDK4lkH81h2\nho29eoDN+mwt50jh+V08CXMCVE69phFXmb7jHkAmvwMhy6Sy1w4lzpHO/mSUko0O\nmip2BszjvwPgAPMXMlp3RUZfOdOJ80v10Eaxrv5eWxtr2s04aH81WR7sA4Ql+uki\nbTiLbo4odpMVPkoJZATZKQd+L/bBM4a+b3IM87/TE7skMrSgQE6cnjjTI5Uk+WSl\nxjiZvj5XmticW3vPavL/ZXPEZqy5IxvcxdF5rGHCHVu4ah0CmDdc9A3jF0flhewK\nV6mOViqbKGInnMn4kt3l4C3+wF2+dge6t8BQ/TMtwwKBgQDBnpjiC+wRVQy36KCs\ntYdZ60ykuQeKqMyACt6FvC74xy+PjLVntxDaYArva2PVaZSm9B2FgGHPz9AfW80/\n1ZeNHcuwymni8n+4MNpQbJuhuHK8UjSo0rFq6Nrddi9RCjzASSX8s4Dlm01VM65b\nKBnM5p50I9QEY4F4gSZfLLMNowKBgQC3+Tpz23qhkxJPu9cVuvPRFfg1y0NNsp7k\n0qHYMegz1GHoMVs1kg36OtbROqpG2+rIrj0JWTGwLO14fX2TY0jWfao21CGrpkXM\nlY1KSDIMuQv6pd5yh74oqvDDpZwKxxu/nmzcQbd1lN/nFkEW5g0b7e27UoCoovwS\n7qSENbqOLwKBgHYWp8H+aX1stPQZ8p1DngiupTE2FK5yIz/Y4T0JuFBNE+nmdOGL\n2sCFoUXC5sHLwjlNXBAHbCCV66akk/th5yvPR2NNIOWk51bMnOo+Q3GQEJJhRPLO\nhhzhZlN5+IPhzYmtU3jbdjsTzEex3J6GR64b3fqRu4bttZJsmp2jopUnAoGAWW+7\nzt7/+tR4rnJu2Y2NQjQf+mbaTUddb2kWbPe2Hpw9DJgR8zURvngkPor6hIAc33p1\nCbpmwXLV7yFyjthRbJSizwzJYZzvicmaamY2jqDXBf7k6WC8PSD88t/rwAGTp8/o\ntBruiSbawoi7E9q6vL0qOUqeaVzylnGVYQCNtNkCgYBwqL1MNTR8IrXDfZyYdDRP\nWNCRqm7ymuQi7IUKVa+yaBM1ubvEe7EPrlZWlFPDdPmaScx02Qwf++xcGHWzzDX0\nQPmd95OTGafvECXuKVy2NAf2AdCYVruL+17wfPhuz7ANIpgEqsiNAZNe0GtGBjyZ\nVuiSVVML3jW4XUtf63V0/A==\n-----END PRIVATE KEY-----\n";

$private_key = openssl_get_privatekey($raw_key_data);
if ($private_key === FALSE)
{
    error_log ("Unable to extract private key from raw key data: " . openssl_error_string());
};

print("$private_key\n");

//{Base64url encoded JSON header}

$jwtHeader = base64url_encode(json_encode(array(
"alg" => "RS256",
"typ" => "JWT"
)));

//{Base64url encoded JSON claim set}
$now = time();
$jwtClaim = base64url_encode(json_encode(array(
"iss" => "myService-account-id@mySite.iam.gserviceaccount.com",
"scope" => "https://www.googleapis.com/auth/drive.file",
"aud" => "https://www.googleapis.com/oauth2/v4/token",
"exp" => $now + 3600,
"iat" => $now
)));

//The base string for the signature: {Base64url encoded JSON header}.    {Base64url encoded JSON claim set}

openssl_sign(
$jwtHeader.".".$jwtClaim,
$jwtSig,
$private_key,
"SHA256"
);

$jwtSign = base64url_encode($jwtSig);

//{Base64url encoded JSON header}.{Base64url encoded JSON claim set}.    {Base64url encoded signature}
$jwtAssertion = $jwtHeader.".".$jwtClaim.".".$jwtSig;
print("$jwtAssertion\n");

?>
</code>```

When I run this code, I get Resource id #4 followed by a nonsense signature. I even tried putting the private key in a file and reading from the file in which there is multiple lines (private key separated at \n ) but no success. I can't generate meaningful JWT signature from the private key. Can anyone help me with this issue?

Thanks,

答:
I have managed to solve this issue. Below is the updated code that reads the JSON file downloaded from Google and creates an assertion with which one can then get access token from Google:

```<code><?php
//helper function
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

// Read the JSON credential file my-private-key.json download from Google
$private_key_file="my-private-key.json";
$json_file = file_get_contents($private_key_file);

$info = json_decode($json_file);
$private_key = $info->{'private_key'};

//{Base64url encoded JSON header}
$jwtHeader = base64url_encode(json_encode(array(
"alg" => "RS256",
"typ" => "JWT"
)));

//{Base64url encoded JSON claim set}
$now = time();
$jwtClaim = base64url_encode(json_encode(array(
"iss" => $info->{'client_email'},
"scope" => "https://www.googleapis.com/auth/drive.file",
"aud" => "https://www.googleapis.com/oauth2/v4/token",
"exp" => $now + 3600,
"iat" => $now
)));

$data = $jwtHeader.".".$jwtClaim;

// Signature
$Sig = '';
openssl_sign($data,$Sig,$private_key,'SHA256');
$jwtSign = base64url_encode( $Sig  );

//{Base64url encoded JSON header}.{Base64url encoded JSON claim set}.{Base64url encoded signature}

$jwtAssertion = $data.".".$jwtSign;
echo "$jwtAssertion\n";
</code>```

You may then test your code by communicating with Google Drive for example:

```<code>curl -d 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=YOUR-JWT-ASSERTION-BUILD-ABOVE' https://www.googleapis.com/oauth2/v4/token
</code>```

Body:
I am having trouble creating a JWT for Google Drive authorization.
The instruction is given in this link.

<?php
//helper function
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

//Google's Documentation of Creating a JWT https://developers.google.com/identity/protocols/OAuth2ServiceAccount#authorizingrequests

$raw_key_data="-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkWhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCLJN7B2USp0bTH\n7aVt1K/pAJa9rgUEkebbRQUPEopManZHgJK8SMzq5nUM3OOVlTdyDyuzxUZW65Y+\nR1xajNHSidE+rJJ3MWwuevXBuUws5oiA+DXJBB6FsTtHDvUPT7sePbJx8Y80S1Jr\nB3apJNdohjSef4UihgjJ93A0PgeSVz7CeUKxrBHdGiK2Ikf7wTCzcRzz/15I6QLu\ncsNbWxo0+koXo9D0+wT3RN+riSyTa2WwYn//B8v6VmDPVrcjxETEXraAIMpqURtK\n4BuK4Qp2pSd1u2zrGc58BVGuT6+nPVpmX6wiZ21sqOulTzgIOXKIuc4zdKvZ+jz/\n1jst3ertAgMBAAECggEADRGn+IYbLGYdeD/Kb2/wG87p2aP8Jas8hzDK4lkH81h2\nho29eoDN+mwt50jh+V08CXMCVE69phFXmb7jHkAmvwMhy6Sy1w4lzpHO/mSUko0O\nmip2BszjvwPgAPMXMlp3RUZfOdOJ80v10Eaxrv5eWxtr2s04aH81WR7sA4Ql+uki\nbTiLbo4odpMVPkoJZATZKQd+L/bBM4a+b3IM87/TE7skMrSgQE6cnjjTI5Uk+WSl\nxjiZvj5XmticW3vPavL/ZXPEZqy5IxvcxdF5rGHCHVu4ah0CmDdc9A3jF0flhewK\nV6mOViqbKGInnMn4kt3l4C3+wF2+dge6t8BQ/TMtwwKBgQDBnpjiC+wRVQy36KCs\ntYdZ60ykuQeKqMyACt6FvC74xy+PjLVntxDaYArva2PVaZSm9B2FgGHPz9AfW80/\n1ZeNHcuwymni8n+4MNpQbJuhuHK8UjSo0rFq6Nrddi9RCjzASSX8s4Dlm01VM65b\nKBnM5p50I9QEY4F4gSZfLLMNowKBgQC3+Tpz23qhkxJPu9cVuvPRFfg1y0NNsp7k\n0qHYMegz1GHoMVs1kg36OtbROqpG2+rIrj0JWTGwLO14fX2TY0jWfao21CGrpkXM\nlY1KSDIMuQv6pd5yh74oqvDDpZwKxxu/nmzcQbd1lN/nFkEW5g0b7e27UoCoovwS\n7qSENbqOLwKBgHYWp8H+aX1stPQZ8p1DngiupTE2FK5yIz/Y4T0JuFBNE+nmdOGL\n2sCFoUXC5sHLwjlNXBAHbCCV66akk/th5yvPR2NNIOWk51bMnOo+Q3GQEJJhRPLO\nhhzhZlN5+IPhzYmtU3jbdjsTzEex3J6GR64b3fqRu4bttZJsmp2jopUnAoGAWW+7\nzt7/+tR4rnJu2Y2NQjQf+mbaTUddb2kWbPe2Hpw9DJgR8zURvngkPor6hIAc33p1\nCbpmwXLV7yFyjthRbJSizwzJYZzvicmaamY2jqDXBf7k6WC8PSD88t/rwAGTp8/o\ntBruiSbawoi7E9q6vL0qOUqeaVzylnGVYQCNtNkCgYBwqL1MNTR8IrXDfZyYdDRP\nWNCRqm7ymuQi7IUKVa+yaBM1ubvEe7EPrlZWlFPDdPmaScx02Qwf++xcGHWzzDX0\nQPmd95OTGafvECXuKVy2NAf2AdCYVruL+17wfPhuz7ANIpgEqsiNAZNe0GtGBjyZ\nVuiSVVML3jW4XUtf63V0/A==\n-----END PRIVATE KEY-----\n";

$private_key = openssl_get_privatekey($raw_key_data);
if ($private_key === FALSE)
{
    error_log ("Unable to extract private key from raw key data: " . openssl_error_string());
};

print("$private_key\n");

//{Base64url encoded JSON header}

$jwtHeader = base64url_encode(json_encode(array(
"alg" => "RS256",
"typ" => "JWT"
)));

//{Base64url encoded JSON claim set}
$now = time();
$jwtClaim = base64url_encode(json_encode(array(
"iss" => "myService-account-id@mySite.iam.gserviceaccount.com",
"scope" => "https://www.googleapis.com/auth/drive.file",
"aud" => "https://www.googleapis.com/oauth2/v4/token",
"exp" => $now + 3600,
"iat" => $now
)));

//The base string for the signature: {Base64url encoded JSON header}.    {Base64url encoded JSON claim set}

openssl_sign(
$jwtHeader.".".$jwtClaim,
$jwtSig,
$private_key,
"SHA256"
);

$jwtSign = base64url_encode($jwtSig);

//{Base64url encoded JSON header}.{Base64url encoded JSON claim set}.    {Base64url encoded signature}
$jwtAssertion = $jwtHeader.".".$jwtClaim.".".$jwtSig;
print("$jwtAssertion\n");

?>

When I run this code, I get Resource id #4 followed by a nonsense signature. I even tried putting the private key in a file and reading from the file in which there is multiple lines (private key separated at \n ) but no success. I can't generate meaningful JWT signature from the private key. Can anyone help me with this issue?

Thanks,

Body:
I have managed to solve this issue. Below is the updated code that reads the JSON file downloaded from Google and creates an assertion with which one can then get access token from Google:

<?php
//helper function
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

// Read the JSON credential file my-private-key.json download from Google
$private_key_file="my-private-key.json";
$json_file = file_get_contents($private_key_file);

$info = json_decode($json_file);
$private_key = $info->{'private_key'};

//{Base64url encoded JSON header}
$jwtHeader = base64url_encode(json_encode(array(
"alg" => "RS256",
"typ" => "JWT"
)));

//{Base64url encoded JSON claim set}
$now = time();
$jwtClaim = base64url_encode(json_encode(array(
"iss" => $info->{'client_email'},
"scope" => "https://www.googleapis.com/auth/drive.file",
"aud" => "https://www.googleapis.com/oauth2/v4/token",
"exp" => $now + 3600,
"iat" => $now
)));

$data = $jwtHeader.".".$jwtClaim;

// Signature
$Sig = '';
openssl_sign($data,$Sig,$private_key,'SHA256');
$jwtSign = base64url_encode( $Sig  );

//{Base64url encoded JSON header}.{Base64url encoded JSON claim set}.{Base64url encoded signature}

$jwtAssertion = $data.".".$jwtSign;
echo "$jwtAssertion\n";

You may then test your code by communicating with Google Drive for example:

curl -d 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=YOUR-JWT-ASSERTION-BUILD-ABOVE' https://www.googleapis.com/oauth2/v4/token


问:
Passing data to another UIViewController with buttons
so I have a UIScrollView with all of these buttons overlayed with images:

http://i.imgur.com/W6hagsa.png

and I need it so that if you click on a teacher, like Mr Edmondson for maths, In another UIViewController, an email screen pops up and it needs to set the email recipient to edmondson@gmail.com.

Basically you click on whatever teacher, and it sets the email recipient to that teacher. My current code in the recipients & message body is:

```<code>let toRecipients = ["placeholder@gmail.com"]
mc.setMessageBody("blah blah blah blah")
</code>```

How would I do this ?

答:
You may use segue in your storyboard. Then use the prepareSegue

Something like this in your TableViewController

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

if segue.identifier == "detailSegue" {
    let vc = segue.destination as! ViewController
    vc.teacher = teachers[selectedItem]
   }
}
</code>```

You must manage the selected teacher with a var selectedItem: Int in

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedItem = indexPath
        print (selectedItem.row)
    }
</code>```

If it's not clear, feel free to give me more details about your code if you need more explanations.

Regards
Seb

Body:
so I have a UIScrollView with all of these buttons overlayed with images:

http://i.imgur.com/W6hagsa.png

and I need it so that if you click on a teacher, like Mr Edmondson for maths, In another UIViewController, an email screen pops up and it needs to set the email recipient to edmondson@gmail.com.

Basically you click on whatever teacher, and it sets the email recipient to that teacher. My current code in the recipients & message body is:

let toRecipients = ["placeholder@gmail.com"]
mc.setMessageBody("blah blah blah blah")

How would I do this ?

Body:
You may use segue in your storyboard. Then use the prepareSegue

Something like this in your TableViewController

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

if segue.identifier == "detailSegue" {
    let vc = segue.destination as! ViewController
    vc.teacher = teachers[selectedItem]
   }
}

You must manage the selected teacher with a var selectedItem: Int in

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedItem = indexPath
        print (selectedItem.row)
    }

If it's not clear, feel free to give me more details about your code if you need more explanations.

Regards
Seb


问:
pass Excel file from html form input to rest java method
I want to take excel file from html form input (input) and pass it to my rest java method and perform some operations on it. I am also using angularJs. </p>

答:
You have to proccess it in your java code. Than create some json from it and post it throught rest.

You can proccess your excel with https://poi.apache.org/spreadsheet/.

Here is a great example how to use restful services.
https://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/


问:
Correctly defining this data relation in Django models
I'm working on a Django project, where I have amongst others, two models that have a relationship.

The first model describes a dish in general. It has a name and some other basic information, for instance:

```<code>dish(models.Model):
    name = models.CharField(max_length=100)
    short_desc = models.CharField(max_lenght=255)
    vegetarian = models.BooleanField(default=False)
    vegan = models.BooleanField(default=False)
</code>```

The second model is related to the dish, I assume in form of a one-to-one relationship. This model contains the preparation and the ingredients. This data may change over time for the dish (e.g. preparation text is adjusted). Old versions of this text are still stored, but not connected to the dish. So  the dish gets a new field, which points to the current preparation text.

```<code>    preparation = models.???(???)
</code>```

So, whenever the preparation description is changed a new entry is created for the preparation and the dish's reference to the preparation is updated.

The preparation itself looks like this:

```<code>preparation(models.Model):
    prep_test = models.TextField()
    ingredients = models.TextField()
    last_update = models.DateTimeField()
</code>```

As stated before, I believe that a one-to-one relation would be reasonable between the dish and the preparation.

Is my assumption with the one-to-one relation correct and if so, how do I correctly define it?

答:
why you don't make one2many relation of dish with preparation.

I dish have multiple preparation but have only one active. you can attach latest on base of last_update = models.DateTimeField()

your model will be like:

```<code>class preparation(models.Model):
    dish = models.ForeignKey(dish)
    ...
</code>```

Body:
I'm working on a Django project, where I have amongst others, two models that have a relationship.

The first model describes a dish in general. It has a name and some other basic information, for instance:

dish(models.Model):
    name = models.CharField(max_length=100)
    short_desc = models.CharField(max_lenght=255)
    vegetarian = models.BooleanField(default=False)
    vegan = models.BooleanField(default=False)

The second model is related to the dish, I assume in form of a one-to-one relationship. This model contains the preparation and the ingredients. This data may change over time for the dish (e.g. preparation text is adjusted). Old versions of this text are still stored, but not connected to the dish. So  the dish gets a new field, which points to the current preparation text.

    preparation = models.???(???)

So, whenever the preparation description is changed a new entry is created for the preparation and the dish's reference to the preparation is updated.

The preparation itself looks like this:

preparation(models.Model):
    prep_test = models.TextField()
    ingredients = models.TextField()
    last_update = models.DateTimeField()

As stated before, I believe that a one-to-one relation would be reasonable between the dish and the preparation.

Is my assumption with the one-to-one relation correct and if so, how do I correctly define it?

Body:
why you don't make one2many relation of dish with preparation.

I dish have multiple preparation but have only one active. you can attach latest on base of last_update = models.DateTimeField()

your model will be like:

class preparation(models.Model):
    dish = models.ForeignKey(dish)
    ...


问:
Calculate System.Decimal Precision and Scale
Suppose that we have a System.Decimal number.

For illustration, let's take one whose ToString() representation is as follows:

```<code>d.ToString() = "123.4500"
</code>```

The following can be said about this Decimal. For our purposes here, scale is defined as the number of digits to the right of the decimal point. Effective scale is similar but ignores any trailing zeros that occur in the fractional part. (In other words, these parameters are defined like SQL decimals plus some additional parameters to account for the System.Decimal concept of trailing zeros in the fractional part.)

Precision: 7

Scale:     4

EffectivePrecision: 5

EffectiveScale: 2

Given an arbitrary System.Decimal, how can I compute all four of these parameters efficiently and without converting to a String and examining the String? The solution probably requires Decimal.GetBits.

Some more examples:

```<code>Examples Precision  Scale  EffectivePrecision  EffectiveScale
0        1 (?)      0      1 (?)               0
0.0      2 (?)      1      1 (?)               0
12.45    4          2      4                   2
12.4500  6          4      4                   2
770      3          0      3                   0
</code>```

(?) Alternatively interpreting these precisions as zero would be fine.

答:
I came across this article when I needed to validate precision and scale before writing a decimal value to a database. I had actually come up with a different way to achieve this using System.Data.SqlTypes.SqlDecimal which turned out to be faster that the other two methods discussed here. </p>

```<code> static DecimalInfo SQLInfo(decimal dec)

     {

         System.Data.SqlTypes.SqlDecimal x;
         x = new  System.Data.SqlTypes.SqlDecimal(dec);
         return new DecimalInfo((int)x.Precision, (int)x.Scale, (int)0);
     }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Suppose that we have a System.Decimal number.

For illustration, let's take one whose ToString() representation is as follows:

d.ToString() = "123.4500"

The following can be said about this Decimal. For our purposes here, scale is defined as the number of digits to the right of the decimal point. Effective scale is similar but ignores any trailing zeros that occur in the fractional part. (In other words, these parameters are defined like SQL decimals plus some additional parameters to account for the System.Decimal concept of trailing zeros in the fractional part.)

Precision: 7

Scale:     4

EffectivePrecision: 5

EffectiveScale: 2

Given an arbitrary System.Decimal, how can I compute all four of these parameters efficiently and without converting to a String and examining the String? The solution probably requires Decimal.GetBits.

Some more examples:

Examples Precision  Scale  EffectivePrecision  EffectiveScale
0        1 (?)      0      1 (?)               0
0.0      2 (?)      1      1 (?)               0
12.45    4          2      4                   2
12.4500  6          4      4                   2
770      3          0      3                   0

(?) Alternatively interpreting these precisions as zero would be fine.

Body:
I came across this article when I needed to validate precision and scale before writing a decimal value to a database. I had actually come up with a different way to achieve this using System.Data.SqlTypes.SqlDecimal which turned out to be faster that the other two methods discussed here.

 static DecimalInfo SQLInfo(decimal dec)

     {

         System.Data.SqlTypes.SqlDecimal x;
         x = new  System.Data.SqlTypes.SqlDecimal(dec);
         return new DecimalInfo((int)x.Precision, (int)x.Scale, (int)0);
     }


问:
Search within a big vector in C++
I have following vectors:

```<code>std::vector<A*> vec;
std::vector<std::pair<A*, A*>> vec_pair;
</code>```

vec_pair size is much more than vec size. I would like to find a pair within vec_pair which both members are inside vec.

contents of the vec_pair are constant. However after each iteration the contents of the vec will change and I would like to do the test again.

I know I can do a for loop and do the check. However considering size difference and recurrence of the job, I am looking for a smart and efficient way to do it.

答:
vec_pair size is much more than vec size.

This should act as a clue to you to use std::map.
Put all the elements of vector vec inside a map : myMap[vec[i]] = 1;
Then go through each pair in vec_pair, and do

```<code>if (myMap.find(vec_pair[i].first != myMap.end()) &&
    myMap.find(vec_pair[i].second != myMap.end()) )
{
    return FOUND;
}
else
    return NOT_FOUND;`
</code>```

As commented by Gates, use unordered_map for faster operations.

Title: Search within a big vector in C++

Body:
I have following vectors:

std::vector vec;
std::vector<std::pair> vec_pair;

vec_pair size is much more than vec size. I would like to find a pair within vec_pair which both members are inside vec.

contents of the vec_pair are constant. However after each iteration the contents of the vec will change and I would like to do the test again.

I know I can do a for loop and do the check. However considering size difference and recurrence of the job, I am looking for a smart and efficient way to do it.

Body:
vec_pair size is much more than vec size.

This should act as a clue to you to use std::map.
Put all the elements of vector vec inside a map : myMap[vec[i]] = 1;
Then go through each pair in vec_pair, and do

if (myMap.find(vec_pair[i].first != myMap.end()) &&
    myMap.find(vec_pair[i].second != myMap.end()) )
{
    return FOUND;
}
else
    return NOT_FOUND;`

As commented by Gates, use unordered_map for faster operations.


问:
ES6 Dyanmic Promise Chaining from array
Scenario

I have an array of URLs that I need to download, however each must also be supplied with a unique transaction ID that must be requested from the server and only increments when a request is successful.

Problem

As I loop through the array I need to wait for both the request for the transaction ID and the request for the file to complete before starting the next iteration of the loop but the number of files is not fixed so need to dynamically build a chain of promises.

Pseudocode

Below is some pseudocode, getFiles() is the problem because all the requests get the same transaction Id as they don't wait for the previous request to finish.

```<code>function getTransationId(){
    return new Promise((resolve,reject)=> {
        let id = getNextTransactionId();
        if(id!=error){
            resolve(id);
        }else{
            reject(error);
        }
    })
}

function getFile(url, transactionId){
    return new Promise((resolve,reject)=>{
        http.request(url+transactionId, function(err,response){
            if(err){
                reject(err);
            }else{
                resolve(response);
            }
        });
    });
}

function getFilesFromArray(urlArray){
    for(let url of urlArray){
        getTransactionId().then(resolve=>getFile(url,resolve),reject=>console.error(reject));
    }
}
</code>```

Question

How do I chain chain promises together dynamically?

Answer

Here's a JSFiddle of Ovidiu's answer

答:
You can do something along these lines</p>

```<code>function getAllFiles(i, results, urlArray) {
    if(i == urlArray.length) return;

    getTransationId().then(id => {
        return new Promise((resolve, reject) => {
            http.request(urlArray[i] + id, (err, response) => {
                if(err){
                    reject();
                }else{
                    results.push(response);
                    resolve();
                }
            });
        });
    }).then(() => {
        getAllFiles(i + 1, results, urlArray);
    })
}
</code>```

Title: ES6 Dyanmic Promise Chaining from array

Body:
Scenario

I have an array of URLs that I need to download, however each must also be supplied with a unique transaction ID that must be requested from the server and only increments when a request is successful.

Problem

As I loop through the array I need to wait for both the request for the transaction ID and the request for the file to complete before starting the next iteration of the loop but the number of files is not fixed so need to dynamically build a chain of promises.

Pseudocode

Below is some pseudocode, getFiles() is the problem because all the requests get the same transaction Id as they don't wait for the previous request to finish.

function getTransationId(){
    return new Promise((resolve,reject)=> {
        let id = getNextTransactionId();
        if(id!=error){
            resolve(id);
        }else{
            reject(error);
        }
    })
}

function getFile(url, transactionId){
    return new Promise((resolve,reject)=>{
        http.request(url+transactionId, function(err,response){
            if(err){
                reject(err);
            }else{
                resolve(response);
            }
        });
    });
}

function getFilesFromArray(urlArray){
    for(let url of urlArray){
        getTransactionId().then(resolve=>getFile(url,resolve),reject=>console.error(reject));
    }
}

Question

How do I chain chain promises together dynamically?

Answer

Here's a JSFiddle of Ovidiu's answer

Body:
You can do something along these lines

function getAllFiles(i, results, urlArray) {
    if(i == urlArray.length) return;

    getTransationId().then(id => {
        return new Promise((resolve, reject) => {
            http.request(urlArray[i] + id, (err, response) => {
                if(err){
                    reject();
                }else{
                    results.push(response);
                    resolve();
                }
            });
        });
    }).then(() => {
        getAllFiles(i + 1, results, urlArray);
    })
}


问:
GWT code-splitting download progressbar - like gmail
I have to use code-splitting in my project. but anyway there are some codes for initial downloading for first time.

Now I want to show to end-user the progress for code downloading (.cache.html - or other code-splitting) like gmail startup progress.

Would you please help me.

RGDS

答:
According to the design (roughly), it mentions splitting off modules where it makes sense since it doesn't technically support pre-fetching; that being said, I can only assume GMail is showing progress based on the module loading progress checked via callbacks (i.e GWT.runAsync()). Not all modules are the same size, but you could "guesstimate" and assign a weighted percentage for each module (See GWT's compile report)

If your initial page size download is large(>= 1 MB), I would recommend looking into refactoring and optimizing your design to be a little more lightweight (scaffolding). Which would mean more trips to the server but limit the initial download size. That would provide the basis to plumb some more precise feedback to the user that the page is  "working" (i.e. indeterminate progress bar) and avoid unnecessary precision.

Total page size is a difficult thing to really measure en-route to the client/browser, it would be more trouble than it's worth to display this to the user. You could probably accomplish this with several lightweight modules but you'll have to compensate for all the generated resources like ClientBundle because GWT creates a specific set for each browser permutation.

Sidenote:
Real time feedback such as for file size precision progress (e.g. 80 KB of 1.29MB (6% Complete)) is typically used when downloading a file (e.g. images, video, music, et al) to the user's hard drive. The data at that point is no longer transient and storage space may be a concern, caches clear out and flush so it's generally not a big deal how big a web page is.


问:
Laravel Route : route::resource
I'm very new in laravel,
I'm following some tutorial

this code work fine

```<code>Route::group(['middleware' => 'web'], function() {
    Route::resource('tes', 'TesController');
});
<form action="{{ route('tes.destroy',3) }}" method="post">
</code>```

until i modified it like this one

```<code>Route::resource('tes/keren', 'TesController');

<form action="{{ route('tes/keren.destroy',3) }}" method="post">
</code>```

It said tes/keren.destroy undefined....
just simple question, which should I modify so, I can route with /

Thank you

答:
route() helper uses route name to build URL, so you should do this instead:

```<code><form action="{{ route('keren.destroy', 3) }}" method="post">
</code>```

You can see all available routes and route names with this command:

```<code>php artisan route:list
</code>```

Title: Laravel Route : route::resource

Body:
I'm very new in laravel,
I'm following some tutorial

this code work fine

Route::group(['middleware' => 'web'], function() {
    Route::resource('tes', 'TesController');
});
<form action="{{ route('tes.destroy',3) }}" method="post">

until i modified it like this one

Route::resource('tes/keren', 'TesController');

<form action="{{ route('tes/keren.destroy',3) }}" method="post">

It said tes/keren.destroy undefined....
just simple question, which should I modify so, I can route with /

Thank you

Body:
route() helper uses route name to build URL, so you should do this instead:

<form action="{{ route('keren.destroy', 3) }}" method="post">

You can see all available routes and route names with this command:

php artisan route:list


问:
How to use Hazelcast REST Client to retrieve Entry from a Map where key is a customized class?
As per link http://docs.hazelcast.org/docs/3.5/manual/html/restclient.html

Hazelcast provides a REST interface, i.e. it provides an HTTP service in each node so that you can access your map using HTTP protocol. If you want to retrieve an entry, you can use a GET call.

For Example: http://10.20.17.1:5701/hazelcast/rest/maps/mapName/key1.

But what if my key is a Java custom object like:

```<code>public class RuleCacheKey implements Serializable {
    private static final long serialVersionUID = -4469783255830688852L;
    private int id;
    private String type;
}
</code>```

Is there a way to retrieve all keys in the map using REST API?

答:
The REST API is in general only considered to be like a "last resort" type of access interface (for languages that do not have a native client, like PHP), since it'll not perform as good as native clients. On the other hand the built-in REST API only supports string or binary keys. That said it would be possible to build it, however it'll be much more complicated (you would have to serialize upfront and make sure, it'll be the same serialization as with Hazelcast).

You're probably better of to use the native Hazelcast client in your app or to build your own, specific REST API (webservice) to access the cluster information. The way to go most probably depends on your exact use case.

Body:
As per link http://docs.hazelcast.org/docs/3.5/manual/html/restclient.html

Hazelcast provides a REST interface, i.e. it provides an HTTP service in each node so that you can access your map using HTTP protocol. If you want to retrieve an entry, you can use a GET call.

For Example: http://10.20.17.1:5701/hazelcast/rest/maps/mapName/key1.

But what if my key is a Java custom object like:

public class RuleCacheKey implements Serializable {
    private static final long serialVersionUID = -4469783255830688852L;
    private int id;
    private String type;
}

Is there a way to retrieve all keys in the map using REST API?


问:
Assigning date to a cell in excel vba
I am just trying to enter the current date into a cell through excel vba macro.

Following is the code for the same.

```<code>Cells(i,j).value = Format(Date, "mm-dd-yyyy")
</code>```

Its giving me

Application-defined OR Object defined error

答:
```<code>Cells(i,j).value = Format(Now, "mm-dd-yyyy")
</code>```

Title: Assigning date to a cell in excel vba

Body:
I am just trying to enter the current date into a cell through excel vba macro.

Following is the code for the same.

Cells(i,j).value = Format(Date, "mm-dd-yyyy")

Its giving me

Application-defined OR Object defined error


问:
how can I set my rowspan value based on the no. of results in a query and change the value if it is a group or set depending on their set id?
Good day! I'm just new here and I hope someone or anyone can help me with my problem.

I've searched this site already and I found some near answer to my question but it's a bit now the answer I'm seeking.

I want to know how to merge rowspan based on the returned result in sql. I have this query:select * from equipments. then this is the table:

```<code>article | prop_num | value | meas | set_id
++++++++++++++++++++++++++++++++++++++++++
cpu     | desk_123 |80,000 | set  | dell01
mouse   | desk_123 |80,000 | set  | dell01
keyboard| desk_123 |80,000 | set  | dell01
monitor | desk_123 |80,000 | set  | dell01
camera  | cam123   |40,000 | unit | 1
cpu     | desk234  |5,000  | set  | 2
mouse   | desk234  |500    | set  | 3
keyboard| desk234  |500    | set  | 4
monitor | desk234  |2000   | set  | 5
printer | print111 |7,000  | unit | 6
</code>```

Then this is what I want to output:

```<code>article | prop_num | value | meas | set_id
++++++++++++++++++++++++++++++++++++++++++
Desktop | desk_123 |80,000 | set  | dell01
Computer| desk_123 |       | set  | dell01
        | desk_123 |       | set  | dell01
        | desk_123 |       | set  | dell01
camera  | cam123   |40,000 | unit | 1
Desktop | desk234  |8,000  | set  | 2
Computer| desk234  |       | set  | 3
        | desk234  |       | set  | 4
        | desk234  |       | set  | 5
printer | print111 |7,000  | unit | 6
</code>```

Sorry it's a bit messy. as u can see, there are two types of computer set, the one with fixed price and the one with individual price.   the first computer set is a fixed dell computer set that's why it has a set id, the other one is an assembled computer set(parts are like from different brands), which have their set id as a whole positive no.

I hope someone can help me, please!! thank ypu so much in advance!

答:
```<code>drop table if exists equipments;
create table equipments(article varchar(20), prop_num varchar(20), value int, meas varchar(20), set_id varchar(20));
insert into equipments values
('cpu'     , 'desk_123' ,80000 , 'set'  , 'dell01'),
('mouse'   , 'desk_123' ,80000 , 'set'  , 'dell01'),
('keyboard', 'desk_123' ,80000 , 'set'  , 'dell01'),
('monitor' , 'desk_123' ,80000 , 'set'  , 'dell01'),
('camera'  , 'cam123'   ,40000 , 'unit' , '1'),
('cpu'     , 'desk234'  ,5000  , 'set'  , '2'),
('mouse'   , 'desk234'  ,500   , 'set'  , '3'),
('keyboard', 'desk234'  ,500   , 'set'  , '4'),
('monitor' , 'desk234'  ,2000  , 'set'  , '5'),
('printer' , 'print111' ,7000  , 'unit' , '6');
</code>```

First Calculate total costs for sets where set_id is a number (testing the first character for an ascii number)

```<code>select prop_num,
        sum(value) as sumvalue
from equipments
where substring(set_id,1,1) between char(48) and char(57) and meas = 'set'
group by prop_num
order by prop_num
</code>```

result

```<code>+----------+----------+
| prop_num | sumvalue |
+----------+----------+
| desk234  |     8000 |
+----------+----------+
1 row in set (0.00 sec)
</code>```

Then join equipments to this adding a rownumber

```<code>select
        if(e.prop_num <> @p, @rn:=1,@rn:=@rn+1) Rownumber,
        @p:=e.prop_num,
        case when meas = 'set' then 'Desktop Computer'
        else article
        end
        as article1,
        e.*,
        case when s.prop_num is null then value
        else s.sumvalue
        end as sumvalue
from    equipments e
left join
(
select prop_num,
        sum(value) as sumvalue
from equipments
where substring(set_id,1,1) between char(48) and char(57) and meas = 'set'
group by prop_num
order by prop_num
) s
on s.prop_num = e.prop_num
,(select @rn:=0,@p:='') rn
order by prop_num
</code>```

result

```<code>+-----------+----------------+------------------+----------+----------+-------+------+--------+----------+
| Rownumber | @p:=e.prop_num | article1         | article  | prop_num | value | meas | set_id | sumvalue |
+-----------+----------------+------------------+----------+----------+-------+------+--------+----------+
|         1 | cam123         | camera           | camera   | cam123   | 40000 | unit | 1      |    40000 |
|         1 | desk234        | Desktop Computer | cpu      | desk234  |  5000 | set  | 2      |     8000 |
|         2 | desk234        | Desktop Computer | monitor  | desk234  |  2000 | set  | 5      |     8000 |
|         3 | desk234        | Desktop Computer | keyboard | desk234  |   500 | set  | 4      |     8000 |
|         4 | desk234        | Desktop Computer | mouse    | desk234  |   500 | set  | 3      |     8000 |
|         1 | desk_123       | Desktop Computer | cpu      | desk_123 | 80000 | set  | dell01 |    80000 |
|         2 | desk_123       | Desktop Computer | monitor  | desk_123 | 80000 | set  | dell01 |    80000 |
|         3 | desk_123       | Desktop Computer | keyboard | desk_123 | 80000 | set  | dell01 |    80000 |
|         4 | desk_123       | Desktop Computer | mouse    | desk_123 | 80000 | set  | dell01 |    80000 |
|         1 | print111       | printer          | printer  | print111 |  7000 | unit | 6      |     7000 |
+-----------+----------------+------------------+----------+----------+-------+------+--------+----------+
10 rows in set (0.00 sec)
</code>```

And finally decide what we want to display based on rownumber

```<code>select case when t.rownumber = 1 then t.article1 else '' end as article,
         t.prop_num,
         case when t.rownumber = 1 then t.sumvalue else '' end as value,
         t.meas,
         t.set_id
from
(
select
        if(e.prop_num <> @p, @rn:=1,@rn:=@rn+1) Rownumber,
        @p:=e.prop_num,
        case when meas = 'set' then 'Desktop Computer'
        else article
        end
        as article1,
        e.*,
        case when s.prop_num is null then value
        else s.sumvalue
        end as sumvalue
from equipments e
left join
(
select prop_num,
        sum(value) as sumvalue
from equipments
where substring(set_id,1,1) between char(48) and char(57) and meas = 'set'
group by prop_num
order by prop_num
) s
on s.prop_num = e.prop_num
,(select @rn:=0,@p:='') rn
order by prop_num
) t
order by t.prop_num, t.rownumber
</code>```

Result

```<code>+------------------+----------+-------+------+--------+
| article          | prop_num | value | meas | set_id |
+------------------+----------+-------+------+--------+
| camera           | cam123   | 40000 | unit | 1      |
| Desktop Computer | desk234  | 8000  | set  | 2      |
|                  | desk234  |       | set  | 5      |
|                  | desk234  |       | set  | 4      |
|                  | desk234  |       | set  | 3      |
| Desktop Computer | desk_123 | 80000 | set  | dell01 |
|                  | desk_123 |       | set  | dell01 |
|                  | desk_123 |       | set  | dell01 |
|                  | desk_123 |       | set  | dell01 |
| printer          | print111 | 7000  | unit | 6      |
+------------------+----------+-------+------+--------+
10 rows in set (0.00 sec)
</code>```

Having said all that it's probably best done in PHP (not one of my languages)

Body:
Good day! I'm just new here and I hope someone or anyone can help me with my problem.

I've searched this site already and I found some near answer to my question but it's a bit now the answer I'm seeking.

I want to know how to merge rowspan based on the returned result in sql. I have this query:select * from equipments. then this is the table:

article | prop_num | value | meas | set_id
++++++++++++++++++++++++++++++++++++++++++
cpu     | desk_123 |80,000 | set  | dell01
mouse   | desk_123 |80,000 | set  | dell01
keyboard| desk_123 |80,000 | set  | dell01
monitor | desk_123 |80,000 | set  | dell01
camera  | cam123   |40,000 | unit | 1
cpu     | desk234  |5,000  | set  | 2
mouse   | desk234  |500    | set  | 3
keyboard| desk234  |500    | set  | 4
monitor | desk234  |2000   | set  | 5
printer | print111 |7,000  | unit | 6

Then this is what I want to output:

article | prop_num | value | meas | set_id
++++++++++++++++++++++++++++++++++++++++++
Desktop | desk_123 |80,000 | set  | dell01
Computer| desk_123 |       | set  | dell01
        | desk_123 |       | set  | dell01
        | desk_123 |       | set  | dell01
camera  | cam123   |40,000 | unit | 1
Desktop | desk234  |8,000  | set  | 2
Computer| desk234  |       | set  | 3
        | desk234  |       | set  | 4
        | desk234  |       | set  | 5
printer | print111 |7,000  | unit | 6

Sorry it's a bit messy. as u can see, there are two types of computer set, the one with fixed price and the one with individual price.   the first computer set is a fixed dell computer set that's why it has a set id, the other one is an assembled computer set(parts are like from different brands), which have their set id as a whole positive no.

I hope someone can help me, please!! thank ypu so much in advance!

Body:
drop table if exists equipments;
create table equipments(article varchar(20), prop_num varchar(20), value int, meas varchar(20), set_id varchar(20));
insert into equipments values
('cpu'     , 'desk_123' ,80000 , 'set'  , 'dell01'),
('mouse'   , 'desk_123' ,80000 , 'set'  , 'dell01'),
('keyboard', 'desk_123' ,80000 , 'set'  , 'dell01'),
('monitor' , 'desk_123' ,80000 , 'set'  , 'dell01'),
('camera'  , 'cam123'   ,40000 , 'unit' , '1'),
('cpu'     , 'desk234'  ,5000  , 'set'  , '2'),
('mouse'   , 'desk234'  ,500   , 'set'  , '3'),
('keyboard', 'desk234'  ,500   , 'set'  , '4'),
('monitor' , 'desk234'  ,2000  , 'set'  , '5'),
('printer' , 'print111' ,7000  , 'unit' , '6');

First Calculate total costs for sets where set_id is a number (testing the first character for an ascii number)

select prop_num,
        sum(value) as sumvalue
from equipments
where substring(set_id,1,1) between char(48) and char(57) and meas = 'set'
group by prop_num
order by prop_num

result

+----------+----------+
| prop_num | sumvalue |
+----------+----------+
| desk234  |     8000 |
+----------+----------+
1 row in set (0.00 sec)

Then join equipments to this adding a rownumber

select
        if(e.prop_num <> @p, @rn:=1,@rn:=@rn+1) Rownumber,
        @p:=e.prop_num,
        case when meas = 'set' then 'Desktop Computer'
        else article
        end
        as article1,
        e.*,
        case when s.prop_num is null then value
        else s.sumvalue
        end as sumvalue
from    equipments e
left join
(
select prop_num,
        sum(value) as sumvalue
from equipments
where substring(set_id,1,1) between char(48) and char(57) and meas = 'set'
group by prop_num
order by prop_num
) s
on s.prop_num = e.prop_num
,(select @rn:=0,@p:='') rn
order by prop_num

result

+-----------+----------------+------------------+----------+----------+-------+------+--------+----------+
| Rownumber | @p:=e.prop_num | article1         | article  | prop_num | value | meas | set_id | sumvalue |
+-----------+----------------+------------------+----------+----------+-------+------+--------+----------+
|         1 | cam123         | camera           | camera   | cam123   | 40000 | unit | 1      |    40000 |
|         1 | desk234        | Desktop Computer | cpu      | desk234  |  5000 | set  | 2      |     8000 |
|         2 | desk234        | Desktop Computer | monitor  | desk234  |  2000 | set  | 5      |     8000 |
|         3 | desk234        | Desktop Computer | keyboard | desk234  |   500 | set  | 4      |     8000 |
|         4 | desk234        | Desktop Computer | mouse    | desk234  |   500 | set  | 3      |     8000 |
|         1 | desk_123       | Desktop Computer | cpu      | desk_123 | 80000 | set  | dell01 |    80000 |
|         2 | desk_123       | Desktop Computer | monitor  | desk_123 | 80000 | set  | dell01 |    80000 |
|         3 | desk_123       | Desktop Computer | keyboard | desk_123 | 80000 | set  | dell01 |    80000 |
|         4 | desk_123       | Desktop Computer | mouse    | desk_123 | 80000 | set  | dell01 |    80000 |
|         1 | print111       | printer          | printer  | print111 |  7000 | unit | 6      |     7000 |
+-----------+----------------+------------------+----------+----------+-------+------+--------+----------+
10 rows in set (0.00 sec)

And finally decide what we want to display based on rownumber

select case when t.rownumber = 1 then t.article1 else '' end as article,
         t.prop_num,
         case when t.rownumber = 1 then t.sumvalue else '' end as value,
         t.meas,
         t.set_id
from
(
select
        if(e.prop_num <> @p, @rn:=1,@rn:=@rn+1) Rownumber,
        @p:=e.prop_num,
        case when meas = 'set' then 'Desktop Computer'
        else article
        end
        as article1,
        e.*,
        case when s.prop_num is null then value
        else s.sumvalue
        end as sumvalue
from equipments e
left join
(
select prop_num,
        sum(value) as sumvalue
from equipments
where substring(set_id,1,1) between char(48) and char(57) and meas = 'set'
group by prop_num
order by prop_num
) s
on s.prop_num = e.prop_num
,(select @rn:=0,@p:='') rn
order by prop_num
) t
order by t.prop_num, t.rownumber

Result

+------------------+----------+-------+------+--------+
| article          | prop_num | value | meas | set_id |
+------------------+----------+-------+------+--------+
| camera           | cam123   | 40000 | unit | 1      |
| Desktop Computer | desk234  | 8000  | set  | 2      |
|                  | desk234  |       | set  | 5      |
|                  | desk234  |       | set  | 4      |
|                  | desk234  |       | set  | 3      |
| Desktop Computer | desk_123 | 80000 | set  | dell01 |
|                  | desk_123 |       | set  | dell01 |
|                  | desk_123 |       | set  | dell01 |
|                  | desk_123 |       | set  | dell01 |
| printer          | print111 | 7000  | unit | 6      |
+------------------+----------+-------+------+--------+
10 rows in set (0.00 sec)

Having said all that it's probably best done in PHP (not one of my languages)


问:
LinkedIn login API gives Access Forbidden 403 in step 3
So I have been following the tutorial to set up a LinkedIn login for my website.

I am able to do first two steps with ease and I get the authorization code.

Now I have to send HTTP POST and get JSON response to complete my LinkedIn API. I used following method to do same but I am getting an error.

Warning: file_get_contents(http://www.linkedin.com): failed to open
  stream: HTTP request failed! HTTP/1.0 403 Forbidden in
  D:\xampp\htdocs\LinkedIn\index.php on line 22 bool(false)

Can Anyone tell me what am I possibly doing wrong or alternative workaround?

答:
2 Years back i worked on linkedin login but it didn't work for me too.
I suggest instead using OAuth login try with javascript SDK.
linkedin login SDK

http to https could also the reason for access forbidden because OAuth hits a server to server request which is basically http to https.

Hope this will help.


问:
How to loop in
 HERE

I have created a loop outside the code and i decided later to put inside of a HTML/jquery Table but everytime I copy paste it doesnt work at all. Is there any posibility to put the foreach inside the ? Here is the Table "in the "LOOP" should be the generated text through foreach"

```<code>$rows += @"
    <div id="tabs">
      <ul>
        <li><a href="#tabs-1">Deutsch (DE)</a></li>
        <li><a href="#tabs-2">Englisch (EN)</a></li>
      </ul>
      <div id="tabs-1">
      <p>LOOP 1</p>
     </div>
      <div id="tabs-2">
        <p>LOOP 2</p>
      </div>

    </div>
    "@
</code>```

the loop

```<code>$tfsWis.Query("Select * from sth where [sample]  <> '' order by [Iteration Path] desc, Id desc") | Foreach-Object `
{
    $backgroundColor = 'background-color:green; color:white;'
    $item = $_
    if($oldIteration -and $oldIteration -ne $item.IterationPath)
    {
        $rows += @"
                </ul>
        </ul>
"@
    }
    if($oldIteration -ne $item.IterationPath)
    {
        $rows += @"
        <ul>
            <li><div>$($item.Fields["it"].value) </div> </li>
                    <ul>

"@
    }
    $rows += @"
                    <li><div>$($item.Fields["ID"].value)</div></li>
                        <ul>
                            <li>
                                <div>Title<br/>$($item.Fields["en"].value)</div>
                            </li>
                            <li>
                                <div>Description<br/>$($item.Fields["deen"].value)</div>
                            </li>

                            <li>
                                <div>Titel<br/>$($item.Fields["dee"].value)</div>
                            </li>
                            <li>
                                <div>Beschreibung<br/>$($item.Fields["es"].value)</div>
                            </li>
                        </ul>
"@
    $oldIteration = $item.IterationPath
}
</code>```

答:
In a simplified version, I would just suggest to split building up the tabs and the content in 2 different variables, and fill them up according to the data that is coming back

After the loop went through, you could then concatenate both the headers and the content

I've build a small sample based on the original code, that should just do what you wanted it to do. Note that my powershell knowledge is very rusty

```<code>$rowContent = @(
    ("title1", "content"),
    ("title2", "content 2"),
    ("title3", "content 3")
);
$tabheader = "<ul>";
$tabcontent = "";
$idx = 0;

for ($idx = 0; $idx -lt $rowContent.length; $idx++) {
    $item = $rowContent[$idx];
    $tabheader += "<li><a href='#tabs-$($idx)'>$($item[0])</a></li>";
    $tabcontent += "<div id='tabs-$($idx)'>$($item[1])</div>";
}
$tabheader += "</ul>";
$rows = "<div id='tabs'>$($tabheader)$($tabcontent)</div>";
Write-Host $rows;
</code>```

if you want to keep your multiline strings, you could also use the -f tag to do insert the values, like in the following example

```<code>$rowContent = @(
    ("title1", "content"),
    ("title2", "content 2"),
    ("title3", "content 3")
);
$tabheader = "";
$tabcontent = "";
$idx = 0;

for ($idx = 0; $idx -lt $rowContent.length; $idx++) {
    $item = $rowContent[$idx];
    $tabheader += @"
        <li>
            <a href='#tabs-{0}'>{1}</a>
        </li>

"@ -f $idx, $item[0];
    $tabcontent += @"
    <div id='tabs-{0}'>
        {1}
    </div>

"@ -f $idx, $item[1];
}
$rows = @"
<div id='tabs'>
    <ul>
{0}
    </ul>
{1}
</div>
"@ -f $tabheader, $tabcontent;
Write-Host $rows;
</code>```

which would output

```<code><div id='tabs'>
    <ul>
        <li>
            <a href='#tabs-0'>title1</a>
        </li>
        <li>
            <a href='#tabs-1'>title2</a>
        </li>
        <li>
            <a href='#tabs-2'>title3</a>
        </li>

    </ul>
    <div id='tabs-0'>
        content
    </div>
    <div id='tabs-1'>
        content 2
    </div>
    <div id='tabs-2'>
        content 3
    </div>

</div>
</code>```

Title: How to loop in <div> HERE <div/>

Body:
I have created a loop outside the code and i decided later to put inside of a HTML/jquery Table but everytime I copy paste it doesnt work at all. Is there any posibility to put the foreach inside the ? Here is the Table "in the "LOOP" should be the generated text through foreach"

$rows += @"

Deutsch (DE)

Englisch (EN)

LOOP 1

LOOP 2

    "@

the loop

$tfsWis.Query("Select * from sth where [sample]  <> '' order by [Iteration Path] desc, Id desc") | Foreach-Object `
{
    $backgroundColor = 'background-color:green; color:white;'
    $item = $_
    if($oldIteration -and $oldIteration -ne $item.IterationPath)
    {
        $rows += @"

"@
    }
    if($oldIteration -ne $item.IterationPath)
    {
        $rows += @"

$($item.Fields["it"].value)

"@
    }
    $rows += @"

$($item.Fields["ID"].value)

Title
$($item.Fields["en"].value)

Description
$($item.Fields["deen"].value)

Titel
$($item.Fields["dee"].value)

Beschreibung
$($item.Fields["es"].value)

"@
    $oldIteration = $item.IterationPath
}

Body:
In a simplified version, I would just suggest to split building up the tabs and the content in 2 different variables, and fill them up according to the data that is coming back

After the loop went through, you could then concatenate both the headers and the content

I've build a small sample based on the original code, that should just do what you wanted it to do. Note that my powershell knowledge is very rusty

$rowContent = @(
    ("title1", "content"),
    ("title2", "content 2"),
    ("title3", "content 3")
);
$tabheader = "<ul>";
$tabcontent = "";
$idx = 0;

for ($idx = 0; $idx -lt $rowContent.length; $idx++) {
    $item = $rowContent[$idx];
    $tabheader += "<li><a href='#tabs-$($idx)'>$($item[0])</a></li>";
    $tabcontent += "<div id='tabs-$($idx)'>$($item[1])</div>";
}
$tabheader += "</ul>";
$rows = "<div id='tabs'>$($tabheader)$($tabcontent)</div>";
Write-Host $rows;

if you want to keep your multiline strings, you could also use the -f tag to do insert the values, like in the following example

$rowContent = @(
    ("title1", "content"),
    ("title2", "content 2"),
    ("title3", "content 3")
);
$tabheader = "";
$tabcontent = "";
$idx = 0;

for ($idx = 0; $idx -lt $rowContent.length; $idx++) {
    $item = $rowContent[$idx];
    $tabheader += @"
        <li>
            <a href='#tabs-{0}'>{1}</a>
        </li>

"@ -f $idx, $item[0];
    $tabcontent += @"
    <div id='tabs-{0}'>
        {1}
    </div>

"@ -f $idx, $item[1];
}
$rows = @"
<div id='tabs'>
    <ul>
{0}
    </ul>
{1}
</div>
"@ -f $tabheader, $tabcontent;
Write-Host $rows;

which would output

<div id='tabs'>
    <ul>
        <li>
            <a href='#tabs-0'>title1</a>
        </li>
        <li>
            <a href='#tabs-1'>title2</a>
        </li>
        <li>
            <a href='#tabs-2'>title3</a>
        </li>

    </ul>
    <div id='tabs-0'>
        content
    </div>
    <div id='tabs-1'>
        content 2
    </div>
    <div id='tabs-2'>
        content 3
    </div>

</div>


答: Create a property in viewcontoller and set it in prepareForSegue method.</p>

Title: Passing data to another UIViewController with buttons

Body:
so I have a UIScrollView with all of these buttons overlayed with images:

http://i.imgur.com/W6hagsa.png

and I need it so that if you click on a teacher, like Mr Edmondson for maths, In another UIViewController, an email screen pops up and it needs to set the email recipient to edmondson@gmail.com.

Basically you click on whatever teacher, and it sets the email recipient to that teacher. My current code in the recipients & message body is:

let toRecipients = ["placeholder@gmail.com"]
mc.setMessageBody("blah blah blah blah")

How would I do this ?


问:
Search for TRUE in a vector containing TRUE / FALSE
```<code>A<-(FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE)
</code>```

<p>I want an efficient way to find if A has TRUE and stop when TRUE is found. </p>

答:
If you just want to know if A contains any TRUE values, you can use any():

```<code>> A <- c(FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE)
> any(A)
[1] TRUE
</code>```

Body:
A<-(FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE)

I want an efficient way to find if A has TRUE and stop when TRUE is found.

Body:
If you just want to know if A contains any TRUE values, you can use any():

> A <- c(FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE)
> any(A)
[1] TRUE

ContentLicense: CC BY-SA 4.0


问:
C Memory Buffer corrupting micro-controller memory allocation - Atmel ATxmega
I am using the ATxmega128A1 8-bit microcontroller, and I am trying to figure out why my memory buffer is behaving strangely.

I have a FIFO buffer of the following structure:

```<code>typedef struct
{
  FIFOid ID;                        //ID value to determine the type of FIFO being used
  BOOL LOCK;                        //A lock to prevent multiple FIFO accessing (i.e. data corruption)
  UINT16 Start, End;                //Value of the current start and end FIFO index
  UINT16 volatile NbBytes;          //Number of bytes currently inside the FIFO
  UINT8 Buffer[FIFO_SIZE];          //Memory buffer for the FIFO buffer
} TFIFO;
</code>```

And I define 2 FIFOs:

```<code>//FIFO Buffers for USART
TFIFO RxFIFO;           //Creates the Receive FIFO
TFIFO TxFIFO;           //Creates the Transmit FIFO
</code>```

Where FIFO_SIZE is

```<code>#define FIFO_SIZE 256
</code>```

When I want to get a byte from the Buffer[] I pass a pointer to the FIFO through this function:

```<code>BOOL FIFO_Get(TFIFO * const FIFO, UINT8 * const dataPtr);
</code>```

This works fine, however, once I increase my FIFO_SIZE above ~510 bytes - Passing this FIFO pointer through this function causes another one of my FIFOs' buffer to be altered.

I have seen on my debugger, there is no problem at this line:

```<code>if(FIFO_Get(&TxFIFO, &data)){       //Get a byte from TxFIFO
</code>```

And once I step over, and it is passed through to the function, the RxFIFO->Buffer[] array is modified, namely the larger address values.
FIFO_Get function:

```<code>// ----------------------------------------
// FIFO_Get
// ----------------------------------------
// Remove one character from the FIFO
// Input:
//   FIFO is a  pointer to a FIFO struct with data to be retrieved
//   dataPtr is a pointer to a memory location to place the retrieved byte
// Output:
//   TRUE if the operation was successful and the data is valid
// Conditions:
//   Assumes that FIFO_Init has been called

BOOL FIFO_Get(TFIFO * const FIFO, UINT8 * const dataPtr)
{
    BOOL FIFOGetSuccess;
    FIFOGetSuccess = bFALSE;

    //disable interrupts
    //if we're GETTING from the USART receive FIFO
    //we need to disable the receive interrupt so
    //there is no data being 'Put' during a 'Get'
    if(FIFO->ID == URX){
        USARTD0.CTRLA = USART_RXCINTLVL_OFF_gc; //Rx interrupts off
        USARTD1.CTRLA = USART_RXCINTLVL_OFF_gc; //Rx interrupts off
    }

    //Attempt to get a byte from the FIFO
    if(FIFO->LOCK == bFALSE){                           //Check that the FIFO is not locked
        FIFO->LOCK = bTRUE;                             //lock the FIFO
        if (FIFO->NbBytes == 0){                        //Checks whether FIFO is empty; number of bytes in FIFO = 0
            FIFOGetSuccess = bFALSE;                    //If empty, false is Returned
        }else{
            *dataPtr = FIFO->Buffer[FIFO->Start];       //Reads the byte in the FIFO start position, and saves it to the location of the data pointer
            if (FIFO->Start == (FIFO_SIZE - 1)){        //Checks whether the start position is equal to FIFO size, the last valid 8 bit number
                FIFO->Start = 0;                        //If so, the position is set to 0
            }else{                                      //If not fifo size;
                FIFO->Start++;                          //Increments the start position by 1
            }
            FIFO->NbBytes--;                            //Decrements the number of bytes in the FIFO by 1
            FIFOGetSuccess =  bTRUE;                    //Returns true if this is successful
        }
        FIFO->LOCK = bFALSE;                            //unlock the FIFO
    }

    //re-enable interrupts
    if(FIFO->ID == URX){
        USARTD0.CTRLA = USART_RXCINTLVL_LO_gc;  //low level interrupts on Rx
        USARTD1.CTRLA = USART_RXCINTLVL_LO_gc;  //low level interrupts on Rx
    }

    return FIFOGetSuccess;
}
</code>```

My guess is that i am not safely allocating memory in the microcontroller, however there seems to be plenty of memory left in the chip, after build:

```<code>        Program Memory Usage    :   21460 bytes   15.4 % Full
        Data Memory Usage       :   6967 bytes   12.1 % Full
</code>```

How do I go about fixing this & what am I doing wrong?

EDIT:

I have found that increasing the FIFO SIZE maps the FIFO buffer over the SRAM address range (the SRAM of the ATxmega128A1 goes from 0x2000 to 0x3FFF)

FIFO address mapping

The addresses 0x3FF7 to 0x3FFF are changing when the other FIFO is passed through a function

EDIT 2:
Elf Files

Body:
I am using the ATxmega128A1 8-bit microcontroller, and I am trying to figure out why my memory buffer is behaving strangely.

I have a FIFO buffer of the following structure:

typedef struct
{
  FIFOid ID;                        //ID value to determine the type of FIFO being used
  BOOL LOCK;                        //A lock to prevent multiple FIFO accessing (i.e. data corruption)
  UINT16 Start, End;                //Value of the current start and end FIFO index
  UINT16 volatile NbBytes;          //Number of bytes currently inside the FIFO
  UINT8 Buffer[FIFO_SIZE];          //Memory buffer for the FIFO buffer
} TFIFO;

And I define 2 FIFOs:

//FIFO Buffers for USART
TFIFO RxFIFO;           //Creates the Receive FIFO
TFIFO TxFIFO;           //Creates the Transmit FIFO

Where FIFO_SIZE is

#define FIFO_SIZE 256

When I want to get a byte from the Buffer[] I pass a pointer to the FIFO through this function:

BOOL FIFO_Get(TFIFO * const FIFO, UINT8 * const dataPtr);

This works fine, however, once I increase my FIFO_SIZE above ~510 bytes - Passing this FIFO pointer through this function causes another one of my FIFOs' buffer to be altered.

I have seen on my debugger, there is no problem at this line:

if(FIFO_Get(&TxFIFO, &data)){       //Get a byte from TxFIFO

And once I step over, and it is passed through to the function, the RxFIFO->Buffer[] array is modified, namely the larger address values.
FIFO_Get function:

// ----------------------------------------
// FIFO_Get
// ----------------------------------------
// Remove one character from the FIFO
// Input:
//   FIFO is a  pointer to a FIFO struct with data to be retrieved
//   dataPtr is a pointer to a memory location to place the retrieved byte
// Output:
//   TRUE if the operation was successful and the data is valid
// Conditions:
//   Assumes that FIFO_Init has been called

BOOL FIFO_Get(TFIFO * const FIFO, UINT8 * const dataPtr)
{
    BOOL FIFOGetSuccess;
    FIFOGetSuccess = bFALSE;

    //disable interrupts
    //if we're GETTING from the USART receive FIFO
    //we need to disable the receive interrupt so
    //there is no data being 'Put' during a 'Get'
    if(FIFO->ID == URX){
        USARTD0.CTRLA = USART_RXCINTLVL_OFF_gc; //Rx interrupts off
        USARTD1.CTRLA = USART_RXCINTLVL_OFF_gc; //Rx interrupts off
    }

    //Attempt to get a byte from the FIFO
    if(FIFO->LOCK == bFALSE){                           //Check that the FIFO is not locked
        FIFO->LOCK = bTRUE;                             //lock the FIFO
        if (FIFO->NbBytes == 0){                        //Checks whether FIFO is empty; number of bytes in FIFO = 0
            FIFOGetSuccess = bFALSE;                    //If empty, false is Returned
        }else{
            *dataPtr = FIFO->Buffer[FIFO->Start];       //Reads the byte in the FIFO start position, and saves it to the location of the data pointer
            if (FIFO->Start == (FIFO_SIZE - 1)){        //Checks whether the start position is equal to FIFO size, the last valid 8 bit number
                FIFO->Start = 0;                        //If so, the position is set to 0
            }else{                                      //If not fifo size;
                FIFO->Start++;                          //Increments the start position by 1
            }
            FIFO->NbBytes--;                            //Decrements the number of bytes in the FIFO by 1
            FIFOGetSuccess =  bTRUE;                    //Returns true if this is successful
        }
        FIFO->LOCK = bFALSE;                            //unlock the FIFO
    }

    //re-enable interrupts
    if(FIFO->ID == URX){
        USARTD0.CTRLA = USART_RXCINTLVL_LO_gc;  //low level interrupts on Rx
        USARTD1.CTRLA = USART_RXCINTLVL_LO_gc;  //low level interrupts on Rx
    }

    return FIFOGetSuccess;
}

My guess is that i am not safely allocating memory in the microcontroller, however there seems to be plenty of memory left in the chip, after build:

        Program Memory Usage    :   21460 bytes   15.4 % Full
        Data Memory Usage       :   6967 bytes   12.1 % Full

How do I go about fixing this & what am I doing wrong?

EDIT:

I have found that increasing the FIFO SIZE maps the FIFO buffer over the SRAM address range (the SRAM of the ATxmega128A1 goes from 0x2000 to 0x3FFF)

FIFO address mapping

The addresses 0x3FF7 to 0x3FFF are changing when the other FIFO is passed through a function

EDIT 2:
Elf Files

Body:
From the ELF file, I can see this memory map:

00802000 B __bss_start
00802000 D __data_end
00802000 D __data_start
00802000 D _edata
00802000 00000002 b n.4418
00802002 00000001 b packetEnd.1686
00802003 00000002 b byteCount.1684
00802005 00000002 b StepsCounted.4253
00802007 00000001 b ErrorCode.4252
00802008 00000001 b SuccessNb.4251
00802009 00000001 b ReturnNb.4250
0080200a 00000004 b stepsOutOpto.4211
0080200e 00000004 b HomingError.4212
00802012 00000008 b stepscounted.4210
0080201a 00000004 b CntHomeState.4209
0080201e 00000001 b byteCount.4166
0080201f 00000002 B EjectMsgID
00802021 00000001 B VersionMinor
00802022 00000002 B QueueEnd
00802024 00000001 B VersionMonth
00802025 00000001 B ACC1_IN
00802026 0000001f B PacketQRx
00802045 0000001f B PacketTx
00802064 00000001 B VersionMajor
00802065 00000001 B DeviceTypeId
00802066 00000001 B debugCycler_bytes
00802067 00000001 B debugAXIS_ACK
00802068 000000d4 B AXIS
0080213c 00000001 B LVL_SENSE_IN
0080213d 00000001 B LID_DETECTION_ON
0080213e 00000001 B readyimmediateTx
0080213f 0000001f B PacketQTx
0080215e 00000004 B RobotSerialNumber
00802162 00000001 B USBIN
00802163 00000001 B startupComplete
00802164 000007c0 B PacketQueue
00802924 0000001f B PacketRx
00802943 00000001 B ACC2_IN
00802944 00000002 B QueueNb
00802946 00000001 B QueuedCommandCalled
00802947 0000001f B dummyPkt
00802966 00000001 B CYCLER_IN
00802967 00000002 B QueueStart
00802969 00000001 B HardwareRevision
0080296a 00000001 B VersionYear
0080296b 00000980 B AXISRxFIFO
008032eb 00000004 B RTS
008032ef 00000980 B AXISTxFIFO
00803c6f 00000068 B AXIS_SPI_Tx_Packet
00803cd7 00000004 B ReturnPacketMissed
00803cdb 00000068 B AXIS_SPI_Rx_Packet
00803d43 00000004 B NbPacketsInAxisFIFO
00803d47 00000100 B CyclerEEPROM
00803e47 00000260 B TxFIFO
008040a7 00000260 B RxFIFO
00804307 B __bss_end

Note: the way I had this map was by using nm with the command nm -S -n MotorBoard\ Xmega\ Large\ FIFO.elf. The first column is the address and the second column is the size of the variables.

ATMEL ATxmega128A1 Datasheet says you have 8KB of SRAM between 0x2000 and 0x3FFF. As you can see both of your FIFO buffer overlap the 0x3FFF limit (0x3E47 for TxFIFO and 0x40A7 for RxFIFO).

One way to fix your issue is to move some of your variable into ROM by declaring them as const. For instance, I can see VersionMonth, VersionMajor that are probably constant.


问:
Find Textbox control
In my application i have 50 textboxes i want find all the textbox control using the code and i want to perform a color change in the textbox after doing certain validations. How can i acheive that? i used the following code but it doesnt work properly

```<code>foreach (Control cntrl in Page.Controls)
    {
        if (cntrl is TextBox)
        {
            //Do the operation
        }
    }
</code>```

<%@ Page Language="C#" MasterPageFile="~/HomePageMaster.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="Default" Title="Sample Page" %>

答:
I've recently started doing this the 'modern' LINQ way. First you need an extension method to grab all the controls of the type you're interested in:

```<code>//Recursively get all the formControls
public static IEnumerable<Control> GetAllControls(this Control parent)
{
     foreach (Control control in parent.Controls)
        {
            yield return control;
            foreach (Control descendant in control.GetAllControls())
            {
                yield return descendant;
            }
     }
}`
</code>```

Then you can call it in your webform / control:

```<code>var formCtls = this.GetAllControls().OfType<Checkbox>();

foreach(Checkbox chbx in formCtls){
</code>```

//do what you gotta do ;)
}

Regards,

5arx

Title: Find Textbox control

Body:
In my application i have 50 textboxes i want find all the textbox control using the code and i want to perform a color change in the textbox after doing certain validations. How can i acheive that? i used the following code but it doesnt work properly

foreach (Control cntrl in Page.Controls)
    {
        if (cntrl is TextBox)
        {
            //Do the operation
        }
    }

<%@ Page Language="C#" MasterPageFile="~/HomePageMaster.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="Default" Title="Sample Page" %>

Body:
I've recently started doing this the 'modern' LINQ way. First you need an extension method to grab all the controls of the type you're interested in:

//Recursively get all the formControls
public static IEnumerable<Control> GetAllControls(this Control parent)
{
     foreach (Control control in parent.Controls)
        {
            yield return control;
            foreach (Control descendant in control.GetAllControls())
            {
                yield return descendant;
            }
     }
}`

Then you can call it in your webform / control:

var formCtls = this.GetAllControls().OfType<Checkbox>();

foreach(Checkbox chbx in formCtls){

//do what you gotta do ;)
}

Regards,

5arx


问:
How to redirect to another page after form action?
I am using Simple Form (getsimpleform.com) to email the HTML form contents to my email. The problem I am facing is that the HTML Form action is handled by getsimpleform so when the user clicks on submit button of the form, they are redirected to https://getsimpleform.com/ but I want them to stay be redirected to another page (i.e. contact.html).

So I want the form action to be performed but at the same time, I want the user to be redirected to another web page.

Thanks.

答:
Just fill up your action attribute</p>

```<code><form action="next-page-please-url">
<button>butt</button>
</form>
</code>```

Body:
Just fill up your action attribute

<form action="next-page-please-url">
<button>butt</button>
</form>


问:
How to use checkboxes to filter data in angular smart table?
I'm trying to filter data with checkboxes because I just need yes or no options.

```<code>    <div class="col-xs-3">
        <input type="checkbox" data-st-search="option1" checked>
    </div>
    <div class="col-xs-3">
        <input type="checkbox" data-st-search="option2" checked>
    </div>
    <div class="col-xs-3">
         <input type="checkbox" data-st-search="option3" checked>
    </div>
    <div class="col-xs-3">
         <input type="checkbox" data-st-search="option4" checked>
    </div>
</code>```

It sends just the last one always on

答:
You can use a directive with require: '^stTable' then, when checkbox model change, use table.search(value, scope.predicate);

OR

```<code><input type="checkbox" data-st-search="option3" ng-true-value="'YES'" ng-false-value="'NO'" checked>
</code>```

Body:
I'm trying to filter data with checkboxes because I just need yes or no options.

        <input type="checkbox" data-st-search="option1" checked>

        <input type="checkbox" data-st-search="option2" checked>

         <input type="checkbox" data-st-search="option3" checked>

         <input type="checkbox" data-st-search="option4" checked>

It sends just the last one always on

Body:
You can use a directive with require: '^stTable' then, when checkbox model change, use table.search(value, scope.predicate);

OR

<input type="checkbox" data-st-search="option3" ng-true-value="'YES'" ng-false-value="'NO'" checked>


问:
Split string into array in Python
I have a string with the following structure.

string = "[abcd, abc, a, b, abc]"

I would like to convert that into an array. I keep using the split function in Python but I get spaces and the brackets on the start and the end of my new array. I tried working around it with some if statements but I keep missing letters in the end from some words.

Keep in mind that I don't know the length of the elements in the string. It could be 1, 2, 3 etc.

答: First remove [ and ] from your string, then split on commas, then remove spaces from resulting items (using strip).

Title: Split string into array in Python


问:
Basic authentication in Lumen
I have already written an API call for check authentication using Laravel. I need to move that controller to Lumen for use it as micro service.

This is my controller in Laravel.

```<code>public function byCredantial(Request $request)
{
    $user = [
        'email' => $request->input('email'),
        'password' => $request->input('password')
    ];

    if (Auth::attempt($user)) {
        $response = $this->getSuccess(Auth::user()->id);

        return response()->json($response, 200);
    } else {
        $response = $this->getError($user);

        return response()->json($response, 401);
    }
}
</code>```

Lumen doc is not provide how to do such authentication. They has not function for check creadential is correct. How can i do this in Lumen. Is this possible?

答:
You can do this in Lumen. Facades are disabled by default (if you want to enable it you can see the instructions in the documentation), but I would not recommend enabling the facades as the add additional overhead to your application. Instead, I would modify your function to call app('auth'). This will return the class that the Auth facade proxies without loading all the other facades.

```<code>public function byCredantial(Request $request)
{
    $user = [
        'email' => $request->input('email'),
        'password' => $request->input('password')
    ];

    $auth = app('auth');

    if ($auth->attempt($user)) {
        $response = $this->getSuccess($auth->user()->id);

        return response()->json($response, 200);
    } else {
        $response = $this->getError($user);

        return response()->json($response, 401);
    }
}
</code>```

Also, I would recommend reading the authentication documentation and placing the bulk of this code in the AuthServiceProvider.

Title: Basic authentication in Lumen

Body:
I have already written an API call for check authentication using Laravel. I need to move that controller to Lumen for use it as micro service.

This is my controller in Laravel.

public function byCredantial(Request $request)
{
    $user = [
        'email' => $request->input('email'),
        'password' => $request->input('password')
    ];

    if (Auth::attempt($user)) {
        $response = $this->getSuccess(Auth::user()->id);

        return response()->json($response, 200);
    } else {
        $response = $this->getError($user);

        return response()->json($response, 401);
    }
}

Lumen doc is not provide how to do such authentication. They has not function for check creadential is correct. How can i do this in Lumen. Is this possible?

Body:
You can do this in Lumen. Facades are disabled by default (if you want to enable it you can see the instructions in the documentation), but I would not recommend enabling the facades as the add additional overhead to your application. Instead, I would modify your function to call app('auth'). This will return the class that the Auth facade proxies without loading all the other facades.

public function byCredantial(Request $request)
{
    $user = [
        'email' => $request->input('email'),
        'password' => $request->input('password')
    ];

    $auth = app('auth');

    if ($auth->attempt($user)) {
        $response = $this->getSuccess($auth->user()->id);

        return response()->json($response, 200);
    } else {
        $response = $this->getError($user);

        return response()->json($response, 401);
    }
}

Also, I would recommend reading the authentication documentation and placing the bulk of this code in the AuthServiceProvider.


问:
Linux system call getname info return EAI_AGAIN
In my C++ application I use getnameinfo and it returns EAI_AGAIN - what causes this error?

```<code>struct sockaddr_storage ss;
socklen_t salen = sizeof(ss);
struct sockaddr *sa;
struct addrinfo hints, *paddr, *paddrp;

sa = (struct sockaddr *)&ss;

if (getpeername(sock, sa, &salen) != 0) {
    error = errno;
    return -1;
}

char hbuf[NI_MAXHOST];
char pbuf[NI_MAXSERV];
if (0 != (error = getnameinfo(sa, salen,
                  hbuf, sizeof(hbuf),
                  pbuf, sizeof(pbuf),
                  0))) {
    return -1;//here it returns, the error is -3=EAI_AGAIN
}
</code>```

答:
According to getnameinfo:

[EAI_AGAIN] The name could not be resolved at this time. Future attempts may succeed.

The most likely reason would be some kind of timeout during the DNS lookup.

Body:
In my C++ application I use getnameinfo and it returns EAI_AGAIN - what causes this error?

struct sockaddr_storage ss;
socklen_t salen = sizeof(ss);
struct sockaddr *sa;
struct addrinfo hints, *paddr, *paddrp;

sa = (struct sockaddr *)&ss;

if (getpeername(sock, sa, &salen) != 0) {
    error = errno;
    return -1;
}

char hbuf[NI_MAXHOST];
char pbuf[NI_MAXSERV];
if (0 != (error = getnameinfo(sa, salen,
                  hbuf, sizeof(hbuf),
                  pbuf, sizeof(pbuf),
                  0))) {
    return -1;//here it returns, the error is -3=EAI_AGAIN
}


问:
Scala Play WebSocket - One Actor, multiple message types
What I want to do is basically 1:1 this: Scala Play Websocket - use one out actor to send both: Array[Byte] and String messages

Sadly the API has changed a lot since 2.4 (I am on 2.6.0-M4 right now).

What I tried (does not compile for obvious reasons):

```<code>WebSocket.accept[WSMessage, WSMessage]
    {
      request =>
        ActorFlow.actorRef
        {
          out => WebSocketActor.props(out)
        }
    }

  sealed trait WSMessage
  case class StringMessage(s: String) extends WSMessage
  case class BinaryMessage(a: Array[Byte]) extends WSMessage
  case class JsonMessage(js: JsValue) extends WSMessage

  object MyMessageFlowTransformer
  {
    implicit val WSMessageFlowTransformer: MessageFlowTransformer[WSMessage, WSMessage] =
    {
      new MessageFlowTransformer[WSMessage, WSMessage]
      {
        def transform(flow: Flow[WSMessage, WSMessage, _]) =
        {
          AkkaStreams.bypassWith[Message, WSMessage, Message](Flow[Message] collect
          {
            case StringMessage(s) => Left(s)
            case BinaryMessage(b) => Left(b)
            case JsonMessage(j) => Left(j)
            case _ => Right(CloseMessage(Some(CloseCodes.Unacceptable)))
          })(flow map WSMessage.apply)
        }
      }
    }
  }
</code>```

I am somewhat lost. play.api.http.websocket.Message is a sealed trait, and probably for a good reason...

答:
Define a MessageFlowTransformer[Either[String, Array[Byte]], Either[String, Array[Byte]]]:

type WSMessage = Either[String, Array[Byte]]

implicit val mixedMessageFlowTransformer: MessageFlowTransformer[WSMessage, WSMessage] = {
  new MessageFlowTransformer[WSMessage, WSMessage] {
    def transform(flow: Flow[WSMessage, WSMessage, _]) = {
      AkkaStreams.bypassWith[Message, WSMessage, Message](Flow[Message].collect {
        case BinaryMessage(data) => Left(Right(data.toArray))
        case TextMessage(text) => Left(Left(text))
      })(flow map {
        case Right(data) => BinaryMessage.apply(ByteString.apply(data))
        case Left(text) => TextMessage.apply(text)
      })
    }
  }
}
```

Body:
What I want to do is basically 1:1 this: Scala Play Websocket - use one out actor to send both: Array[Byte] and String messages

Sadly the API has changed a lot since 2.4 (I am on 2.6.0-M4 right now).

What I tried (does not compile for obvious reasons):

WebSocket.accept[WSMessage, WSMessage]
    {
      request =>
        ActorFlow.actorRef
        {
          out => WebSocketActor.props(out)
        }
    }

  sealed trait WSMessage
  case class StringMessage(s: String) extends WSMessage
  case class BinaryMessage(a: Array[Byte]) extends WSMessage
  case class JsonMessage(js: JsValue) extends WSMessage

  object MyMessageFlowTransformer
  {
    implicit val WSMessageFlowTransformer: MessageFlowTransformer[WSMessage, WSMessage] =
    {
      new MessageFlowTransformer[WSMessage, WSMessage]
      {
        def transform(flow: Flow[WSMessage, WSMessage, _]) =
        {
          AkkaStreams.bypassWith[Message, WSMessage, Message](Flow[Message] collect
          {
            case StringMessage(s) => Left(s)
            case BinaryMessage(b) => Left(b)
            case JsonMessage(j) => Left(j)
            case _ => Right(CloseMessage(Some(CloseCodes.Unacceptable)))
          })(flow map WSMessage.apply)
        }
      }
    }
  }

I am somewhat lost. play.api.http.websocket.Message is a sealed trait, and probably for a good reason...


问:
How can query string parameters be forwarded through a proxy_pass with nginx?
```<code>upstream apache {
   server 127.0.0.1:8080;
}
server{
   location ~* ^/service/(.*)$ {
      proxy_pass http://apache/$1;
      proxy_redirect off;
   }
 }
</code>```

The above snippet will redirect requests where the url includes the string "service" to another server, but it does not include query parameters.

答:
To redirect Without Query String add below lines in Server block under listen port line:

```<code>if ($uri ~ .*.containingString$) {
           return 301 https://$host/$uri/;
}
</code>```

With Query String:

```<code>if ($uri ~ .*.containingString$) {
           return 301 https://$host/$uri/?$query_string;
}
</code>```

Body:
upstream apache {
   server 127.0.0.1:8080;
}
server{
   location ~* ^/service/(.*)$ {
      proxy_pass http://apache/$1;
      proxy_redirect off;
   }
 }

The above snippet will redirect requests where the url includes the string "service" to another server, but it does not include query parameters.

Body:
To redirect Without Query String add below lines in Server block under listen port line:

if ($uri ~ .*.containingString$) {
           return 301 https://$host/$uri/;
}

With Query String:

if ($uri ~ .*.containingString$) {
           return 301 https://$host/$uri/?$query_string;
}


答:
Your code seems nice. However, the problem is probably that you do not declare the activesheet. Or see what are the values of i and j:

```<code>debug.print i; j
ActiveSheet.Cells(i,j).value = Format(Date, "mm-dd-yyyy")
</code>```

or

```<code>Worksheets(1).Cells(i,j).value = Format(Date, "mm-dd-yyyy")
</code>```

See a bit about the range object here:
https://msdn.microsoft.com/en-us/library/office/ff838238.aspx

Title: Assigning date to a cell in excel vba

Body:
I am just trying to enter the current date into a cell through excel vba macro.

Following is the code for the same.

Cells(i,j).value = Format(Date, "mm-dd-yyyy")

Its giving me

Application-defined OR Object defined error

Body:
Your code seems nice. However, the problem is probably that you do not declare the activesheet. Or see what are the values of i and j:

debug.print i; j
ActiveSheet.Cells(i,j).value = Format(Date, "mm-dd-yyyy")

or

Worksheets(1).Cells(i,j).value = Format(Date, "mm-dd-yyyy")

See a bit about the range object here:
https://msdn.microsoft.com/en-us/library/office/ff838238.aspx


问:
kube-proxy reports wrong ip address
In my kubernetes cluster, each node is a virtualbox vm with two NICs, eth0 for NAT and eth1 for Host-Local communicating.

kubectl get pod --all-namespaces -o wide shows

We can see k8s-3 and k8s-4 reports correct IPs while k8s-2 doesn't.

I've tried to add --bind-address=192.168.99.202 in k8s-2's kube-proxy.yaml but it just don't work.

Anyone has any advice?

答:
https://github.com/kubernetes/kubernetes/issues/44702

Problem solved by passing --node-ip= to kubelet.

Title: kube-proxy reports wrong ip address