问:
Visual Studio "Could not copy" .... during build
I keep getting this error during the build of my VS2012 C# project

```<code>Error   41  Could not copy "obj\Debug\WeinGartner.WeinCad.exe" to
 "bin\Debug\WeinGartner.WeinCad.exe".
 Exceeded retry count of 10. Failed.

Error   42  Unable to copy file "obj\Debug\WeinGartner.WeinCad.exe" to
"bin\Debug\WeinGartner.WeinCad.exe". The process cannot access the file
'bin\Debug\WeinGartner.WeinCad.exe' because it is being used by another
process.
</code>```

Now I've figured out that killing the process

```<code>Weingartner.WeinCad.vhost.exe
</code>```

works (sometimes ) but this is getting on my nerves. Any way to stop this happening at all?

My debugger settings are

答: I managed to get around the issue by running the Visual Studio as administrator. </p>

Body:
I keep getting this error during the build of my VS2012 C# project

Error   41  Could not copy "obj\Debug\WeinGartner.WeinCad.exe" to
 "bin\Debug\WeinGartner.WeinCad.exe".
 Exceeded retry count of 10. Failed.

Error   42  Unable to copy file "obj\Debug\WeinGartner.WeinCad.exe" to
"bin\Debug\WeinGartner.WeinCad.exe". The process cannot access the file
'bin\Debug\WeinGartner.WeinCad.exe' because it is being used by another
process.

Now I've figured out that killing the process

Weingartner.WeinCad.vhost.exe

works (sometimes ) but this is getting on my nerves. Any way to stop this happening at all?

My debugger settings are


来源: stackexchange

问:
Implementing a tail recursive version of quicksort-like function in F#/OCaml
Is it possible to implement a tail recursive version of the quick sort algorithm (via the continuation pattern)? And if it is, how would one implement it?

Normal (not optimized) version:

```<code>let rec quicksort list =
 match list with
 | [] -> []
 | element::[] -> [element]
 | pivot::rest -> let ``elements smaller than pivot``, ``elements larger or equal to pivot``=
                    rest |> List.partition(fun element -> element < pivot)
                  quicksort ``elements smaller than pivot`` @ [pivot] @ quicksort ``elements larger or equal to pivot``
</code>```

答:
Quick attempt, seeems to work:

```<code>let rec quicksort list cont =
    match list with
    | [] -> cont []
    | element::[] -> cont [element]
    | pivot::rest ->
        let ``elements smaller than pivot``, ``elements larger or equal to pivot`` =
            rest |> List.partition (fun element -> element < pivot)
        quicksort ``elements smaller than pivot``
            (fun x -> quicksort ``elements larger or equal to pivot`` (fun y -> cont (x @ [pivot] @ y)))

> quicksort [2; 6; 3; 8; 5; 1; 9; 4] id;;
val it : int list = [1; 2; 3; 4; 5; 6; 8; 9]
</code>```

Edit:

