问:
How can I get system configuration for jenkins using remote access API
Jenkins provide nice Remote Access API, which can be used to fetch lots of information like jobs and views.

I wonder whether or how to fetch the system (global) configurations from remote access API.

Those information are in web page http://your.jenkins.url/manage

答:
In my plugin i have accessed the system configuartion,"Artifactory credentials".
1) add the artifactory dependency in pom.xml.
     i.e.

```<code><dependency>
            <groupId>org.jenkins-ci.plugins</groupId>
            <artifactId>artifactory</artifactId>
            <version>2.9.0</version>
            <type>jar</type>
        </dependency>
</code>```

2) find the exact maching global.jelly config.
i found in org.jfrog.hudson.ArtifactoryBuilder

```<code>                            <table style="width: 100%" id="legacyDeployerCredentials${server.url}">
                                <f:entry title="Username"
                                         help="/plugin/artifactory/help/common/help-deployerUserName.html">
                                    <f:textbox name="username" field="username"
                                               value="${server.deployerCredentialsConfig.username}"/>
                                </f:entry>
                                <f:entry title="Password"
                                         help="/plugin/artifactory/help/common/help-deployerPassword.html">
                                    <f:password name="password" field="password"
                                                value="${server.deployerCredentialsConfig.password}"/>
                                </f:entry>
                            </table>
                        </f:block>
                    </f:section>
</code>```

3) identify the class used for applying the configuration.
     org.jfrog.hudson.ArtifactoryBuilder.java
4) create jenkins instance and access the plugin descriptor get user credential.

```<code>ArtifactoryBuilder.DescriptorImpl ab = (ArtifactoryBuilder.DescriptorImpl) jenkins.model.Jenkins.getInstance().getDescriptor(ArtifactoryBuilder.class);
        ArtifactoryServer server = ab.getArtifactoryServers().iterator().next();
        this.userName =  server.getDeployerCredentialsConfig().getUsername();
        this.password =  server.getDeployerCredentialsConfig().getPassword();
</code>```

Body:
In my plugin i have accessed the system configuartion,"Artifactory credentials".
1) add the artifactory dependency in pom.xml.
     i.e.

<dependency>
            <groupId>org.jenkins-ci.plugins</groupId>
            <artifactId>artifactory</artifactId>
            <version>2.9.0</version>
            <type>jar</type>
        </dependency>

2) find the exact maching global.jelly config.
i found in org.jfrog.hudson.ArtifactoryBuilder

                            <table style="width: 100%" id="legacyDeployerCredentials${server.url}">
                                <f:entry title="Username"
                                         help="/plugin/artifactory/help/common/help-deployerUserName.html">
                                    <f:textbox name="username" field="username"
                                               value="${server.deployerCredentialsConfig.username}"/>
                                </f:entry>
                                <f:entry title="Password"
                                         help="/plugin/artifactory/help/common/help-deployerPassword.html">
                                    <f:password name="password" field="password"
                                                value="${server.deployerCredentialsConfig.password}"/>
                                </f:entry>
                            </table>
                        </f:block>
                    </f:section>

3) identify the class used for applying the configuration.
     org.jfrog.hudson.ArtifactoryBuilder.java
4) create jenkins instance and access the plugin descriptor get user credential.

ArtifactoryBuilder.DescriptorImpl ab = (ArtifactoryBuilder.DescriptorImpl) jenkins.model.Jenkins.getInstance().getDescriptor(ArtifactoryBuilder.class);
        ArtifactoryServer server = ab.getArtifactoryServers().iterator().next();
        this.userName =  server.getDeployerCredentialsConfig().getUsername();
        this.password =  server.getDeployerCredentialsConfig().getPassword();


来源: stackexchange

问:
How to sync with a remote Git repository?
I forked a project on github, made some changes, so far so good.

In the meantime, the repository I forked from changed and I would like to get those changes into my repository. How do I do that ?

答:
You need to add the original repository (the one that you forked) as a remote.

git remote add github (clone url for the orignal repository)

Then you need to bring in the changes to your local repository

git fetch github

Now you will have all the branches of the original repository in your local one. For example, the master branch will be github/master. With these branches you can do what you will. Merge them into your branches etc

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
animation CSS3+jquery
https://jsfiddle.net/8953ob8g/

I am a bit confused why the animation doesn't occur BOTH whenever I reveal/close the menu but only when I reveal it? I'd really love to hear some tips regarding the issue, thank you very much in advance for any sort of reply.

```<code><!doctype html>
<html>

  <head>
    <meta charset="UTF-8">
    <title>projekt powazny</title>
    <!--external style-sheet-->
    <link rel="stylesheet" type="text/css" href="css/custom.css">
    <!--external scripts, jquery-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/custom.js"></script>
    <script src="https://use.fontawesome.com/39b504251e.js"></script>
  </head>

  <body>
    <!--header with nav-->
    <header>
      <!--menu-->
      <div id="menu-click">
        <i class="fa fa-bars" aria-hidden="true"></i>
      </div>
      <!--menu-hidden + add class show on click-->
      <div id="menu-hidden">
      </div>
    </header>
  </body>
</html>

body {
  margin: 0px auto;
  background-color: #233D4D;
}

#menu-click {
  position: absolute;
  right: 30px;
  top: 20px;
  width: 50px;
  height: 50px;
  cursor: pointer;
  font-size: 32px;
  color: white;
}

#menu-hidden {
  position: absolute;
  left: -200px;
  height: 100%;
  background-color: #FE7F2D;
  width: 200px;
}

.open {
  animation: slide-in 300ms ease forwards;
}

@keyframes slide-in {
  0% {
    left: -200px;
  }
  100% {
    left: 0px;
  }
}

$(document).ready(function() {
  $("#menu-click").click(function() {
    $("#menu-hidden").toggleClass("open");
  });
});
</code>```

答:
You are only animating the reveal (with slide-in). To fix:

```<code>$(function() {
    var $menuClick = $('#menu-click'),
        $menuHidden = $('#menu-hidden');

  $menuClick.off('click').on('click', function() {
      if ($menuHidden.hasClass('initial')) {
          $menuHidden.removeClass('initial').addClass('open');
      } else if ($menuHidden.hasClass('open')) {
        $menuHidden.removeClass('open').addClass('close');
      } else {
        $menuHidden.removeClass('close').addClass('open');
      }
  });
});
</code>```

And in your css:

```<code>body {
  margin: 0px auto;
  background-color: #233D4D;
}

#menu-click {
  position: absolute;
  right: 30px;
  top: 20px;
  width: 50px;
  height: 50px;
  cursor: pointer;
  font-size: 32px;
  color: white;
}

#menu-hidden {
  position: absolute;
  left: -200px;
  height: 100%;
  background-color: #FE7F2D;
  width: 200px;
}

.open {
  animation: slide-in 300ms ease forwards;
}

.close {
  animation: slide-out 300ms ease backwards;
}

@keyframes slide-in {
  0% {
    left: -200px;
  }
  100% {
    left: 0px;
  }
}

@keyframes slide-out {
  0% {
    left: 0;
  }
  100% {
    left: -200px;
  }
}
</code>```

Title: animation CSS3+jquery

Body:
https://jsfiddle.net/8953ob8g/

I am a bit confused why the animation doesn't occur BOTH whenever I reveal/close the menu but only when I reveal it? I'd really love to hear some tips regarding the issue, thank you very much in advance for any sort of reply.

<!doctype html>

    <meta charset="UTF-8">
    <title>projekt powazny</title>

    <link rel="stylesheet" type="text/css" href="css/custom.css">

body {
  margin: 0px auto;
  background-color: #233D4D;
}

#menu-click {
  position: absolute;
  right: 30px;
  top: 20px;
  width: 50px;
  height: 50px;
  cursor: pointer;
  font-size: 32px;
  color: white;
}

#menu-hidden {
  position: absolute;
  left: -200px;
  height: 100%;
  background-color: #FE7F2D;
  width: 200px;
}

.open {
  animation: slide-in 300ms ease forwards;
}

@keyframes slide-in {
  0% {
    left: -200px;
  }
  100% {
    left: 0px;
  }
}

$(document).ready(function() {
  $("#menu-click").click(function() {
    $("#menu-hidden").toggleClass("open");
  });
});

Body:
You are only animating the reveal (with slide-in). To fix:

$(function() {
    var $menuClick = $('#menu-click'),
        $menuHidden = $('#menu-hidden');

  $menuClick.off('click').on('click', function() {
      if ($menuHidden.hasClass('initial')) {
          $menuHidden.removeClass('initial').addClass('open');
      } else if ($menuHidden.hasClass('open')) {
        $menuHidden.removeClass('open').addClass('close');
      } else {
        $menuHidden.removeClass('close').addClass('open');
      }
  });
});

And in your css:

body {
  margin: 0px auto;
  background-color: #233D4D;
}

#menu-click {
  position: absolute;
  right: 30px;
  top: 20px;
  width: 50px;
  height: 50px;
  cursor: pointer;
  font-size: 32px;
  color: white;
}

#menu-hidden {
  position: absolute;
  left: -200px;
  height: 100%;
  background-color: #FE7F2D;
  width: 200px;
}

.open {
  animation: slide-in 300ms ease forwards;
}

.close {
  animation: slide-out 300ms ease backwards;
}

@keyframes slide-in {
  0% {
    left: -200px;
  }
  100% {
    left: 0px;
  }
}

@keyframes slide-out {
  0% {
    left: 0;
  }
  100% {
    left: -200px;
  }
}


问:
How to render front-end pages in Slim Framework route?
I have Slim installed in my folder, and I want to know if it's possible to render a full html/css/js page from a Slim route.

Suppose that this is the file that control the routes:

rControl.php

```<code><?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require '../vendor/autoload.php';

$app = new \Slim\App;
$app->get('/myroute', function (Request $request, Response $response){

    /* I want to render the page when enter in this route*/

return $response;
});

$app->run();
</code>```

and suppose that I have a custom html file with css formatting:

myTemplate.html

```<code><!DOCTYPE html>
<html lang="pt-br">
<head>

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>My title </title>
</head>

<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.min.css">

<script src="jquery-2.2.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/engine.js"></script>

<body>

<h1> Some text </h1>

<p> example text here </p>

<div> hi! more content... </div>

</body>
</html>
</code>```

The question is: How can I show the content of myTemplate.html page when the user go to the route "/myroute"?

答:
The easiest way is to use PHP-View.

```<code><?php
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Views\PhpRenderer;

require '../vendor/autoload.php';

$app = new \Slim\App;
$container = $app->getContainer();
$container['renderer'] = new PhpRenderer("./templates");

$app->get('/myroute', function (Request $request, Response $response){
    return $this->renderer->render($response, "/myTemplate.html");
});

$app->run();
</code>```

Traditionally, we use the .phtml extension for the templates to indicate that they can have PHP code in them. You can pass data to the template file via an array as the third parameter to render().

