问:
Nesting @keyframe in @media
I have to fix a bug with curly brackets. But all opening brackets have pair.
There are error on line 212

Expected RBRACE at line 212, col 2.
      @-webkit-keyframes move {

But when I test code separate before 212 and after 212 - no errors seen.

```<code>@media all and (min-width:  1px){
.main-pointing-slider .box .dot-4{
    bottom: -2px;
    left: 128px;
    top: auto;
    right: auto;
    bottom: -2px;
    left: calc(50% - 3px);
    position: absolute;
    -webkit-animation-name: dotShow;
    -webkit-animation-duration: 0.5s;
    -webkit-animation-delay: 2s;
    -webkit-animation-timing-function: linear;
    -moz-animation-name: dotShow;
    -moz-animation-duration: 0.5s;
    -moz-animation-delay: 2s;
    -moz-animation-timing-function: linear;
    animation-name: dotShow;
    animation-duration: 0.5s;
    animation-delay: 2s;
    animation-timing-function: linear;
    -webkit-animation-fill-mode: forwards;
    -moz-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
    background: linear-gradient(to bottom, #dcd4cb 0%, #f3c886 100%)
}
.main-pointing-slider .box .svg-gradient{
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    position: absolute
}
.main-pointing-slider .box .svg-gradient .svg-box{
    width: 100%;
    height: 100%
}
.main-pointing-slider .box .svg-gradient .svg-box rect{
    visibility: visible
}
.main-pointing-slider .slide{
    /*display: none;*/
    width: 100%;
    height: 100%;
    top: 0;
    /*position: absolute;*/
    overflow: hidden
}
.main-pointing-slider .slide .point{
    top: 1px;
    right: 0;
    bottom: 0;
    left: 1px;
    position: relative;
    width: 248px;
    height: 126px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    -webkit-border-radius: 120px;
    -moz-border-radius: 120px;
    border-radius: 120px;
    opacity: 0;
    margin: 0
    auto
}
.main-pointing-slider .slide .point .svg-gradient-point{
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    position: absolute;
    z-index: 2
}
.main-pointing-slider .slide .point .svg-gradient-point .svg-box{
    width: 100%;
    height: 100%
}
.main-pointing-slider .slide .point .svg-gradient-point .svg-box rect{
    stroke-width: 2
}
.main-pointing-slider .slide .point .point-inner{
    top: 0;
    right: auto;
    bottom: auto;
    left: 0;
    position: absolute;
    width: 100%;
    height: 100%;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    -webkit-border-radius: 120px;
    -moz-border-radius: 120px;
    border-radius: 120px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    overflow: hidden;
    background: no-repeat 50%;
    background-size: cover
}
.main-pointing-slider .slide .point-shadow{
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    position: absolute;
    width: 260px;
    height: 130px;
    width: calc(260px - 6px);
    height: calc(130px - 6px);
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    -webkit-border-radius: 120px;
    -moz-border-radius: 120px;
    border-radius: 120px;
    opacity: 0;
    z-index: 3;
    margin: 0
    auto;
    background: black
}
.main-pointing-slider .slide .upper-text{
    top: auto;
    right: -100%;
    bottom: 72%;
    left: auto;
    position: absolute;
    width: 62%;
    text-transform: uppercase;
    text-align: right;
    font-size: 13px;
    font-family: "Tahoma Bold",sans-serif;
    font-weight: 600;
    line-height: 1.12;
    color: #e7c28b;
    display: none
}
.main-pointing-slider .slide .lower-text{
    top: 34%;
    right: -100%;
    bottom: auto;
    left: auto;
    position: absolute;
    width: 53%;
    font-size: 12px;
    font-family: "Tahoma Regular",sans-serif;
    line-height: 1.3;
    text-align: right;
    color: white;
    display: none
}
.main-pointing-slider .slide.active{
    display: block
}
.main-pointing-slider.startFirstFrame .line{
    -webkit-animation-name: move;
    -webkit-animation-duration: 0.9s;
    -webkit-animation-delay: 0s;
    -webkit-animation-timing-function: ease;
    -moz-animation-name: move;
    -moz-animation-duration: 0.9s;
    -moz-animation-delay: 0s;
    -moz-animation-timing-function: ease;
    animation-name: move;
    animation-duration: 0.9s;
    animation-delay: 0s;
    animation-timing-function: ease
}
.slide.animationIn .point{
    -webkit-animation-name: point;
    -webkit-animation-duration: 1s;
    -webkit-animation-delay: 0s;
    -webkit-animation-timing-function: ease-out;
    -moz-animation-name: point;
    -moz-animation-duration: 1s;
    -moz-animation-delay: 0s;
    -moz-animation-timing-function: ease-out;
    animation-name: point;
    animation-duration: 1s;
    animation-delay: 0s;
    animation-timing-function: ease-out;
    -webkit-animation-fill-mode: forwards;
    -moz-animation-fill-mode: forwards;
    animation-fill-mode: forwards
}
.slide.animationIn .point-shadow{
    -webkit-animation-name: point;
    -webkit-animation-duration: 1s;
    -webkit-animation-delay: 0s;
    -webkit-animation-timing-function: ease-out;
    -moz-animation-name: point;
    -moz-animation-duration: 1s;
    -moz-animation-delay: 0s;
    -moz-animation-timing-function: ease-out;
    animation-name: point;
    animation-duration: 1s;
    animation-delay: 0s;
    animation-timing-function: ease-out;
    -webkit-animation-fill-mode: forwards;
    -moz-animation-fill-mode: forwards;
    animation-fill-mode: forwards
}
.slide.animationIn .upper-text{
    animation: slideLeft 0.5s 0.25s ease forwards, slideLeftFinish 0.25s 0.75s ease forwards;
}
.slide.animationIn .lower-text{
    animation: slideLeft 0.5s 0.5s ease forwards, slideLeftFinish 0.25s 1s ease forwards;
}
@-webkit-keyframes move {
    0% {
        -webkit-transform: scaleX(0.1);
        -moz-transform: scaleX(0.1);
        -ms-transform: scaleX(0.1);
        transform: scaleX(0.1);
        opacity: 1
    }
    100% {
        -webkit-transform: scaleX(1);
        -moz-transform: scaleX(1);
        -ms-transform: scaleX(1);
        transform: scaleX(1);
        opacity: 1
    }

}
</code>```

}

Because of this error, validator can't see a closet bracket in @media.

答:
According to the W3C specification:

At-rules inside @media are invalid in CSS2.1.

ref: www.w3.org - Media types

So this won't work:

```<code>@media (max-width: 768px) {

   @media (max-width: 450px) {

   }

}
</code>```

Neither will this:

```<code>@media (max-width: 768px) {

   @-webkit-keyframes animation {

   }

}
</code>```

Keyframe animations should be declared outside of any media types then applied within the applicable or relevant media quieres when and where necessary.

Title: Nesting @keyframe in @media

Body:
I have to fix a bug with curly brackets. But all opening brackets have pair.
There are error on line 212