Of course, this code is highly inefficient. I hope nobody will use it in real code.
The code was not difficult to write, but continuations might be difficult to read and can be error-prone (it's easy to forget a call to cont). If you want to play more, you can write a continuation monad (Brian wrote a blog post about it).

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to implement a tail recursive version of the quick sort algorithm (via the continuation pattern)? And if it is, how would one implement it?

Normal (not optimized) version:

let rec quicksort list =
 match list with
 | [] -> []
 | element::[] -> [element]
 | pivot::rest -> let ``elements smaller than pivot``, ``elements larger or equal to pivot``=
                    rest |> List.partition(fun element -> element < pivot)
                  quicksort ``elements smaller than pivot`` @ [pivot] @ quicksort ``elements larger or equal to pivot``

Body:
Quick attempt, seeems to work:

let rec quicksort list cont =
    match list with
    | [] -> cont []
    | element::[] -> cont [element]
    | pivot::rest ->
        let ``elements smaller than pivot``, ``elements larger or equal to pivot`` =
            rest |> List.partition (fun element -> element < pivot)
        quicksort ``elements smaller than pivot``
            (fun x -> quicksort ``elements larger or equal to pivot`` (fun y -> cont (x @ [pivot] @ y)))

> quicksort [2; 6; 3; 8; 5; 1; 9; 4] id;;
val it : int list = [1; 2; 3; 4; 5; 6; 8; 9]

Edit:

Of course, this code is highly inefficient. I hope nobody will use it in real code.
The code was not difficult to write, but continuations might be difficult to read and can be error-prone (it's easy to forget a call to cont). If you want to play more, you can write a continuation monad (Brian wrote a blog post about it).

ContentLicense: CC BY-SA 3.0


问:
Shipping calculator Button at Checkout page
I am new to woocommerce and I do not have much knowledge about that. In a project I want to hide shipping calculation button from cart page.but want to show the same configuration with button on checkout page.

I want help regarding how to add shipping button on checkout.

答:
you can fire an event after calc_shipping buton is clicked, but you need to wait native calc_shipping method to end. I used jQuery(document).ajaxComplete to wait that execution:</p>

```<code>jQuery('[name="calc_shipping"]').click(function () {
jQuery(document).ajaxComplete(function () {
    your_pretty_code;
});
</code>```

Body:
you can fire an event after calc_shipping buton is clicked, but you need to wait native calc_shipping method to end. I used jQuery(document).ajaxComplete to wait that execution:

jQuery('[name="calc_shipping"]').click(function () {
jQuery(document).ajaxComplete(function () {
    your_pretty_code;
});


问:
Declare variable without var outside 'use strict'
I don't understand why it throws error

str = 'string'; // str is not defined. Why?
let str = 'string2';

console.log(str);```

I thought declaring a variable without a keyword would make it look like a var. But it is not.

答:
You need to declare the variable first, then use it, that's how let works. If you were using the var keyword instead it would have worked.

Using let

```<code>str = 'string';        // DOES NOT WORK! here it hasn't been declared
let str = 'string2';   // move this line up before the above line

console.log(str);
</code>```

Using var

```<code>str = 'string';        // IT WORKS because of variable hoisting!
var str = 'string2';

console.log(str);
</code>```

See: What's the difference between using "let" and "var"?

Body:
I don't understand why it throws error

str = 'string'; // str is not defined. Why?
let str = 'string2';

console.log(str);

I thought declaring a variable without a keyword would make it look like a var. But it is not.

Body:
You need to declare the variable first, then use it, that's how let works. If you were using the var keyword instead it would have worked.

Using let

str = 'string';        // DOES NOT WORK! here it hasn't been declared
let str = 'string2';   // move this line up before the above line

console.log(str);

Using var

str = 'string';        // IT WORKS because of variable hoisting!
var str = 'string2';

console.log(str);

See: What's the difference between using "let" and "var"?


问:
Comparing two Strings using Java 8 features
I was exploring various efficient ways to compare two strings in Java and I was comparing below two code snippets

Approach 1 :- Traditional Way

```<code>public static boolean stringCheck(String test1, String test2) {
    if ((test1 == null) || (test2 == null)) {
        return false;
    }
    return test1.compareTo(test2) > 0;
}
</code>```

and to test this code

```<code>String test1 = null;
String test2 = null;
boolean isTrue1 = stringCheck(test1, test2);
System.out.println("Return of stringCheck is" + isTrue1);
</code>```

which prints => Return of stringCheck is false  which is correct

Approach 2 :- Using Java 8 Features

```<code>public static boolean stringCheckWithJava8(String test1, String test2) {
    return Optional.ofNullable(test1)
            .map(s1 -> s1.equals(test2))
            .orElseGet(() -> test2 == null).booleanValue();
}
</code>```

and to test this code

```<code>String test1 = null;
String test2 = null;
boolean isTrue = stringCheckWithJava8(test1, test2);
</code>```

which prints => Return of stringCheckWithJava8 is true
which is logically correct  .

Now my question is How can I modify my code in Approach 2 with Java 8 feature shown above to handle a to return false when both strings are null?

答:
There is no need to use Java 8 at all. You can just simplify your existing method like this:

```<code>public static boolean stringCheck(String test1, String test2) {
    return test1 != null && test2 != null && test1.compareTo(test2) == 0;
}
</code>```

Or even shorter:

```<code>public static boolean stringCheck(String test1, String test2) {
    return test1 != null && test1.equals(test2);
}
</code>```

If you really want to use Java 8 you can use an Optional like this:

```<code>public static boolean stringCheck2(String test1, String test2) {
    return Optional.ofNullable(test1).filter(t -> t.equals(test2)).isPresent();
}
</code>```

Body:
I was exploring various efficient ways to compare two strings in Java and I was comparing below two code snippets

Approach 1 :- Traditional Way

public static boolean stringCheck(String test1, String test2) {
    if ((test1 == null) || (test2 == null)) {
        return false;
    }
    return test1.compareTo(test2) > 0;
}

and to test this code

String test1 = null;
String test2 = null;
boolean isTrue1 = stringCheck(test1, test2);
System.out.println("Return of stringCheck is" + isTrue1);

which prints => Return of stringCheck is false  which is correct

Approach 2 :- Using Java 8 Features

public static boolean stringCheckWithJava8(String test1, String test2) {
    return Optional.ofNullable(test1)
            .map(s1 -> s1.equals(test2))
            .orElseGet(() -> test2 == null).booleanValue();
}

and to test this code

String test1 = null;
String test2 = null;
boolean isTrue = stringCheckWithJava8(test1, test2);

which prints => Return of stringCheckWithJava8 is true
which is logically correct  .

Now my question is How can I modify my code in Approach 2 with Java 8 feature shown above to handle a to return false when both strings are null?

Body:
There is no need to use Java 8 at all. You can just simplify your existing method like this:

public static boolean stringCheck(String test1, String test2) {
    return test1 != null && test2 != null && test1.compareTo(test2) == 0;
}

Or even shorter:

public static boolean stringCheck(String test1, String test2) {
    return test1 != null && test1.equals(test2);
}

If you really want to use Java 8 you can use an Optional like this:

public static boolean stringCheck2(String test1, String test2) {
    return Optional.ofNullable(test1).filter(t -> t.equals(test2)).isPresent();
}


答:
As of HTML5 then text/javascript is the standard when no type is specified.

Personally however, I'd be inclined to always specify type - better safe than sorry!

Additionally, I'd always advise writing code under the assumption that someone else will have to support it.  Do you think the next person along will thank you for your 'time-saving' solutions that make the code harder to follow? I very much doubt it ;)

Title: Can "text/javascript" be assumed a de facto default for the <script> element?

Body: Despite that the HTML4 standard states there is no default for the


问:
Google Chrome doesn't offer translation for my website
Google translation icon doens't appear on a website I'm working on, and I can't find a reason for this. Should I add a specific code to enable chrome to suggest translating it?

Please note that I don't want to add Google Chrome widget, and Chrome settings are OK.

I'd like to make Chrome suggests to translate the pages of the website.

Here's an example: https://drive.google.com/file/d/1hKlPcs_HnIXApSa7jYX1pvDZigvdh9mc/view?usp=sharing

答: Can you try adding text in another language except english and then load the page ?</p>


问:
Angular 1.5 Component: passing a function
Is it possible to passing a function to a component and call this function inside the component passing a parameter?

Example:

List of posts

```<code><post-list posts="blog.posts"
           loading="blog.loadingPosts"
           get-post-url="blog.getPostUrl"
           is-user-authenticate="blog.user">
</post-list>
</code>```

getPostUrl is a function (inside the container controller):

```<code>const getPostUrl = (postId) => {
    const protocol = $location.protocol();
    const host = $location.host();
    const port = $location.port();

    return protocol + "://" + host + "" + (port !== 80 ? ":" + port : "") + "/blog/post/" + postId;
};
</code>```

List of posts: component

```<code>const PostList = {
  "bindings": {
    "posts": "<",
    "loading": "<",
    "getPostUrl": "&", //Function getPostUrl
    "isUserAuthenticate": "<"
  },
  "template": `<div>
                <div class="col-md-9 text-center" data-ng-if="$ctrl.loading">
                  <i class="fa fa-spinner fa-spin fa-2x"></i>
                </div>

                <div class="col-md-9 posts" data-ng-if="!$ctrl.loading">
                  <div data-ng-repeat="post in $ctrl.posts">
                    <post creation-date="{{post.creationDate}}"
                          content="{{post.content}}"
                          post-url="{{$ctrl.getPostUrl(post.creationDate)}}"
                          is-user-authenticate="$ctrl.user">
                    </post>
                  </div>
                </div>
              </div>`,
   "transclude": false
};

 angular
  .module("blog")
  .component("postList", PostList);
</code>```

In this line:

post-url="{{$ctrl.getPostUrl(post.creationDate)}}" I want to call the function passing a parameter and this function is returning a string.

In post component (not PostList) the postUrl is a string attribute @.

But... Is not working!

angular.js:13550 Error: [$interpolate:interr] Can't interpolate: {{$ctrl.getPostUrl(post.creationDate)}}
  TypeError: Cannot use 'in' operator to search for 'blog' in 1459329888892
  Error Link

Is it possible to do it? And how?

Thank you so much!

答:
According to Todd Motto's Standards, it is not suggested to use '=' instead try using '&' that is passing a method from parent to child component and calling the method in the child will trigger back in the parent. Let's take an example.

Parent Component's template(HTML):

```<code><child take-me-to-school="$ctrl.searchBikeKeyAndStart>
</code>```

Child Component's controller:

```<code>public someFunction = () => {
  this.takeMeToSchool();
}
</code>```

Once the function is called from the child component's controller then the function mapped in the parent will get triggered.

Parent Component's controller(HTML):

```<code>public searchBikeKeyAndStart = () => {
  .....
}
</code>```

When you want to pass an argument to the same function

Parent Component's template(HTML):

```<code><child take-me-to-school="$ctrl.searchBikeKeyAndStart(**key**)>
</code>```

Child Component's controller:

```<code>public someFunction = () => {
  this.takeMeToSchool({key: parameterValue});
}
</code>```

Once the function is called from the child component's controller then the function mapped in the parent will get triggered.

Parent Component's controller(HTML):

```<code>public searchBikeKeyAndStart = (**key**) => {
  console.log(**key**) //will print the param passed
}
</code>```

Body:
Is it possible to passing a function to a component and call this function inside the component passing a parameter?

Example:

List of posts

<post-list posts="blog.posts"
           loading="blog.loadingPosts"
           get-post-url="blog.getPostUrl"
           is-user-authenticate="blog.user">
</post-list>

getPostUrl is a function (inside the container controller):

const getPostUrl = (postId) => {
    const protocol = $location.protocol();
    const host = $location.host();
    const port = $location.port();

    return protocol + "://" + host + "" + (port !== 80 ? ":" + port : "") + "/blog/post/" + postId;
};

List of posts: component

const PostList = {
  "bindings": {
    "posts": "<",
    "loading": "<",
    "getPostUrl": "&", //Function getPostUrl
    "isUserAuthenticate": "<"
  },
  "template": `

                    <post creation-date="{{post.creationDate}}"
                          content="{{post.content}}"
                          post-url="{{$ctrl.getPostUrl(post.creationDate)}}"
                          is-user-authenticate="$ctrl.user">
                    </post>

`,
   "transclude": false
};

 angular
  .module("blog")
  .component("postList", PostList);

In this line:

post-url="{{$ctrl.getPostUrl(post.creationDate)}}" I want to call the function passing a parameter and this function is returning a string.

In post component (not PostList) the postUrl is a string attribute @.

But... Is not working!

angular.js:13550 Error: [$interpolate:interr] Can't interpolate: {{$ctrl.getPostUrl(post.creationDate)}}
  TypeError: Cannot use 'in' operator to search for 'blog' in 1459329888892
  Error Link

Is it possible to do it? And how?

Thank you so much!

Body:
According to Todd Motto's Standards, it is not suggested to use '=' instead try using '&' that is passing a method from parent to child component and calling the method in the child will trigger back in the parent. Let's take an example.

Parent Component's template(HTML):

<child take-me-to-school="$ctrl.searchBikeKeyAndStart>

Child Component's controller:

public someFunction = () => {
  this.takeMeToSchool();
}

Once the function is called from the child component's controller then the function mapped in the parent will get triggered.

Parent Component's controller(HTML):

public searchBikeKeyAndStart = () => {
  .....
}

When you want to pass an argument to the same function

Parent Component's template(HTML):

<child take-me-to-school="$ctrl.searchBikeKeyAndStart(**key**)>

Child Component's controller:

public someFunction = () => {
  this.takeMeToSchool({key: parameterValue});
}

Once the function is called from the child component's controller then the function mapped in the parent will get triggered.

Parent Component's controller(HTML):

public searchBikeKeyAndStart = (**key**) => {
  console.log(**key**) //will print the param passed
}


问:
Why is my SQL query not returning any records when it should be?
I have a select query with a bunch of where clauses. I tested a couple situations and they worked great! BUT tested another situation and it didn't return anything when it should have.

In access, i used the "create query" feature, I put all the same values and it returned 4 records, which is what it is expected! So, why is my query not able to find these records?

```<code>Set rstV = cdb.OpenRecordset("SELECT * FROM " & tableVName & " WHERE ValveSize IN (" & mVSize & "," & mLineSize & ") AND ValveFamily = '" & confgType & _
    "' AND CV >= " & mCV & " AND NO = 'X'")
</code>```

when I remove NO = 'X' , then it finds a bunch of records (including the ones that I am looking for), but I need NO='X' so that I can specifically find those 4 records.

i have a feeling that 'X' might be causing the issue some how, but it worked in other situations. I tried looking at columns field properties and it all looks good...

please help!

答:
Is far as I recall, YES and NO could be values, so try using brackets around NO:</p>

```<code>[NO] = 'X'
</code>```

Body:
I have a select query with a bunch of where clauses. I tested a couple situations and they worked great! BUT tested another situation and it didn't return anything when it should have.

In access, i used the "create query" feature, I put all the same values and it returned 4 records, which is what it is expected! So, why is my query not able to find these records?

Set rstV = cdb.OpenRecordset("SELECT * FROM " & tableVName & " WHERE ValveSize IN (" & mVSize & "," & mLineSize & ") AND ValveFamily = '" & confgType & _
    "' AND CV >= " & mCV & " AND NO = 'X'")

when I remove NO = 'X' , then it finds a bunch of records (including the ones that I am looking for), but I need NO='X' so that I can specifically find those 4 records.

i have a feeling that 'X' might be causing the issue some how, but it worked in other situations. I tried looking at columns field properties and it all looks good...

please help!

Body:
Is far as I recall, YES and NO could be values, so try using brackets around NO:

[NO] = 'X'


问:
W3C Pay (Bobpay sample chrome extension) - MAC OS - Fails to redirect to chrome extension. Works on Windows
I am evaluating W3C pay Google examples by enabling the Chrome Extension from Google's example here: https://bobpay.xyz/   (Clicking "Install web payment app" on the bottom).  This installs the W3C Pay Chrome extension.

I then use their demo here:
https://paymentrequest.show/demo/

I am able to submit a payment using the "Bobpay" extension, see below:

... however when it comes time to redirect to the Bob pay "Account Selector" web application (the front end of the Payment Handler), I get the following error in Chrome's Developer tools:

"Aborting payment handler window "https://bobpay.xyz/pay" because of navigation to an insecure url "chrome-extension://noojglkidnpfjbincgijbaiedldjfbhh/data/shared/tpc-check.html"

It's complaining that the redirection to the chrome-extension URL scheme is insecure.

I already took both Certs from bobpay.xyz and paymentrequest.show sites, and installed them to my System keychain.  Then I trusted both SSL certs.  This didn't help.

BTW, this works on Windows, but not on MacOS  (Chrome on both).

Also:  submitting a sample credit card payment outside of the Bobpay extension works fine (by using a locally stored Credit card option, and not the Bobpay extension)  - returns tokenized card to be forwarded to payment processor.

This demo code also does not work on any other browsers, such as Firefox or Safari (unsupported on both).

In the Security panel of Chrome Developer tools, we can also see that the Chrome Extension for Bobpay is marked as "Unsecure":

I also installed the whole thing on Localhost, created a self signed SSL cert, added it to keychain, trusted it, and ran an https-server with that cert, but I get the same issue on https://localhost:8080/bobpay as well.

答:
After verifying that the demo worked on another MacOS machine, I figured I introduced an issue trying to clone bobpay and deploy it on localhost under another name.  The two payment handlers were somehow trampling over each other, when redirecting to the Frontend Handler page.   </p>

<p>I ended up removing all Chrome files in ~/Library/Application Support/Google/Chrome, clearing all Chrome settings (reset to default), and re-installing Chrome.  This cleaned out all extensions, cached data, and service workers under Dev Console --> Application.   I am now able to proceed without errors.  </p>

Body:
After verifying that the demo worked on another MacOS machine, I figured I introduced an issue trying to clone bobpay and deploy it on localhost under another name.  The two payment handlers were somehow trampling over each other, when redirecting to the Frontend Handler page.

I ended up removing all Chrome files in ~/Library/Application Support/Google/Chrome, clearing all Chrome settings (reset to default), and re-installing Chrome.  This cleaned out all extensions, cached data, and service workers under Dev Console --> Application.   I am now able to proceed without errors.


问:
How to use cl2.hpp with AMD GPU and rocm
I've been developing with OpenCL on my Laptop for a while now, but want to move to my more powerful desktop pc with an AMD GPU. I followed the breadcrumbs through APP SDK (which is apparently gone) through amdgpu-pro drivers (which completely crash my system) and landed on rocm. I can't install the drivers on my kernel, but the rocm-dev seems to work fine. Unfortunately I can't seem to be able to use Khronos' cl2.hpp anymore, as it doesn't seem tk link to any cl calls. I would like to still be able to work with the Intel CPU on my laptop without completely rewriting my code. Is it possible to easily integrate cl2.hpp into my rocm installation? </p>

答: Found it. I wasn't linking against the libOpenCL.so correctly. I am using cmake and set OpenCL_LIBRARY to the amdgpu-pro lib directory rather than the actual library file. Apparently FIND (OpenCL) doesn't work with the /opt paths rocm and amdgpu provide.


问:
Htaccess redirect adds filepath to url
I'm trying to redirect my .html links to .php. The actual files have been renamed to php as well so my current .html links don't work. I tried this rewrite first which works as in it loads the page but doesn't change the url.

```<code>RewriteRule ^(.*)\.html$ $1.php [L]
</code>```

But when I change the rewrite to redirect, it no longer works. It adds the file path to the url.

```<code>RewriteRule ^(.*)\.html$ $1.php [L,R=302]
</code>```

For instance: www.domain.com/page.html redirects to www.domain.com/home/username/public_html/page.php

I've read many similar questions and tried their solutions but I haven't been able to solve the problem.

答:
If you add slash before destination and rewritebase maybe it work:

```<code>RewriteEngine On
RewriteBase /
</code>```

Rewrite file.html to file.php

```<code>RewriteRule ^(.*)\.html$ /$1.php [L]
</code>```

301 Redirect to file.php

```<code>RewriteRule ^(.*)\.html$ /$1.php [R=301,L]
</code>```

Title: Htaccess redirect adds filepath to url

Body:
I'm trying to redirect my .html links to .php. The actual files have been renamed to php as well so my current .html links don't work. I tried this rewrite first which works as in it loads the page but doesn't change the url.

RewriteRule ^(.*)\.html$ $1.php [L]

But when I change the rewrite to redirect, it no longer works. It adds the file path to the url.

RewriteRule ^(.*)\.html$ $1.php [L,R=302]

For instance: www.domain.com/page.html redirects to www.domain.com/home/username/public_html/page.php

I've read many similar questions and tried their solutions but I haven't been able to solve the problem.

Body:
If you add slash before destination and rewritebase maybe it work:

RewriteEngine On
RewriteBase /

Rewrite file.html to file.php

RewriteRule ^(.*)\.html$ /$1.php [L]

301 Redirect to file.php

RewriteRule ^(.*)\.html$ /$1.php [R=301,L]


问:
Prometheus Counter Inconsistency
I'm using the Prometheus Java simpleclient within a web service to keep track of how many events result in one status or another.

I'm able to check within the logs that the counter is being invoked and is incrementing internally, but it seems that a lot of times the data is not making it to the /metrics endpoint.

For example, just now, after incrementing the counter 3 times for the same status a few minutes apart each, the log would print out "Current Value = 0, New value = 1" three times. The first two times did not show any data on the /metrics endpoint, and after the 3rd increment, it finally showed a value of 1, which means I lost the record of the first 2 events.

The code I have is the following below, besides some name changes.

```<code>private static final Counter myCounter = Counter.build()
        .name("myMetric")
        .help("My metric")
        .labelNames("status").register();
...

private static void incrementCounter(String status) {
    Counter.Child counter = myCounter.labels(status);
    Logger.info("Before Incrementing counter for status= " + status + ". Current value=" + counter.get());
    counter.inc();
    Logger.info("After Incrementing counter for status= " + status + ". New value=" + counter.get());
}
</code>```

I'm at a loss as for why Prometheus doesn't seem to be able to keep track of these counters consistently. Is anyone able to see what's wrong or a better way to record these Counter metrics?

答:
The only reason I can guess are concurrent incrementCounter calls.
The io.prometheus.client.SimpleCollector#labels method is not thread-safe (despite that children field has ConcurrentMap type), thus it is possible to get different io.prometheus.client.Counter.Child on every call.

As for getting metrics via http - every call to /metrics endpoint leads to io.prometheus.client.Counter#collect method call, which retrieves value of the only one child.

I would suggest you to use your own concurrent map to store counters:

```<code>private static final ConcurrentMap<String, Counter.Child> counters = new ConcurrentHashMap<>();

// ...

private static void incrementCounter(String status) {
  Counter.Child counter = counters.computeIfAbsent(status, myCounter::labels) ;
  // ...
}
</code>```

Title: Prometheus Counter Inconsistency

Body:
I'm using the Prometheus Java simpleclient within a web service to keep track of how many events result in one status or another.

I'm able to check within the logs that the counter is being invoked and is incrementing internally, but it seems that a lot of times the data is not making it to the /metrics endpoint.

For example, just now, after incrementing the counter 3 times for the same status a few minutes apart each, the log would print out "Current Value = 0, New value = 1" three times. The first two times did not show any data on the /metrics endpoint, and after the 3rd increment, it finally showed a value of 1, which means I lost the record of the first 2 events.

The code I have is the following below, besides some name changes.

private static final Counter myCounter = Counter.build()
        .name("myMetric")
        .help("My metric")
        .labelNames("status").register();
...

private static void incrementCounter(String status) {
    Counter.Child counter = myCounter.labels(status);
    Logger.info("Before Incrementing counter for status= " + status + ". Current value=" + counter.get());
    counter.inc();
    Logger.info("After Incrementing counter for status= " + status + ". New value=" + counter.get());
}

I'm at a loss as for why Prometheus doesn't seem to be able to keep track of these counters consistently. Is anyone able to see what's wrong or a better way to record these Counter metrics?

Body:
The only reason I can guess are concurrent incrementCounter calls.
The io.prometheus.client.SimpleCollector#labels method is not thread-safe (despite that children field has ConcurrentMap type), thus it is possible to get different io.prometheus.client.Counter.Child on every call.

As for getting metrics via http - every call to /metrics endpoint leads to io.prometheus.client.Counter#collect method call, which retrieves value of the only one child.

I would suggest you to use your own concurrent map to store counters:

private static final ConcurrentMap<String, Counter.Child> counters = new ConcurrentHashMap<>();

// ...

private static void incrementCounter(String status) {
  Counter.Child counter = counters.computeIfAbsent(status, myCounter::labels) ;
  // ...
}


问:
in datatable initComplete not called after table.ajax.reload();
In a datatable on initComplete I wrote some code. The first time it works fine but after calling table.ajax.reload() the initComplete is not performing in the datatable.

"initComplete": function(settings, json) {
  $("#customerBids tr.cls-x-setTr").each(function() {
    debugger;
    var trId = $(this).attr('id');
    $('#' + trId + ' td').hide();
    $('#' + trId).append(' 	');
  });
},
```

<p>I added this interval which created the issue:</p>

```timer = setInterval(function() {
  table.ajax.reload(null, false);
}, 15000);
```

答:
The first argument of reload() is the reference of a callback function to execute. As such you can extract your initComplete() logic to its own function which is called from both events. Try this:

```<code>// in datatable settings:
"initComplete": foo,

// your reload logic:
timer = setInterval(function() {
  table.ajax.reload(foo, false); // note 'foo' here
}, 15000);

// somewhere outside of your datatable definition:
function foo() {
  $("#customerBids tr.cls-x-setTr").each(function() {
    debugger;
    var trId = $(this).attr('id');
    $('#' + trId + ' td').hide();
    $('#' + trId).append('<td class="cls-x-tmpTD" colspan="18"> </td>');
  });
}
</code>```

Body:
In a datatable on initComplete I wrote some code. The first time it works fine but after calling table.ajax.reload() the initComplete is not performing in the datatable.

"initComplete": function(settings, json) {
  $("#customerBids tr.cls-x-setTr").each(function() {
    debugger;
    var trId = $(this).attr('id');
    $('#' + trId + ' td').hide();
    $('#' + trId).append(' 	');
  });
},

I added this interval which created the issue:

timer = setInterval(function() {
  table.ajax.reload(null, false);
}, 15000);

Body:
The first argument of reload() is the reference of a callback function to execute. As such you can extract your initComplete() logic to its own function which is called from both events. Try this:

// in datatable settings:
"initComplete": foo,

// your reload logic:
timer = setInterval(function() {
  table.ajax.reload(foo, false); // note 'foo' here
}, 15000);

// somewhere outside of your datatable definition:
function foo() {
  $("#customerBids tr.cls-x-setTr").each(function() {
    debugger;
    var trId = $(this).attr('id');
    $('#' + trId + ' td').hide();
    $('#' + trId).append('<td class="cls-x-tmpTD" colspan="18"> </td>');
  });
}


问:
How to concatenate several logical operators like 'a and not (b or c or d)'
How do I write this correctly: </p>

```<code>for root, dirs, files in os.walk(SEARCHDIR):
    files = [f for f in files if not f[0] == '.' and not ("BLACKBOX" or ".RTN" or ".log") in f]
</code>```

<p>I want to achieve my file list to contain all files instead of hidden files or files conaining one of the strings "BLACKBOX" or ".RTN" or ".log".
Anyway only the first expression is evaluated ("BLACKBOX") the others are ignored.  </p>

答:
Change this:

```<code>not ("BLACKBOX" or ".RTN" or ".log") in f
</code>```

To this:

```<code>not any([x in f for x in ["BLACKBOX", ".RTN", ".log"]])
</code>```

Body:
How do I write this correctly:

for root, dirs, files in os.walk(SEARCHDIR):
    files = [f for f in files if not f[0] == '.' and not ("BLACKBOX" or ".RTN" or ".log") in f]

I want to achieve my file list to contain all files instead of hidden files or files conaining one of the strings "BLACKBOX" or ".RTN" or ".log".
Anyway only the first expression is evaluated ("BLACKBOX") the others are ignored.

Body:
Change this:

not ("BLACKBOX" or ".RTN" or ".log") in f

To this:

not any([x in f for x in ["BLACKBOX", ".RTN", ".log"]])


问:
Getting to the next page using scrapy
I am trying to make a web scraper but I'm unable to get the link of the next page. I have tried some combinations but none of them work. The tutorial on scrapy.org has a simpler format so it doesn't solve my problem

The site I'm scraping has the following layout:

```<code><nav class="nav_class">
    <a class="class_1" href="1.html">
    <a class="class_2" href="2.html">
    <a class="class_3" href="3.html">
</code>```

I want to get the 3.html link using css selectors

```<code>import scrapy

class MySpider(scrapy.Spider):
    name = "flip_spider"

    def start_requests(self):
        urls = [
            "https://www.flipkart.com/mobiles/pr?sid=tyy%2C4io&p%5B%5D=facets.processor_brand%255B%255D%3DSnapdragon&p%5B%5D=facets.serviceability%5B%5D%3Dfalse&p%5B%5D=facets.offer_type%255B%255D%3DExchange%2BOffer&otracker=clp_banner_1_10.bannerX3.BANNER_mobile-phones-store_HPUGCU9BYBF6&fm=neo%2Fmerchandising&iid=M_934db066-154e-4074-a4b1-96f56a0af28e_6.HPUGCU9BYBF6&ppt=HomePage&ppn=Home&ssid=85m4yqvgzk0000001558978084715&page=1",
        ]

        for url in urls:
            yield scrapy.Request(url, callback=self.parse)

    def parse(self, response):
        # page_id=response.url.split("=")[-1]
        phone_details = response.css("div._1-2Iqu.row")

        for ph in phone_details:
            phone = ph.css("div._3wU53n::text").get()
            rating = ph.css("div.hGSR34::text").get()
            price = ph.css("div._1vC4OE._2rQ-NK::text").get()

            yield{
                "name": phone,
                "rating": rating,
                "price": price,
            }
        final = "https://www.flipkart.com/mobiles/pr?sid=tyy%2C4io&p%5B%5D=facets.processor_brand%255B%255D%3DSnapdragon&p%5B%5D=facets.serviceability%5B%5D%3Dfalse&p%5B%5D=facets.offer_type%255B%255D%3DExchange%2BOffer&otracker=clp_banner_1_10.bannerX3.BANNER_mobile-phones-store_HPUGCU9BYBF6&fm=neo%2Fmerchandising&iid=M_934db066-154e-4074-a4b1-96f56a0af28e_6.HPUGCU9BYBF6&ppt=HomePage&ppn=Home&ssid=85m4yqvgzk0000001558978084715&page=6"
        next_page_id = response.css("nav._1ypTlJ a._3fVaIS::attr(href)").get()

        # ^This is the line I need help with

        if next_page_id is not final:
            next_page = response.urljoin(next_page_id)
            yield scrapy.Request(next_page, callback=self.parse)
</code>```

It only scrapes the first page and then stops

答:
Change you code to this and it will work</p>

```<code>next_page_id = response.css("nav._1ypTlJ a._3fVaIS::attr(href)").get()

if next_page_id:
    next_page = response.urljoin(next_page_id)
    yield scrapy.Request(next_page, callback=self.parse)
</code>```

Title: Getting to the next page using scrapy

Body:
I am trying to make a web scraper but I'm unable to get the link of the next page. I have tried some combinations but none of them work. The tutorial on scrapy.org has a simpler format so it doesn't solve my problem

The site I'm scraping has the following layout:

I want to get the 3.html link using css selectors

import scrapy

class MySpider(scrapy.Spider):
    name = "flip_spider"

    def start_requests(self):
        urls = [
            "https://www.flipkart.com/mobiles/pr?sid=tyy%2C4io&p%5B%5D=facets.processor_brand%255B%255D%3DSnapdragon&p%5B%5D=facets.serviceability%5B%5D%3Dfalse&p%5B%5D=facets.offer_type%255B%255D%3DExchange%2BOffer&otracker=clp_banner_1_10.bannerX3.BANNER_mobile-phones-store_HPUGCU9BYBF6&fm=neo%2Fmerchandising&iid=M_934db066-154e-4074-a4b1-96f56a0af28e_6.HPUGCU9BYBF6&ppt=HomePage&ppn=Home&ssid=85m4yqvgzk0000001558978084715&page=1",
        ]

        for url in urls:
            yield scrapy.Request(url, callback=self.parse)

    def parse(self, response):
        # page_id=response.url.split("=")[-1]
        phone_details = response.css("div._1-2Iqu.row")

        for ph in phone_details:
            phone = ph.css("div._3wU53n::text").get()
            rating = ph.css("div.hGSR34::text").get()
            price = ph.css("div._1vC4OE._2rQ-NK::text").get()

            yield{
                "name": phone,
                "rating": rating,
                "price": price,
            }
        final = "https://www.flipkart.com/mobiles/pr?sid=tyy%2C4io&p%5B%5D=facets.processor_brand%255B%255D%3DSnapdragon&p%5B%5D=facets.serviceability%5B%5D%3Dfalse&p%5B%5D=facets.offer_type%255B%255D%3DExchange%2BOffer&otracker=clp_banner_1_10.bannerX3.BANNER_mobile-phones-store_HPUGCU9BYBF6&fm=neo%2Fmerchandising&iid=M_934db066-154e-4074-a4b1-96f56a0af28e_6.HPUGCU9BYBF6&ppt=HomePage&ppn=Home&ssid=85m4yqvgzk0000001558978084715&page=6"
        next_page_id = response.css("nav._1ypTlJ a._3fVaIS::attr(href)").get()

        # ^This is the line I need help with

        if next_page_id is not final:
            next_page = response.urljoin(next_page_id)
            yield scrapy.Request(next_page, callback=self.parse)

It only scrapes the first page and then stops

Body:
Change you code to this and it will work

next_page_id = response.css("nav._1ypTlJ a._3fVaIS::attr(href)").get()

if next_page_id:
    next_page = response.urljoin(next_page_id)
    yield scrapy.Request(next_page, callback=self.parse)


问:
Google Espresso java.lang.RuntimeException: Could not launch intent Intent { act=android.intent.action.MAIN
I am new to Espresso UI testing.

I am getting this error while running tests (ADT Eclipse IDE ).

The app is already developed and there are lots of request going on while launching the app. it is not possible to rewrite the app. but i need to find the way to test this UI even if there is any delay in the loading of the components.

```<code>        java.lang.RuntimeException: Could not launch intent Intent { act=android.intent.action.MAIN flg=0x14000000 cmp=com.xx.android/com.yy.core.android.map.MapActivity } within 45 seconds. Perhaps the main thread has not gone idle within a reasonable amount of time? There could be an animation or something constantly repainting the screen. Or the activity is doing network calls on creation? See the threaddump logs. For your reference the last time the event queue was idle before your activity launch request was 1390913271702 and and now the last time the queue went idle was: 1390913271767. If these numbers are the same your activity might be hogging the event queue.
        at com.google.android.apps.common.testing.testrunner.GoogleInstrumentation.startActivitySync(GoogleInstrumentation.java:277)
        at android.test.InstrumentationTestCase.launchActivityWithIntent(InstrumentationTestCase.java:119)
        at android.test.InstrumentationTestCase.launchActivity(InstrumentationTestCase.java:97)
        at android.test.ActivityInstrumentationTestCase2.getActivity(ActivityInstrumentationTestCase2.java:104)
        at com.gulesider.android.test.UItest.setUp(UItest.java:25)
        at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190)
        at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175)
        at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
        at com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner.onStart(GoogleInstrumentationTestRunner.java:167)
        at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1799)
</code>```

I have one library project called “Core” - it will not generate any .apk

Also i have one Android project called “AA” which will access “Core”.  - This is AA.apk

Now i have created a test project called “UItest”

Manifest:

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.AA.android.test"
        android:versionCode="1"
        android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8"
            android:targetSdkVersion="18" />
    <instrumentation
      android:name="com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner"
      android:targetPackage="com.AA.android"/>
    <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
    <activity
                android:name="com.core.android.map.MapActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <uses-library android:name="android.test.runner" />
        </application>
    </manifest>
</code>```

My test:

```<code>    public class UItest extends ActivityInstrumentationTestCase2<MapActivity> {
        public UItest() {
            super(MapActivity.class);
        }

        @Override
        public void setUp() throws Exception {
            super.setUp();

            getActivity();

        }

        public void testSearchBox() {

            Espresso.onView(ViewMatchers.withId(R.id.menu_button_logo)).perform(ViewActions.click());

        }

    }
</code>```

答:
I faced this error when I trying to test the opening of another activity when the user clicked on a given view. What I was doing wrong was not replacing:

```<code>@Rule
public ActivityTestRule<MyActivity> myActivityActivityTestRule = new ActivityTestRule<>(MyActivity.class);
</code>```

Per:

```<code>@Rule
public IntentsTestRule<MyActivity> myActivityActivityTestRule =
            new IntentsTestRule<>(MyActivity.class);
</code>```

Body:
I am new to Espresso UI testing.

I am getting this error while running tests (ADT Eclipse IDE ).

The app is already developed and there are lots of request going on while launching the app. it is not possible to rewrite the app. but i need to find the way to test this UI even if there is any delay in the loading of the components.

        java.lang.RuntimeException: Could not launch intent Intent { act=android.intent.action.MAIN flg=0x14000000 cmp=com.xx.android/com.yy.core.android.map.MapActivity } within 45 seconds. Perhaps the main thread has not gone idle within a reasonable amount of time? There could be an animation or something constantly repainting the screen. Or the activity is doing network calls on creation? See the threaddump logs. For your reference the last time the event queue was idle before your activity launch request was 1390913271702 and and now the last time the queue went idle was: 1390913271767. If these numbers are the same your activity might be hogging the event queue.
        at com.google.android.apps.common.testing.testrunner.GoogleInstrumentation.startActivitySync(GoogleInstrumentation.java:277)
        at android.test.InstrumentationTestCase.launchActivityWithIntent(InstrumentationTestCase.java:119)
        at android.test.InstrumentationTestCase.launchActivity(InstrumentationTestCase.java:97)
        at android.test.ActivityInstrumentationTestCase2.getActivity(ActivityInstrumentationTestCase2.java:104)
        at com.gulesider.android.test.UItest.setUp(UItest.java:25)
        at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190)
        at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175)
        at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
        at com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner.onStart(GoogleInstrumentationTestRunner.java:167)
        at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1799)

I have one library project called “Core” - it will not generate any .apk

Also i have one Android project called “AA” which will access “Core”.  - This is AA.apk

Now i have created a test project called “UItest”

Manifest:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.AA.android.test"
        android:versionCode="1"
        android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8"
            android:targetSdkVersion="18" />
    <instrumentation
      android:name="com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner"
      android:targetPackage="com.AA.android"/>
    <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
    <activity
                android:name="com.core.android.map.MapActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <uses-library android:name="android.test.runner" />
        </application>
    </manifest>

My test:

    public class UItest extends ActivityInstrumentationTestCase2<MapActivity> {
        public UItest() {
            super(MapActivity.class);
        }

        @Override
        public void setUp() throws Exception {
            super.setUp();

            getActivity();

        }

        public void testSearchBox() {

            Espresso.onView(ViewMatchers.withId(R.id.menu_button_logo)).perform(ViewActions.click());

        }

    }

Body:
I faced this error when I trying to test the opening of another activity when the user clicked on a given view. What I was doing wrong was not replacing:

@Rule
public ActivityTestRule<MyActivity> myActivityActivityTestRule = new ActivityTestRule<>(MyActivity.class);

Per:

@Rule
public IntentsTestRule<MyActivity> myActivityActivityTestRule =
            new IntentsTestRule<>(MyActivity.class);


问:
Initializing properties inside ngOnInit scope
I'm using ngOnInit in order to get a response from a Loopback API call.
The property I initialize inside this scope can't be used outside the subscribe scope. I know this is a simple answer but I'm just not seeing it

```<code>private siteData: Kiosk;

  constructor(private dataService: DataService){}

 ngOnInit(){
    this.dataService.getDataByID(this.dataService.getSiteID())
        .subscribe((data:Site) => {
             this.siteData = data;
             console.log(this.siteData); // This outputs correctly
    });
    console.log(this.siteData); // This is undefined
  }

  site: any[] = [{
    title: this.siteData.title, // this is undefined and throws error
  }];
</code>```

I expect output to not be undefined and be the data that is in the response

答:
I also want to point you towards developing a better understanding of the lifecycle hooks in Angular. You are setting your class property like this:

```<code>site: any[] = [{
    title: this.siteData.title, // this is undefined and throws error
  }];
</code>```

This means, you are accessing this.sideData, which is only set in the ngOnInit hook that actually runs after the component has been initialised (constructed). Furthermore, you are only subscribing to the Observable in the lifecycle hook (OnInit), i.e. you are not actively assigning the result just yet, only after the observable emits a result. Your observable does not have to be asynchronous, but in your case most likely is.

Short story: You are getting errors, because you are trying to access a property of an object this.siteData, that is at that point of time undefined.

Body:
I'm using ngOnInit in order to get a response from a Loopback API call.
The property I initialize inside this scope can't be used outside the subscribe scope. I know this is a simple answer but I'm just not seeing it

private siteData: Kiosk;

  constructor(private dataService: DataService){}

 ngOnInit(){
    this.dataService.getDataByID(this.dataService.getSiteID())
        .subscribe((data:Site) => {
             this.siteData = data;
             console.log(this.siteData); // This outputs correctly
    });
    console.log(this.siteData); // This is undefined
  }

  site: any[] = [{
    title: this.siteData.title, // this is undefined and throws error
  }];

I expect output to not be undefined and be the data that is in the response

Body:
I also want to point you towards developing a better understanding of the lifecycle hooks in Angular. You are setting your class property like this:

site: any[] = [{
    title: this.siteData.title, // this is undefined and throws error
  }];

This means, you are accessing this.sideData, which is only set in the ngOnInit hook that actually runs after the component has been initialised (constructed). Furthermore, you are only subscribing to the Observable in the lifecycle hook (OnInit), i.e. you are not actively assigning the result just yet, only after the observable emits a result. Your observable does not have to be asynchronous, but in your case most likely is.

Short story: You are getting errors, because you are trying to access a property of an object this.siteData, that is at that point of time undefined.


问:
How to sort an Observable Array based on a certain item inside each Array
I have an Observable array in knockout with arrays inside, there is an item inside each of the arrays called 'time'. How would I order the arrays inside my observable array so that they are in order, from low to high, based on the value of the item. The values are in Hour:Minute:Second format.

function viewModel() {
  var self = this;

  self.myObservable = ko.observableArray([
  {time: "01:00:00", name: 'frank'},
  {time: "05:30:00", name: 'bob'},
  {time: "03:00:00", name: 'bill'},
  {time: "00:00:21", name: 'john'},
  {time: "00:12:00", name: 'paul'}
  ])
}```

答:
You should use the sort() function.</p>

```<code>    self.myObservable.sort(function (left, right) {
        return left.age === right.age ? 0
             : left.age < right.age ? -1
             : 1;
    });
</code>```

Body:
You should use the sort() function.

    self.myObservable.sort(function (left, right) {
        return left.age === right.age ? 0
             : left.age < right.age ? -1
             : 1;
    });


问:
A Question with using scapy.sniff for get the 'Ethernet Frame' in pcap files
Aim: Get the arrival time from the pcap files
Language: python3.7
Tools: Scapy.sniff

Above all ,i want get the arrival time data,in the .pcap ,when i use wireshark ,i saw the data in the Ethernet Frame,but when i use
 #Scapy.sniff(offline='.pcap') ,i just get the Ether,TCP,IP and others ,so how can i get that data?
Thanx alot!

>>from scapy.all  import *
>>a = sniff(offline = '***.pcap')
>>a[0]

[out]:
<Ether  dst=*:*:*:*:*:* src=*:*:*:*:*:* type=** |<IP  version=4 ihl=5 tos=0x20 len=52 id=14144 flags=DF frag=0 ttl=109 proto=tcp chksum=0x5e3b src=*.*.*.* dst=*.*.*.* |<TCP  sport=gcsp dport=http seq=1619409885 ack=1905830025 dataofs=8 reserved=0 flags=A window=65535 chksum=0xfdb5 urgptr=0 options=[('NOP', None), ('NOP', None), ('SAck', (1905831477, 1905831485))] |>>>
[ ]:

```

答:
The packet time from the pcap is available in the time member:

```<code>print(a[0].time)
</code>```

It's kept as a floating point value (the standard python "timestamp" format). To get it in a form more easily understandable, you may want to use the datetime module:

```<code>>>> from datetime import datetime
>>> dt = datetime.fromtimestamp(a[0].time)
>>> print(dt)
2018-11-12 03:03:00.259780
</code>```

The scapy documentation isn't great. It can be very instructive to use the interactive help facility. For example, in the interpreter:

```<code>$ python
>>> from scapy.all import *
>>> a = sniff(offline='mypcap.pcap')
>>> help(a[0])
</code>```

This will show you all the methods and attributes of the object represented by a[0]. In your case, that is an instance of class Ether(scapy.packet.Packet).

Body:
The packet time from the pcap is available in the time member:

print(a[0].time)

It's kept as a floating point value (the standard python "timestamp" format). To get it in a form more easily understandable, you may want to use the datetime module:

>>> from datetime import datetime
>>> dt = datetime.fromtimestamp(a[0].time)
>>> print(dt)
2018-11-12 03:03:00.259780

The scapy documentation isn't great. It can be very instructive to use the interactive help facility. For example, in the interpreter:

$ python
>>> from scapy.all import *
>>> a = sniff(offline='mypcap.pcap')
>>> help(a[0])

This will show you all the methods and attributes of the object represented by a[0]. In your case, that is an instance of class Ether(scapy.packet.Packet).


问:
Why is `'\t\n ' == false` in JavaScript?
In JavaScript...

```<code>'\t\n ' == false // true
</code>```

I can assume that any string that consists solely of whitespace characters is considered equal to false in JavaScript.

According to this article, I figured that false would be converted to 0, but was unable to find mention of whitespace considered equal to false using Google.

Why is this? Is there some good reading on the subject besides digging into the ECMAScript spec?

答:
This page provides a good summary of the rules.

Going by those rules, the '\t\n ' is converted in a number (Number('\t\n') ==> 0), and the false is converted into a number (Number(false) ==> 0), and hence the two are equal.

Alex's answer is also a good breakdown of the particular case of '\t\n ' == false.

An important distinction is that '\t\n ' is not falsy. For example:

```<code>if ('\t\n ') alert('not falsy'); // will produce the alert
</code>```

Body:
In JavaScript...

'\t\n ' == false // true

I can assume that any string that consists solely of whitespace characters is considered equal to false in JavaScript.

According to this article, I figured that false would be converted to 0, but was unable to find mention of whitespace considered equal to false using Google.

Why is this? Is there some good reading on the subject besides digging into the ECMAScript spec?

Body:
This page provides a good summary of the rules.

Going by those rules, the '\t\n ' is converted in a number (Number('\t\n') ==> 0), and the false is converted into a number (Number(false) ==> 0), and hence the two are equal.

Alex's answer is also a good breakdown of the particular case of '\t\n ' == false.

An important distinction is that '\t\n ' is not falsy. For example:

if ('\t\n ') alert('not falsy'); // will produce the alert


问:
Importing JS from one site to another
I created a script that asks you about the difficulty that you want of the game (and a cheat. I realize this isn't a secure way to add a cheat, but that's not the point). I want to save it on another section of my site, and have done so with the import method. I cannot get it to work. How would I export the function getDiff from http://www.willmargulies.com/password.htm and run it?

import{getDiff} from 'http://www.willmargulies.com/password.htm'
getDiff();
```

答:
The other file needs to:

Be a javascript file

Have a line somewhat like:

export function getDiff() {
 };

Title: Importing JS from one site to another


问:
Comparing two Strings using Java 8 features
I was exploring various efficient ways to compare two strings in Java and I was comparing below two code snippets

Approach 1 :- Traditional Way

```<code>public static boolean stringCheck(String test1, String test2) {
    if ((test1 == null) || (test2 == null)) {
        return false;
    }
    return test1.compareTo(test2) > 0;
}
</code>```

and to test this code

```<code>String test1 = null;
String test2 = null;
boolean isTrue1 = stringCheck(test1, test2);
System.out.println("Return of stringCheck is" + isTrue1);
</code>```

which prints => Return of stringCheck is false  which is correct

Approach 2 :- Using Java 8 Features

```<code>public static boolean stringCheckWithJava8(String test1, String test2) {
    return Optional.ofNullable(test1)
            .map(s1 -> s1.equals(test2))
            .orElseGet(() -> test2 == null).booleanValue();
}
</code>```

and to test this code

```<code>String test1 = null;
String test2 = null;
boolean isTrue = stringCheckWithJava8(test1, test2);
</code>```

which prints => Return of stringCheckWithJava8 is true
which is logically correct  .

Now my question is How can I modify my code in Approach 2 with Java 8 feature shown above to handle a to return false when both strings are null?

答:
You can simply return false if test1 is null. There is no need to test if test2 == null.

```<code>public static boolean stringCheckWithJava8(String test1, String test2) {
        return Optional.ofNullable(test1).map(s1 -> s1.equals(test2)).orElseGet(() -> false).booleanValue();
    }
</code>```

Body:
I was exploring various efficient ways to compare two strings in Java and I was comparing below two code snippets

Approach 1 :- Traditional Way

public static boolean stringCheck(String test1, String test2) {
    if ((test1 == null) || (test2 == null)) {
        return false;
    }
    return test1.compareTo(test2) > 0;
}

and to test this code

String test1 = null;
String test2 = null;
boolean isTrue1 = stringCheck(test1, test2);
System.out.println("Return of stringCheck is" + isTrue1);

which prints => Return of stringCheck is false  which is correct

Approach 2 :- Using Java 8 Features

public static boolean stringCheckWithJava8(String test1, String test2) {
    return Optional.ofNullable(test1)
            .map(s1 -> s1.equals(test2))
            .orElseGet(() -> test2 == null).booleanValue();
}

and to test this code

String test1 = null;
String test2 = null;
boolean isTrue = stringCheckWithJava8(test1, test2);

which prints => Return of stringCheckWithJava8 is true
which is logically correct  .

Now my question is How can I modify my code in Approach 2 with Java 8 feature shown above to handle a to return false when both strings are null?

Body:
You can simply return false if test1 is null. There is no need to test if test2 == null.

public static boolean stringCheckWithJava8(String test1, String test2) {
        return Optional.ofNullable(test1).map(s1 -> s1.equals(test2)).orElseGet(() -> false).booleanValue();
    }


问:
How to parse JSON element that can be either simple string or an object into Class Object
I am not able to unmarshall a JSON key which can hold either a string value or an another JSON Object using Jackson Library.

Ex:- Below are the two possible values.

1)

```<code>"ProviderData": {
    "INVALID": "HEX",
    "#text": "Sample"
}
</code>```

2)

```<code>"ProviderData": "1C"
</code>```

Could someone please verify and suggest me on this issue.

答: you could deserialize to JsonNode and then extract the contents individually, or deserialize to an Object and use instanceof to determine if it's a Map or another type, or use a custom deserializer to unpack the data into a custom object that handles both cases.

Body:
I am not able to unmarshall a JSON key which can hold either a string value or an another JSON Object using Jackson Library.

Ex:- Below are the two possible values.

1)

"ProviderData": {
    "INVALID": "HEX",
    "#text": "Sample"
}

2)

"ProviderData": "1C"

Could someone please verify and suggest me on this issue.


问:
How to avoid created empty logger file if no valid parsing output in python?
I have a python script to run log parsing and it will periodically scan through some log files on the disk and try to parse them. However, If the file is not parsable or have no data, my code should just exit for the parsing.
The problem is my script generating an empty log file even when there is not a valid data.

ie:
-rw-r--r-- 1 user userid  0 May 28 08:10 parse.py_20190528_08_10_03.log

I guess this is probably because logger is already initialized when my script is started.
What I want to know is if there is some other way to avoid this by setting? I tried to check a few places but do not know how.

This is my import logger in my script:

import logger
logger = logging.getLogger('upgrade.py')
formatter=logging.Formatter("%(asctime)s - %(levelname)-8s %(message)s")
log_filename = '{}/{}_{}.log'.format(os.getcwd(),os.path.basename(sys.argv[0]),time.strftime("%Y%m%d_%H_%M_%S"))
fh = logging.FileHandler(log_filename)
fh.setLevel(logging.INFO)
fh.setFormatter(formatter)
logger.addHandler(fh)
```

<p>After my parsing function, I use below to just make sure it did not dump data if no valid data.</p>

<pre class="lang-py prettyprint-override"><code>   main()
     ......parsing....
    if len(outputs) != 0:
        logger.info(outputs)
     .......
     .... output filtering.....
    if len(out_list) == 0:
        exit(0)
     .....
</code>```

However, this still not prevents it is creating 0 kb file in my directory. I trigger this tool in crontab and it is running periodically which generate lots of such files which is annoying and bad to check.
I know I can also have some outside watcher script to clear those file but that is not a smart act.

答:
You can achieve this by setting the delay parameter to True for the FileHandler:

```<code>fh = logging.FileHandler(log_filename, delay=True)
</code>```

From the docs:
https://docs.python.org/3/library/logging.handlers.html#logging.FileHandler

If delay is true, then file opening is deferred until the first call
  to emit().

Body:
I have a python script to run log parsing and it will periodically scan through some log files on the disk and try to parse them. However, If the file is not parsable or have no data, my code should just exit for the parsing.
The problem is my script generating an empty log file even when there is not a valid data.

ie:
-rw-r--r-- 1 user userid  0 May 28 08:10 parse.py_20190528_08_10_03.log

I guess this is probably because logger is already initialized when my script is started.
What I want to know is if there is some other way to avoid this by setting? I tried to check a few places but do not know how.

This is my import logger in my script:

import logger
logger = logging.getLogger('upgrade.py')
formatter=logging.Formatter("%(asctime)s - %(levelname)-8s %(message)s")
log_filename = '{}/{}_{}.log'.format(os.getcwd(),os.path.basename(sys.argv[0]),time.strftime("%Y%m%d_%H_%M_%S"))
fh = logging.FileHandler(log_filename)
fh.setLevel(logging.INFO)
fh.setFormatter(formatter)
logger.addHandler(fh)

After my parsing function, I use below to just make sure it did not dump data if no valid data.

   main()
     ......parsing....
    if len(outputs) != 0:
        logger.info(outputs)
     .......
     .... output filtering.....
    if len(out_list) == 0:
        exit(0)
     .....

However, this still not prevents it is creating 0 kb file in my directory. I trigger this tool in crontab and it is running periodically which generate lots of such files which is annoying and bad to check.
I know I can also have some outside watcher script to clear those file but that is not a smart act.

Body:
You can achieve this by setting the delay parameter to True for the FileHandler:

fh = logging.FileHandler(log_filename, delay=True)

From the docs:
https://docs.python.org/3/library/logging.handlers.html#logging.FileHandler

If delay is true, then file opening is deferred until the first call
  to emit().


问:
When typing a item code into one cell, how to get a description and price to automatically go into other cells
This is probably a really easy fix but I'm having trouble getting it to work.  I am a frequent user of functions in excel but haven't dabbled with VBA much.

I have a vendor that refuses to itemize their invoices.  It becomes very difficult for me when making a PO.  I have begun to itemize their invoices myself but as they get bigger and bigger this is consuming more of my time.  I would like to be able to type an item code into a cell and in the two cells to the right automatically populate the description and the price.

For example:

Type "Temporary Wire" in A2, and "Installing a Temporary Wire Gap Gate up to 100 foot wide" would automatically populate in B2, followed by "$650.00" automatically populating in C2.

答:
You question is too board but i will provide some guidelines :</p>

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim strSearchValue As String

    'Check if the range affected is A2 and the number of cells affected is 1
    If Not Intersect(Target, Range("A2")) Is Nothing And Target.Count = 1 Then

        'Assign to strSearchValue the value in range("A2")
        strSearchValue = Target

        'Insert more code

    End If

End Sub
</code>```

Body:
You question is too board but i will provide some guidelines :

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim strSearchValue As String

    'Check if the range affected is A2 and the number of cells affected is 1
    If Not Intersect(Target, Range("A2")) Is Nothing And Target.Count = 1 Then

        'Assign to strSearchValue the value in range("A2")
        strSearchValue = Target

        'Insert more code

    End If

End Sub


问:
MongoDB Docker container: ERROR: Cannot write pid file to /tmp/tmp.aLmNg7ilAm: No space left on device
I started a MongoDB container like so:

```<code>docker run -d -p 27017:27017 --net=cdt-net --name cdt-mongo mongo
</code>```

I saw that my MongoDB container exited:

```<code>0e35cf68a29c        mongo               "docker-entrypoint.s…"   Less than a second ago   Exited (1) 3 seconds ago                       cdt-mongo
</code>```

I checked my Docker logs, I see:

```<code>$ docker logs 0e35cf68a29c
about to fork child process, waiting until server is ready for connections.
forked process: 21
2018-01-12T23:42:03.413+0000 I CONTROL  [main] ***** SERVER RESTARTED *****
2018-01-12T23:42:03.417+0000 I CONTROL  [main] ERROR: Cannot write pid file to /tmp/tmp.aLmNg7ilAm: No space left on device
ERROR: child process failed, exited with error number 1
</code>```

Does anyone know what this error is about? Not enough space in the container?

答:
We've experienced this problem recently while using docker-compose with mongo and a bunch of other services. There are two fixes which have worked for us.

Clear down unused stuff

# close down all services
docker-compose down

# clear unused docker images
docker system prune

# press y
```

Increase the image memory available to docker - this will depend on your installation of docker. On Mac, for example, it defaults to 64Gb and we doubled it to 128Gb via the UI.

We've had this problem in both Windows and Mac and the above fixed it.

Body:
I started a MongoDB container like so:

docker run -d -p 27017:27017 --net=cdt-net --name cdt-mongo mongo

I saw that my MongoDB container exited:

0e35cf68a29c        mongo               "docker-entrypoint.s…"   Less than a second ago   Exited (1) 3 seconds ago                       cdt-mongo

I checked my Docker logs, I see:

$ docker logs 0e35cf68a29c
about to fork child process, waiting until server is ready for connections.
forked process: 21
2018-01-12T23:42:03.413+0000 I CONTROL  [main] ***** SERVER RESTARTED *****
2018-01-12T23:42:03.417+0000 I CONTROL  [main] ERROR: Cannot write pid file to /tmp/tmp.aLmNg7ilAm: No space left on device
ERROR: child process failed, exited with error number 1

Does anyone know what this error is about? Not enough space in the container?

Body:
We've experienced this problem recently while using docker-compose with mongo and a bunch of other services. There are two fixes which have worked for us.

Clear down unused stuff

# close down all services
docker-compose down

# clear unused docker images
docker system prune

# press y

Increase the image memory available to docker - this will depend on your installation of docker. On Mac, for example, it defaults to 64Gb and we doubled it to 128Gb via the UI.

We've had this problem in both Windows and Mac and the above fixed it.


问:
How do I write VBA script so that it will compare data?
We need a script to compare the dates in column D to the dates in column E.

If the date in column D is two days before the date in column E then we need column F to state that in the corresponding row to D. We have a range of 2 days before and 2 days after (shoulder days). We need to be able to easily reproduce this and have it be able to run when we import it into access. we have roughly 3300 unique days to check.

I have tried using datevalue or a formula but we need to be able to reproduce this in the future and the formula doesn't allow us to easily do that.

答:
I will not provide a complete implementation, but I can show you the way how you can do it (either the Excel formula way or with VBA code). Both ways will automatically calculate the values you need so you can easily import it into Microsoft Access - the import will take the calculated values from the cells you've selected.

The first way, which is also the simplest way, is to do that with simple Excel formula, consider this picture showing how the formula will calculate the values in columns F and G:

(Note: It is showing German date format, but you can easily change that in Excel).

In column G it calculates the difference D2 - D1 and displays it in days.
Then, in column F there is a simple if condition to determine if the date D1 is less, greater or equal than D2. The Result is calculated automatically.

The formula in row 2 are:

Hint: You can drag and drop the formula to the rows 3 - n below, so you can create a lot of rows prefilled with that formula.

A second way is that you can write a VBA function for the (simple) calculation formula in column F:

```<code>Function CalcResult(D1 As Variant, D2 As Variant) As Variant

    CalcResult = ""
    Dim result As String
    Dim diff As Single
    diff = D2 - D1
    If (diff > 0) Then
        result = "D1 < D2"
    ElseIf (diff = 0) Then
        result = "D1 = D2"
    ElseIf (diff < 0) Then
        result = "D1 > D2"
    End If
    CalcResult = result

End Function
</code>```

This needs to be entered in the VBA editor, which you can display if you press Alt+F11. After you have done that, press Alt+F11 again to close VBA and return to your Excel sheet.

Then, place the formula =CalcResult(E2; D2) in cell F2 as shown below:

Like in the previous example, you can drag & drop the formula to the rows 3 - n below, so you can create a lot of rows prefilled with that formula.

The advantage of the 2nd approach is that you can refine the function CalcResult later without having to change the cells again (as it is the case in the first example).

Note: The function above needs to be in a separate module and you need to save the workbook as "Macro enabled workbook" later - otherwise you'll lose the VBA code.

A third way is to use the Excel macro recorder and record whatever you intend to do. It will create a public module with VBA code. If the recorder asks you, choose to store the code in the workbook.

Later you re-visit the generated VBA code and refine it - for example, put a for loop around it to automate things you've recorded once.
This approach is good for creating a "Calculate" button and put some logic behind it.

Body:
I will not provide a complete implementation, but I can show you the way how you can do it (either the Excel formula way or with VBA code). Both ways will automatically calculate the values you need so you can easily import it into Microsoft Access - the import will take the calculated values from the cells you've selected.

The first way, which is also the simplest way, is to do that with simple Excel formula, consider this picture showing how the formula will calculate the values in columns F and G:

(Note: It is showing German date format, but you can easily change that in Excel).

In column G it calculates the difference D2 - D1 and displays it in days.
Then, in column F there is a simple if condition to determine if the date D1 is less, greater or equal than D2. The Result is calculated automatically.

The formula in row 2 are:

Hint: You can drag and drop the formula to the rows 3 - n below, so you can create a lot of rows prefilled with that formula.

A second way is that you can write a VBA function for the (simple) calculation formula in column F:

Function CalcResult(D1 As Variant, D2 As Variant) As Variant

    CalcResult = ""
    Dim result As String
    Dim diff As Single
    diff = D2 - D1
    If (diff > 0) Then
        result = "D1 < D2"
    ElseIf (diff = 0) Then
        result = "D1 = D2"
    ElseIf (diff < 0) Then
        result = "D1 > D2"
    End If
    CalcResult = result

End Function

This needs to be entered in the VBA editor, which you can display if you press Alt+F11. After you have done that, press Alt+F11 again to close VBA and return to your Excel sheet.

Then, place the formula =CalcResult(E2; D2) in cell F2 as shown below:

Like in the previous example, you can drag & drop the formula to the rows 3 - n below, so you can create a lot of rows prefilled with that formula.

The advantage of the 2nd approach is that you can refine the function CalcResult later without having to change the cells again (as it is the case in the first example).

Note: The function above needs to be in a separate module and you need to save the workbook as "Macro enabled workbook" later - otherwise you'll lose the VBA code.

A third way is to use the Excel macro recorder and record whatever you intend to do. It will create a public module with VBA code. If the recorder asks you, choose to store the code in the workbook.

Later you re-visit the generated VBA code and refine it - for example, put a for loop around it to automate things you've recorded once.
This approach is good for creating a "Calculate" button and put some logic behind it.


问:
How to remove dupes and replace column variables
I'm working with a data set named CCCrn on candidates in a local election with some duplicate values. Here's a sample:

```<code>Adam Hill         4100 New Texas Rd.            Pittsburgh 15239 School Director   PLUM       Democratic     4          5

Adam Hill         4100 New Texas Rd.            Pittsburgh 15239 School Director   PLUM       Republican     4          5
</code>```

As you can see, this candidate cross listed and was on both parties' ballots. I'd like to remove one of the rows, and then edit the Party variable to say "Cross Listed.

Obviously unique and distinct haven't been much help. I tried
test <- CCCrn[!duplicated(CCCrn$Name), ] which succeeded in removing the duplicate canidates, but now I'm not sure how I would go back and edit the "Party" variable.

答:
create a flag for duplicate record</p>

```<code>df <- df %>% mutate(dup = ifelse(duplicated(name)|duplicated(name, fromLast=TRUE),1,0))
df <- df[!duplicated(df$name),]   ## remove duplicate

df <- df %>% mutate(party= ifelse(dup==1, "Cross Listed", party)) # update party

df <- df%>% select(-dup)  ## remove flag
</code>```

Body:
I'm working with a data set named CCCrn on candidates in a local election with some duplicate values. Here's a sample:

Adam Hill         4100 New Texas Rd.            Pittsburgh 15239 School Director   PLUM       Democratic     4          5

Adam Hill         4100 New Texas Rd.            Pittsburgh 15239 School Director   PLUM       Republican     4          5

As you can see, this candidate cross listed and was on both parties' ballots. I'd like to remove one of the rows, and then edit the Party variable to say "Cross Listed.

Obviously unique and distinct haven't been much help. I tried
test <- CCCrn[!duplicated(CCCrn$Name), ] which succeeded in removing the duplicate canidates, but now I'm not sure how I would go back and edit the "Party" variable.

Body:
create a flag for duplicate record

df <- df %>% mutate(dup = ifelse(duplicated(name)|duplicated(name, fromLast=TRUE),1,0))
df <- df[!duplicated(df$name),]   ## remove duplicate

df <- df %>% mutate(party= ifelse(dup==1, "Cross Listed", party)) # update party

df <- df%>% select(-dup)  ## remove flag


问:
Is it possible to use bootstrap 4 in a nextjs project by just adding a link stylesheet?
I have this project where I imported bootstrap like this on my header:

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
</code>```

Everything was working fine until I decided to add a carousel.
The carousel shows up properly, but it doesn't rotate and the buttons on the side doesn't work.
I also noticed that my colapsed menu also don't work.

On my research I saw a lot of people suggesting to use reactstrap and some other third party libraries, but I'm wondering if it's possible keep using the link stylesheet.

From what I read the problem is with the jquery and bootstrap being imported in the wrong order, which might cause those elements to break.

答:
Solved the issue using another website as reference:
https://www.bootstrapcdn.com/

Instead of using

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
</code>```

I used

```<code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</code>```

And it is finally working.

Body:
I have this project where I imported bootstrap like this on my header:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />

Everything was working fine until I decided to add a carousel.
The carousel shows up properly, but it doesn't rotate and the buttons on the side doesn't work.
I also noticed that my colapsed menu also don't work.

On my research I saw a lot of people suggesting to use reactstrap and some other third party libraries, but I'm wondering if it's possible keep using the link stylesheet.

From what I read the problem is with the jquery and bootstrap being imported in the wrong order, which might cause those elements to break.

Body:
Solved the issue using another website as reference:
https://www.bootstrapcdn.com/

Instead of using

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />

I used

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

And it is finally working.


问:
Angular async pipe is not refreshing when observable changed
I have an Angular app.

On the app init we should show redirecting spinner (user is not logged in)

When the user is logged in, then we should show content

I've done it as below:
HTML:

```<code><div *ngIf="(isLoggedIn$ | async); else loading">
    <!-- some other content -->
    <router-outlet></router-outlet>
</div>

<ng-template #loading>
    <app-spinner text="Redirecting..."></app-spinner>
</ng-template>
</code>```

TS:

```<code>isLoggedIn$: Observable<boolean>;

constructor(private authService: AuthService) {}

ngOnInit() {
    this.isLoggedIn$ = this.authService.isLoggedIn();
}
</code>```

It works well on the app init. When the user is logged in, I still see the redirection spinner. I have to refresh the window to see the router-outlet content.

My temporary workaround is to put <router-outlet> inside <ng-template #loading>, eg:

```<code><ng-template #loading>
    <app-spinner text="Redirecting..."></app-spinner>
    <router-outlet></router-outlet> <!-- HERE workaround -->
</ng-template>
</code>```

But don't want to use this workaround permanently as I want to fix this Observable problem - as I mentioned it is not refreshed even when the console.log() says that I'm logged in.

Here is my Auth Service:

```<code>@Injectable({
    providedIn: 'root'
})
export class AuthService {

  manager: UserManager = new UserManager(environment.settings);

  constructor() {
  }

  getUser(): Observable<User> {
    return from(this.manager.getUser());
  }

  isLoggedIn(): Observable<boolean> {
    return this.getUser()
      .pipe(
        map(user => {
          return user != null && !user.expired;
        })
      );
  }

  startAuthentication(): Promise<void> {
    return this.manager.signinRedirect();
  }

  completeAuthentication(): Observable<User> {
    return from(this.manager.signinRedirectCallback());
  }

  async signOut() {
    await this.manager.signoutRedirect();
  }
}
</code>```

Of course, I am using CanActivate as well.

答:
My solution is to add emitCompleted method to AuthService and calling it from AuthCallback component.

AuthService:

```<code>private isLoggedInState = new BehaviorSubject<boolean>(false);

isLoggedIn(): Observable<boolean> {
    return this.isLoggedInState.asObservable();
}

emitCompleted(user: User) {
    this.isLoggedInState.next(user != null && !user.expired);
}
</code>```

AuthCallback component:

```<code>export class AuthCallbackComponent implements OnInit {

  constructor(
    private authService: AuthService,
    private router: Router
    ) { }

  ngOnInit() {
    this.authService.completeAuthentication()
      .subscribe((result => {
        this.authService.emitCompleted(result);
      })
    );
  }
}
</code>```

Body:
I have an Angular app.

On the app init we should show redirecting spinner (user is not logged in)

When the user is logged in, then we should show content

I've done it as below:
HTML:

    <router-outlet></router-outlet>

<ng-template #loading>
    <app-spinner text="Redirecting..."></app-spinner>
</ng-template>

TS:

isLoggedIn$: Observable<boolean>;

constructor(private authService: AuthService) {}

ngOnInit() {
    this.isLoggedIn$ = this.authService.isLoggedIn();
}

It works well on the app init. When the user is logged in, I still see the redirection spinner. I have to refresh the window to see the router-outlet content.

My temporary workaround is to put <router-outlet> inside <ng-template #loading>, eg:

<ng-template #loading>
    <app-spinner text="Redirecting..."></app-spinner>
    <router-outlet></router-outlet>
</ng-template>

But don't want to use this workaround permanently as I want to fix this Observable problem - as I mentioned it is not refreshed even when the console.log() says that I'm logged in.

Here is my Auth Service:

@Injectable({
    providedIn: 'root'
})
export class AuthService {

  manager: UserManager = new UserManager(environment.settings);

  constructor() {
  }

  getUser(): Observable<User> {
    return from(this.manager.getUser());
  }

  isLoggedIn(): Observable<boolean> {
    return this.getUser()
      .pipe(
        map(user => {
          return user != null && !user.expired;
        })
      );
  }

  startAuthentication(): Promise<void> {
    return this.manager.signinRedirect();
  }

  completeAuthentication(): Observable<User> {
    return from(this.manager.signinRedirectCallback());
  }

  async signOut() {
    await this.manager.signoutRedirect();
  }
}

Of course, I am using CanActivate as well.

Body:
My solution is to add emitCompleted method to AuthService and calling it from AuthCallback component.

AuthService:

private isLoggedInState = new BehaviorSubject<boolean>(false);

isLoggedIn(): Observable<boolean> {
    return this.isLoggedInState.asObservable();
}

emitCompleted(user: User) {
    this.isLoggedInState.next(user != null && !user.expired);
}

AuthCallback component:

export class AuthCallbackComponent implements OnInit {

  constructor(
    private authService: AuthService,
    private router: Router
    ) { }

  ngOnInit() {
    this.authService.completeAuthentication()
      .subscribe((result => {
        this.authService.emitCompleted(result);
      })
    );
  }
}


问:
Windows threading: _beginthread vs _beginthreadex vs CreateThread C++
What's a better way to start a thread, _beginthread, _beginthreadx or CreateThread?

I'm trying to determine what are the advantages/disadvantages of _beginthread, _beginthreadex and CreateThread.  All of these functions return a thread handle to a newly created thread, I already know that CreateThread provides a little extra information when an error occurs (it can be checked by calling GetLastError)... but what are some things I should consider when I'm using these functions?

I'm working with a windows application, so cross-platform compatibility is already out of the question.

I have gone through the msdn documentation and I just can't understand, for example, why anybody would decide to use _beginthread instead of CreateThread or vice versa.

Cheers!

Update:
OK, thanks for all the info, I've also read in a couple of places that I can't call WaitForSingleObject() if I used _beginthread(), but if I call _endthread() in the thread shouldn't that work? What's the deal there?

答:
You should use _beginthread or _beginthreadex to  allow the C runtime library to do it's own initialization of the thread.  Only C/C++ programmers need to know this as they should now the rules of using their own development environment.

If you use _beginthread you do not need to call CloseHandle as the RTL will do for you.  This is why you cannot wait on the handle if you have used _beginthread.  Also _beginthread leads to confusion if the thread function exits immediately (quickly) as the launching thread my be left holding an invalid thread handle to the thread it just launched.

_beginthreadex handles can be used for wait but also require an explicit call to CloseHandle.  This is part of what makes them safe for using with wait.  There other issue to make it completely foolproof is to always start the thread suspended.  Check for success, record handle etc.  The resume thread.  This is required to prevent a thread from terminating before the launching thread can record its handle.

Best practice is to use _beginthreadex, start suspended then resume after recording handle, wait on handle is OK, CloseHandle must be called.

OwnerDisplayName: Kiril Gantchev

LastEditorDisplayName: Kiril Gantchev


问:
Cannot start IIS Express
I has just installed Visual Studio 2012 and wanted to create my first WCF Service Application. I am a Java developer coming to .NET world, so please be understanding :)