Body:
I have Slim installed in my folder, and I want to know if it's possible to render a full html/css/js page from a Slim route.

Suppose that this is the file that control the routes:

rControl.php

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require '../vendor/autoload.php';

$app = new \Slim\App;
$app->get('/myroute', function (Request $request, Response $response){

    /* I want to render the page when enter in this route*/

return $response;
});

$app->run();

and suppose that I have a custom html file with css formatting:

myTemplate.html

<!DOCTYPE html>

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>My title </title>

<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.min.css">

 Some text

 example text here

 hi! more content...

The question is: How can I show the content of myTemplate.html page when the user go to the route "/myroute"?

Body:
The easiest way is to use PHP-View.

<?php
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Views\PhpRenderer;

require '../vendor/autoload.php';

$app = new \Slim\App;
$container = $app->getContainer();
$container['renderer'] = new PhpRenderer("./templates");

$app->get('/myroute', function (Request $request, Response $response){
    return $this->renderer->render($response, "/myTemplate.html");
});

$app->run();

Traditionally, we use the .phtml extension for the templates to indicate that they can have PHP code in them. You can pass data to the template file via an array as the third parameter to render().


问:
how to delete row from grid ( CRUD ) in PHP without using jquery & $_GET?
I want to delete row from grid without using jquery and $_GET. because I dont want to show Row ID.</p>

```<code><form action="" method="post">
<?php

$readsql= "select * from country";
$readresult=$conn->query($readsql);
if ($readresult->num_rows > 0) {
 while($row = $readresult->fetch_assoc()) {
   echo '<tr>';
     echo '<td>'. $row['country_id'] . '</td>';
     echo '<td>'. $row['country_name'] . '</td>';
     echo '<td>'. $row['country_phon'] . '</td>';
     echo '<td width=250>';
     echo '<button type="button" class="btn btn-success abc"  data-toggle="modal" data-cid='. $row['country_id'] .' data-cphone='.$row['country_phon'].' data-cname='.$row['country_name'].' >Update</button>';
     echo ' ';
     echo '<button type="submit" class="btn btn-danger del" name="delete" data-id='.$row['country_id'].'>Delete</button>';
     echo '</td>';
     echo '</tr>';  } echo "</table>";
   } else {
   echo "0 results";
   }?></form>
</code>```

答:
If you want to hide the row, create a CSS class

```<code>.hidden { display:none;}
</code>```

Then change the type of the delete button to button. Add an onclick attribute to the button:

onclick="this.parentNode.parentNode.className= 'hidden'"

If you want to delete it from the data table, you will need to send some term to the server to identify the record.

Body:
I want to delete row from grid without using jquery and $_GET. because I dont want to show Row ID.

<form action="" method="post">
<?php

$readsql= "select * from country";
$readresult=$conn->query($readsql);
if ($readresult->num_rows > 0) {
 while($row = $readresult->fetch_assoc()) {
   echo '
';
     echo ''. $row['country_id'] . '	';
     echo ''. $row['country_name'] . '	';
     echo ''. $row['country_phon'] . '	';
     echo '';
     echo '<button type="button" class="btn btn-success abc"  data-toggle="modal" data-cid='. $row['country_id'] .' data-cphone='.$row['country_phon'].' data-cname='.$row['country_name'].' >Update</button>';
     echo ' ';
     echo '<button type="submit" class="btn btn-danger del" name="delete" data-id='.$row['country_id'].'>Delete</button>';
     echo '	';
     echo '
';  } echo "
";
   } else {
   echo "0 results";
   }?></form>

Body:
If you want to hide the row, create a CSS class

.hidden { display:none;}

Then change the type of the delete button to button. Add an onclick attribute to the button:

onclick="this.parentNode.parentNode.className= 'hidden'"

If you want to delete it from the data table, you will need to send some term to the server to identify the record.


问:
What is the craic with ContainerViews? (Assertion Failed: calling set on destroyed object)
All,

I have searched around for an answer to this but have yet to find a good explanation and solution.  Hopefully, you can help.

I have a route that renders an Ember.ContainerView (as opposed to a standard Ember.View).  When I transition away from this route and then back to it (either via the back button, a link-helper or just changing the url) I get the following error in the console:

```<code>Uncaught Error: Assertion Failed: calling set on destroyed object
</code>```

I understand that a high level reason for this is that when we transition away from the route with the ContainerView, it's childViews are marked as destroyed.  When we transition back to the route, the problem has something to do with Ember trying to set the childViews back to the destroyed instances.

I'm not exactly clear but that is the vague understanding I currently have.

So, my questions are as follows:

Can you please correct my understanding of this problem if it is not correct?

Can you please tell me how to fix this error?

For your convenience, I have created a JSBin example for your viewing pleasure.  To replicate the error, open your JS console, click on the Go to Route two link, then click on the Go to index link.  Now check your logs.

Thanks in advance for any assistance you can provide.

答:
if you are using Ember.Instrumentation namespace for publishing your events and Ember.subscribe to listen to them in your code, when you publish events, it stack all the subscribers and call them even when they are destroyed.

so basically, when for example your route is destroyed which is running subscribe statements it will fail and give above error.

Here is a solution to this problem:  Use Ember.Instrumentation.reset() to remove previous subscribers which are destroyed. This solution helped me in acceptance tests where app was destroyed after tests are finished.
I wrote Ember.Instrumentation.reset() in startApp function of module-for-acceptance.js and it worked.

Hope that helps.

Body:
All,

I have searched around for an answer to this but have yet to find a good explanation and solution.  Hopefully, you can help.

I have a route that renders an Ember.ContainerView (as opposed to a standard Ember.View).  When I transition away from this route and then back to it (either via the back button, a link-helper or just changing the url) I get the following error in the console:

Uncaught Error: Assertion Failed: calling set on destroyed object

I understand that a high level reason for this is that when we transition away from the route with the ContainerView, it's childViews are marked as destroyed.  When we transition back to the route, the problem has something to do with Ember trying to set the childViews back to the destroyed instances.

I'm not exactly clear but that is the vague understanding I currently have.

So, my questions are as follows:

Can you please correct my understanding of this problem if it is not correct?

Can you please tell me how to fix this error?

For your convenience, I have created a JSBin example for your viewing pleasure.  To replicate the error, open your JS console, click on the Go to Route two link, then click on the Go to index link.  Now check your logs.

Thanks in advance for any assistance you can provide.


问:
Wordpress custom login with error processing
Hi I'm trying to get my Wordpress custom login which is in a dropdown in header.php to display errors when an incorrect email or password is entered, or even if both or 1 is left blank.

Here is the login form I'm using

```<code><?php
if ( ! is_user_logged_in() ) { // Display WordPress login form:
    $args = array(
      'redirect' => admin_url(),
      'form_id' => 'loginform-custom',
      'label_username' => __( 'Username custom text' ),
      'label_password' => __( 'Password custom text' ),
      'label_remember' => __( 'Remember Me custom text' ),
      'label_log_in' => __( 'Log In custom text' ),
      'remember' => true
    );
    wp_login_form( $args );
} else { // If logged in:
    wp_loginout( home_url() ); // Display "Log Out" link.
    echo " | ";
    wp_register('', ''); // Display "Site Admin" link.
}
?>
</code>```

and I have found this code from here:
https://wordpress.stackexchange.com/questions/61267/prevent-wp-login-form-from-redirecting-to-wp-admin-when-there-are-errors

```<code>function wp_authenticate($username, $password) {
    $username = sanitize_user($username);
    $password = trim($password);

    $user = apply_filters('authenticate', null, $username, $password);

    if ( $user == null ) {
        $user = new WP_Error('authentication_failed', __('<strong>ERROR</strong>: Invalid username or incorrect password.'));
    }

    $ignore_codes = array('empty_username', 'empty_password');

    if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) {

        // Put your code here

    }

    return $user;
}
</code>```

I've copied the above into functions.php in my theme folder but it's not working - do I have to call it in my form, if so how? And what code should I put where it says:

// Put your code here?

答:
wp_signon() function using custom login and its work fine for me :</p>

```<code>require('wp-load.php');
$err = '';
$success = '';
global $wpdb,$current_user;
    $response = array();
    $data = json_decode(file_get_contents("php://input"));

    $email    = $data->email_id;
    $password = $data->password;
    $username = $wpdb->escape($email);
    $password = $wpdb->escape($password);
    $remember = true;
    if($remember) $remember = "true";
    else $remember = "false";
    $login_data = array();
    $login_data['user_login'] = $username;
    $login_data['user_password'] = $password;
    $login_data['remember'] = $remember;

    $user_verify = wp_signon( $login_data, false );
    set_current_user($user_verify->ID);
    if (is_user_logged_in())
    {
        get_currentuserinfo();

            $response['user_id']=$user_verify->ID;
            $response['first_name']=$current_user->user_firstname ;
            $response['last_name']=$current_user->user_lastname;
            $response['email']=$current_user->user_email;
      $status="success";
      $msg="";
    } else {
      $status="failed";
      $msg="Invalid Credential.";
     }
</code>```

Body:
Hi I'm trying to get my Wordpress custom login which is in a dropdown in header.php to display errors when an incorrect email or password is entered, or even if both or 1 is left blank.

Here is the login form I'm using

<?php
if ( ! is_user_logged_in() ) { // Display WordPress login form:
    $args = array(
      'redirect' => admin_url(),
      'form_id' => 'loginform-custom',
      'label_username' => __( 'Username custom text' ),
      'label_password' => __( 'Password custom text' ),
      'label_remember' => __( 'Remember Me custom text' ),
      'label_log_in' => __( 'Log In custom text' ),
      'remember' => true
    );
    wp_login_form( $args );
} else { // If logged in:
    wp_loginout( home_url() ); // Display "Log Out" link.
    echo " | ";
    wp_register('', ''); // Display "Site Admin" link.
}
?>

and I have found this code from here:
https://wordpress.stackexchange.com/questions/61267/prevent-wp-login-form-from-redirecting-to-wp-admin-when-there-are-errors

function wp_authenticate($username, $password) {
    $username = sanitize_user($username);
    $password = trim($password);

    $user = apply_filters('authenticate', null, $username, $password);

    if ( $user == null ) {
        $user = new WP_Error('authentication_failed', __('ERROR: Invalid username or incorrect password.'));
    }

    $ignore_codes = array('empty_username', 'empty_password');

    if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) {

        // Put your code here

    }

    return $user;
}

I've copied the above into functions.php in my theme folder but it's not working - do I have to call it in my form, if so how? And what code should I put where it says:

// Put your code here?

Body:
wp_signon() function using custom login and its work fine for me :