Expected RBRACE at line 212, col 2.
      @-webkit-keyframes move {

But when I test code separate before 212 and after 212 - no errors seen.

@media all and (min-width:  1px){
.main-pointing-slider .box .dot-4{
    bottom: -2px;
    left: 128px;
    top: auto;
    right: auto;
    bottom: -2px;
    left: calc(50% - 3px);
    position: absolute;
    -webkit-animation-name: dotShow;
    -webkit-animation-duration: 0.5s;
    -webkit-animation-delay: 2s;
    -webkit-animation-timing-function: linear;
    -moz-animation-name: dotShow;
    -moz-animation-duration: 0.5s;
    -moz-animation-delay: 2s;
    -moz-animation-timing-function: linear;
    animation-name: dotShow;
    animation-duration: 0.5s;
    animation-delay: 2s;
    animation-timing-function: linear;
    -webkit-animation-fill-mode: forwards;
    -moz-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
    background: linear-gradient(to bottom, #dcd4cb 0%, #f3c886 100%)
}
.main-pointing-slider .box .svg-gradient{
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    position: absolute
}
.main-pointing-slider .box .svg-gradient .svg-box{
    width: 100%;
    height: 100%
}
.main-pointing-slider .box .svg-gradient .svg-box rect{
    visibility: visible
}
.main-pointing-slider .slide{
    /*display: none;*/
    width: 100%;
    height: 100%;
    top: 0;
    /*position: absolute;*/
    overflow: hidden
}
.main-pointing-slider .slide .point{
    top: 1px;
    right: 0;
    bottom: 0;
    left: 1px;
    position: relative;
    width: 248px;
    height: 126px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    -webkit-border-radius: 120px;
    -moz-border-radius: 120px;
    border-radius: 120px;
    opacity: 0;
    margin: 0
    auto
}
.main-pointing-slider .slide .point .svg-gradient-point{
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    position: absolute;
    z-index: 2
}
.main-pointing-slider .slide .point .svg-gradient-point .svg-box{
    width: 100%;
    height: 100%
}
.main-pointing-slider .slide .point .svg-gradient-point .svg-box rect{
    stroke-width: 2
}
.main-pointing-slider .slide .point .point-inner{
    top: 0;
    right: auto;
    bottom: auto;
    left: 0;
    position: absolute;
    width: 100%;
    height: 100%;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    -webkit-border-radius: 120px;
    -moz-border-radius: 120px;
    border-radius: 120px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    overflow: hidden;
    background: no-repeat 50%;
    background-size: cover
}
.main-pointing-slider .slide .point-shadow{
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    position: absolute;
    width: 260px;
    height: 130px;
    width: calc(260px - 6px);
    height: calc(130px - 6px);
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    -webkit-border-radius: 120px;
    -moz-border-radius: 120px;
    border-radius: 120px;
    opacity: 0;
    z-index: 3;
    margin: 0
    auto;
    background: black
}
.main-pointing-slider .slide .upper-text{
    top: auto;
    right: -100%;
    bottom: 72%;
    left: auto;
    position: absolute;
    width: 62%;
    text-transform: uppercase;
    text-align: right;
    font-size: 13px;
    font-family: "Tahoma Bold",sans-serif;
    font-weight: 600;
    line-height: 1.12;
    color: #e7c28b;
    display: none
}
.main-pointing-slider .slide .lower-text{
    top: 34%;
    right: -100%;
    bottom: auto;
    left: auto;
    position: absolute;
    width: 53%;
    font-size: 12px;
    font-family: "Tahoma Regular",sans-serif;
    line-height: 1.3;
    text-align: right;
    color: white;
    display: none
}
.main-pointing-slider .slide.active{
    display: block
}
.main-pointing-slider.startFirstFrame .line{
    -webkit-animation-name: move;
    -webkit-animation-duration: 0.9s;
    -webkit-animation-delay: 0s;
    -webkit-animation-timing-function: ease;
    -moz-animation-name: move;
    -moz-animation-duration: 0.9s;
    -moz-animation-delay: 0s;
    -moz-animation-timing-function: ease;
    animation-name: move;
    animation-duration: 0.9s;
    animation-delay: 0s;
    animation-timing-function: ease
}
.slide.animationIn .point{
    -webkit-animation-name: point;
    -webkit-animation-duration: 1s;
    -webkit-animation-delay: 0s;
    -webkit-animation-timing-function: ease-out;
    -moz-animation-name: point;
    -moz-animation-duration: 1s;
    -moz-animation-delay: 0s;
    -moz-animation-timing-function: ease-out;
    animation-name: point;
    animation-duration: 1s;
    animation-delay: 0s;
    animation-timing-function: ease-out;
    -webkit-animation-fill-mode: forwards;
    -moz-animation-fill-mode: forwards;
    animation-fill-mode: forwards
}
.slide.animationIn .point-shadow{
    -webkit-animation-name: point;
    -webkit-animation-duration: 1s;
    -webkit-animation-delay: 0s;
    -webkit-animation-timing-function: ease-out;
    -moz-animation-name: point;
    -moz-animation-duration: 1s;
    -moz-animation-delay: 0s;
    -moz-animation-timing-function: ease-out;
    animation-name: point;
    animation-duration: 1s;
    animation-delay: 0s;
    animation-timing-function: ease-out;
    -webkit-animation-fill-mode: forwards;
    -moz-animation-fill-mode: forwards;
    animation-fill-mode: forwards
}
.slide.animationIn .upper-text{
    animation: slideLeft 0.5s 0.25s ease forwards, slideLeftFinish 0.25s 0.75s ease forwards;
}
.slide.animationIn .lower-text{
    animation: slideLeft 0.5s 0.5s ease forwards, slideLeftFinish 0.25s 1s ease forwards;
}
@-webkit-keyframes move {
    0% {
        -webkit-transform: scaleX(0.1);
        -moz-transform: scaleX(0.1);
        -ms-transform: scaleX(0.1);
        transform: scaleX(0.1);
        opacity: 1
    }
    100% {
        -webkit-transform: scaleX(1);
        -moz-transform: scaleX(1);
        -ms-transform: scaleX(1);
        transform: scaleX(1);
        opacity: 1
    }

}

}

Because of this error, validator can't see a closet bracket in @media.

Body:
According to the W3C specification:

At-rules inside @media are invalid in CSS2.1.

ref: www.w3.org - Media types

So this won't work:

@media (max-width: 768px) {

   @media (max-width: 450px) {

   }

}

Neither will this:

@media (max-width: 768px) {

   @-webkit-keyframes animation {

   }

}

Keyframe animations should be declared outside of any media types then applied within the applicable or relevant media quieres when and where necessary.


来源: stackexchange

问:
google admin sdk Not Authorized to access this resource/api php
Need help about google admin sdk. I m newbie on google admin sdk. So i am stuck on its showing error while authorizing like code 403: Not Authorized to access this resource/api. Here is my Code.

```<code><?php
include_once '../vendor/autoload.php';
include_once "base.php";
session_start();
echo pageHeader("Service Account Access");
/************************************************
  Make an API request authenticated with a service
  account.
 ************************************************/
$client = new Google_Client();
$client->setAuthConfig('client_secret1.json');

$client->setApplicationName("automate user");

$client->setScopes(['https://www.googleapis.com/auth/admin.directory.user']);
$client->setSubject('admin@XXXXX');

$client->setIncludeGrantedScopes(true);
$client->setAccessType('offline');
//$auth_url = $client->createAuthUrl();

//header('Location: '.filter_var($auth_url, FILTER_SANITIZE_URL));

if(isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
    $client->setAccessToken($_SESSION['access_token']);

    if ($credentials_file = checkServiceAccountCredentialsFile()) {
  // set the location manually
  $client->setAuthConfig('client_secret1.json');
} elseif (getenv('GOOGLE_APPLICATION_CREDENTIALS=automate user.json')) {
  // use the application default credentials
  $client->useApplicationDefaultCredentials();
} else {
  echo missingServiceAccountDetailsWarning();
  return;
}

$dir = new Google_Service_Directory($client);
$user = new Google_Service_Directory_User();
$name = new Google_Service_Directory_UserName();

$results = $dir->users->get('xxxxx@xxx.org');

if($results) {
     echo "Name : ".$results->name->fullName."";
} else{
     echo " User doesn't exist : ".$email;
}

}
else {

    $redirect_uri = 'http://'.$_SERVER['HTTP_HOST']. '/google/oauth.php';
    header('Location: '.filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
 pageFooter(__FILE__); ?>
</code>```

Actually i want o create an user through google api. Please tell me anybody what's i do wrong ? please help me

答:
You can create a user through Users: insert. There is a Try it now to test if you have entered correct/valid data.

Here is a sample code from quickstart to help your progress.

```<code><?php
require_once __DIR__ . '/vendor/autoload.php';

define('APPLICATION_NAME', 'Directory API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/admin-directory_v1-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/admin-directory_v1-php-quickstart.json
define('SCOPES', implode(' ', array(
  Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY)
));

if (php_sapi_name() != 'cli') {
  throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfig(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  }
  return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Directory($client);

// Print the first 10 users in the domain.
$optParams = array(
  'customer' => 'my_customer',
  'maxResults' => 10,
  'orderBy' => 'email',
);
$results = $service->users->listUsers($optParams);

if (count($results->getUsers()) == 0) {
  print "No users found.\n";
} else {
  print "Users:\n";
  foreach ($results->getUsers() as $user) {
    printf("%s (%s)\n", $user->getPrimaryEmail(),
        $user->getName()->getFullName());
  }
}
</code>```

For further information about this error, see this SO post.

you need to enable domain-wide delegation for your service
  account, and then have the service account impersonate a domain admin
  when it makes the request:

ContentLicense: CC BY-SA 3.0

Body:
Need help about google admin sdk. I m newbie on google admin sdk. So i am stuck on its showing error while authorizing like code 403: Not Authorized to access this resource/api. Here is my Code.

<?php
include_once '../vendor/autoload.php';
include_once "base.php";
session_start();
echo pageHeader("Service Account Access");
/************************************************
  Make an API request authenticated with a service
  account.
 ************************************************/
$client = new Google_Client();
$client->setAuthConfig('client_secret1.json');

$client->setApplicationName("automate user");

$client->setScopes(['https://www.googleapis.com/auth/admin.directory.user']);
$client->setSubject('admin@XXXXX');

$client->setIncludeGrantedScopes(true);
$client->setAccessType('offline');
//$auth_url = $client->createAuthUrl();

//header('Location: '.filter_var($auth_url, FILTER_SANITIZE_URL));

if(isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
    $client->setAccessToken($_SESSION['access_token']);

    if ($credentials_file = checkServiceAccountCredentialsFile()) {
  // set the location manually
  $client->setAuthConfig('client_secret1.json');
} elseif (getenv('GOOGLE_APPLICATION_CREDENTIALS=automate user.json')) {
  // use the application default credentials
  $client->useApplicationDefaultCredentials();
} else {
  echo missingServiceAccountDetailsWarning();
  return;
}

$dir = new Google_Service_Directory($client);
$user = new Google_Service_Directory_User();
$name = new Google_Service_Directory_UserName();

$results = $dir->users->get('xxxxx@xxx.org');

if($results) {
     echo "Name : ".$results->name->fullName."";
} else{
     echo " User doesn't exist : ".$email;
}

}
else {

    $redirect_uri = 'http://'.$_SERVER['HTTP_HOST']. '/google/oauth.php';
    header('Location: '.filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
 pageFooter(__FILE__); ?>

Actually i want o create an user through google api. Please tell me anybody what's i do wrong ? please help me

Body:
You can create a user through Users: insert. There is a Try it now to test if you have entered correct/valid data.

Here is a sample code from quickstart to help your progress.

<?php
require_once __DIR__ . '/vendor/autoload.php';

define('APPLICATION_NAME', 'Directory API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/admin-directory_v1-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/admin-directory_v1-php-quickstart.json
define('SCOPES', implode(' ', array(
  Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY)
));

if (php_sapi_name() != 'cli') {
  throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfig(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  }
  return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Directory($client);

// Print the first 10 users in the domain.
$optParams = array(
  'customer' => 'my_customer',
  'maxResults' => 10,
  'orderBy' => 'email',
);
$results = $service->users->listUsers($optParams);

if (count($results->getUsers()) == 0) {
  print "No users found.\n";
} else {
  print "Users:\n";
  foreach ($results->getUsers() as $user) {
    printf("%s (%s)\n", $user->getPrimaryEmail(),
        $user->getName()->getFullName());
  }
}

For further information about this error, see this SO post.

you need to enable domain-wide delegation for your service
  account, and then have the service account impersonate a domain admin
  when it makes the request:


问:
Use-case of the ServiceClient?
Is the use-case of the ServiceClient to send messages to devices?

ServiceClient supports only amqp messages. Documentation for Azure Devices namespace says "Transport types supported by ServiceClient - Amqp and Amqp over WebSocket only". In code the TransportType exposes only Amqp. Would it be changed in the future?

If the ServiceClient is been used for C2D messages, why in this answer, is written that "For ServiceClient, you need Azure IoT Hub connection string, not device connection string"?

What is the performance's impact and resources' utilization, if we hold a reference of the created ServiceClient object (or the Registry Manager)?

and what is the impact in case

when we open-close the connection?

when we leave open the conection?

答:
Is the use-case of the ServiceClient to send messages to devices?

Yes. You need use ServiceClient to send C2D messages.

ServiceClient supports only amqp messages. Documentation for Azure
  Devices namespace says "Transport types supported by ServiceClient -
  Amqp and Amqp over WebSocket only". In code the TransportType exposes
  only Amqp. Would it be changed in the future?

For future plans, you can reference this guide ask a question.

If the ServiceClient is been used for C2D messages, why in this
  answer, is written that "For ServiceClient, you need Azure IoT Hub
  connection string, not device connection string"?

Device connection string: Connection string based on primary key used in API calls which allows device to communicate with Iot Hub. It allows you to receive C2D messages, not send C2D messages. IoT Hub exposes its functionality to various actors, like per-device and service.

What is the performance's impact and resources' utilization, if we
  hold a reference of the created ServiceClient object (or the Registry
  Manager)?

You can check IoT Hub throttling and you and IoT Hub quotas and throttling for more detail.

Title: Use-case of the ServiceClient?


问:
Netty: Using `IdleStateHandler` to detect disconnection
I read the documentation of IdleStateHandlerand from my Server I implemented it same as from the documentation,
but I don't understand on how can I exactly tell if the Client become disconnected for example the Client loses the Wifi Connectivity.

from my understanding, inside my Handler, the method channelInactive() was trigger when the client become disconnected,
then using IdleStateHandler, the IdleState.READER_IDLE will be triggered when no read was performed for the specified period of time,
then after 3 seconds of no read from the client I closed the channel and was expecting that the channelInactive will be trigger but it's not, why?.

Initializer

```<code>public class ServerInitializer extends ChannelInitializer<SocketChannel> {

    String TAG = "LOG: ";
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        System.out.println(TAG + "Starting ServerInitializer class...");
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
        pipeline.addLast("encoder", new ObjectEncoder());
        pipeline.addLast("idleStateHandler", new IdleStateHandler(6, 3, 0, TimeUnit.SECONDS));
        pipeline.addLast("handler", new ServerHandler());
    }
}
</code>```

Handler

```<code>public class ServerHandler extends ChannelInboundHandlerAdapter {

    private String TAG = "LOG: ";

    public ServerHandler(){}

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Log.w(TAG,"New Client become connected, Sending a message to the Client. Client Socket is: " + ctx.channel().remoteAddress().toString());

        List<String> msg = new ArrayList<>();
        msg.add(0,"sample message 1");
        msg.add(1,"sample message 2");
        sendMessage(ctx, msg);
    }

    public void sendMessage(ChannelHandlerContext ctx, List message){
        ctx.write(message);
        ctx.flush();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Log.w(TAG,"A Client become disconnected. Client Socket is: " + ctx.channel().remoteAddress().toString() + " id: " + (String.valueOf(ctx.channel().hashCode())));
         //COnnection id dead, do something here...
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object object) { // (2)
        Log.w(TAG, "CLIENT: "+ ctx.channel().remoteAddress().toString() + " SAYS: " + object);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // Close the connection for that client  when an exception is raised.
        Log.e(TAG,"Something's wrong, CLIENT: "+ ctx.channel().remoteAddress().toString() + " CAUSE: " + cause.toString());
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        Log.w(TAG,"LOLO");
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {

                ctx.close(); //Closed the Channel so that the `channelInactive` will be trigger

            } else if (e.state() == IdleState.WRITER_IDLE) {

                ctx.writeAndFlush("ping\n"); //Send ping to client

            }
        }

    }
}
</code>```

Anyone can help me out

答: Use the ReadTimeoutHandler instead of IdleStateHandler and override the exceptionCaught method.</p>

Body:
I read the documentation of IdleStateHandlerand from my Server I implemented it same as from the documentation,
but I don't understand on how can I exactly tell if the Client become disconnected for example the Client loses the Wifi Connectivity.

from my understanding, inside my Handler, the method channelInactive() was trigger when the client become disconnected,
then using IdleStateHandler, the IdleState.READER_IDLE will be triggered when no read was performed for the specified period of time,
then after 3 seconds of no read from the client I closed the channel and was expecting that the channelInactive will be trigger but it's not, why?.

Initializer

public class ServerInitializer extends ChannelInitializer<SocketChannel> {

    String TAG = "LOG: ";
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        System.out.println(TAG + "Starting ServerInitializer class...");
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
        pipeline.addLast("encoder", new ObjectEncoder());
        pipeline.addLast("idleStateHandler", new IdleStateHandler(6, 3, 0, TimeUnit.SECONDS));
        pipeline.addLast("handler", new ServerHandler());
    }
}

Handler

public class ServerHandler extends ChannelInboundHandlerAdapter {

    private String TAG = "LOG: ";

    public ServerHandler(){}

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Log.w(TAG,"New Client become connected, Sending a message to the Client. Client Socket is: " + ctx.channel().remoteAddress().toString());

        List<String> msg = new ArrayList<>();
        msg.add(0,"sample message 1");
        msg.add(1,"sample message 2");
        sendMessage(ctx, msg);
    }

    public void sendMessage(ChannelHandlerContext ctx, List message){
        ctx.write(message);
        ctx.flush();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Log.w(TAG,"A Client become disconnected. Client Socket is: " + ctx.channel().remoteAddress().toString() + " id: " + (String.valueOf(ctx.channel().hashCode())));
         //COnnection id dead, do something here...
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object object) { // (2)
        Log.w(TAG, "CLIENT: "+ ctx.channel().remoteAddress().toString() + " SAYS: " + object);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // Close the connection for that client  when an exception is raised.
        Log.e(TAG,"Something's wrong, CLIENT: "+ ctx.channel().remoteAddress().toString() + " CAUSE: " + cause.toString());
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        Log.w(TAG,"LOLO");
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {

                ctx.close(); //Closed the Channel so that the `channelInactive` will be trigger

            } else if (e.state() == IdleState.WRITER_IDLE) {

                ctx.writeAndFlush("ping\n"); //Send ping to client

            }
        }

    }
}

Anyone can help me out


问:
How to display questions one by one on save and next basis
I have a quiz management system and need to fetch the data from the database and displaying the data one by one on clicking next button.

I want to use Ajax to insert data into database after clicking next button by using file read and write function.

```<code>$sql=mysqli_query($con,"select * from tbl_question where setid='$set' and status=1 ORDER BY RAND()");
while($sha=mysqli_fetch_array($sql)) {

<h4><? echo $sha['id'];?></h4>
</code>```

I want to submit questions by Ajax. Please suggest me solution.

答:
I am using this response to create three questions which appear on clicking the button.

I hope answer is self explanatory. If not please let me know. I have used vanilla js. Cheers.

window.onload = getRequest();

let response;
let allFirstNames;
let questionDiv = document.getElementById("question");

function getRequest() {
  let xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
     if(xmlhttp.readyState == 4) {
        response = xmlhttp.responseText;
        parseResponse()
     }
  }
  xmlhttp.open("GET", "https://reqres.in/api/users?page=2", true);
  xmlhttp.send();
}

function parseResponse() {
   allFirstNames = JSON.parse(response)["data"].map((dataObj) => {
     return dataObj["first_name"];
   });
}

document.getElementById("printQ").onclick = printQuestions;

function printQuestions() {
   clearCurrentQuestions();
     if (allFirstNames[0] != undefined) {
       let question = document.createElement("p");
       question.innerHTML = "Who is "+ allFirstNames[0] + " ?";
       document.getElementById("question").appendChild(question);
       allFirstNames.splice(0,1);
      }
      else {
         let question = document.createElement("p");
         question.innerHTML = "No More Questions. End of Quiz";
         document.getElementById("question").appendChild(question);
      }
}

function clearCurrentQuestions() {
   let node = document.getElementById("question")
   while(node.hasChildNodes()) {
     node.removeChild(node.lastChild);
   }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="printQ">
Print Next Question
</button>
<div id="question">
<p>
Hi, Welcome to the Quiz, Click above button for Qns
</p>
</div></code>```

Body:
I have a quiz management system and need to fetch the data from the database and displaying the data one by one on clicking next button.

I want to use Ajax to insert data into database after clicking next button by using file read and write function.

$sql=mysqli_query($con,"select * from tbl_question where setid='$set' and status=1 ORDER BY RAND()");
while($sha=mysqli_fetch_array($sql)) {

<? echo $sha['id'];?>

I want to submit questions by Ajax. Please suggest me solution.

Body:
I am using this response to create three questions which appear on clicking the button.

I hope answer is self explanatory. If not please let me know. I have used vanilla js. Cheers.

window.onload = getRequest();

let response;
let allFirstNames;
let questionDiv = document.getElementById("question");

function getRequest() {
  let xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
     if(xmlhttp.readyState == 4) {
        response = xmlhttp.responseText;
        parseResponse()
     }
  }
  xmlhttp.open("GET", "https://reqres.in/api/users?page=2", true);
  xmlhttp.send();
}

function parseResponse() {
   allFirstNames = JSON.parse(response)["data"].map((dataObj) => {
     return dataObj["first_name"];
   });
}

document.getElementById("printQ").onclick = printQuestions;

function printQuestions() {
   clearCurrentQuestions();
     if (allFirstNames[0] != undefined) {
       let question = document.createElement("p");
       question.innerHTML = "Who is "+ allFirstNames[0] + " ?";
       document.getElementById("question").appendChild(question);
       allFirstNames.splice(0,1);
      }
      else {
         let question = document.createElement("p");
         question.innerHTML = "No More Questions. End of Quiz";
         document.getElementById("question").appendChild(question);
      }
}

function clearCurrentQuestions() {
   let node = document.getElementById("question")
   while(node.hasChildNodes()) {
     node.removeChild(node.lastChild);
   }
}

<button id="printQ">
Print Next Question
</button>
<div id="question">
<p>
Hi, Welcome to the Quiz, Click above button for Qns
</p>
</div>


问:
Is there a way to make Phing ZipTask output a file that can be extracted with a 1.0 version of zip?
We use Phing on a macOS High Sierra to deploy a WordPress plugin and its ZipTask to build the final archive.

The output of file command against the archives give us this information:

```<code>push-notifications-for-wordpress.zip: Zip archive data, at least v2.0 to extract
</code>```

From which we can see the minimum version to extract archive is v2.0.

Now, we are having troubles with WordPress installer system that does not support those archives:

```<code>Could not extract file from archive. push-notifications-for-wordpress/./
</code>```

If we extract the file and re-create it with the zip command line resulting in a v1.0 compatible file:

```<code>push-notifications-for-wordpress.zip: Zip archive data, at least v1.0 to extract
</code>```

WordPress will successfully extract it and we are reasonably sure that minimum version needed to extract file is the key problem.

So, is there a way to force ZipTask to make a v1.0 compliant zip archive?

Thank you!

答:
With version 2.0, the Zip specification introduced support for folders. Previously it did not:

```<code>   4.4.3 version needed to extract (2 bytes)
        4.4.3.2 Current minimum feature versions are as defined below:

         2.0 - File is a folder (directory)
         2.0 - File is compressed using Deflate compression
         2.0 - File is encrypted using traditional PKWARE encryption
</code>```

Source: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT

So it does not make sense to support zip v1 at all, and you have to look for the error elsewhere.

Body:
We use Phing on a macOS High Sierra to deploy a WordPress plugin and its ZipTask to build the final archive.

The output of file command against the archives give us this information:

push-notifications-for-wordpress.zip: Zip archive data, at least v2.0 to extract

From which we can see the minimum version to extract archive is v2.0.

Now, we are having troubles with WordPress installer system that does not support those archives:

Could not extract file from archive. push-notifications-for-wordpress/./

If we extract the file and re-create it with the zip command line resulting in a v1.0 compatible file:

push-notifications-for-wordpress.zip: Zip archive data, at least v1.0 to extract

WordPress will successfully extract it and we are reasonably sure that minimum version needed to extract file is the key problem.

So, is there a way to force ZipTask to make a v1.0 compliant zip archive?

Thank you!

Body:
With version 2.0, the Zip specification introduced support for folders. Previously it did not:

   4.4.3 version needed to extract (2 bytes)
        4.4.3.2 Current minimum feature versions are as defined below:

         2.0 - File is a folder (directory)
         2.0 - File is compressed using Deflate compression
         2.0 - File is encrypted using traditional PKWARE encryption

Source: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT

So it does not make sense to support zip v1 at all, and you have to look for the error elsewhere.


问:
CSS grid - hide a grid-area on click of a button
I'm trying to create a sidenav that can be shown/hidden on a button click.
I have used grid-area and grid-template-areas for the layout.
I have a grid-area for sidenav. I want the grid-area also to be hidden when the sidenav is hidden. Is it possible to achieve this?

The full code is here - https://codepen.io/devi_ks/pen/Ebddwo

$("a").on("click", function() {
  $("#sidenav").hide();
  return false;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#header {
  grid-area: header;
  border: 1px solid red;
}

#sidenav {
  grid-area: sidenav;
  border: 1px solid green;
}

#content {
  grid-area: content;
  border: 1px solid black;
}

body {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: 0.5fr 2fr;
  grid-template-areas: "header header" "sidenav content"
}</code>```

  Click me

 menu 1

 menu 2

 menu 3

  Some content goes here....

```

答:
```<code>$("a").on("click", function(){
     if($("#sidenav").is(":visible")){
       $("#sidenav").hide();
       $("#content").hide();
     }else{
       $("#sidenav").show();
       $("#content").show();
     }
      return false;
    });
</code>```

Body:
I'm trying to create a sidenav that can be shown/hidden on a button click.
I have used grid-area and grid-template-areas for the layout.
I have a grid-area for sidenav. I want the grid-area also to be hidden when the sidenav is hidden. Is it possible to achieve this?

The full code is here - https://codepen.io/devi_ks/pen/Ebddwo

$("a").on("click", function() {
  $("#sidenav").hide();
  return false;
});

#header {
  grid-area: header;
  border: 1px solid red;
}

#sidenav {
  grid-area: sidenav;
  border: 1px solid green;
}

#content {
  grid-area: content;
  border: 1px solid black;
}

body {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: 0.5fr 2fr;
  grid-template-areas: "header header" "sidenav content"
}

  Click me

 menu 1

 menu 2

 menu 3

  Some content goes here....


问:
find longest running uninterrupted series
Suppose I have a data frame that is built like this:

```<code>library(lubridate)

seq_date <- rep(seq.Date(from = dmy('01-01-2016'), to = dmy('05-01-2016'), by = 'day'), 3)

vec_a <- c(rep('a', 3), NA, 'a')
vec_b <- c(rep('b', 4), NA)
vec_c <- c(NA, rep('c', 2), NA, 'c')

demo_df <- data.frame(date = seq_date,
                      var = c(vec_a, vec_b, vec_c))

demo_df
         date  var
1  2016-01-01    a
2  2016-01-02    a
3  2016-01-03    a
4  2016-01-04 <NA>
5  2016-01-05    a
6  2016-01-01    b
7  2016-01-02    b
8  2016-01-03    b
9  2016-01-04    b
10 2016-01-05 <NA>
11 2016-01-01 <NA>
12 2016-01-02    c
13 2016-01-03    c
14 2016-01-04 <NA>
15 2016-01-05    c
</code>```

What I would like to find out is the the longest running uninterrupted sequence for each var. The expected output should be something on the lines of:

```<code>a 3
b 4
c 2
</code>```

Each of the three categories in var start and end on the same date and a series would always be broken by an NA. Any help will be greatly appreciated.

答:
We can use rleid from data.table.  Convert the 'data.frame' to 'data.table' (setDT(demo_df)), grouped by the run-length-id of non-NA elements of 'var' and the 'var', get the count (.N), then with second [], grouped by 'var', get the max specifying the 'i' with is.na or use na.rm=TRUE in max

```<code>library(data.table)
setDT(demo_df)[, .N, .(var, rleid(!is.na(var)))][!is.na(var), .(count = max(N)), var]
#    var count
#1:   a     3
#2:   b     4
#3:   c     2
</code>```

If we need a dplyr solution

```<code>library(dplyr)
demo_df %>%
   count(grp = cumsum(is.na(var)), var)  %>%
   filter(!is.na(var)) %>%
   group_by(var) %>%
   summarise(Count = max(n))
</code>```

Body:
Suppose I have a data frame that is built like this:

library(lubridate)

seq_date <- rep(seq.Date(from = dmy('01-01-2016'), to = dmy('05-01-2016'), by = 'day'), 3)

vec_a <- c(rep('a', 3), NA, 'a')
vec_b <- c(rep('b', 4), NA)
vec_c <- c(NA, rep('c', 2), NA, 'c')

demo_df <- data.frame(date = seq_date,
                      var = c(vec_a, vec_b, vec_c))

demo_df
         date  var
1  2016-01-01    a
2  2016-01-02    a
3  2016-01-03    a
4  2016-01-04 <NA>
5  2016-01-05    a
6  2016-01-01    b
7  2016-01-02    b
8  2016-01-03    b
9  2016-01-04    b
10 2016-01-05 <NA>
11 2016-01-01 <NA>
12 2016-01-02    c
13 2016-01-03    c
14 2016-01-04 <NA>
15 2016-01-05    c

What I would like to find out is the the longest running uninterrupted sequence for each var. The expected output should be something on the lines of:

a 3
b 4
c 2

Each of the three categories in var start and end on the same date and a series would always be broken by an NA. Any help will be greatly appreciated.

Body:
We can use rleid from data.table.  Convert the 'data.frame' to 'data.table' (setDT(demo_df)), grouped by the run-length-id of non-NA elements of 'var' and the 'var', get the count (.N), then with second [], grouped by 'var', get the max specifying the 'i' with is.na or use na.rm=TRUE in max

library(data.table)
setDT(demo_df)[, .N, .(var, rleid(!is.na(var)))][!is.na(var), .(count = max(N)), var]
#    var count
#1:   a     3
#2:   b     4
#3:   c     2

If we need a dplyr solution

library(dplyr)
demo_df %>%
   count(grp = cumsum(is.na(var)), var)  %>%
   filter(!is.na(var)) %>%
   group_by(var) %>%
   summarise(Count = max(n))


问:
array.split to create a string with multiple whitespaces
I am trying to create several strings comprising of varying amounts of whitespaces only. I have been able to do this once with array.(number of indexes).join(" ");

However when I go into a loop to add more strings with an incrementing amount of white space in each string, the string is set to 'undefined.' I am not sure where I am going wrong. The function seems to work outside of the loop but not inside. Any ideas what I have done wrong?

function towerBuilder(nFloors) {
    // build here
    var towers = [];
    var stars = "*";
    var spaceNo = nFloors -1;
    let spaces = Array(spaceNo).join(" ");
    spaceNo -= 1;
    towers[0] = spaces + stars + spaces;
    for(i = 1; i <= nFloors -1; i++)
    {
      stars = stars + Array(i + 2).join('*');
      let edges = Array(spaceNo).join(" ");
      towers[i] = edges + stars + edges;
      spaceNo -= 1;
    }

    return towers;
}
console.log(towerBuilder(3));```
</div>
</div>
</p>

<p>At the top, this works:</p>

``` let spaces = Array(spaceNo).join(" ");
```

<p>However, down in the loop, this outputs 'undefined'</p>

```let edges = Array(spaceNo).join(" ");
```

<p>The idea is that the spaces wrap the star symbols so that a tower can be built out of an array. Example, calling towerBuilder(3) would output the below: (I don't need to output it with carriage returns. The array alone will suffice.)</p>

```[
  '  *  ',
  ' *** ',
  '*****'
]
```

答:
Array.join is used to concatenate all the array's values, with the given string between them:

['foo','bar'].join(',') // = 'foo,bar'

You are expecting Array(2).join(' ') to be two spaces, but it will be only one since it's concatenating two empty values with a space in between.

Just remove the -1 at row 5 and it will work as expected:

function towerBuilder(nFloors) {
    // build here
    var towers = [];
    var stars = "*";
    var spaceNo = nFloors; // was nFloors - 1
    let spaces = Array(spaceNo).join(" ");
    spaceNo -= 1;
    towers[0] = spaces + stars + spaces;
    for(i = 1; i <= nFloors -1; i++)
    {
      stars = stars + Array(i + 2).join('*');
      let edges = Array(spaceNo).join(" ");
      towers[i] = edges + stars + edges;
      spaceNo -= 1;
    }

    return towers;
}
console.log(towerBuilder(3));```
</div>
</div>
</p>

<p>Btw, it would look a lot better if written like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function towerBuilder(nFloors) {
    // build here
    var towers = [];

    for(var floor = 0; floor < nFloors; floor++)
    {
      var nStars = (floor * 2) + 1;
      var stars = Array(nStars + 1).join('*');
      var edges = Array(nFloors - floor).join(" ");
      towers[floor] = edges + stars + edges;
    }

    return towers;
}
console.log(towerBuilder(3));</code>```

Body:
I am trying to create several strings comprising of varying amounts of whitespaces only. I have been able to do this once with array.(number of indexes).join(" ");

However when I go into a loop to add more strings with an incrementing amount of white space in each string, the string is set to 'undefined.' I am not sure where I am going wrong. The function seems to work outside of the loop but not inside. Any ideas what I have done wrong?

function towerBuilder(nFloors) {
    // build here
    var towers = [];
    var stars = "*";
    var spaceNo = nFloors -1;
    let spaces = Array(spaceNo).join(" ");
    spaceNo -= 1;
    towers[0] = spaces + stars + spaces;
    for(i = 1; i <= nFloors -1; i++)
    {
      stars = stars + Array(i + 2).join('*');
      let edges = Array(spaceNo).join(" ");
      towers[i] = edges + stars + edges;
      spaceNo -= 1;
    }

    return towers;
}
console.log(towerBuilder(3));

At the top, this works:

 let spaces = Array(spaceNo).join(" ");

However, down in the loop, this outputs 'undefined'

let edges = Array(spaceNo).join(" ");

The idea is that the spaces wrap the star symbols so that a tower can be built out of an array. Example, calling towerBuilder(3) would output the below: (I don't need to output it with carriage returns. The array alone will suffice.)

[
  '  *  ',
  ' *** ',
  '*****'
]

Body:
Array.join is used to concatenate all the array's values, with the given string between them:

['foo','bar'].join(',') // = 'foo,bar'

You are expecting Array(2).join(' ') to be two spaces, but it will be only one since it's concatenating two empty values with a space in between.

Just remove the -1 at row 5 and it will work as expected:

function towerBuilder(nFloors) {
    // build here
    var towers = [];
    var stars = "*";
    var spaceNo = nFloors; // was nFloors - 1
    let spaces = Array(spaceNo).join(" ");
    spaceNo -= 1;
    towers[0] = spaces + stars + spaces;
    for(i = 1; i <= nFloors -1; i++)
    {
      stars = stars + Array(i + 2).join('*');
      let edges = Array(spaceNo).join(" ");
      towers[i] = edges + stars + edges;
      spaceNo -= 1;
    }

    return towers;
}
console.log(towerBuilder(3));

Btw, it would look a lot better if written like this:

function towerBuilder(nFloors) {
    // build here
    var towers = [];

    for(var floor = 0; floor < nFloors; floor++)
    {
      var nStars = (floor * 2) + 1;
      var stars = Array(nStars + 1).join('*');
      var edges = Array(nFloors - floor).join(" ");
      towers[floor] = edges + stars + edges;
    }

    return towers;
}
console.log(towerBuilder(3));


问:
Error: Cannot find module '@ionic/app-scripts'
I'm new to Ionic. I was following the Ionic documentation "get started", created a project sample named "super". The problem is that when I run the command line ionic serve in the project directory, it threw an error Error: Cannot find module '@ionic/app-scripts'

答: Just open a new terminal window/session. I could not figure it out, but it's probably related to env.</p>


问:
EditTextPreference Disable Buttons?
I want to have an EditTextPreference that will disable the OK button if there is no text in the EditText field. I created a custom EditTextPreference class and I am able to get the EditText object and set a TextWatcher, but I can't find a way to disable the button. It looks like I just don't have access to the OK and Cancel buttons in the Dialog.

Anyone know a way to get at these buttons or to do what I am trying to do?

Only other option is to try to create from scratch a custom Dialog that looks like and mimics the EditTextPreference.

答:
Here is a code sample that enables/disables button depending on whether onCheckValue function returns true or false.

```<code>public class ValidatedEditTextPreference extends EditTextPreference
{
    public ValidatedEditTextPreference(Context ctx, AttributeSet attrs, int defStyle)
    {
        super(ctx, attrs, defStyle);
    }

    public ValidatedEditTextPreference(Context ctx, AttributeSet attrs)
    {
        super(ctx, attrs);
    }

    private class EditTextWatcher implements TextWatcher
    {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count){}

        @Override
        public void beforeTextChanged(CharSequence s, int start, int before, int count){}

        @Override
        public void afterTextChanged(Editable s)
        {
            onEditTextChanged();
        }
    }
    EditTextWatcher m_watcher = new EditTextWatcher();

    /**
     * Return true in order to enable positive button or false to disable it.
     */
    protected boolean onCheckValue(String value)
    {
        return Strings.hasValue(value);
    }

    protected void onEditTextChanged()
    {
        boolean enable = onCheckValue(getEditText().getText().toString());
        Dialog dlg = getDialog();
        if(dlg instanceof AlertDialog)
        {
            AlertDialog alertDlg = (AlertDialog)dlg;
            Button btn = alertDlg.getButton(AlertDialog.BUTTON_POSITIVE);
            btn.setEnabled(enable);
        }
    }

    @Override
    protected void showDialog(Bundle state)
    {
        super.showDialog(state);

        getEditText().removeTextChangedListener(m_watcher);
        getEditText().addTextChangedListener(m_watcher);
        onEditTextChanged();
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: EditTextPreference Disable Buttons?

Body:
Here is a code sample that enables/disables button depending on whether onCheckValue function returns true or false.

public class ValidatedEditTextPreference extends EditTextPreference
{
    public ValidatedEditTextPreference(Context ctx, AttributeSet attrs, int defStyle)
    {
        super(ctx, attrs, defStyle);
    }

    public ValidatedEditTextPreference(Context ctx, AttributeSet attrs)
    {
        super(ctx, attrs);
    }

    private class EditTextWatcher implements TextWatcher
    {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count){}

        @Override
        public void beforeTextChanged(CharSequence s, int start, int before, int count){}

        @Override
        public void afterTextChanged(Editable s)
        {
            onEditTextChanged();
        }
    }
    EditTextWatcher m_watcher = new EditTextWatcher();

    /**
     * Return true in order to enable positive button or false to disable it.
     */
    protected boolean onCheckValue(String value)
    {
        return Strings.hasValue(value);
    }

    protected void onEditTextChanged()
    {
        boolean enable = onCheckValue(getEditText().getText().toString());
        Dialog dlg = getDialog();
        if(dlg instanceof AlertDialog)
        {
            AlertDialog alertDlg = (AlertDialog)dlg;
            Button btn = alertDlg.getButton(AlertDialog.BUTTON_POSITIVE);
            btn.setEnabled(enable);
        }
    }

    @Override
    protected void showDialog(Bundle state)
    {
        super.showDialog(state);

        getEditText().removeTextChangedListener(m_watcher);
        getEditText().addTextChangedListener(m_watcher);
        onEditTextChanged();
    }
}


问:
Accessing appSettings config values from log4net config section
Does anyone know if it's possible to access key/values from the appSettings section of a config file from the log4net config section in the same file (without using code)?

For example:

```<code><appSettings>
    <add key="Environment" value="DEV" />
    <!-- etc -->
</appSettings>
<log4net>
    <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="${APPDATA}\MyApp\${Environment}\MyApp.log" />
    <!-- etc -->
</log4net>
</code>```

There doesn't seem to be any documentation on this, so I'm not hopeful...  If all else fails, I'll just add "DEV" into the file value and subst it alongside the appSettings' Environment variable.

Thanks in advance,

Rob

答:
You should work with log4net.Util.PatternString as the file type and refer to the app setting using %appSetting{SETTING}

See code below:

```<code><appSettings>
    <add key="Environment" value="DEV" />
    <!-- etc -->
</appSettings>
<log4net>
    <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString"
        value="${APPDATA}\MyApp\%appSetting{Environment}\MyApp.log"/>
    <!-- etc -->
</log4net>
</code>```

Hope this still helps :)

Body:
Does anyone know if it's possible to access key/values from the appSettings section of a config file from the log4net config section in the same file (without using code)?

For example:

<appSettings>
    <add key="Environment" value="DEV" />

</appSettings>
<log4net>
    <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="${APPDATA}\MyApp\${Environment}\MyApp.log" />

</log4net>

There doesn't seem to be any documentation on this, so I'm not hopeful...  If all else fails, I'll just add "DEV" into the file value and subst it alongside the appSettings' Environment variable.

Thanks in advance,

Rob

Body:
You should work with log4net.Util.PatternString as the file type and refer to the app setting using %appSetting{SETTING}

See code below:

<appSettings>
    <add key="Environment" value="DEV" />
    <!-- etc -->
</appSettings>
<log4net>
    <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString"
        value="${APPDATA}\MyApp\%appSetting{Environment}\MyApp.log"/>
    <!-- etc -->
</log4net>

Hope this still helps :)


问:
How does tuple<Ts...>& base = t; work in tuple implementation
When I read post Variadic templates in C++, I could not get one line in the implementation of tuple.

```<code>template <size_t k, class... Ts>
typename std::enable_if<
    k == 0, typename elem_type_holder<0, tuple<Ts...>>::type&>::type
get(tuple<Ts...>& t) {
  return t.tail;
}

template <size_t k, class T, class... Ts>
typename std::enable_if<
    k != 0, typename elem_type_holder<k, tuple<T, Ts...>>::type&>::type
get(tuple<T, Ts...>& t) {
  tuple<Ts...>& base = t;
  return get<k - 1>(base);
}
</code>```

What does tuple<Ts...>& base = t; mean? I think type of t is tuple<T, Ts...>& which cannot be converted to tuple<Ts...>&.

答:
It is a conversion from a derived class reference to a base class reference which is a perfectly valid C++ code.

As you might see in the implementation, tuple<T, Ts...> is derived from tuple<Ts...>:

```<code>template <class... Ts> struct tuple {};

template <class T, class... Ts>
struct tuple<T, Ts...> : tuple<Ts...> {
  tuple(T t, Ts... ts) : tuple<Ts...>(ts...), tail(t) {}

  T tail;
};
</code>```

As t has a type of tuple<T, Ts...>&, you might cast it to tuple<Ts...>& and "throw out" one element from the tuple.

Body:
When I read post Variadic templates in C++, I could not get one line in the implementation of tuple.

template <size_t k, class... Ts>
typename std::enable_if<
    k == 0, typename elem_type_holder<0, tuple<Ts...>>::type&>::type
get(tuple<Ts...>& t) {
  return t.tail;
}

template <size_t k, class T, class... Ts>
typename std::enable_if<
    k != 0, typename elem_type_holder<k, tuple<T, Ts...>>::type&>::type
get(tuple<T, Ts...>& t) {
  tuple<Ts...>& base = t;
  return get<k - 1>(base);
}

What does tuple<Ts...>& base = t; mean? I think type of t is tuple<T, Ts...>& which cannot be converted to tuple<Ts...>&.

Body:
It is a conversion from a derived class reference to a base class reference which is a perfectly valid C++ code.

As you might see in the implementation, tuple<T, Ts...> is derived from tuple<Ts...>:

template <class... Ts> struct tuple {};

template <class T, class... Ts>
struct tuple<T, Ts...> : tuple<Ts...> {
  tuple(T t, Ts... ts) : tuple<Ts...>(ts...), tail(t) {}

  T tail;
};

As t has a type of tuple<T, Ts...>&, you might cast it to tuple<Ts...>& and "throw out" one element from the tuple.


问:
Spring 5 & Encoding settings
I using Spring 5. Have problems with encoding, like this:

ÐÐµÑ ÑÐ°ÐºÐ¾Ð³Ð¾ Ð±ÑÐµÐ½Ð´Ð°: 1000. ÐÐ¾Ð¶Ð°Ð»ÑÐ¹ÑÑÐ°, Ð¿ÑÐ¾Ð²ÐµÑÑÑÐµ Ð·Ð°Ð¿ÑÐ¾Ñ.

I tried to fix encoding this way:

```<code>@Configuration
public class AppInit extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        addEncodingFilter(servletContext);
        super.onStartup(servletContext);
    }

...

private void addEncodingFilter(ServletContext servletContext) {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);

        EnumSet<DispatcherType> dispatcherTypes
                = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ERROR);

        FilterRegistration.Dynamic characterEncoding
                = servletContext.addFilter("characterEncoding", characterEncodingFilter);
        characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
        characterEncoding.setAsyncSupported(true);
    }
}
</code>```

but have no result. Please, give me ready solution how to set encoding for Spring 5.

答:
Solution was:

```<code>@Bean
public MessageSource messageSource() {
    ResourceBundleMessageSource source = new ResourceBundleMessageSource();
    source.setBasename("i18n/messages");
    source.setDefaultEncoding("UTF-8");
    return source;
}
</code>```

I needed simply to set default encoding for i18n files.

Title: Spring 5 & Encoding settings

Body:
I using Spring 5. Have problems with encoding, like this:

ÐÐµÑ ÑÐ°ÐºÐ¾Ð³Ð¾ Ð±ÑÐµÐ½Ð´Ð°: 1000. ÐÐ¾Ð¶Ð°Ð»ÑÐ¹ÑÑÐ°, Ð¿ÑÐ¾Ð²ÐµÑÑÑÐµ Ð·Ð°Ð¿ÑÐ¾Ñ.

I tried to fix encoding this way:

@Configuration
public class AppInit extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        addEncodingFilter(servletContext);
        super.onStartup(servletContext);
    }

...

private void addEncodingFilter(ServletContext servletContext) {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);

        EnumSet<DispatcherType> dispatcherTypes
                = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ERROR);

        FilterRegistration.Dynamic characterEncoding
                = servletContext.addFilter("characterEncoding", characterEncodingFilter);
        characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
        characterEncoding.setAsyncSupported(true);
    }
}

but have no result. Please, give me ready solution how to set encoding for Spring 5.

Body:
Solution was:

@Bean
public MessageSource messageSource() {
    ResourceBundleMessageSource source = new ResourceBundleMessageSource();
    source.setBasename("i18n/messages");
    source.setDefaultEncoding("UTF-8");
    return source;
}

I needed simply to set default encoding for i18n files.


答:
However, as far as __________________________ (put any random thing here), I have decided to give it a try on your input-output:

```<code>Option Explicit

Public Sub TestMe()

    Debug.Print RemoveSomeSlashed("4/30/2017 1151015004 130154701L01 / L02 / L03 / L50")
    Debug.Print RemoveSomeSlashed("4/30/2017 11780 130974003L01 / L02 / L03 / L30 / L50")

End Sub

Public Function RemoveSomeSlashed(myInput As String) As String

    Dim cnt         As Long
    Dim startCnt    As Long
    Dim endCnt      As Long
    Dim compare     As String

    compare = Replace(myInput, "/", "")
    endCnt = Len(myInput) - Len(compare) - 2

    For cnt = Len(myInput) To 1 Step -1
        If Mid(myInput, cnt, 1) = "/" Then
            Mid(myInput, cnt, 1) = "?"
            startCnt = startCnt + 1
            If startCnt = endCnt Then
                RemoveSomeSlashed = Replace(myInput, "?", "")
                Exit Function
            End If
        End If
    Next cnt

End Function
</code>```

That is not the best solution, but it works. The idea is that it removes all the slashes but two and you are not allowed to have the ? sign in the string.

As a bonus, it will display empty string if your text does not have at least 3 slashes :).

Title: excel vba_specify special character then split to different row

Body:
I have a sheet like below

DATA_DT   G_GLACNO_OLD    G_GLACCTNO

4/30/2017 1150007000  130134001L01 / L02 / L03 / L50

4/30/2017 1151009000  130150901L01 / L02 / L03 / L50

4/30/2017 1151014026  130154602L01 / L02 / L03 / L50

4/30/2017 1151014027  130154602L01 / L02 / L03 / L50

4/30/2017 1151015003  130154701L01 / L02 / L03 / L50

4/30/2017 1151015004  130154701L01 / L02 / L03 / L50

4/30/2017 1151015006  130154701L01 / L02 / L03 / L50

4/30/2017 1178036000  130974003L01 / L02 / L03 / L30 / L50

4/30/2017 1151015011  130154701L01 / L02 / L03 / L50

4/30/2017 1151015001  130154702L01 / L02 / L03 / L50

4/30/2017 1151015002  130154702L01 / L02 / L03 / L50

I would like split the row by the special character "/"

so

4/30/2017   1150007000  130134001L01 / L02 / L03 / L50

i want to become

4/30/2017 1150007000 130134001L02

4/30/2017 1150007000 130134001L03

4/30/2017 1150007000 130134001L50

4/30/2017 1150007000 130134001L01

Is there any quick solution?

4/30/2017 1150007000  130134001L01 / L02 / L03 / L50

There are some rows have 4 slashes, some rows have 5 slashes.

Body:
However, as far as __________________________ (put any random thing here), I have decided to give it a try on your input-output:

Option Explicit

Public Sub TestMe()

    Debug.Print RemoveSomeSlashed("4/30/2017 1151015004 130154701L01 / L02 / L03 / L50")
    Debug.Print RemoveSomeSlashed("4/30/2017 11780 130974003L01 / L02 / L03 / L30 / L50")

End Sub

Public Function RemoveSomeSlashed(myInput As String) As String

    Dim cnt         As Long
    Dim startCnt    As Long
    Dim endCnt      As Long
    Dim compare     As String

    compare = Replace(myInput, "/", "")
    endCnt = Len(myInput) - Len(compare) - 2

    For cnt = Len(myInput) To 1 Step -1
        If Mid(myInput, cnt, 1) = "/" Then
            Mid(myInput, cnt, 1) = "?"
            startCnt = startCnt + 1
            If startCnt = endCnt Then
                RemoveSomeSlashed = Replace(myInput, "?", "")
                Exit Function
            End If
        End If
    Next cnt

End Function

That is not the best solution, but it works. The idea is that it removes all the slashes but two and you are not allowed to have the ? sign in the string.

As a bonus, it will display empty string if your text does not have at least 3 slashes :).

ContentLicense: CC BY-SA 4.0


问:
Give a toggle button the color "#FF5D0000" in the main window
I want to give mij text on my button a customized color in the MainWindow.xaml.cs

Normally you give the color in the cs file by this way to the  command:

```<code>ToggleButton.Foreground = Brushes.Green;
</code>```

But I want to give the hexnumber

I've already tried something like this :

```<code>SolidColorBrush Owncolor = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FF5D0000"));
ToggleButton.Foreground = Brushes.Owncolor;
</code>```

答:
Instead of doing it in code behind (unless you have a very specific reason to do that), you can work on your xaml

```<code><ToggleButton Foreground = "#FF5D0000"/>
</code>```

if you are doing it based on some condition, also please take a look at this. It's always a better practice to handle graphical stuff in your xaml as much as you can

for instance you can do

```<code>        <ToggleButton>
            <ToggleButton.Style>
                <Style TargetType="{x:Type ToggleButton}">
                    <Style.Triggers>
                        <Trigger Property="IsChecked" Value="True">
                            <Setter Property="Foreground" Value="Green"/>
                        </Trigger>
                        <Trigger Property="IsChecked" Value="False">
                            <Setter Property="Foreground" Value="Red"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </ToggleButton.Style>
        </ToggleButton>
</code>```

Body:
I want to give mij text on my button a customized color in the MainWindow.xaml.cs

Normally you give the color in the cs file by this way to the  command:

ToggleButton.Foreground = Brushes.Green;

But I want to give the hexnumber

I've already tried something like this :

SolidColorBrush Owncolor = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FF5D0000"));
ToggleButton.Foreground = Brushes.Owncolor;

Body:
Instead of doing it in code behind (unless you have a very specific reason to do that), you can work on your xaml

<ToggleButton Foreground = "#FF5D0000"/>

if you are doing it based on some condition, also please take a look at this. It's always a better practice to handle graphical stuff in your xaml as much as you can

for instance you can do

        <ToggleButton>
            <ToggleButton.Style>
                <Style TargetType="{x:Type ToggleButton}">
                    <Style.Triggers>
                        <Trigger Property="IsChecked" Value="True">
                            <Setter Property="Foreground" Value="Green"/>
                        </Trigger>
                        <Trigger Property="IsChecked" Value="False">
                            <Setter Property="Foreground" Value="Red"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </ToggleButton.Style>
        </ToggleButton>


问:
How to get text from <Strong> tag using xpath?
Here is my HTML code</p>

```<code><p>
<strong>Telephone:</strong>
 1(111)656-3485
<br/>
</code>```

答:
You can use Xpaths to get it, Please find the code below:

```<code>WebElement eleText=driver.findElement(By.xpath("//strong[contains(text(),'Telephone:')]"));

String textTelephone=eleText.getText();
System.out.println(textTelephone);
</code>```

You can use another xpath like that

```<code>WebElement eleText=driver.findElement(By.xpath("//*[contains(text(),'Telephone:')]"));

String textTelephone=eleText.getText();
System.out.println(textTelephone);
</code>```

Body:
Here is my HTML code

Telephone:
 1(111)656-3485

Body:
You can use Xpaths to get it, Please find the code below:

WebElement eleText=driver.findElement(By.xpath("//strong[contains(text(),'Telephone:')]"));

String textTelephone=eleText.getText();
System.out.println(textTelephone);

You can use another xpath like that

WebElement eleText=driver.findElement(By.xpath("//*[contains(text(),'Telephone:')]"));

String textTelephone=eleText.getText();
System.out.println(textTelephone);


问:
how to get list of long values in hibernate from the table while casting from bigint to long
I get the following exception when using the getEvents method:

org.hibernate.MappingException: Unknown entity: java.lang.Long

```<code>public List<Long> getEvents(Person person) {

    String q = "select new java.lang.Long(te.event_id) "
        + "from teachers_event te"
        + "where te.teachers_id = :personId ";
    Query query = entityManager.createNativeQuery(q, Long.class);
    query.setParameter("personId", person.getId());
    return (List<Long>) query.getResultList();
}
</code>```

The teachers_event table in database connects the id of teacher with the event. I don't map this table to an entity. I only want to get the ids from it. The ids in the PostgreSQL table are bigint.
Is there any way to achieve it without making a separate class to map the TeacherEvents entity?

答:
In JPA 2.1 there is a feature called "result set mapping".

Basically you have to define a POJO class which would hold the result values (all the values must be passed using the constructor):

```<code>public class IdResult{

    private Object id;

    public IdResult(Object id){
        this.id = id;
    }

     public Long getLongId(){
        return (Long)id;
     }
}
</code>```

Then you have to declare the mapping on one of your entities (does not matter on which, it just has to be a declated @Entity):

```<code>@SqlResultSetMapping(name="IdMapping", classes = {
    @ConstructorResult(targetClass = IdResult.class,
    columns = {@ColumnResult(name="id")})
})
</code>```

You would have to use an alias in your query to match the @ColumnResult name:

```<code>select te.event_id as id
...
</code>```

And finally use in the query creation:

```<code>Query query = entityManager.createNativeQuery(q, IdMapping.class);
return (List<IdResult>) query.getResultList();
</code>```

Then in your service layer you would just use getLongId();

Body:
I get the following exception when using the getEvents method:

org.hibernate.MappingException: Unknown entity: java.lang.Long

public List<Long> getEvents(Person person) {

    String q = "select new java.lang.Long(te.event_id) "
        + "from teachers_event te"
        + "where te.teachers_id = :personId ";
    Query query = entityManager.createNativeQuery(q, Long.class);
    query.setParameter("personId", person.getId());
    return (List<Long>) query.getResultList();
}

The teachers_event table in database connects the id of teacher with the event. I don't map this table to an entity. I only want to get the ids from it. The ids in the PostgreSQL table are bigint.
Is there any way to achieve it without making a separate class to map the TeacherEvents entity?

Body:
In JPA 2.1 there is a feature called "result set mapping".

Basically you have to define a POJO class which would hold the result values (all the values must be passed using the constructor):

public class IdResult{

    private Object id;

    public IdResult(Object id){
        this.id = id;
    }

     public Long getLongId(){
        return (Long)id;
     }
}

Then you have to declare the mapping on one of your entities (does not matter on which, it just has to be a declated @Entity):

@SqlResultSetMapping(name="IdMapping", classes = {
    @ConstructorResult(targetClass = IdResult.class,
    columns = {@ColumnResult(name="id")})
})

You would have to use an alias in your query to match the @ColumnResult name:

select te.event_id as id
...

And finally use in the query creation:

Query query = entityManager.createNativeQuery(q, IdMapping.class);
return (List<IdResult>) query.getResultList();

Then in your service layer you would just use getLongId();


问:
Kill a stuck thread on a running VM (JBoss Instance) in Java?
A bug in a third party library is causing an infinite loop in a worker thread on a JBoss instance of mine.  Do you know of a way to kill this "stuck" thread without restarting the server?  We'd like to be able to recover from this  until a fix is deployed, preferably without having to restart.

I've seen a few people mention using Thread.interrupt() - if I were to code my own MBean, how would I get a handle to the thread in question in order to interrupt it?

Update: Wasn't able to solve using any of these methods.  I did come across another thread about the same issue that had a link to why Thread.stop() is deprecated. Someone else has asked a similar question with similar results. It seems like more sophisticated containers should provide this kind of health mechanism, but I guess their hands are tied w/r/t the JVM.

答:
You could use the discouraged myThread.stop() method. But then it is very likely the Thread is still referenced there, so you should use some reflection magic to remove all references to this thread from the components holding it.

How to find the Thread? Use Thread.getThreadGroup() and ThreadGroup.getThreadGroup() to go up to the root ThreadGroup(), and then use the iterate() functions to go through all threads.


问:
Pessimistically locking code between processes
We have the following processes that can modify the same dataset:

Web site (Asp.NET Web API that modifies some parent/child dataset)

Azure Web Job (C# cod that modifies the same parent/child dataset)

What are the recommended ways to ensure that we keep data integrity when the Parent/Child datasets are modified by the two processes simultaneously (C# Lock statement won't work because it's code running in different processes).

Currently they are using Entity Framework, and the process will load the dataset in memory, work on the data, and then save it.  The problem is that the data may change by the other process A after it is initially read by process B.

The data is in a SQL Azure database.

Can I create a blocking transaction on the parent table record (Id = XXXX) and so other processes just have to wait until the lock is released.  How best to do that?

Otherwise, perhaps some other ideas off the top of my head might be setting a "Locked" field on the parent record, or checking the MAX RowVersion for the parent UNION with each child table (for the Parent ID) and check this RowVersion before and after each change?

答:
The sp_getapplock stored procedure seems to be exactly what you need.

It is very useful when you want to synchronize processes that need to get exclusive access to a part of the database.

This should be something like below. Where ctx is a DbContext and each of the processes you want to synchronize is using the same shared logical name string "MYLOCKNAME", or anything you want.

```<code>using (var tran = ctx.Database.BeginTransaction())
{
    try
    {
        const string lockName = "MYLOCKNAME";

        var resourceParam = new SqlParameter("Resource", SqlDbType.NVarChar, 255) { Value = lockName };
        var lockModeParam = new SqlParameter("LockMode", SqlDbType.NVarChar, 32) { Value = "Transaction" };
        ctx.Database.ExecuteSqlCommand("EXEC sp_getapplock @Resource, @LockMode", resourceParam, lockModeParam);

        // Do stuff with ctx
        // ...

        tran.Commit();
    }
    catch
    {
        tran.Rollback();
    }
}
</code>```

Body:
The sp_getapplock stored procedure seems to be exactly what you need.

It is very useful when you want to synchronize processes that need to get exclusive access to a part of the database.

This should be something like below. Where ctx is a DbContext and each of the processes you want to synchronize is using the same shared logical name string "MYLOCKNAME", or anything you want.

using (var tran = ctx.Database.BeginTransaction())
{
    try
    {
        const string lockName = "MYLOCKNAME";

        var resourceParam = new SqlParameter("Resource", SqlDbType.NVarChar, 255) { Value = lockName };
        var lockModeParam = new SqlParameter("LockMode", SqlDbType.NVarChar, 32) { Value = "Transaction" };
        ctx.Database.ExecuteSqlCommand("EXEC sp_getapplock @Resource, @LockMode", resourceParam, lockModeParam);

        // Do stuff with ctx
        // ...

        tran.Commit();
    }
    catch
    {
        tran.Rollback();
    }
}


问:
Convert Data to Oracle Data
I am receiving this date from a WS 2017-12-03T05:44:57 , that I want to convert to Oracle Date, but I don't T05 but refers exactly.

```<code>TZD Daylight savings information. For example, 'PST' ?
TZH Time zone hour. ?
TZM Time zone minute. ?
TZR Time zone region. ?
</code>```

答:
2017-12-03T05:44:57 is according to ISO-8601 standard. T is the separator between date and time values (actually often it is skipped - and thus not strictly according to the standard)

2017-12-03T05:44:57 does not contain any time information, i.e. you don't know the time zone.

Time zone information are provided for example as 2017-12-03T05:44:57+08:00 or 2017-12-03T05:44:57Z for UTC times.

Conversion to a DATE/TIMESTAMP would be like this

```<code>SELECT
    TO_DATE('2017-12-03T05:44:57', 'YYYY-MM-DD"T"HH24:MI:SS'),
    TO_TIMESTAMP('2017-12-03T05:44:57', 'YYYY-MM-DD"T"HH24:MI:SS')
FROM dual;
</code>```

Title: Convert Data to Oracle Data

Body:
I am receiving this date from a WS 2017-12-03T05:44:57 , that I want to convert to Oracle Date, but I don't T05 but refers exactly.

TZD Daylight savings information. For example, 'PST' ?
TZH Time zone hour. ?
TZM Time zone minute. ?
TZR Time zone region. ?

Body:
2017-12-03T05:44:57 is according to ISO-8601 standard. T is the separator between date and time values (actually often it is skipped - and thus not strictly according to the standard)

2017-12-03T05:44:57 does not contain any time information, i.e. you don't know the time zone.

Time zone information are provided for example as 2017-12-03T05:44:57+08:00 or 2017-12-03T05:44:57Z for UTC times.

Conversion to a DATE/TIMESTAMP would be like this

SELECT
    TO_DATE('2017-12-03T05:44:57', 'YYYY-MM-DD"T"HH24:MI:SS'),
    TO_TIMESTAMP('2017-12-03T05:44:57', 'YYYY-MM-DD"T"HH24:MI:SS')
FROM dual;


问:
Running mulitple process in Node JS
Okay so I'm trying to build a web service for twitter automation. I have build bots before that works only for a single account.

The service that I'm looking to build will enable users to register and then set up some preference (like follow users that tweets #ILoveProgramming).

My main question is - right now if I need to run the bot I just type "node bot.js" and the bot will run. How do I run multiple process for all the hundred users that'll be using my Web Service ?

答:
You can specify cluster information in pm2 configuration file like this,

File: process.yml

apps:
  - script   : <your script name>
    name     : <name of your app>
    instances: <number of instances you want to run>
    exec_mode: cluster

and then start pm2 like this,

pm2 start process.yml

Title: Running mulitple process in Node JS


问:
VBA call webpage without opening browser or returning data
I am trying to create an excel UDF that calls a web page that runs scripts which take values from parameters in the URL. EG: "http://example.com.com/script.php?variable1=123&variable2=456&etc=etc"

I have used this after much googling and trying things from other stackoverflow answers. yes it creates a udf, yes you can enter a cell value in the udf, but no it does not call the URL (visits tracking on the URL says it has not been called).

```<code>Function callurl(urltocall As String) As String
Dim urlText As String
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", urltocall, False
.send
urlText = .responseText
End With
End Function
</code>```

I do not need it to return any data, just to call the URL to run the script. The point of doing this is to take variables from excel and use them as parameters in the URL which will run a script and update a web SQL database.

The actual result was nothing (blank cell in excel, no visit to webpage).

答:
The function doesn't return any result. Here's correct code:</p>

```<code>Function callurl(urltocall As String) As String
    Dim urlText As String
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", urltocall, False
        .Send
        urlText = .responseText
    End With
    callurl = urltext
End Function
</code>```

Body:
I am trying to create an excel UDF that calls a web page that runs scripts which take values from parameters in the URL. EG: "http://example.com.com/script.php?variable1=123&variable2=456&etc=etc"

I have used this after much googling and trying things from other stackoverflow answers. yes it creates a udf, yes you can enter a cell value in the udf, but no it does not call the URL (visits tracking on the URL says it has not been called).

Function callurl(urltocall As String) As String
Dim urlText As String
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", urltocall, False
.send
urlText = .responseText
End With
End Function

I do not need it to return any data, just to call the URL to run the script. The point of doing this is to take variables from excel and use them as parameters in the URL which will run a script and update a web SQL database.

The actual result was nothing (blank cell in excel, no visit to webpage).

Body:
The function doesn't return any result. Here's correct code:

Function callurl(urltocall As String) As String
    Dim urlText As String
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", urltocall, False
        .Send
        urlText = .responseText
    End With
    callurl = urltext
End Function


问:
Transform array by combining same element

I been trying to minimize my code by combining same data in one
  multidimensional array.

here is my array :

```<code>data:[
    0:{
        id:"1"
        date:"2017-11-27"
        type:"Meeting"
        log_in:"06:30:00"
        log_out:"11:50:00"
    }
    1:{
        id:"1"
        date:"2017-11-27"
        type:"Lunch"
        log_in:"12:00:00"
        log_out:"01:00:00"
    }
    2:{
        id:"1"
        date:"2017-11-27"
        type:"Seminar"
        log_in:"1:15:00"
        log_out:"03:05:00"
    }
    3:{
        id:"1"
        date:"2017-11-28"
        type:"Lunch"
        log_in:"12:00:00"
        log_out:"01:00:00"
    }
    4:{
        id:"1"
        date:"2017-12-28"
        type:"Out of the Office"
        log_in:"03:00:00"
        log_out:"05:00:00"
    } ]
</code>```

I been trying to transform my array to this:

```<code>new_data:[
    0:{
     id:"1"
     date:"2017-11-27"
     logs:[
        {type:"Meeting",log_in:"06:30:00",log_out:"11:50:00"},
        {type:"Lunch",log_in:"12:00:00",log_out:"01:00:00"},
        {type:"Seminar",log_in:"1:15:00",log_out:"03:05:00"}
     ]
    }
    1:{
     id:"1"
     date:"2017-11-28"
     logs:[
        {type:"Lunch",log_in:"12:00:00",log_out:"01:00:00"},
        {type:"Out of the Office",log_in:"03:00:00",log_out:"05:00:00"}
     ]
    }
]
</code>```

I have try the code in this is link but I cannot manipulate it
  well. I just use the right answer in the that link.

答:
Simple solution using for loop,

var data = [
  {
    id: "1",
    date: "2017-11-27",
    type: "Meeting",
    log_in: "06:30:00",
    log_out: "11:50:00"
  },
  {
    id: "1",
    date: "2017-11-27",
    type: "Lunch",
    log_in: "12:00:00",
    log_out: "01:00:00"
  },
  {
    id: "1",
    date: "2017-11-27",
    type: "Seminar",
    log_in: "1:15:00",
    log_out: "03:05:00",
  },
  {
    id: "2",
    date: "2017-11-28",
    type: "Lunch",
    log_in: "12:00:00",
    log_out: "01:00:00"
   },
   {
      id: "2",
      date: "2017-12-28",
      type: "Out of the Office",
      log_in: "03:00:00",
      log_out: "05:00:00"
   }
];

var newObj = {};
for (var i = 0; i < data.length; ++i) {

    //if a obj for this id does not exist yet, create
    if (newObj[data[i].id] == undefined)
    {
       newObj[data[i].id] = {"id": data[i].id, "date": data[i].date, "logs": []};
    }

    //store log into logs array using obj id
    newObj[data[i].id].logs.push({"type" : data[i].type, "log_in" : data[i].log_in, "log_out" : data[i].log_out});
}

console.log(newObj);```

Body:
I been trying to minimize my code by combining same data in one
  multidimensional array.

here is my array :

data:[
    0:{
        id:"1"
        date:"2017-11-27"
        type:"Meeting"
        log_in:"06:30:00"
        log_out:"11:50:00"
    }
    1:{
        id:"1"
        date:"2017-11-27"
        type:"Lunch"
        log_in:"12:00:00"
        log_out:"01:00:00"
    }
    2:{
        id:"1"
        date:"2017-11-27"
        type:"Seminar"
        log_in:"1:15:00"
        log_out:"03:05:00"
    }
    3:{
        id:"1"
        date:"2017-11-28"
        type:"Lunch"
        log_in:"12:00:00"
        log_out:"01:00:00"
    }
    4:{
        id:"1"
        date:"2017-12-28"
        type:"Out of the Office"
        log_in:"03:00:00"
        log_out:"05:00:00"
    } ]

I been trying to transform my array to this:

new_data:[
    0:{
     id:"1"
     date:"2017-11-27"
     logs:[
        {type:"Meeting",log_in:"06:30:00",log_out:"11:50:00"},
        {type:"Lunch",log_in:"12:00:00",log_out:"01:00:00"},
        {type:"Seminar",log_in:"1:15:00",log_out:"03:05:00"}
     ]
    }
    1:{
     id:"1"
     date:"2017-11-28"
     logs:[
        {type:"Lunch",log_in:"12:00:00",log_out:"01:00:00"},
        {type:"Out of the Office",log_in:"03:00:00",log_out:"05:00:00"}
     ]
    }
]

I have try the code in this is link but I cannot manipulate it
  well. I just use the right answer in the that link.