I have created a new C# project WCF Service Application. Then I hit Debug (or F5) and I get an error saying:

```<code>Unable to launch IIS Express
</code>```

When I click again there is another error like this, but this time IIS appears in tray and I  get a notification (bubble) and when I click it there is a message saying:

```<code>Port '53234' is already being used by process 'IIS Express' (process ID '5524')
</code>```

I have tried changing the port in project properties in Web tab, but it does not change anything. The msgs are the same, just the port number changes.

For me this is quite funny, but I cannot fix it. Already tried changing the ports, I reinstalled IIS, restarting Visual Studio and PC. Nothing is running on the ports that I want to use.

I am using Windows 8.1 x64, Visual Studio 2012 (IIS 8).

EDIT

There is a log msg in IIS:

```<code>Failed to register URL "http://localhost:53234/" for site "WcfService1" application "/". Error description: Cannot create a file when that file already exists. (0x800700b7)
Registration completed
</code>```

答: I tried netsh http show urlacl and didn't see my address, my applicationHost.config file looked correct, and there was nothing troubling inside IIS. I fixed it by closing Visual Studio, deleting the .vs directory out of the solution folder, and restarting Visual Studio.

Title: Cannot start IIS Express

Body:
I has just installed Visual Studio 2012 and wanted to create my first WCF Service Application. I am a Java developer coming to .NET world, so please be understanding :)