require('wp-load.php');
$err = '';
$success = '';
global $wpdb,$current_user;
    $response = array();
    $data = json_decode(file_get_contents("php://input"));

    $email    = $data->email_id;
    $password = $data->password;
    $username = $wpdb->escape($email);
    $password = $wpdb->escape($password);
    $remember = true;
    if($remember) $remember = "true";
    else $remember = "false";
    $login_data = array();
    $login_data['user_login'] = $username;
    $login_data['user_password'] = $password;
    $login_data['remember'] = $remember;

    $user_verify = wp_signon( $login_data, false );
    set_current_user($user_verify->ID);
    if (is_user_logged_in())
    {
        get_currentuserinfo();

            $response['user_id']=$user_verify->ID;
            $response['first_name']=$current_user->user_firstname ;
            $response['last_name']=$current_user->user_lastname;
            $response['email']=$current_user->user_email;
      $status="success";
      $msg="";
    } else {
      $status="failed";
      $msg="Invalid Credential.";
     }


问:
Why does the C# compiler create a new Action instance for every passed delegate?
Consider the following code:

```<code>public static void M() {
    A(V);
    A(V);
    A(V);
}

public static void V() {

}

public static void A(Action x) {
    x();
}
</code>```

This gets compiled behind-the-scenes as:

```<code>public static void M() {
    A(new Action(V));
    A(new Action(V));
    A(new Action(V));
}
</code>```

However, we can write our own simple performance improvement that reduces unnecessary garbage:

```<code>private static readonly Action v = new Action(V);
A(v);
A(v);
A(v);
</code>```

For this very simple case, is there any reason Roslyn couldn't make a similar optimisation?

If the answer is no, what about when the methods are not static but instance members? And what about when there are closed-over variables captured?

答:
we can write our own simple performance improvement that reduces unnecessary garbage

You have rediscovered a special case of common subexpression elimination -- the optimization of identifying when two or more expressions have exactly the same value, computing the value once, and storing it in a variable to be re-used.

Before continuing, I caution you that all so-called "optimizations" are actually trading off one thing for another. Your proposed optimization trades a small amount of collection pressure generated on each call for instead a small memory leak. The cached value in the static field would become a permanent member of the gen 2 heap. Is that worthwhile?  It's a question that you'd want to answer by actually making measurements.

For this very simple case, is there any reason Roslyn couldn't make a similar optimisation?

There is no in principle reason why this optimization could not be performed if the optimization did not produce an unacceptable change in the behaviour of the program.

In particular, the optimization causes two delegates that were previously value-equal but not reference-equal to become reference-equal. That's likely acceptable.

In practice, implementing optimizations requires large amounts of effort in designing, implementing, testing and maintaining the code that does the optimization.  C# does not implement common subexpression elimination optimizations. This optimization has poor bang-for-buck. Few people write code that would benefit from the optimization, and the optimization is small, and it is easy, as you discovered, to do the optimization "by hand" if you care.

I note that C# does do a similar cache on lambdas. It will not do common subexpression elimination, but it will generate certain lambdas only once and cache the results:

```<code>void M() { Action x = () => {}; ... }
</code>```

is generated as though you wrote:

```<code>static Action anon = null;
void M()
{
  if (anon == null) anon = () => {};
  Action x = anon;
  ...
</code>```

If the answer is no, what about when the methods are not static but instance members?

There is no in principle reason why this optimization could not be performed if the optimization did not produce an unacceptable change in the behaviour of the program.

I note that in this case the optimization would be required to deduce when the instances were the same of course. To not do so would be to fail to maintain the invariant that program behaviour must not change.

Again, in practice, C# does not do common subexpression elimination.

And what about when there are closed-over variables captured?

Captured by what? You were talking about method group conversions to delegates just now, and apparently now we are talking about lambdas converted to delegates.

The C# specification explicitly states that the compiler may choose to do common subexpression elimination on identical lambdas, or not, as it sees fit.

There is no in principle reason why this optimization could not be performed if the optimization did not produce an unacceptable change in the behaviour of the program. Since the specification explicitly calls out that this optimization is permitted, it is by definition acceptable.

Again, in practice, C# does not do common subexpression elimination.

Perhaps you are noticing a trend here. The answer to the question "is such and such an optimization permitted?" is almost always "yes, if it does not produce an unacceptable change in the behaviour of the program".  But the answer to the question "does C# implement such and such an optimization in practice?" is usually no.

If you want some background on the optimizations the compiler does perform, I described them in 2009.

Roslyn does a better job of these optimizations for the most part. For example, Roslyn does a better job of reifying temporary values and locals as ephemeral rather than durable variables. I completely rewrote the nullable arithmetic optimizer; my eight-part series of articles describing how is here.    And there were many more improvements. We never considered doing CSE though.

Body:
Consider the following code:

public static void M() {
    A(V);
    A(V);
    A(V);
}

public static void V() {

}

public static void A(Action x) {
    x();
}

This gets compiled behind-the-scenes as:

public static void M() {
    A(new Action(V));
    A(new Action(V));
    A(new Action(V));
}

However, we can write our own simple performance improvement that reduces unnecessary garbage:

private static readonly Action v = new Action(V);
A(v);
A(v);
A(v);

For this very simple case, is there any reason Roslyn couldn't make a similar optimisation?

If the answer is no, what about when the methods are not static but instance members? And what about when there are closed-over variables captured?

Body:
we can write our own simple performance improvement that reduces unnecessary garbage

You have rediscovered a special case of common subexpression elimination -- the optimization of identifying when two or more expressions have exactly the same value, computing the value once, and storing it in a variable to be re-used.

Before continuing, I caution you that all so-called "optimizations" are actually trading off one thing for another. Your proposed optimization trades a small amount of collection pressure generated on each call for instead a small memory leak. The cached value in the static field would become a permanent member of the gen 2 heap. Is that worthwhile?  It's a question that you'd want to answer by actually making measurements.

For this very simple case, is there any reason Roslyn couldn't make a similar optimisation?

There is no in principle reason why this optimization could not be performed if the optimization did not produce an unacceptable change in the behaviour of the program.

In particular, the optimization causes two delegates that were previously value-equal but not reference-equal to become reference-equal. That's likely acceptable.

In practice, implementing optimizations requires large amounts of effort in designing, implementing, testing and maintaining the code that does the optimization.  C# does not implement common subexpression elimination optimizations. This optimization has poor bang-for-buck. Few people write code that would benefit from the optimization, and the optimization is small, and it is easy, as you discovered, to do the optimization "by hand" if you care.

I note that C# does do a similar cache on lambdas. It will not do common subexpression elimination, but it will generate certain lambdas only once and cache the results:

void M() { Action x = () => {}; ... }

is generated as though you wrote:

static Action anon = null;
void M()
{
  if (anon == null) anon = () => {};
  Action x = anon;
  ...

If the answer is no, what about when the methods are not static but instance members?

There is no in principle reason why this optimization could not be performed if the optimization did not produce an unacceptable change in the behaviour of the program.

I note that in this case the optimization would be required to deduce when the instances were the same of course. To not do so would be to fail to maintain the invariant that program behaviour must not change.

Again, in practice, C# does not do common subexpression elimination.

And what about when there are closed-over variables captured?

Captured by what? You were talking about method group conversions to delegates just now, and apparently now we are talking about lambdas converted to delegates.

The C# specification explicitly states that the compiler may choose to do common subexpression elimination on identical lambdas, or not, as it sees fit.

There is no in principle reason why this optimization could not be performed if the optimization did not produce an unacceptable change in the behaviour of the program. Since the specification explicitly calls out that this optimization is permitted, it is by definition acceptable.

Again, in practice, C# does not do common subexpression elimination.

Perhaps you are noticing a trend here. The answer to the question "is such and such an optimization permitted?" is almost always "yes, if it does not produce an unacceptable change in the behaviour of the program".  But the answer to the question "does C# implement such and such an optimization in practice?" is usually no.

If you want some background on the optimizations the compiler does perform, I described them in 2009.

Roslyn does a better job of these optimizations for the most part. For example, Roslyn does a better job of reifying temporary values and locals as ephemeral rather than durable variables. I completely rewrote the nullable arithmetic optimizer; my eight-part series of articles describing how is here.    And there were many more improvements. We never considered doing CSE though.


问:
CSS/HTML: What is producing this sub-menu arrow?
Can you see what is causing this up arrow @ this page.

I have right-clicked on it > inspect element, and I am shown:

```<code>.genesis-nav-menu .sub-menu .sub-menu
</code>```

but I see no CSS rules to generate the up arrow there.

答:
It's a pseudo-element :after declared with the following rule:

.genesis-nav-menu li:last-of-type .sub-menu li:first-child a:after

Body:
Can you see what is causing this up arrow @ this page.

I have right-clicked on it > inspect element, and I am shown:

.genesis-nav-menu .sub-menu .sub-menu

but I see no CSS rules to generate the up arrow there.


问:
Using Data in Rich Push notification on iOS with FCM
My question might be bad, but I can't find any answer anywhere, I'm lost...

So I want to display a rich notification with a nice image in iOS 10+.

For this I'm using FCM and an UNNotificationServiceExtension which, if I understood correctly, should get the Data payload, find the image URL and load it before modifying the UNNotificationContent.

The issue I have is that I can't get a hold of this "data".

What I'm sending to FCM is the following :

```<code>{
"to": "device_token",
"content_available": true,
"mutable_content": true,
"badge" : 9,
"notification": {
    "title": "You still need the iPhone ?",
    "body": "Give it back if you finished you tests !"
},
"data": {
    "message": "test !",
    "mediaUrl": "http://usr.audioasylum.com/images/2/20352/Cat_and_rose.jpg"
},
"priority": "high"
}
</code>```

What I get in the phone is :

```<code>{
aps =     {
    alert =         {
        body = "Give it back if you finished you tests !";
        title = "You still need the iPhone ?";
    };
    "content-available" = 1;
    "mutable-content" = 1;
};
"gcm.message_id" = "0:1489054783357873%1ee659bb1ee659bb";
mediaUrl = "http://usr.audioasylum.com/images/2/20352/Cat_and_rose.jpg";
message = "Offer!";
}
</code>```

As I understand it, the mediaURL and message should end up in "aps" and not outside, which is why I can't find them in the extension.

And inside the extension I get : (I split it on coma for more readability)

```<code><UNNotificationRequest: 0x117d3c170;
identifier: FDC13B60-FE5A-40C6-896D-06D422043CCE
content: <UNNotificationContent: 0x117d3a650; title: You still need the iPhone ?
subtitle: (null)
body: Give it back if you finished you tests !
categoryIdentifier:
launchImageName:
peopleIdentifiers: ()
threadIdentifier:
attachments: ()
badge: (null)
sound: (null)
hasDefaultAction: YES
shouldAddToNotificationsList: YES
shouldAlwaysAlertWhileAppIsForeground: NO
shouldLockDevice: NO
shouldPauseMedia: NO
isSnoozeable: NO
fromSnooze: NO
darwinNotificationName: (null)
darwinSnoozedNotificationName: (null)
trigger: <UNPushNotificationTrigger: 0x117d3fe90; contentAvailable: YES
 mutableContent: YES>>
</code>```

Is the problem how I send information with FCM, or the way I retrieve them? Maybe it's the way I treat them ?

As always, thanks for the help!

Edit : Added code for the receiver (which is just a print in the extension)

```<code>@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService

- (void) didReceiveNotificationRequest: (UNNotificationRequest *) request
                    withContentHandler: (void (^)(UNNotificationContent *_Nonnull))contentHandler
{
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];

    NSLog(@"------------------- %@ -------------------", request);

    // Modify the notification content here...
    self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [modified]", self.bestAttemptContent.title];
    self.bestAttemptContent.body = [NSString stringWithFormat:@"%@", request.content];
    self.contentHandler(self.bestAttemptContent);
}
</code>```

答:
I'm seeing two main questions here:

The issue I have is that I can't get a hold of this "data".

You mentioned that you're expecting that the mediaUrl parameter should be inside aps.

Seeing as you included the mediaUrl in your data payload, the behavior is just as expected (mediaUrl is outside aps). To get the details, you'll have to implement what was stated in the documentation:

Receive data messages on iOS 10

To receive data messages when your app is in the foreground, on iOS 10 devices, you'll need to handle applicationReceivedRemoteMessage:. Your app can still receive data messages when it is in the background without this callback, but for foreground cases you'll need logic like the following in your app delegate:

```<code>#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// Receive data message on iOS 10 devices while app is in the foreground.
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
  // Print full message
  NSLog(@"%@", remoteMessage.appData);
}
#endif
</code>```

 P.S.: I'm not entirely sure if you already tried this out, but there wasn't any similar code in your post so I figured this should be tried.

As I understand it, the mediaURL and message should end up in "aps" and not outside, which is why I can't find them in the extension.

The thing is, there are only specific parameters that are to be expected inside aps:

Any other keys in the aps dictionary are ignored by Apple.

At the same time, there are only some corresponding parameters that you can use in FCM that will appear in the aps payload. With that, you should simply expect that any custom key-value pair you include will be outside the aps parameter. From the Apple docs above (emphasis mine):

In addition to the aps dictionary, the JSON dictionary can include custom keys and values with your app-specific content.

With regards to the blog you linked in the comments, I haven't looked to deeply into it since it's not really using FCM, where it would be best to presume that the behavior is different.

Body:
My question might be bad, but I can't find any answer anywhere, I'm lost...

So I want to display a rich notification with a nice image in iOS 10+.

For this I'm using FCM and an UNNotificationServiceExtension which, if I understood correctly, should get the Data payload, find the image URL and load it before modifying the UNNotificationContent.

The issue I have is that I can't get a hold of this "data".

What I'm sending to FCM is the following :

{
"to": "device_token",
"content_available": true,
"mutable_content": true,
"badge" : 9,
"notification": {
    "title": "You still need the iPhone ?",
    "body": "Give it back if you finished you tests !"
},
"data": {
    "message": "test !",
    "mediaUrl": "http://usr.audioasylum.com/images/2/20352/Cat_and_rose.jpg"
},
"priority": "high"
}

What I get in the phone is :

{
aps =     {
    alert =         {
        body = "Give it back if you finished you tests !";
        title = "You still need the iPhone ?";
    };
    "content-available" = 1;
    "mutable-content" = 1;
};
"gcm.message_id" = "0:1489054783357873%1ee659bb1ee659bb";
mediaUrl = "http://usr.audioasylum.com/images/2/20352/Cat_and_rose.jpg";
message = "Offer!";
}

As I understand it, the mediaURL and message should end up in "aps" and not outside, which is why I can't find them in the extension.

And inside the extension I get : (I split it on coma for more readability)

<UNNotificationRequest: 0x117d3c170;
identifier: FDC13B60-FE5A-40C6-896D-06D422043CCE
content: <UNNotificationContent: 0x117d3a650; title: You still need the iPhone ?
subtitle: (null)
body: Give it back if you finished you tests !
categoryIdentifier:
launchImageName:
peopleIdentifiers: ()
threadIdentifier:
attachments: ()
badge: (null)
sound: (null)
hasDefaultAction: YES
shouldAddToNotificationsList: YES
shouldAlwaysAlertWhileAppIsForeground: NO
shouldLockDevice: NO
shouldPauseMedia: NO
isSnoozeable: NO
fromSnooze: NO
darwinNotificationName: (null)
darwinSnoozedNotificationName: (null)
trigger: <UNPushNotificationTrigger: 0x117d3fe90; contentAvailable: YES
 mutableContent: YES>>

Is the problem how I send information with FCM, or the way I retrieve them? Maybe it's the way I treat them ?

As always, thanks for the help!

Edit : Added code for the receiver (which is just a print in the extension)

@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService

- (void) didReceiveNotificationRequest: (UNNotificationRequest *) request
                    withContentHandler: (void (^)(UNNotificationContent *_Nonnull))contentHandler
{
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];

    NSLog(@"------------------- %@ -------------------", request);

    // Modify the notification content here...
    self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [modified]", self.bestAttemptContent.title];
    self.bestAttemptContent.body = [NSString stringWithFormat:@"%@", request.content];
    self.contentHandler(self.bestAttemptContent);
}

Body:
I'm seeing two main questions here:

The issue I have is that I can't get a hold of this "data".

You mentioned that you're expecting that the mediaUrl parameter should be inside aps.

Seeing as you included the mediaUrl in your data payload, the behavior is just as expected (mediaUrl is outside aps). To get the details, you'll have to implement what was stated in the documentation:

Receive data messages on iOS 10

To receive data messages when your app is in the foreground, on iOS 10 devices, you'll need to handle applicationReceivedRemoteMessage:. Your app can still receive data messages when it is in the background without this callback, but for foreground cases you'll need logic like the following in your app delegate:

#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// Receive data message on iOS 10 devices while app is in the foreground.
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
  // Print full message
  NSLog(@"%@", remoteMessage.appData);
}
#endif

 P.S.: I'm not entirely sure if you already tried this out, but there wasn't any similar code in your post so I figured this should be tried.

As I understand it, the mediaURL and message should end up in "aps" and not outside, which is why I can't find them in the extension.

The thing is, there are only specific parameters that are to be expected inside aps:

Any other keys in the aps dictionary are ignored by Apple.

At the same time, there are only some corresponding parameters that you can use in FCM that will appear in the aps payload. With that, you should simply expect that any custom key-value pair you include will be outside the aps parameter. From the Apple docs above (emphasis mine):

In addition to the aps dictionary, the JSON dictionary can include custom keys and values with your app-specific content.

With regards to the blog you linked in the comments, I haven't looked to deeply into it since it's not really using FCM, where it would be best to presume that the behavior is different.


问:
Check if a webcam is available/unavailable using EMGU.CV
I am working with multiple webcams in VB.NET using EMGU.CV, specifically for Recording Video Realtime.

The problem is, when a camera is unplugged or suddenly malfunctioned, I need the PictureBox containing the image capture to display only nothing.

I am working with this code:

```<code>    Try
                '===================== CAM 1
                imagez0 = Capturez0.RetrieveBgrFrame
                PictureBox1.BackgroundImage = imagez0.ToBitmap()
                Videoz.WriteFrame(imagez0)
                drawbitmap1 = New Bitmap(PictureBox1.Width, PictureBox1.Height)
                graph = Graphics.FromImage(drawbitmap1)
                graph.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
                graph.DrawString(x + " | CAM 1 | Faculty", Label1.Font, brush, PictureBox1.Location)
                PictureBox1.Image = drawbitmap1
            Catch ex As Exception
                Capturez0.Stop()
                imagez0 = Nothing
                Videoz.WriteFrame(imagez0)
                PictureBox1.Image = Nothing
                PictureBox1.BackgroundImage = Nothing
                Videoz = Nothing
End Try
</code>```

But when I try to unplug the webcam, it only hangs on the last image it captures and then does nothing, just hangs on that image. I think the code did not fall to the Catch exception that is why the image is still available.

Then when I try to put the camera back, it won't resume recording. Its just there stuck.

答:
If you want to detect accidental USB unplug then you can have a Timer control which will check for input device list as described in following link

You can also refer to this link. It describes all the functions you need to work with a Web Cam.

Other useful Links

Emgu CV Camera Capture Documentation

Body:
I am working with multiple webcams in VB.NET using EMGU.CV, specifically for Recording Video Realtime.

The problem is, when a camera is unplugged or suddenly malfunctioned, I need the PictureBox containing the image capture to display only nothing.

I am working with this code:

    Try
                '===================== CAM 1
                imagez0 = Capturez0.RetrieveBgrFrame
                PictureBox1.BackgroundImage = imagez0.ToBitmap()
                Videoz.WriteFrame(imagez0)
                drawbitmap1 = New Bitmap(PictureBox1.Width, PictureBox1.Height)
                graph = Graphics.FromImage(drawbitmap1)
                graph.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
                graph.DrawString(x + " | CAM 1 | Faculty", Label1.Font, brush, PictureBox1.Location)
                PictureBox1.Image = drawbitmap1
            Catch ex As Exception
                Capturez0.Stop()
                imagez0 = Nothing
                Videoz.WriteFrame(imagez0)
                PictureBox1.Image = Nothing
                PictureBox1.BackgroundImage = Nothing
                Videoz = Nothing
End Try

But when I try to unplug the webcam, it only hangs on the last image it captures and then does nothing, just hangs on that image. I think the code did not fall to the Catch exception that is why the image is still available.

Then when I try to put the camera back, it won't resume recording. Its just there stuck.


问:
Paypal as payment gateway?
i have to choose between several payment gateways. I heard that PayPal is quite a mess and there were several fraud-issues? Does some of you have experiences with PayPal?

Thanks in advance

答: I've used paypal for long time and had problems. Remember that Buyer is almost always right if you chose to work with them. Also you may get your account locked if you have unexpected amount of trx in a day. But yet, that is what most of the users use nowadays. I can only suggest you to call them and talk with them about what you are developing and what kind of sales volume are you expecting. You can reduce the risk to the minimum this way. Good luck</p>

Title: Paypal as payment gateway?


问:
Calling your own Action method that returns IHttpActionResult
It seems maybe my question was unclear.  Here is what I am looking to do.

I am writing a web api that makes calls into another web api.  Inside of my API I would like to call to the UpdateAssignmentStatus method from the MarkAllTasksDone method.  I don't know what to do with the return type of IHttpActionResult, meaning how to process it.  How do I get the information that is being returned in the method.  In the UpdateAssignmentStatus method it returns a BadRequest with a message, a InternalServerError with a message, or an Ok with a message.  How do I get to that data?  Sorry, I should have provided that info before.

Just to add more here.  When I debug I can see that the actionResultUAS object is one of my return types that I stated in my UpdateAssignmentStatus method.  BadRequest returns System.Web.Http.Results.BadRequestErrorMessageResult, an Ok returns System.Web.Http.Results.OkNegotiatedContentResult, and InternalServerError returns System.Web.Http.Results.ExceptionResult.  I would assume that I will need to cast to each of these types.  Is there a good way to do that, maybe a generic way.

```<code>    [HttpGet]
    public IHttpActionResult MarkAllTasksDone(string projectID)
    {
        try
        {
            var assignments = GetAssignments("ASSGN/search?projectID=" + projectID + "&fields=taskID&fields=status" + "&apiKey=" + ApiKey);

            foreach (var assignment in assignments.Where(a => a.AssignmentStatus != "DN"))
            {
                var actionResultUAS = UpdateAssignmentStatus(assignment.AssignmentID, "DONE");
                //****how to get the ok or failure code and the returned data from the actionResultUAS object

                var responseMessageUT = UpdateTaskPercentComplete(assignment.TaskID, 100);
                }
            }
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }

        return Ok();

    }

[HttpGet]
public IHttpActionResult UpdateAssignmentStatus(string assignmentID, string assignmentStatus)
{
    HttpResponseMessage httpResponse = new HttpResponseMessage();
    try
    {
        var convertedStatus = ConvertAssignmentStatus(assignmentStatus);
        httpResponse = Put("ASSGN?ID=" + assignmentID + "&status=" + convertedStatus + "&apiKey=" + ApiKey);
    }
    catch (ApplicationException ae)
    {
        return BadRequest(ae.Message);

    }
    catch (Exception ex)
    {
        return InternalServerError(ex);
    }
    HttpResponseData httpResponseData = new HttpResponseData();
    httpResponseData.IsSuccessful = httpResponse.IsSuccessStatusCode;
    httpResponseData.Content = httpResponse.Content.ReadAsStringAsync().Result;
    httpResponseData.StatusCode = httpResponse.StatusCode.ToString();

    return Ok(httpResponseData);
}
</code>```

答:
You need to return status code and info like this in your Api method,

```<code>return Content(HttpStatusCode.BadRequest, myData);
</code>```

OR

```<code>return Content(HttpStatusCode.OK, myData);
</code>```

Then,

```<code>try
{
    var convertedStatus = ConvertAssignmentStatus(assignmentStatus);
    //httpResponse = Put("ASSGN?ID=" + assignmentID + "&status=" + //convertedStatus + "&apiKey=" + ApiKey);

    var http = new HttpClient { BaseAddress =
                                new Uri("http://localhost:11111/") };
    //I'm passing the value as query string. See the bellow line
    string apiUrl = "api/ControllerName/ASSGN?ID=" + assignmentID +
                    "&status=" + convertedStatus + "&apiKey=" + ApiKey";

    var _response = http.PutAsJsonAsync(http.BaseAddress + apiUrl, "").Result;

    var returnStatus = _response.StatusCode;
}
</code>```

Body:
It seems maybe my question was unclear.  Here is what I am looking to do.

I am writing a web api that makes calls into another web api.  Inside of my API I would like to call to the UpdateAssignmentStatus method from the MarkAllTasksDone method.  I don't know what to do with the return type of IHttpActionResult, meaning how to process it.  How do I get the information that is being returned in the method.  In the UpdateAssignmentStatus method it returns a BadRequest with a message, a InternalServerError with a message, or an Ok with a message.  How do I get to that data?  Sorry, I should have provided that info before.

Just to add more here.  When I debug I can see that the actionResultUAS object is one of my return types that I stated in my UpdateAssignmentStatus method.  BadRequest returns System.Web.Http.Results.BadRequestErrorMessageResult, an Ok returns System.Web.Http.Results.OkNegotiatedContentResult, and InternalServerError returns System.Web.Http.Results.ExceptionResult.  I would assume that I will need to cast to each of these types.  Is there a good way to do that, maybe a generic way.

    [HttpGet]
    public IHttpActionResult MarkAllTasksDone(string projectID)
    {
        try
        {
            var assignments = GetAssignments("ASSGN/search?projectID=" + projectID + "&fields=taskID&fields=status" + "&apiKey=" + ApiKey);

            foreach (var assignment in assignments.Where(a => a.AssignmentStatus != "DN"))
            {
                var actionResultUAS = UpdateAssignmentStatus(assignment.AssignmentID, "DONE");
                //****how to get the ok or failure code and the returned data from the actionResultUAS object

                var responseMessageUT = UpdateTaskPercentComplete(assignment.TaskID, 100);
                }
            }
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }

        return Ok();

    }

[HttpGet]
public IHttpActionResult UpdateAssignmentStatus(string assignmentID, string assignmentStatus)
{
    HttpResponseMessage httpResponse = new HttpResponseMessage();
    try
    {
        var convertedStatus = ConvertAssignmentStatus(assignmentStatus);
        httpResponse = Put("ASSGN?ID=" + assignmentID + "&status=" + convertedStatus + "&apiKey=" + ApiKey);
    }
    catch (ApplicationException ae)
    {
        return BadRequest(ae.Message);

    }
    catch (Exception ex)
    {
        return InternalServerError(ex);
    }
    HttpResponseData httpResponseData = new HttpResponseData();
    httpResponseData.IsSuccessful = httpResponse.IsSuccessStatusCode;
    httpResponseData.Content = httpResponse.Content.ReadAsStringAsync().Result;
    httpResponseData.StatusCode = httpResponse.StatusCode.ToString();

    return Ok(httpResponseData);
}

Body:
You need to return status code and info like this in your Api method,

return Content(HttpStatusCode.BadRequest, myData);

OR

return Content(HttpStatusCode.OK, myData);

Then,

try
{
    var convertedStatus = ConvertAssignmentStatus(assignmentStatus);
    //httpResponse = Put("ASSGN?ID=" + assignmentID + "&status=" + //convertedStatus + "&apiKey=" + ApiKey);

    var http = new HttpClient { BaseAddress =
                                new Uri("http://localhost:11111/") };
    //I'm passing the value as query string. See the bellow line
    string apiUrl = "api/ControllerName/ASSGN?ID=" + assignmentID +
                    "&status=" + convertedStatus + "&apiKey=" + ApiKey";

    var _response = http.PutAsJsonAsync(http.BaseAddress + apiUrl, "").Result;

    var returnStatus = _response.StatusCode;
}


问:
How can I disable the IIS Express launch profile for ASP.NET Core?
I'm writing an ASP.NET Core app (on the full .NET Framework) that uses WebListener, rather than Kestrel.¹ I'm using Visual Studio 2015 with Update 3, and ".NET Core 1.0.1 tools Preview 2" (the latest VS tooling on the download site as of this writing).

Because I'm using WebListener, and because WebListener is not compatible with IIS Express, I would like to disable the "IIS Express" launch profile in Visual Studio, so that when my teammates open this solution, their Visual Studios will default to running the console app instead of IIS Express, and they'll be able to just hit Run and not get errors.

But so far, I haven't been able to rid VS of the "IIS Express" launch profile. The Project Properties > Debug tab lets me edit the list of profiles, but when I select the "IIS Express" profile, the "Delete" button is disabled. If I edit launchSettings.json directly, and delete the "IIS Express" element from under "profiles", the File > Save operation silently inserts the "IIS Express" profile back into the JSON that it saves to disk!

Apparently Microsoft really wants to always have an "IIS Express" launch profile, even though it isn't necessarily compatible with all ASP.NET Core projects. But it's worth asking: Has anyone found a way to disable the "IIS Express" launch profile in an ASP.NET Core project, and have only the self-host option(s) in the launch-profile selector?

¹ For the curious, I'm using WebListener because it will let me self-host in a Windows service and still support NTLM authentication, on a machine without IIS installed. Kestrel only supports NTLM when it's hosted in IIS, not when it's self-hosted.

答:
UPDATE:

The issue should be fixed with the latest release (update) of Visual Studio 2017.

Initial answer:

As mentioned in comments in ssmith answer, Visual Studio keeps restoring the settings on restart.

Since I could not find a better solution, I just denied the write permissions on launchsettings.json for Visual Studio. I left the instructions in my other answer for similar question, here is just a copy&paste:

Update your launchsettings.json for the last time.

Close Visual Studio.

Open security settings (right-click on launchsettings.json in Explorer -> Properties -> Security)

Click Advanced -> Change Permissions

Select "Authenticated Users" (or other user group under which Visual Studio is running on your machine) from the "Permissions entries" list and click Edit ->

Check Deny for "Create files / write data" permission.

Click OK in all open dialogs and warnings to save changes.

Reopen Visual Studio and see it fail to do it's update.

Hope it helps.


问:
How to filter the access to path with gtk.fileselection (python)?
I working with gtk.fileselection and it works perfectly. But how can I block the access to a given path with fileselection widget.
If I do not block access to a certain path, the user can see sensitive information inside my system.

```<code>class FileSelection:
# Get the selected filename and print it to the console
def file_ok_sel(self, w):
    print "%s" % self.filew.get_filename()

def destroy(self, widget):
    gtk.main_quit()

def __init__(self):
    #Create a new file selection widget
    self.filew = gtk.FileSelection("File selection")
    self.filew.hide_fileop_buttons()
    self.filew.get_focus()

    self.filew.connect("destroy", self.destroy)
    # Connect the ok_button to file_ok_sel method
    self.filew.ok_button.connect("clicked", self.file_ok_sel)

    # Connect the cancel_button to destroy the widget
    self.filew.cancel_button.connect("clicked",lambda w: self.filew.destroy())

    # Lets set the filename, as if this were a save dialog,
    # and we are giving a default filename
    self.filew.set_filename("penguin.png")

    self.filew.show()

def main(self):
    gtk.main()
    print "selection"*10
    return 0
</code>```

In fact I would like to allow access only to the paths that hang from "mnt/tnc/" and not allow access to any more.

答:
```<code> archivosTNC = os.listdir("/mnt/tnc")
    lista = []
    for a in archivosTNC:
        if a[-2:] == ".H":
            lista.append(a)
        elif a[-4:] == ".txt":
            lista.append(a)
        elif a[-4:] == ".png":
            lista.append(a)
        elif a[-4:] == ".jpg":
            lista.append(a)

    ventana = gtk.Window()
    ventana.set_default_size(-1, 300)
    scrolledWindow = gtk.ScrolledWindow()
    scrolledWindow.set_policy (hscrollbar_policy=gtk.POLICY_NEVER, vscrollbar_policy=gtk.POLICY_AUTOMATIC)
    ventana.add(scrolledWindow)
    tabla=table()
    vbox = gtk.VBox()
    tabla.attachToCell(vbox, col=1, row=1)
    scrolledWindow.add_with_viewport(tabla)

    #ventana.add(vbox)
    for item in lista:
        boton = gtk.Button(str(item))
        boton.connect('clicked', self.devolverNombreArchivo)
        vbox.pack_start(boton)
</code>```

Body:
I working with gtk.fileselection and it works perfectly. But how can I block the access to a given path with fileselection widget.
If I do not block access to a certain path, the user can see sensitive information inside my system.

class FileSelection:
# Get the selected filename and print it to the console
def file_ok_sel(self, w):
    print "%s" % self.filew.get_filename()