I have created a new C# project WCF Service Application. Then I hit Debug (or F5) and I get an error saying:

Unable to launch IIS Express

When I click again there is another error like this, but this time IIS appears in tray and I  get a notification (bubble) and when I click it there is a message saying:

Port '53234' is already being used by process 'IIS Express' (process ID '5524')

I have tried changing the port in project properties in Web tab, but it does not change anything. The msgs are the same, just the port number changes.

For me this is quite funny, but I cannot fix it. Already tried changing the ports, I reinstalled IIS, restarting Visual Studio and PC. Nothing is running on the ports that I want to use.

I am using Windows 8.1 x64, Visual Studio 2012 (IIS 8).

EDIT

There is a log msg in IIS:

Failed to register URL "http://localhost:53234/" for site "WcfService1" application "/". Error description: Cannot create a file when that file already exists. (0x800700b7)
Registration completed


问:
Use Perl to select multiple query output data from SQL database and place into single Excel sheet
I am new to Perl so I'm hoping someone can help me with this,

I'm working on a special validation project where we extract data from database and show as an report in a excel. I have a Perl script to extract data from database and place into excel. But i tried to exact data from multiple query and to display the multiple output in a single excel sheet.

How do i return multiple query output in a single excel sheet?

```<code>use strict;
use DBI;
use Excel::Writer::XLSX;

# connect to the db
my $dbh = DBI->connect('dbi:ODBC:dbname', 'dblogin', 'dbpassword');

my $sth1 = $dbh->selectall_arrayref(" select col1, col2 from table");

foreach my $ln (@$sth1) {
  my($col1, $col2) = @$ln;
  print "$col1 $col2\n";
}

my $workbook = Excel::Writer::XLSX->new( 'col1col2test.xlsx' );
my $worksheet = $workbook->add_worksheet();
$worksheet->write( "A1", "$col1" );
$worksheet->write( "A2", "$col2" );
</code>```

答:
If that is your code, then it will be throwing errors complaining about $col1 and $col2 needing an "explicit package name".

This means that you haven't declared the variables correctly. You declare variables using the keyword my. But my declares the variables within a block of code. So when you write this:

```<code>foreach my $ln (@$sth1) {
  my($col1, $col2) = @$ln;
  print "$col1 $col2\n";
}
</code>```

the variables are only declared within that block. And when you try to use them outside the block:

```<code>$worksheet->write( "A1", "$col1" );
$worksheet->write( "A2", "$col2" );
</code>```

You will get the error I mentioned above.

The fix for this is to declare the variables at the correct level - that is outside of the loop.

```<code>my ($col1, $col2);
foreach my $ln (@$sth1) {
  ($col1, $col2) = @$ln;
  print "$col1 $col2\n";
}
</code>```

For future reference, when asking for help on a site like this it's really useful if you give us all the useful information - particularly any error messages that you see.

Body:
I am new to Perl so I'm hoping someone can help me with this,

I'm working on a special validation project where we extract data from database and show as an report in a excel. I have a Perl script to extract data from database and place into excel. But i tried to exact data from multiple query and to display the multiple output in a single excel sheet.

How do i return multiple query output in a single excel sheet?

use strict;
use DBI;
use Excel::Writer::XLSX;