def destroy(self, widget):
    gtk.main_quit()

def __init__(self):
    #Create a new file selection widget
    self.filew = gtk.FileSelection("File selection")
    self.filew.hide_fileop_buttons()
    self.filew.get_focus()

    self.filew.connect("destroy", self.destroy)
    # Connect the ok_button to file_ok_sel method
    self.filew.ok_button.connect("clicked", self.file_ok_sel)

    # Connect the cancel_button to destroy the widget
    self.filew.cancel_button.connect("clicked",lambda w: self.filew.destroy())

    # Lets set the filename, as if this were a save dialog,
    # and we are giving a default filename
    self.filew.set_filename("penguin.png")

    self.filew.show()

def main(self):
    gtk.main()
    print "selection"*10
    return 0

In fact I would like to allow access only to the paths that hang from "mnt/tnc/" and not allow access to any more.


问:
How to vertically align a TextBox based on its content
I have a text block I want to vertically align so it appears in the center of a circle. It's a single character, such as 'a', 'y', '?', 'R' or any other valid character. It could have a descender, ascender, be a capital, non alphabetical etc.

With the following code, it appears to align the text block according to the height of a capital letter. So a lower case letter appears too low, and letter with a descender even more so.

```<code>    <Grid Width="32" Background="Green"  Height="32">
        <Ellipse Width="32" Height="32" Stroke="Red" Fill="White"/>
        <TextBlock Text="{Binding Character}" Foreground="Blue" HorizontalAlignment="Center" FontWeight="Bold" VerticalAlignment="Center" FontFamily="Arial"  FontSize="28"/>
    </Grid>
</code>```

Is there a way to get to align vertically based on the text content of the TextBlock, instead of the reserved area of the text that might be in it?

If it is not possible, what other controls / methods are available in WPF to achieve this?

答:
A more complete sample that works for me -

```<code><ControlTemplate TargetType="{x:Type local:LevelControl}">
                <Viewbox x:Name="Frame">
                    <Grid Margin="2" Background="Transparent" VerticalAlignment="Center" HorizontalAlignment="Center" Width="26" Height="26">
                        <Ellipse x:Name="outerEllipse" Fill="{Binding Fill, ElementName=innerEllipse}" Stretch="UniformToFill" Grid.Row="0" Opacity="0.5" />
                        <Ellipse x:Name="innerEllipse" Fill="Gray" Stretch="UniformToFill" Margin="4" Grid.Row="0" />
                        <TextBlock x:Name="Label" FontWeight="Bold" FontSize="18" Foreground="White" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Margin="7.948,0,7.698,2.125" />
                    </Grid>
                </Viewbox>

            </ControlTemplate>
</code>```

or try a label

Body:
I have a text block I want to vertically align so it appears in the center of a circle. It's a single character, such as 'a', 'y', '?', 'R' or any other valid character. It could have a descender, ascender, be a capital, non alphabetical etc.

With the following code, it appears to align the text block according to the height of a capital letter. So a lower case letter appears too low, and letter with a descender even more so.

    <Grid Width="32" Background="Green"  Height="32">
        <Ellipse Width="32" Height="32" Stroke="Red" Fill="White"/>
        <TextBlock Text="{Binding Character}" Foreground="Blue" HorizontalAlignment="Center" FontWeight="Bold" VerticalAlignment="Center" FontFamily="Arial"  FontSize="28"/>
    </Grid>

Is there a way to get to align vertically based on the text content of the TextBlock, instead of the reserved area of the text that might be in it?

If it is not possible, what other controls / methods are available in WPF to achieve this?

Body:
A more complete sample that works for me -

<ControlTemplate TargetType="{x:Type local:LevelControl}">
                <Viewbox x:Name="Frame">
                    <Grid Margin="2" Background="Transparent" VerticalAlignment="Center" HorizontalAlignment="Center" Width="26" Height="26">
                        <Ellipse x:Name="outerEllipse" Fill="{Binding Fill, ElementName=innerEllipse}" Stretch="UniformToFill" Grid.Row="0" Opacity="0.5" />
                        <Ellipse x:Name="innerEllipse" Fill="Gray" Stretch="UniformToFill" Margin="4" Grid.Row="0" />
                        <TextBlock x:Name="Label" FontWeight="Bold" FontSize="18" Foreground="White" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Margin="7.948,0,7.698,2.125" />
                    </Grid>
                </Viewbox>

            </ControlTemplate>

or try a label <Label VerticalAlignment="Center" VerticalContentAlignment="Center" ></Label>


问:
JQuery Texteditor: keep format when I copy & paste text from somewhere else
jQuery Text Editor: Remove pasted formatting that is not allowed

I am using the jQuery Text Editor, a wysiwyg editor to create rich formatted HTML in a textarea input.

I can initiate the editor in my javascript code and allow / disallow certain formatting options. But when I copy & paste text from somewhere else (Word, E-Mail client, etc.), it keeps all the formatting, even if I disallowed this particular formatting option in the editor.

Is there any smart way to strip all HTML formatting that I disallowed? Or even better can I tell the editor to strip disallowed formatting automatically that is pasted?

答:
Try this.</p>
```<code>$(document).on("paste", ".jqte_editor", function(e) {

    e.preventDefault();
    var text = e.originalEvent.clipboardData.getData("text/plain");

    //Do required strip of HTML elements

    document.execCommand("insertText", false, text);
});
</code>```

Body:
Try this.

$(document).on("paste", ".jqte_editor", function(e) {

    e.preventDefault();
    var text = e.originalEvent.clipboardData.getData("text/plain");

    //Do required strip of HTML elements

    document.execCommand("insertText", false, text);
});

ContentLicense: CC BY-SA 4.0


问:
WAMP Server - local server - 1 of 2 services running
I installed WAMP server and ran the applpication. The icon in the taskbar stays orange and says "local server - 1 of 2 services running" . Also, I am able to see the phpMyAdmin page in the browser but when I try to login it gives the following error:

```<code>#2002 - No connection could be made because the target machine actively refused it. <br />The server is not responding (or the local server's socket is not correctly configured).
</code>```

I have tested port 80 and I got this response:

```<code>    ***** Test which uses port 80 *****

===== Tested by command netstat filtered on port 80 =====

Test for TCP
Your port 80 is used by a processus with PID = 6612
The processus of PID 6612 is 'httpd.exe' Session: Services
The service of PID 6612 for 'httpd.exe' is 'wampapache64'
This service is from Wampserver - It is correct

Test for TCPv6
Your port 80 is used by a processus with PID = 6612
The processus of PID 6612 is 'httpd.exe' Session: Services
The service of PID 6612 for 'httpd.exe' is 'wampapache64'
This service is from Wampserver - It is correct

===== Tested by attempting to open a socket on port 80 =====

Your port 80 is actually used by :

Server: Apache/2.4.18 (Win64) PHP/5.6.19
</code>```

I believe that the above result means that there is no problem with the port. I even tried changing the port and still gives the same status - orange icon.

Note - When a prompt from Windows Firewall was shown after installing WAMP, I didn't give access to both private and public networks, i.e. I unchecked both the options.

Kindly help me to run both the services in the local server.

Thank you!

答:
Click on the WAMP icon in the tray and go to Apache > service Administration and check if the service is installed or if it isn't running . You can even reinstall it by removing and installing it again. Do the same with MySQL  . Go to MySQL > Service Administration and do the same things . In my case Apache service wasn't installed and Installing it did the trick. check the image below.

See this image

Body:
I installed WAMP server and ran the applpication. The icon in the taskbar stays orange and says "local server - 1 of 2 services running" . Also, I am able to see the phpMyAdmin page in the browser but when I try to login it gives the following error:

#2002 - No connection could be made because the target machine actively refused it.
The server is not responding (or the local server's socket is not correctly configured).

I have tested port 80 and I got this response:

    ***** Test which uses port 80 *****

===== Tested by command netstat filtered on port 80 =====

Test for TCP
Your port 80 is used by a processus with PID = 6612
The processus of PID 6612 is 'httpd.exe' Session: Services
The service of PID 6612 for 'httpd.exe' is 'wampapache64'
This service is from Wampserver - It is correct

Test for TCPv6
Your port 80 is used by a processus with PID = 6612
The processus of PID 6612 is 'httpd.exe' Session: Services
The service of PID 6612 for 'httpd.exe' is 'wampapache64'
This service is from Wampserver - It is correct

===== Tested by attempting to open a socket on port 80 =====

Your port 80 is actually used by :

Server: Apache/2.4.18 (Win64) PHP/5.6.19

I believe that the above result means that there is no problem with the port. I even tried changing the port and still gives the same status - orange icon.

Note - When a prompt from Windows Firewall was shown after installing WAMP, I didn't give access to both private and public networks, i.e. I unchecked both the options.

Kindly help me to run both the services in the local server.

Thank you!


问:
Inno Setup - Prevent installation and execute program when installer is executed without administrator privileges
I want my installer to check admin rights at the beginning, and if not to execute a program that popups a form and exit the installation

procedure MyAfterInstall();
var
  MyProgChecked: boolean;
  ErrorCode : Integer;
begin
  MyProgChecked := not IsAdminLoggedOn;
  if MyProgChecked =true then
    ShellExec('', ExpandConstant('\users\public\EzPasteFiles\RAADMIN.EXE'), '',
              '', SW_SHOW, ewNoWait,ErrorCode ) ;
  ExitProcess(0);
end;
```

<p>My question is, where to put and how to make <strong>RAADMIN.EXE</strong> available to the procedure? </p>

<p>I have tried without success</p>

```Source: "c:\Dropbox\word\EzPasteOffice64Win10\RunAsAnAdminTutorial\RAADMIN.exe"; \
  DestDir: "\users\public\EzPasteFiles"; AfterInstall: MyAfterInstall
```

答:
To check for administrator privileges and conditionally abort the installation, use  InitializeSetup event function.

To extract some file before installation, use ExtractTemporaryFile support function

Of course, this all makes sense, only if you set PrivilegesRequired=lowest. Otherwise your installer will never run without administrator privileges in the first place.

[Setup]
PrivilegesRequired=lowest

[Files]
Source: "C:\source\path\RAADMIN.exe"; Flags: dontcopy

[Code]

function InitializeSetup(): Boolean;
var
  ErrorCode: Integer;
  Path: string;
begin
  Result := True;

  if not IsAdminLoggedOn then
  begin
    Log('No admin privileges, executing RAADMIN');
    ExtractTemporaryFile('RAADMIN.exe');
    Path := ExpandConstant('{tmp}\RAADMIN.exe');
    if not Exec(Path, '', '', SW_SHOW, ewNoWait, ErrorCode) then
    begin
      MsgBox('Error executing RAADMIN', mbError, MB_OK);
    end;
    Result := False; { abort installation }
  end;
end;
```

Though if it's just about displaying a form, did you consider implementing the form in Inno Setup?

Body:
I want my installer to check admin rights at the beginning, and if not to execute a program that popups a form and exit the installation

procedure MyAfterInstall();
var
  MyProgChecked: boolean;
  ErrorCode : Integer;
begin
  MyProgChecked := not IsAdminLoggedOn;
  if MyProgChecked =true then
    ShellExec('', ExpandConstant('\users\public\EzPasteFiles\RAADMIN.EXE'), '',
              '', SW_SHOW, ewNoWait,ErrorCode ) ;
  ExitProcess(0);
end;

My question is, where to put and how to make RAADMIN.EXE available to the procedure?

I have tried without success

Source: "c:\Dropbox\word\EzPasteOffice64Win10\RunAsAnAdminTutorial\RAADMIN.exe"; \
  DestDir: "\users\public\EzPasteFiles"; AfterInstall: MyAfterInstall

Body:
To check for administrator privileges and conditionally abort the installation, use  InitializeSetup event function.

To extract some file before installation, use ExtractTemporaryFile support function

Of course, this all makes sense, only if you set PrivilegesRequired=lowest. Otherwise your installer will never run without administrator privileges in the first place.

[Setup]
PrivilegesRequired=lowest

[Files]
Source: "C:\source\path\RAADMIN.exe"; Flags: dontcopy

[Code]

function InitializeSetup(): Boolean;
var
  ErrorCode: Integer;
  Path: string;
begin
  Result := True;

  if not IsAdminLoggedOn then
  begin
    Log('No admin privileges, executing RAADMIN');
    ExtractTemporaryFile('RAADMIN.exe');
    Path := ExpandConstant('{tmp}\RAADMIN.exe');
    if not Exec(Path, '', '', SW_SHOW, ewNoWait, ErrorCode) then
    begin
      MsgBox('Error executing RAADMIN', mbError, MB_OK);
    end;
    Result := False; { abort installation }
  end;
end;

Though if it's just about displaying a form, did you consider implementing the form in Inno Setup?


问:
How do you apply a filter to JavaFX using CSS?
I've been fiddling with JavaFX and the stylesheets incorporation and was trying to figure out a way to manipulate the images a bit. I know there's filter in CSS, but what about JavaFX -fx?

I have the following:

```<code>.root {
    -fx-background-image: url("background.jpg");
    -fx-background-size: cover;
    // -fx-filter: contrast(200%)
}
</code>```

Which is imported with:

```<code>scene.getStylesheets().add(Class.class.getResource("style.css").toExternalForm());
</code>```

Is there a way to do this, or is there a better alternative to Java GUI with more control? Normal filter: contrast(200%) does not work with JavaFX it seems.

答:
Actually, I found a way to do this without CSS. JavaFX actually has effects built in that you can use. For example, for lighting, you can use

```<code>import javafx.scene.effect.Light;
import javafx.scene.effect.Lighting;

import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
</code>```

And then:

```<code>    Light.Distant light = new Light.Distant();

    Lighting lighting = new Lighting(light);
    lighting.setSurfaceScale(5.0);
</code>```

Set up azimuth:

```<code>DoubleProperty azimuth = new SimpleDoubleProperty(0);
azimuth.bind(value);
</code>```

From there, you can apply it on any object:

```<code>light.setAzimuth(azimuth.get());
lighting.setLight(light);
sampletext.setEffect(lighting);
</code>```

Alter the "value" the azimuth is bound to and it should change the lighting.

Referenced:
http://zetcode.com/gui/javafx/effects/

Body:
I've been fiddling with JavaFX and the stylesheets incorporation and was trying to figure out a way to manipulate the images a bit. I know there's filter in CSS, but what about JavaFX -fx?

I have the following:

.root {
    -fx-background-image: url("background.jpg");
    -fx-background-size: cover;
    // -fx-filter: contrast(200%)
}

Which is imported with:

scene.getStylesheets().add(Class.class.getResource("style.css").toExternalForm());

Is there a way to do this, or is there a better alternative to Java GUI with more control? Normal filter: contrast(200%) does not work with JavaFX it seems.

Body:
Actually, I found a way to do this without CSS. JavaFX actually has effects built in that you can use. For example, for lighting, you can use

import javafx.scene.effect.Light;
import javafx.scene.effect.Lighting;

import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;

And then:

    Light.Distant light = new Light.Distant();

    Lighting lighting = new Lighting(light);
    lighting.setSurfaceScale(5.0);

Set up azimuth:

DoubleProperty azimuth = new SimpleDoubleProperty(0);
azimuth.bind(value);

From there, you can apply it on any object:

light.setAzimuth(azimuth.get());
lighting.setLight(light);
sampletext.setEffect(lighting);

Alter the "value" the azimuth is bound to and it should change the lighting.

Referenced:
http://zetcode.com/gui/javafx/effects/


问:
Worksheet Change add Now() without Automatically updating
Hello I am very new to VBA but I was hoping someone can help. I am trying to create a timestamp using the code below. But I can't figure out how to copy it for the next row.

```<code> Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Column = 1 And Target.Row = 2 Then
    If Target.Value = "" Then
      Cells(2, 4).Value = ""
    Else
      Cells(2, 4).Value = Format(Now, "H:mm:ss AM/PM")
    End If
  End If
End Sub
</code>```

It works fine for that 1 cell. But how can I repeat this when I enter something in A3,A4..so on. This is probably a very basic question but I am a total newbie!

答:
just to throw in a one-liner:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column = 1 Then Cells(Target.Row, 4).Value = IIf(Target.Value = "", "", Format(Now, "H:mm:ss AM/PM"))
End Sub
</code>```

NOTE:

with _Change events you normally want to add code lines that set Application.EnableEvents to False before code lines that change something (cells content in this case) and to then back to True once you're done with the changes. This, not to have the event handle trigger itself in a infinite loop

In this case such an Application.EnableEvents handling isn't necessary because your are changing cells in column 4 and the _Change event handler would effectively do something only for changes in column 1

Body:
Hello I am very new to VBA but I was hoping someone can help. I am trying to create a timestamp using the code below. But I can't figure out how to copy it for the next row.

 Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Column = 1 And Target.Row = 2 Then
    If Target.Value = "" Then
      Cells(2, 4).Value = ""
    Else
      Cells(2, 4).Value = Format(Now, "H:mm:ss AM/PM")
    End If
  End If
End Sub

It works fine for that 1 cell. But how can I repeat this when I enter something in A3,A4..so on. This is probably a very basic question but I am a total newbie!

Body:
just to throw in a one-liner:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column = 1 Then Cells(Target.Row, 4).Value = IIf(Target.Value = "", "", Format(Now, "H:mm:ss AM/PM"))
End Sub

NOTE:

with _Change events you normally want to add code lines that set Application.EnableEvents to False before code lines that change something (cells content in this case) and to then back to True once you're done with the changes. This, not to have the event handle trigger itself in a infinite loop

In this case such an Application.EnableEvents handling isn't necessary because your are changing cells in column 4 and the _Change event handler would effectively do something only for changes in column 1


问:
UNIX Programming. struct timeval how to print it (C-programming)
I am trying to print a value of type timeval. Actually I am able to print it, but I get the following warning:

Multiple markers at this line

format ‘%ld’ expects type ‘long int’, but argument 2 has type ‘struct timeval’

The program compiles and it prints the values, but I would like to know if I am doing something wrong.  Thanks.

```<code>    printf("%ld.%6ld\n",usage.ru_stime);
    printf("%ld.%6ld\n",usage.ru_utime);
</code>```

where usage is of type

```<code>typedef struct{
    struct timeval ru_utime; /* user time used */
    struct timeval ru_stime; /* system time used */
    long   ru_maxrss;        /* maximum resident set size */
    long   ru_ixrss;         /* integral shared memory size */
    long   ru_idrss;         /* integral unshared data size */
    long   ru_isrss;         /* integral unshared stack size */
    long   ru_minflt;        /* page reclaims */
    long   ru_majflt;        /* page faults */
    long   ru_nswap;         /* swaps */
    long   ru_inblock;       /* block input operations */
    long   ru_oublock;       /* block output operations */
    long   ru_msgsnd;        /* messages sent */
    long   ru_msgrcv;        /* messages received */
    long   ru_nsignals;      /* signals received */
    long   ru_nvcsw;         /* voluntary context switches */
    long   ru_nivcsw;        /* involuntary context switches */
}rusage;

struct rusage usage;
</code>```

答:
yeah its </p>

```<code>int main( void )
{
    clock_t start, stop;
    long int x;
    double duration;
    static struct timeval prev;
    struct timeval now;

    start = clock();  // get number of ticks before loop

    for( x = 0; x < 1000000000; x++ );
    // sleep(100);

    stop = clock();  // get number of ticks after loop

    // calculate time taken for loop
    duration = ( double ) ( stop - start ) / CLOCKS_PER_SEC;

    printf( "\nThe number of seconds for loop to run was %.2lf\n", duration );

    gettimeofday(&now, NULL);
    prev.tv_sec = duration;
    if (prev.tv_sec)
    {
        int diff = (now.tv_sec-prev.tv_sec)*1000+(now.tv_usec-prev.tv_usec)/1000;
        printf("DIFF %d\n",diff);
    }

    return 0;

}
</code>```

Body:
I am trying to print a value of type timeval. Actually I am able to print it, but I get the following warning:

Multiple markers at this line

format ‘%ld’ expects type ‘long int’, but argument 2 has type ‘struct timeval’

The program compiles and it prints the values, but I would like to know if I am doing something wrong.  Thanks.

    printf("%ld.%6ld\n",usage.ru_stime);
    printf("%ld.%6ld\n",usage.ru_utime);

where usage is of type

typedef struct{
    struct timeval ru_utime; /* user time used */
    struct timeval ru_stime; /* system time used */
    long   ru_maxrss;        /* maximum resident set size */
    long   ru_ixrss;         /* integral shared memory size */
    long   ru_idrss;         /* integral unshared data size */
    long   ru_isrss;         /* integral unshared stack size */
    long   ru_minflt;        /* page reclaims */
    long   ru_majflt;        /* page faults */
    long   ru_nswap;         /* swaps */
    long   ru_inblock;       /* block input operations */
    long   ru_oublock;       /* block output operations */
    long   ru_msgsnd;        /* messages sent */
    long   ru_msgrcv;        /* messages received */
    long   ru_nsignals;      /* signals received */
    long   ru_nvcsw;         /* voluntary context switches */
    long   ru_nivcsw;        /* involuntary context switches */
}rusage;

struct rusage usage;

Body:
yeah its

int main( void )
{
    clock_t start, stop;
    long int x;
    double duration;
    static struct timeval prev;
    struct timeval now;

    start = clock();  // get number of ticks before loop

    for( x = 0; x < 1000000000; x++ );
    // sleep(100);

    stop = clock();  // get number of ticks after loop

    // calculate time taken for loop
    duration = ( double ) ( stop - start ) / CLOCKS_PER_SEC;

    printf( "\nThe number of seconds for loop to run was %.2lf\n", duration );

    gettimeofday(&now, NULL);
    prev.tv_sec = duration;
    if (prev.tv_sec)
    {
        int diff = (now.tv_sec-prev.tv_sec)*1000+(now.tv_usec-prev.tv_usec)/1000;
        printf("DIFF %d\n",diff);
    }

    return 0;

}


问:
How to use requestReview (SKStoreReviewController) to show review popup in the current viewController after a random period of time
I've read about this new feature available in iOS 10.3 and thought it will be more flexible and out of the box. But after I read the docs I found out that you need to decide the time to show it and the viewController who calls it. Is there any way I can make it trigger after a random period of time in any viewController is showing at that moment?   </p>

答:
For Objective - C:

Add StoreKit.framework

Then in your viewController.h

```<code>#import <StoreKit/StoreKit.h>
</code>```

Then in your function call :

```<code>            [SKStoreReviewController requestReview];
</code>```

For Swift

Add StoreKit.framework

In your ViewController.swift

```<code>import StoreKit
</code>```

Then in your function call :

```<code>       if #available(iOS 10.3, *) {
            SKStoreReviewController.requestReview()
        } else {
            // Open App Store with OpenURL method
        }