# connect to the db
my $dbh = DBI->connect('dbi:ODBC:dbname', 'dblogin', 'dbpassword');

my $sth1 = $dbh->selectall_arrayref(" select col1, col2 from table");

foreach my $ln (@$sth1) {
  my($col1, $col2) = @$ln;
  print "$col1 $col2\n";
}

my $workbook = Excel::Writer::XLSX->new( 'col1col2test.xlsx' );
my $worksheet = $workbook->add_worksheet();
$worksheet->write( "A1", "$col1" );
$worksheet->write( "A2", "$col2" );

Body:
If that is your code, then it will be throwing errors complaining about $col1 and $col2 needing an "explicit package name".

This means that you haven't declared the variables correctly. You declare variables using the keyword my. But my declares the variables within a block of code. So when you write this:

foreach my $ln (@$sth1) {
  my($col1, $col2) = @$ln;
  print "$col1 $col2\n";
}

the variables are only declared within that block. And when you try to use them outside the block:

$worksheet->write( "A1", "$col1" );
$worksheet->write( "A2", "$col2" );

You will get the error I mentioned above.

The fix for this is to declare the variables at the correct level - that is outside of the loop.

my ($col1, $col2);
foreach my $ln (@$sth1) {
  ($col1, $col2) = @$ln;
  print "$col1 $col2\n";
}

For future reference, when asking for help on a site like this it's really useful if you give us all the useful information - particularly any error messages that you see.


问:
Have fixed parameters in Java constructor - possible?
I've defined an object in Java - as far as the Java is concerned, they're the same thing, but as far as the data which populates them is concerned, they can be one of three types (wildly named 1,2,3 with 0 for the "root").

What I'd really like to be able to do is have four constructors defined, as they need slightly different params for each type. I could do it with strategic nulls, but it seems like the wrong thing to do. What I'd love to have is something like:

```<code>public MenuNode(int type = 1, param1, param2, param3) {
    doStuffHere();
}
public MenuNode(int type = 2, paramX, paramY) {
    doStuffHere();
}
</code>```

and then call something along the lines of:

```<code>switch (toQueue.itemType) {

    when ITEM_TYPE_STATIC {
        MenuNode mn1 = new MenuNode(ITEM_TYPE_STATIC, param1, param2, param3);
    }

    when ITEM_TYPE_DYNAMIC {
        MenuNode mn2 = new MenuNode(ITEM_TYPE_DYNAMIC, paramX, paramY);
    }

}
</code>```

etc etc.

I hope this makes some sort of sense - it's a bit out there, and Googling only comes up with references to public static void etc.
If someone with a bit more experience/know-how with Java than me can take a look, eternal love and gratitude will be forthcoming.