</code>```

That's it ! Apple will take care of when it would show the rating (randomly).
When in development it will get called every time you call it.

Edited : No need to check OS version, StoreKit won't popup if the OS is less than 10.3, thank Zakaria.

Body:
For Objective - C:

Add StoreKit.framework

Then in your viewController.h

#import <StoreKit/StoreKit.h>

Then in your function call :

            [SKStoreReviewController requestReview];

For Swift

Add StoreKit.framework

In your ViewController.swift

import StoreKit

Then in your function call :

       if #available(iOS 10.3, *) {
            SKStoreReviewController.requestReview()
        } else {
            // Open App Store with OpenURL method
        }

That's it ! Apple will take care of when it would show the rating (randomly).
When in development it will get called every time you call it.

Edited : No need to check OS version, StoreKit won't popup if the OS is less than 10.3, thank Zakaria.


问:
I tried to run Java in Eclipse and it asks me to select ant build and either one I choose it says unable to find ant file to run...

So I just installed JRE, JDK and Eclipse and I was trying to run this famous HelloWorld code, but it shows this message as in attached images. What's the ant build?

Thanks!

答: Try to create a Java class file with suitable name and method.This error usually occurs when compiler doesn't understand which file to execute.</p>


问:
Dataweave Mulesoft Skip XML tags
I am using dataweave to transform a csv file to xml file. At some places there is no value for a certain xml tag and I am getting an empty tag.

What I want is if there is no value than that tag must not be present in xml at all.

It's a long mapping so I don't want to write the entire mapping in the when otherwise tag but just the mapping for that tag in the when otherwise condition.

Data mapping

```<code>    name: ((payload01.name) when payload01.name != ""
    otherwise {}),
</code>```

Output:
If there is value for name in input

```<code>    <name>Kittu</name>
</code>```

Otherwise

```<code>    <name/>
</code>```

What I want is that in the otherwise condition, no tag should come at all.

All help is appreciated. Thanks.

答:
skipNullOn checks if elements or attributes are present or not.
e.g. If name element is not present in your input, then it will not show it in output.

To check if value is empty, you will have to use a condition like this:
(name: payload01.name) when payload01.name != ""

Title: Dataweave Mulesoft Skip XML tags

Body:
I am using dataweave to transform a csv file to xml file. At some places there is no value for a certain xml tag and I am getting an empty tag.

What I want is if there is no value than that tag must not be present in xml at all.

It's a long mapping so I don't want to write the entire mapping in the when otherwise tag but just the mapping for that tag in the when otherwise condition.

Data mapping

    name: ((payload01.name) when payload01.name != ""
    otherwise {}),

Output:
If there is value for name in input

    <name>Kittu</name>

Otherwise

    <name/>

What I want is that in the otherwise condition, no tag should come at all.

All help is appreciated. Thanks.


问:
Convert string to int[,]
I have weird requirement in matrix clustering.

My inputs are like

```<code>string param = "1100,1110,0110,0001";
</code>```

and what I want is

```<code> var matrix = new[,]
        {
              {1,1,0,0},
              {1,1,1,0},
              {0,1,1,0},
              {0,0,0,1}
        };
</code>```

so It should be array of int[4,4].

What I tried?

I tried many ways for this conversation.

First Of all I convert my string to string[], using below code.

```<code>string[] resultantArray = param.Split(',').ToArray();
</code>```

And then I tried to convert my string[] to int[], using below code.

```<code>var intArray = resultantArray .Select(int.Parse).ToArray();
</code>```

but I ended up with removed leading zeros.

Is there any way,
 I can achieve int[4,4] array from string?

答:
Here is a more dynamic approach</p>

```<code>string param = "1100,1110,0110,0001";
int[][] rJagged = param.Split(',').Select(x => x.Select(y => int.Parse(y.ToString())).ToArray()).ToArray();
int[,] result = new int[rJagged.Length, rJagged.Max(x => x.Length)];

for (int i = 0; i < rJagged.Length; i++)
{
    for (int j = 0; j < rJagged[i].Length; j++)
    {
        result[i, j] = rJagged[i][j];
    }
}
</code>```

Title: Convert string to int[,]

Body:
I have weird requirement in matrix clustering.

My inputs are like

string param = "1100,1110,0110,0001";

and what I want is

 var matrix = new[,]
        {
              {1,1,0,0},
              {1,1,1,0},
              {0,1,1,0},
              {0,0,0,1}
        };

so It should be array of int[4,4].

What I tried?

I tried many ways for this conversation.

First Of all I convert my string to string[], using below code.

string[] resultantArray = param.Split(',').ToArray();

And then I tried to convert my string[] to int[], using below code.

var intArray = resultantArray .Select(int.Parse).ToArray();

but I ended up with removed leading zeros.

Is there any way,
 I can achieve int[4,4] array from string?

Body:
Here is a more dynamic approach

string param = "1100,1110,0110,0001";
int[][] rJagged = param.Split(',').Select(x => x.Select(y => int.Parse(y.ToString())).ToArray()).ToArray();
int[,] result = new int[rJagged.Length, rJagged.Max(x => x.Length)];

for (int i = 0; i < rJagged.Length; i++)
{
    for (int j = 0; j < rJagged[i].Length; j++)
    {
        result[i, j] = rJagged[i][j];
    }
}


问:
Rails View DRYness - Do you set variables in the view or just make clean methods?
I have a view in which I have the same link 3 times (actual view is large):

```<code>%h1= link_to "Title", model_path(@model, :class => "lightbox")
= link_to "Check it out", model_path(@model, :class => "lightbox")
%footer= link_to "Last time", model_path(@model, :class => "lightbox")
</code>```

That model_path(@model, :class => "lightbox") call, though fairly clean, can be made even leaner wrapping it in this (maybe you had some more options, so doing this was worthwhile):

```<code>def popup_model_path(model)
  model_path(model, :class => "lightbox")
end
</code>```

My question is, I am having to recalculate that path 3 times in a view.  What is the preferred way of a) DRYing this up and b) optimizing performance?

I think setting variables at the top of the view might be a good idea here:

```<code>- path = model_path(@model, :class => "lightbox")
-# ... rest of view
</code>```

It's almost like mustache in the end then.  What are your thoughts?

答:
This seems like a possible case of premature optimization. Making a function like popup_model_path is a fantastically DRY idea. Especially if that bit of code, however terse it may be originally, is going to be used frequently across multiple views. However, worrying about the performance impact of calculating the path 3 times in one view is, in my opinion, needless. Unless we're talking about something that is going to be used dozens or hundreds of times per view, and you're expecting many many simultaneous users, and the app is running on a shared server or something I really don't see what you have currently having any perceptible impact on performance.

As a general rule, I do my best to avoid variables in my view code. They make it harder to read and with a few exceptions (such as variables directly related to loops that display stuff like lists) I feel they kinda go against the whole MVC concept as I understand it.

I think above all else you should strive for code that is easily readable, understandable, and maintainable; both for yourself and others not previously familiar with your project. popup_model_path as you have it now is simple enough to where anyone who knows Rails can follow what you're doing. I don't see any need to make it any more complicated than that since it's not terribly repetitive. I wish I could find this excellent blog post I remember reading a while ago that made the point that DRYing up your code is great, but it has its limits, and like all great things the law of diminishing returns eventually kicks in.

Body:
I have a view in which I have the same link 3 times (actual view is large):

%h1= link_to "Title", model_path(@model, :class => "lightbox")
= link_to "Check it out", model_path(@model, :class => "lightbox")
%footer= link_to "Last time", model_path(@model, :class => "lightbox")

That model_path(@model, :class => "lightbox") call, though fairly clean, can be made even leaner wrapping it in this (maybe you had some more options, so doing this was worthwhile):

def popup_model_path(model)
  model_path(model, :class => "lightbox")
end

My question is, I am having to recalculate that path 3 times in a view.  What is the preferred way of a) DRYing this up and b) optimizing performance?

I think setting variables at the top of the view might be a good idea here:

- path = model_path(@model, :class => "lightbox")
-# ... rest of view

It's almost like mustache in the end then.  What are your thoughts?


问:
Creating Chart/Graph using Silverlight
I just started to work with Silverlight and wanted to know how I can create simple Silverlight  application that contains Graphs/Charts.
Also what are the component(SDK,SP1 etc) required to work with Silverlight. I am having VS 2010 installed on my machine and installed SDK 4 too but it is giving following error when tried to create application.."The Specified template not found".

Thank You....

答:
Look here for one of the best guides on using Silverlight charting/graphing tools.

Assuming you have already solved your 'template not found' error with the answer above.

Title: Creating Chart/Graph using Silverlight


问:
Get value of select2 when using input type text in php
I am using multiple select2 on my page to send mail to users. One for To users and second for CC users. I am using both fields as input. I want that When I select any user in the TO field It should not display in CC field. The user list is displayed using ajax. So I need to send all users in ajax from to fields. I am using

```<code>var toUser=$("#to_user").select2('data');
</code>```

But I am not getting the users records. What should I use to get all users which are selected in the To field? MY field is like

```<code><input type="text" id="to_users" name="toUsersData"/>
</code>```

答:
Use the following</p>

```<code>var toUser = $("#to_user").val();
</code>```

Body:
I am using multiple select2 on my page to send mail to users. One for To users and second for CC users. I am using both fields as input. I want that When I select any user in the TO field It should not display in CC field. The user list is displayed using ajax. So I need to send all users in ajax from to fields. I am using

var toUser=$("#to_user").select2('data');

But I am not getting the users records. What should I use to get all users which are selected in the To field? MY field is like

<input type="text" id="to_users" name="toUsersData"/>

Body:
Use the following

var toUser = $("#to_user").val();