答:
You are probably looking for method overloading

I don't see why you need to add the type to the call -> if you call it with X parameters, that you know what type it should be., right?

Body:
I've defined an object in Java - as far as the Java is concerned, they're the same thing, but as far as the data which populates them is concerned, they can be one of three types (wildly named 1,2,3 with 0 for the "root").

What I'd really like to be able to do is have four constructors defined, as they need slightly different params for each type. I could do it with strategic nulls, but it seems like the wrong thing to do. What I'd love to have is something like:

public MenuNode(int type = 1, param1, param2, param3) {
    doStuffHere();
}
public MenuNode(int type = 2, paramX, paramY) {
    doStuffHere();
}

and then call something along the lines of:

switch (toQueue.itemType) {

    when ITEM_TYPE_STATIC {
        MenuNode mn1 = new MenuNode(ITEM_TYPE_STATIC, param1, param2, param3);
    }

    when ITEM_TYPE_DYNAMIC {
        MenuNode mn2 = new MenuNode(ITEM_TYPE_DYNAMIC, paramX, paramY);
    }

}

etc etc.

I hope this makes some sort of sense - it's a bit out there, and Googling only comes up with references to public static void etc.
If someone with a bit more experience/know-how with Java than me can take a look, eternal love and gratitude will be forthcoming.


问:
GCP Autoscale Down Protection
So I have a set of long running tasks that have to be run on Compute Engine and have to scale. Each task takes approximately 3 hours. So in order to handle this I thought about using:

https://cloud.google.com/solutions/using-cloud-pub-sub-long-running-tasks

Architecture. And while it works fine there is one huge problem. On scale down, I'd really like to avoid it scaling down a task that is currently running! I'd potentially lose 3 hours worth of processing.

Is there a way to ensure that autoscale down doesn't scale down a VM with a long running / uptime?

EDIT: A few people have asked to elaborate my task. So it's similar to what's described in the link above which is many long running tasks that need to be run on a GPU. There is a chunk of data that needs to be processed. It takes 4 hours (video encoding) then once completed it outputs to a bucket. Well it can take anywhere from 1 to 6 hours depending on the length of the video. Just like the architecture above it would be nice to have the cluster scale up based on queue size. But when scaling down I'd like to ensure that it's not scaling down currently running tasks which is what is currently happening. It being GPU bound doesn't allow me to use the CPU metric.

答: I think you should probably add more details about what kind of task you are running. However, as @Jhon Hanley suggestion, it worth to take a look of Cloud Tasks and see as well the following documentation that talks about the scaling risks.</p>

Title: GCP Autoscale Down Protection