问:
When one of the p tag is not empty, hide other p tag
I am having the structure like this JSFiddle.

What I want to do is that: When the class ("discount") is not empty, the other 3 p tags will be hidden. When the class ("discount") is empty, the other 3 p tags will be shown.

I have been trying

```<code>if($('.discount).is(':not("empty)'))
</code>```

or

```<code>.discount.innerHTML.length != 0
</code>```

But all are not working. Can anyone give me some solution of it?

答:
Can do this as follows:

$('.discount').not(':empty').parent().siblings().hide()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>Info 1</h4>
<div class="information">
  <p class="s">
    <em class="discount">DISCOUNT PROMOTION</em>
  </p>
  <p class="s">
    Title
  </p>
  <p class="s">
    Name
  </p>
  <p class="s">
    Detail
  </p>

</div>

<h4>Info 2</h4>
<div class="information">
  <p class="s">
    <em class="discount"></em>
  </p>
  <p class="s">
    Title
  </p>
  <p class="s">
    Name
  </p>
  <p class="s">
    Detail
  </p>

</div>

<h4>Info 3</h4>
<div class="information">
  <p class="s">
    <em class="discount">DISCOUNT PROMOTION</em>
  </p>
  <p class="s">
    Title
  </p>
  <p class="s">
    Name
  </p>
  <p class="s">
    Detail
  </p>

</div></code>```

Body:
I am having the structure like this JSFiddle.

What I want to do is that: When the class ("discount") is not empty, the other 3 p tags will be hidden. When the class ("discount") is empty, the other 3 p tags will be shown.

I have been trying

if($('.discount).is(':not("empty)'))

or

.discount.innerHTML.length != 0

But all are not working. Can anyone give me some solution of it?

Body:
Can do this as follows:

$('.discount').not(':empty').parent().siblings().hide()

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>Info 1</h4>
<div class="information">
  <p class="s">
    <em class="discount">DISCOUNT PROMOTION</em>
  </p>
  <p class="s">
    Title
  </p>
  <p class="s">
    Name
  </p>
  <p class="s">
    Detail
  </p>

</div>

<h4>Info 2</h4>
<div class="information">
  <p class="s">
    <em class="discount"></em>
  </p>
  <p class="s">
    Title
  </p>
  <p class="s">
    Name
  </p>
  <p class="s">
    Detail
  </p>

</div>

<h4>Info 3</h4>
<div class="information">
  <p class="s">
    <em class="discount">DISCOUNT PROMOTION</em>
  </p>
  <p class="s">
    Title
  </p>
  <p class="s">
    Name
  </p>
  <p class="s">
    Detail
  </p>

</div>


来源: stackexchange

问:
when I click on Browse &;80(http) i got this screen

when I clicked on Browse *;80(http) I got this screen in IIS..what could wrong? please give me solution.

答:
Try installing the ASP.Net Frameworks.

Also check whether you have configured web config file in a proper manner.

All frameworks are very important as far as the configuration goes.

Hope this helps!!

ContentLicense: CC BY-SA 2.5


问:
Theory of automata prerequisites
I'm interested in automata theory to improve my understanding of programming and compiler design (I would like to create some simple syntax's in my own projects , for example; L-Systems, AI, neural net structures and intelligent object-object conversation 'AI dialog') but there are things I need to learn before I go forward.

There are a lot of new symbols and mathematical concepts I need to learn before studying automata theory, I could not copy and paste examples because of the symbols and
I don't have the required reputation to post an image so hears a link to a wiki article.

Context-free grammar article on Wikipedia

Under the heading "Proper CFGs" you can see some definitions. I don't understand them.
Could someone please tell me what this notation is called so I can Google it. Any other pointers or information would also be helpful but just knowing a few key words will help. Also if anyone knows of a comprehensive resource that can be accessed for free e.g, an IIT Video lecture on the subject of that notation I would be eternally grateful as I
can't afford tutoring or even text books at this time.

The resource I'm using at the moment for automata theory(for anyone who is interested) is Theory of Automata IIT Lectures on YouTube.

答:
The symbols ∀ and ∃ are logical quantifiers, respectively meaning "for all" and "there exists".

Typically you are first introduced to them in a discrete mathematics course, though they're a part of predicate logic (also known as first-order logic); in my particular university's CS program, Discrete Math is a pre-requisite for Logic for Computer Science, which in turn is a pre-requisite for Formal Languages and Automata.

The star * symbol in the term (V union Sigma)* there is studied in formal languages/automata theory itself: it is the Kleene star operator. Its input is an alphabet (a set of symbols), and it produces the set of all strings of zero or more symbols over that alphabet.

A useful tool for studying formal languages and automata is JFLAP.

ContentLicense: CC BY-SA 3.0

Title: Theory of automata prerequisites


问:
Disable Unnecessary escape character: \/ no-useless-escape
I have this regex of mine that will check the string if it contains link or url (i.e. https://eslint.org/docs/rules/no-useless-escape). Using this regex /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, I've encountered and error while running my test cases in react about Unnecessary escape character: \/                    no-useless-escape. How to disable this eslint-error in order for me to proceed with my test case and use the regex.

Appreciate for any help!

答:
It's the \/ in [-A-Z0-9+&@#\/%?=~_|!:,.;] and [-A-Z0-9+&@#\/%=~_|] (NOT the ones in :\/\/). Most characters do not have to be escaped within a character class (square brackets). This should be equivalent: /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/ig
See https://www.regular-expressions.info/charclass.html for more info, but the relevant part:

In most regex flavors, the only special characters or metacharacters
inside a character class are the closing bracket ], the backslash ,
the caret ^, and the hyphen -. The usual metacharacters are normal
characters inside a character class, and do not need to be escaped by
a backslash. To search for a star or plus, use [+*]. Your regex will
work fine if you escape the regular metacharacters inside a character
class, but doing so significantly reduces readability.

ContentLicense: CC BY-SA 4.0


问:
Programmatically prevent Windows screensaver from starting
Is there a recommended way to prevent the Windows screensaver from starting?  The closest thing I've found is this article, but what I would really like to do is just tell Windows that the computer isn't idle rather than fooling with the currently set screensaver values.</p>

答: Subtle. The official way to tell Windows that the system is not idle is SetThreadExecutionState. This resets the idle timer, (or turns it off, if you pass ES_CONTINUOUS ). However, even though SetThreadExecutionState resets the idle timer, it does not stop the screensaver!

OwnerDisplayName: Michael Kelley

LastEditorDisplayName: gkrogers

OwnerDisplayName: MSalters


问:
Incomplete html attribute when using rvest
I'm using rvest to scrape from https://www.psychologytoday.com/ca/therapists/m5g ; in particular what I'm after is the  data-myurl  html attribute in the  div  tag with  id="results-page" . If you view source you'll see there's only one  div  with  id="results-page" . The  data-myurl  attribute looks like the main URL except with the addition of a string of numbers separated by a period and underscore, like so

```<code><div id="results-page" data-myurl="https://www.psychologytoday.com/ca/therapists/m5g?sid=1510588046.3852_2969">
</code>```

The numbers you see will likely be different. To try and extract it, I use the following code:

```<code>require(rvest)
fsa <- read_html('https://www.psychologytoday.com/ca/therapists/m5g')
fsa %>% html_node('div #results-page') %>% html_attr("data-myurl")
</code>```

However, this returns only

```<code>[1] "https://www.psychologytoday.com/ca/therapists/m5g"
</code>```

So everything after the original URL is missing. It doesn't seem like a JS thing since I don't see any  script  tags when I view source. Does anyone know what these numbers in the URL actually are and how to extract them? Thanks!

答:
You can't do this with rvest.

The page you're trying to scrape is dynamically rendered after loading the initial page. The content itself is always the same, but the sid numbers change the ordering of the results after loading the page. The sid changes on every visit and page reload.

I suspect this was done to avoid a market bias when searching for a therapist.

If you really want the sid number, you need to use a tool that handles dynamic pages like casperjs.
(http://casperjs.org/)

Edit:

Alternatively, if it has to be done in R then you can use RSelenium.  (https://cran.r-project.org/web/packages/RSelenium/)

The relevant starting point would be here:
https://cran.r-project.org/web/packages/RSelenium/vignettes/RSelenium-headless.html

Body:
I'm using rvest to scrape from https://www.psychologytoday.com/ca/therapists/m5g ; in particular what I'm after is the  data-myurl  html attribute in the  div  tag with  id="results-page" . If you view source you'll see there's only one  div  with  id="results-page" . The  data-myurl  attribute looks like the main URL except with the addition of a string of numbers separated by a period and underscore, like so

The numbers you see will likely be different. To try and extract it, I use the following code:

require(rvest)
fsa <- read_html('https://www.psychologytoday.com/ca/therapists/m5g')
fsa %>% html_node('div #results-page') %>% html_attr("data-myurl")

However, this returns only

[1] "https://www.psychologytoday.com/ca/therapists/m5g"

So everything after the original URL is missing. It doesn't seem like a JS thing since I don't see any  script  tags when I view source. Does anyone know what these numbers in the URL actually are and how to extract them? Thanks!


问:
What does Sync Do in Team Explorer?
I am currently in a project that uses TFS Git as the code repository. In Visual Studio, under Team Explorer -> Sync, there is an option called Sync. Now I am familiar with the Fetch, Pull, and Push actions but Sync is new to me.

Any ideas what this does behind the scenes?

答:
Git in Visual Studio, VSTS, and TFS is standard Git.  Although Sync isn’t a Git command, some GUI environments provide a sync button to both update your local files and push your local changes to your remote (your hosted repository).

The Sync button is available on the Team Explorer pane and and
  also displayed after you create a commit using the extension. The
  sync tool enables you to select how you want to update the project:

sync: performs a git pull and a git push.

fetch: performs a git fetch which retrieves any commits on from your remote without merging them.

pull: performs a git pull.

push: performs a git push.

You can also navigate to the Synchronization view from the Changes view by choosing Sync immediately after making a commit.

Title: What does Sync Do in Team Explorer?


问:
Is it possible to set `var` as const in imagej-macro?
Can anyone show me how to secure the value of variable in imagej macro script?

In general, there is a key word, such as const, to ensure the variable unchangable in most of programming language, but in imagej macro this optional keyword cannot be identified.

答: The ImageJ macro language does not support constants. Use one of the other supported scripting languages instead.</p>


问:
exclude headers on different path
I am running haproxy 1.6.3 and I have the X-Frame-Origin headers set on the frontent. I just come across the situation when the site is loaded in a iframe and the content is blocked because of that header. I have tried to setting an acl rule which looks as the following:

```<code>acl is_embeded path_beg /?embeded=1
http-response set-header x-frame-options "SAMEORIGIN" if !is_embeded
</code>```

when I run haproxy -f /etc/haproxy/haproxy.conf -c I for the following error:

```<code>[WARNING] 316/145915 (23701) : parsing [/etc/haproxy/haproxy.cfg:42] : acl 'is_embeded' will never match because it only involves keywords that are incompatible with 'frontend http-response header rule'
</code>```

Is there a way to get this work?

答:
There are actually two problems with what you are doing.

First, the path fetch is only available during request processing -- not response processing.  This is the reason for the warning.  The path isn't allocated a buffer of its own -- the fetch just extracts it from the pending request buffer whenever it's evaluated, and that pending request buffer is released as soon as the request had been sent to the server.

Second, everything beginning with ? is not part of the path.   That's the query string.

The capture.req.uri is the correct fetch to use, since it includes both the path and the query string, and since a memory buffer is allocated for it, it persists during request processing.

```<code>acl is_embeded capture.req.uri -m beg /?embeded=1
</code>```

capture.req.uri

This extracts the request's URI, which starts at the first slash and ends before the first space in the request (without the host part). Unlike path and url, it can be used in both request and response because it's allocated.

http://cbonte.github.io/haproxy-dconv/1.6/configuration.html#7.3.6-capture.req.uri

Also note the correct spelling for the word embedded.

Title: exclude headers on different path

Body:
I am running haproxy 1.6.3 and I have the X-Frame-Origin headers set on the frontent. I just come across the situation when the site is loaded in a iframe and the content is blocked because of that header. I have tried to setting an acl rule which looks as the following:

acl is_embeded path_beg /?embeded=1
http-response set-header x-frame-options "SAMEORIGIN" if !is_embeded

when I run haproxy -f /etc/haproxy/haproxy.conf -c I for the following error:

[WARNING] 316/145915 (23701) : parsing [/etc/haproxy/haproxy.cfg:42] : acl 'is_embeded' will never match because it only involves keywords that are incompatible with 'frontend http-response header rule'

Is there a way to get this work?

Body:
There are actually two problems with what you are doing.

First, the path fetch is only available during request processing -- not response processing.  This is the reason for the warning.  The path isn't allocated a buffer of its own -- the fetch just extracts it from the pending request buffer whenever it's evaluated, and that pending request buffer is released as soon as the request had been sent to the server.

Second, everything beginning with ? is not part of the path.   That's the query string.

The capture.req.uri is the correct fetch to use, since it includes both the path and the query string, and since a memory buffer is allocated for it, it persists during request processing.

acl is_embeded capture.req.uri -m beg /?embeded=1

capture.req.uri

This extracts the request's URI, which starts at the first slash and ends before the first space in the request (without the host part). Unlike path and url, it can be used in both request and response because it's allocated.

http://cbonte.github.io/haproxy-dconv/1.6/configuration.html#7.3.6-capture.req.uri

Also note the correct spelling for the word embedded.


问:
Java importing .class files
I've been given two .class files. Using Netbeans, I created a folder in my src to import my classes.

Once I've got my classes in the right directory I add my class folder to the project sources:

-Project.

-Properties.

-Sources.

-Add folder.

-Class folder.

Then confirmed all sources are up to date:

-> Source

-> Scan for external changes

I then construct a new instance of the class in my source code, but am given an error message: "cannot find symbol"

I've successfully Imported the .class files in Eclipse but I don't like the Eclipse UI and would like to stick with Netbeans.

答:
The easiest way to do this with Netbeans is to create a class library and then compile it as a jar so that your other project knows how to use it. Once done you can add then add that jar to your project without issue like you would with any other library.

Step 1: In netbeans create a new Java Class Library project.

Step 2: Drag and drop the .class files into your new class library in netbeans, or drop them into the src folder and reload the project.

Step 3: Compile the class library project so that it packages it as a .jar file.

Step 4: Drag the complied jar file into your existing netbeans project, or add it as a library.

Done: You can now use the packaged/complied class files like any normal jar you have imported into your project.

See here for an example I found with some screen shots:
http://featurenotbug.com/2009/06/adding-a-class-file-to-your-java-project/

Title: Java importing .class files


问:
How secure is Wordpress?
Does anyone know how secure Wordpress is?
I have no clue how to define "how secure". But compared to other CMS systems, how secure is it?

Update:

To elaborate a bit on my project.
I'm gonna have a lot of users registering. Once logged in, they will have access to plugins which I'm developing. In about 6 months I will also offer paid services - I'm thinking PayPal. All sensitive details will be handled on PayPals https.

Update2:

(15.07.2013)

I found this article over at MOZ: The Definitive Guide to WordPress Security

答:
You must use security plugins to secure your WP site. There are many of plugins available. I have mentioned best 5 free plugins in my article here -

http://www.technolizers.com/5-best-wordpress-security-plugins/

Attackers first check for wp-login.php URL. You must hide regular login URL to something different. You can use wps hide login plugin for that.

Never use username like admin, demo, admin123, demo123, abc. These are most commonly used usernames.

Use strong password. You can generate strong password on this site absolutely free. https://passwordsgenerator.net/

Never ever use free themes or. Free themes contains vulnerable scripts to enter into WP admin without knowing you.

Always update all the plugins and themes up to date as they continuously updates security patches.

Title: How secure is Wordpress?


问:
How to remove top margin BODY
I got this set up

```<code>.image-head {
    background-image:url(http://placehold.it/1920x1080);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: top center;
    height: 1000px;
    width: 100%;
    margin: 0;
    padding: 0;
    color: black;
    #text-align: center;
}

body {
    margin: 0;
    padding: 0;
}
</code>```

Here is my code in full.

How do I remove the top margin?

答:
There is a margin added by the ul element with class "media_bar".Below is the snapshot.

Set the margin-top:0 in this class

Title: How to remove top margin BODY

Body:
I got this set up

.image-head {
    background-image:url(http://placehold.it/1920x1080);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: top center;
    height: 1000px;
    width: 100%;
    margin: 0;
    padding: 0;
    color: black;
    #text-align: center;
}

body {
    margin: 0;
    padding: 0;
}

Here is my code in full.

How do I remove the top margin?


问:
Why does x^(-1/0) = 0
The expression x^(1/0) results in undefined, and I suppose x^(-1/0) = 1/x^(1/0), but why does this equal 0? What exponent rule is at play here?

I thought (1/0) always returns undefined, so why would there be a difference if this exponent is in the numerator or denominator?

答: FPU rules. 1/0 in floating point results in +INF, and you have -1/0 which results in -INF. Anything to the -INF power is going to be zero.</p>

Title: Why does x^(-1/0) = 0


问:
In Swift fileExistsAtPath(_ path: String, isDirectory isDirectory: UnsafeMutablePointer<ObjCBool>) -> Bool accepts single parameter only
The method fileExistsAtPath() in the example below accept single argument only.

```<code>if fm.fileExistsAtPath(result, isDirectory:&isDir) {
</code>```

The exact error message is: "Extra argument 'isDirectory' in call".

Any idea what's wrong?

答:
You can use the following code as an extension . to check if a directory exists or not in Swift 4.0</p>

```<code>import Foundation

extension FileManager {

    func directoryExists (atPath path: String) -> Bool {
        var directoryExists = ObjCBool.init(false)
        let fileExists = FileManager.default.fileExists(atPath: path, isDirectory: &directoryExists)

        return fileExists && directoryExists.boolValue
    }
}
</code>```

Body:
The method fileExistsAtPath() in the example below accept single argument only.

if fm.fileExistsAtPath(result, isDirectory:&isDir) {

The exact error message is: "Extra argument 'isDirectory' in call".

Any idea what's wrong?

Body:
You can use the following code as an extension . to check if a directory exists or not in Swift 4.0

import Foundation

extension FileManager {

    func directoryExists (atPath path: String) -> Bool {
        var directoryExists = ObjCBool.init(false)
        let fileExists = FileManager.default.fileExists(atPath: path, isDirectory: &directoryExists)

        return fileExists && directoryExists.boolValue
    }
}


问:
Getting an Error when clicking on object
When compiling the code, I am getting an Error on this line: I am using Swift 4.0

```<code>    } as! MKDirectionsHandler)
</code>```

The Error says: Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Can someone please help. The code is listed below:

```<code> @objc func getDirections(sender: AnyObject){
       if let selectedPin = selectedPin {
            let mapItem = MKMapItem(placemark: selectedPin)
            //let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving]
            //mapItem.openInMaps(launchOptions: launchOptions)

            let request = MKDirectionsRequest()
            request.source = MKMapItem.forCurrentLocation()

            request.destination = destination
            request.requestsAlternateRoutes = false

            let directions = MKDirections(request: request)

        directions.calculate(completionHandler: {(response: MKDirectionsResponse!, error: NSError!) in

            if error != nil {
                print("Error \(error)")

            } else {

                //self.displayRout(response)

                var overlays = self.mapView.overlays

                for route in response.routes {

                    self.mapView.add(route.polyline, level: MKOverlayLevel.aboveRoads)

                    for next in route.steps {
                        print(next.instructions)
                    }
                }
            }

            } as! MKDirectionsHandler)
        }

    //***********
    func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer!
    {
        let draw = MKPolylineRenderer(overlay: overlay)
        draw.strokeColor = UIColor.purple
        draw.lineWidth = 3.0
        return draw
    }
    }
</code>```

Also here is the errors I am getting:

```<code>* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
  * frame #0: 0x00000001039d5c74 Map`ViewController.getDirections(sender=0x00007fff5c22e610, self=0x00007ff278553bc0) at ViewController.swift:117
    frame #1: 0x00000001039d6828 Map`@objc ViewController.getDirections(sender:) at ViewController.swift:0
    frame #2: 0x00000001050d1275 UIKit`-[UIApplication sendAction:to:from:forEvent:] + 83
    frame #3: 0x000000010524e4a2 UIKit`-[UIControl sendAction:to:forEvent:] + 67
    frame #4: 0x000000010524e7bf UIKit`-[UIControl _sendActionsForEvents:withEvent:] + 450
    frame #5: 0x000000010524d6ec UIKit`-[UIControl touchesEnded:withEvent:] + 618
    frame #6: 0x00000001056ba1a5 UIKit`_UIGestureEnvironmentSortAndSendDelayedTouches + 5560
    frame #7: 0x00000001056b4045 UIKit`_UIGestureEnvironmentUpdate + 1506
    frame #8: 0x000000010a912d37 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    frame #9: 0x000000010a912c8e CoreFoundation`__CFRunLoopDoObservers + 430
    frame #10: 0x000000010a8f7254 CoreFoundation`__CFRunLoopRun + 1572
    frame #11: 0x000000010a8f69b9 CoreFoundation`CFRunLoopRunSpecific + 409
    frame #12: 0x0000000107e309c6 GraphicsServices`GSEventRunModal + 62
    frame #13: 0x00000001050cf5e8 UIKit`UIApplicationMain + 159
    frame #14: 0x00000001039dac77 Map`main at AppDelegate.swift:12
    frame #15: 0x000000010d79cd81 libdyld.dylib`start + 1
    frame #16: 0x000000010d79cd81 libdyld.dylib`start + 1
</code>```

答:
You have several syntax issues in your code.

Change this line:

```<code>    directions.calculate(completionHandler: {(response: MKDirectionsResponse!, error: NSError!) in
</code>```

to:

```<code>    directions.calculate(completionHandler: {(response, error) in
</code>```

And note that error is an Error, not an NSError.

Then get rid of the as! MKDirectionsHandler. There's no reason to cast the completion handler.

```<code>    directions.calculate(completionHandler: { (response, error) in
        if error != nil {
            print("Error \(error)")
        } else {
            //self.displayRout(response)

            var overlays = self.mapView.overlays

            for route in response.routes {
                self.mapView.add(route.polyline, level: MKOverlayLevel.aboveRoads)

                for next in route.steps {
                    print(next.instructions)
                }
            }
        }
    })
</code>```

Body:
When compiling the code, I am getting an Error on this line: I am using Swift 4.0

    } as! MKDirectionsHandler)

The Error says: Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Can someone please help. The code is listed below:

 @objc func getDirections(sender: AnyObject){
       if let selectedPin = selectedPin {
            let mapItem = MKMapItem(placemark: selectedPin)
            //let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving]
            //mapItem.openInMaps(launchOptions: launchOptions)

            let request = MKDirectionsRequest()
            request.source = MKMapItem.forCurrentLocation()

            request.destination = destination
            request.requestsAlternateRoutes = false

            let directions = MKDirections(request: request)

        directions.calculate(completionHandler: {(response: MKDirectionsResponse!, error: NSError!) in

            if error != nil {
                print("Error \(error)")

            } else {

                //self.displayRout(response)

                var overlays = self.mapView.overlays

                for route in response.routes {

                    self.mapView.add(route.polyline, level: MKOverlayLevel.aboveRoads)

                    for next in route.steps {
                        print(next.instructions)
                    }
                }
            }

            } as! MKDirectionsHandler)
        }

    //***********
    func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer!
    {
        let draw = MKPolylineRenderer(overlay: overlay)
        draw.strokeColor = UIColor.purple
        draw.lineWidth = 3.0
        return draw
    }
    }

Also here is the errors I am getting:

* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
  * frame #0: 0x00000001039d5c74 Map`ViewController.getDirections(sender=0x00007fff5c22e610, self=0x00007ff278553bc0) at ViewController.swift:117
    frame #1: 0x00000001039d6828 Map`@objc ViewController.getDirections(sender:) at ViewController.swift:0
    frame #2: 0x00000001050d1275 UIKit`-[UIApplication sendAction:to:from:forEvent:] + 83
    frame #3: 0x000000010524e4a2 UIKit`-[UIControl sendAction:to:forEvent:] + 67
    frame #4: 0x000000010524e7bf UIKit`-[UIControl _sendActionsForEvents:withEvent:] + 450
    frame #5: 0x000000010524d6ec UIKit`-[UIControl touchesEnded:withEvent:] + 618
    frame #6: 0x00000001056ba1a5 UIKit`_UIGestureEnvironmentSortAndSendDelayedTouches + 5560
    frame #7: 0x00000001056b4045 UIKit`_UIGestureEnvironmentUpdate + 1506
    frame #8: 0x000000010a912d37 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    frame #9: 0x000000010a912c8e CoreFoundation`__CFRunLoopDoObservers + 430
    frame #10: 0x000000010a8f7254 CoreFoundation`__CFRunLoopRun + 1572
    frame #11: 0x000000010a8f69b9 CoreFoundation`CFRunLoopRunSpecific + 409
    frame #12: 0x0000000107e309c6 GraphicsServices`GSEventRunModal + 62
    frame #13: 0x00000001050cf5e8 UIKit`UIApplicationMain + 159
    frame #14: 0x00000001039dac77 Map`main at AppDelegate.swift:12
    frame #15: 0x000000010d79cd81 libdyld.dylib`start + 1
    frame #16: 0x000000010d79cd81 libdyld.dylib`start + 1

Body:
You have several syntax issues in your code.

Change this line:

    directions.calculate(completionHandler: {(response: MKDirectionsResponse!, error: NSError!) in

to:

    directions.calculate(completionHandler: {(response, error) in

And note that error is an Error, not an NSError.

Then get rid of the as! MKDirectionsHandler. There's no reason to cast the completion handler.

    directions.calculate(completionHandler: { (response, error) in
        if error != nil {
            print("Error \(error)")
        } else {
            //self.displayRout(response)

            var overlays = self.mapView.overlays

            for route in response.routes {
                self.mapView.add(route.polyline, level: MKOverlayLevel.aboveRoads)

                for next in route.steps {
                    print(next.instructions)
                }
            }
        }
    })


问:
port networkx graph to graphviz without pygraphviz
I am working in Python 3 on a windows machine and despite many efforts have not been able to get pygraphviz installed. Separate discussion.

I have networkx and graphviz modules...Is there a paradigm for building network graphs in networkx and extracting to a graphviz format for display that does not use pygraphviz?

It seems all the relevant functionality in drawing.nx_agraph and nx_agraph requires pygraphviz but I have gotten accustomed to using networkx and like the functionality therein. In the documentation for networkx it even says they are focusing on the development of graph objects and not on the actual display.

答:
You can use pydot (https://pypi.python.org/pypi/pydot) as a pure Python alternative to PyGraphviz</p>

```<code>In [1]: import networkx

In [2]: import sys

In [3]: G = networkx.path_graph(4)

In [4]: networkx.drawing.nx_pydot.write_dot(G,sys.stdout)
strict graph  {
0;
1;
2;
3;
0 -- 1;
1 -- 2;
2 -- 3;
}
</code>```

Body:
You can use pydot (https://pypi.python.org/pypi/pydot) as a pure Python alternative to PyGraphviz

In [1]: import networkx

In [2]: import sys

In [3]: G = networkx.path_graph(4)

In [4]: networkx.drawing.nx_pydot.write_dot(G,sys.stdout)
strict graph  {
0;
1;
2;
3;
0 -- 1;
1 -- 2;
2 -- 3;
}


问:
Why does the caliburn.Micro explanation not work?
I am working from the caliburn.micro website and they have this example. Why is password returning null?! See here the picture of the example I am trying to work with.

My view.xaml:

```<code><StackPanel>
    <TextBox x:Name="Username" />
    <PasswordBox x:Name="Password" />
    <Button x:Name="Login" Content="Log in" />
</StackPanel>
</code>```

And in viewModel.cs:

```<code>public void Login(string username, string password){
    MessageBox.show(password + " " + username)
}
</code>```

I have managed to get the login button to fire the Login method and it shows the username but blank for the password.

答:
The example works on some of the supported platforms, specifically Silverlight, Windows Phone and UWP.

On WPF however PasswordBox doesn't expose a dependency property for the entered password the framework can't bind the method input to the control.

One approach would be to create your own attached property that exposes the entered password from the control.

You can then customize the PasswordBox convention to use your new property.

Now that newer versions of Caliburn.Micro will be dropping support for some of these platforms it may be time to revisit the example on the homepage.

Body:
I am working from the caliburn.micro website and they have this example. Why is password returning null?! See here the picture of the example I am trying to work with.

My view.xaml:

<StackPanel>
    <TextBox x:Name="Username" />
    <PasswordBox x:Name="Password" />
    <Button x:Name="Login" Content="Log in" />
</StackPanel>

And in viewModel.cs:

public void Login(string username, string password){
    MessageBox.show(password + " " + username)
}

I have managed to get the login button to fire the Login method and it shows the username but blank for the password.


问:
How to trigger tests related to a particular file on Scala SBT
I'm a JS developer and I'm learning Scala, I'm used to the Jest test framework, in JS, which allows you to watch changed files and run tests for the changed modules.

Is there something similar in Scala?

I know that I can do:

~test to watch all the files and trigger all the tests

~test package/test_class to watch all the files and trigger only the specified test class.

Thanks a lot

答:
I think you're looking for testQuick:

The testQuick task, like testOnly, allows to filter the tests to run to specific tests or wildcards using the same syntax to indicate the filters. In addition to the explicit filter, only the tests that satisfy one of the following conditions are run:

The tests that failed in the previous run

The tests that were not run before

The tests that have one or more transitive dependencies, maybe in a different project, recompiled.

You can use it with ~ and filtering that you already know.


问:
How can I change default home directory for Android studio
My workspace for android studio project is in C:\AndroidStudioProjects.
I try this
Android Studio: Default project directory
but it's not working... plz help me to quickly access projects

As shown in the screenshot, there must be some configuration file to change that.

Looking for some hack. So that when I click the home button and it opens my specified directory.
for windows platform.

答:
Create a project and save like that address:
/home/USER/Projects/AndroidStudio/MyApplication

So, the new future projects will be:
/home/USER/Projects/AndroidStudio.


问:
How do I remove gloss from an iPhone app icon?
Here is a tutorial that tells you how to remove the gloss on an app in xcode.  How can I do this in flash cs5?

If I can't, can I do something to the image in photoshop so that it looks like it has no gloss when the gloss is applied?

答: Set UIPrerenderedIcon to true in your plist. This may not work with older versions of iOS.</p>


问:
FullCalendar Date Text Color Not Changing (Not Event Text)
I am using fullcalendar (version 3.6.2) and have set bootstrap3 as the themeSystem.  Upon user triggers some calculation, I would like to update the calendar.  A certain date would have new background colour (e.g. DarkRed) and the text colour (of the date) needs to be white to be visible.

This is what I did originally:

```<code>$('#calendar').fullCalendar('option', 'dayRender', function (date, cell) {
    if (date.local().isSame(moment(newDate))) {
        cell.css("background-color", "DarkRed");
        cell.css("color", "white");
    }
});
</code>```

"newDate" is the calculated date in Moment.

The background colour changed correctly. However, the text colour does not change to white.

Then I inspected the cell and realised that the date is on another div. It's displayed on fc-content-skeleton.

How do I change CSS color for this?

答:
Got it!  Thanks to a friend who gave some pointers.

As above, we already know the date of the cell to be changed.  We can already change background-color.  To get the correct  in the fc-content-skeleton, we find using [data-date] attribute.

$('td').find("[data-date='" + newDateShort + "']") will give the correct , where newDateShort is the date in yyyy-mm-dd format.

Hence, we change colour of it.

```<code>$('td').find("[data-date='" + newDateShort + "']").css("color", "white");
</code>```

Body:
I am using fullcalendar (version 3.6.2) and have set bootstrap3 as the themeSystem.  Upon user triggers some calculation, I would like to update the calendar.  A certain date would have new background colour (e.g. DarkRed) and the text colour (of the date) needs to be white to be visible.

This is what I did originally:

$('#calendar').fullCalendar('option', 'dayRender', function (date, cell) {
    if (date.local().isSame(moment(newDate))) {
        cell.css("background-color", "DarkRed");
        cell.css("color", "white");
    }
});

"newDate" is the calculated date in Moment.

The background colour changed correctly. However, the text colour does not change to white.

Then I inspected the cell and realised that the date is on another div. It's displayed on fc-content-skeleton.

How do I change CSS color for this?

Body:
Got it!  Thanks to a friend who gave some pointers.

As above, we already know the date of the cell to be changed.  We can already change background-color.  To get the correct <td> in the fc-content-skeleton, we find using [data-date] attribute.

$('td').find("[data-date='" + newDateShort + "']") will give the correct <td>, where newDateShort is the date in yyyy-mm-dd format.

Hence, we change colour of it.

$('td').find("[data-date='" + newDateShort + "']").css("color", "white");


问:
Using Bing Custom Search API with Drupal 7
We are planning to use Hosted UI version of Bing Search and have found it only supports query parameter 'q'. This parameter cannot be used with Drupal as it clashes with Drupal standard parameter which is also 'q'.

Is there anyway we can still use Bing Search Hosted UI without changing Drupal parameter 'q'?

Thanks

答:
Reiterating the correct answer based on the above comments with @user2574948. Just replace YOUR_QUERY, YOUR_KEY, and YOUR_CUSTOMCONFIG and it works.</p>

```<code>$endpoint = 'https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search';
$term = 'YOUR_QUERY';
$headers = "Ocp-Apim-Subscription-Key: YOUR_KEY\r\n";
$options = array ('http' => array (
                      'header' => $headers,
                       'method' => 'GET'));
$context = stream_context_create($options);
$result = file_get_contents($url . "?q=" . urlencode($query) . "&customconfig=YOUR_CUSTOMCONFIG&responseFilter=Webpages&mkt=en-us&safesearch=Moderate", false, $context);
</code>```

Body:
Reiterating the correct answer based on the above comments with @user2574948. Just replace YOUR_QUERY, YOUR_KEY, and YOUR_CUSTOMCONFIG and it works.

$endpoint = 'https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search';
$term = 'YOUR_QUERY';
$headers = "Ocp-Apim-Subscription-Key: YOUR_KEY\r\n";
$options = array ('http' => array (
                      'header' => $headers,
                       'method' => 'GET'));
$context = stream_context_create($options);
$result = file_get_contents($url . "?q=" . urlencode($query) . "&customconfig=YOUR_CUSTOMCONFIG&responseFilter=Webpages&mkt=en-us&safesearch=Moderate", false, $context);


问:
Best way to code this, string to map conversion in Groovy
I have a string like

```<code>def data = "session=234567893egshdjchasd&userId=12345673456&timeOut=1800000"
</code>```

I want to convert it to a map

```<code> ["session", 234567893egshdjchasd]
 ["userId", 12345673456]
 ["timeout", 1800000]
</code>```

This is the current way I am doing it,

```<code> def map = [:]

 data.splitEachLine("&"){

   it.each{ x ->

     def object = x.split("=")
     map.put(object[0], object[1])

   }

 }
</code>```

It works, but is there a more efficient way?

答:
If you are in a grails controller, then this is nice and simple:

```<code>GrailsParameterMap map = new GrailsParameterMap(request)
</code>```

http://grails.org/doc/latest/api/org/codehaus/groovy/grails/web/servlet/mvc/GrailsParameterMap.html

Body:
I have a string like

def data = "session=234567893egshdjchasd&userId=12345673456&timeOut=1800000"

I want to convert it to a map

 ["session", 234567893egshdjchasd]
 ["userId", 12345673456]
 ["timeout", 1800000]

This is the current way I am doing it,

 def map = [:]

 data.splitEachLine("&"){

   it.each{ x ->

     def object = x.split("=")
     map.put(object[0], object[1])

   }

 }

It works, but is there a more efficient way?

Body:
If you are in a grails controller, then this is nice and simple:

GrailsParameterMap map = new GrailsParameterMap(request)

http://grails.org/doc/latest/api/org/codehaus/groovy/grails/web/servlet/mvc/GrailsParameterMap.html


问:
Make the onBackPressed in Fragment
How to change code below of activity to the code in Fragment? This is Android Studio code. My page now is Fragment, I want use this code and i want modified to fragment code. If who know, tell me, thanks. And I also put my current code in fragment and the activity connect with fragment.

Fragment Code:

```<code>public class Tab1Fragment extends Fragment {
Context mContext;

public WebView webView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tab1_fragment, container, false);
     mContext = view.getContext();
    webView = (WebView) view.findViewById(R.id.webview);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webView.setInitialScale(1);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(false);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.loadUrl("https://www.facebook.com/");
    webView.setWebViewClient(new WebViewClient());

    return view;

}
}
</code>```

Activity code:

```<code>public class Schedule extends AppCompatActivity {

private static final String TAG = "Schedule";
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.schedule);
    Log.d(TAG, "onCreate: Starting.");
    initialiseView();
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
    setSupportActionBar(toolbar);
    toolbar.setTitle("SCHEDULE");
    mTitle.setText(toolbar.getTitle());
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    if(getSupportActionBar() !=null){
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    setupViewPager(mViewPager);
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

}
private void setupViewPager(ViewPager viewPager){
    SectionPageAdapter adapter = new SectionPageAdapter(getSupportFragmentManager());
    adapter.addFragment(new Tab1Fragment(), "4 Sept 2018");
    adapter.addFragment(new Tab2Fragment(), "5 Sept 2018");
    adapter.addFragment(new Tab3Fragment(), "6 Sept 2018");
    viewPager.setAdapter(adapter);
}
 private void initialiseView() {

mTab1Fragment = new Tab1Fragment();

FragmentManager mFragmentManager = getSupportFragmentManager();

FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();

mFragmentTransaction.replace(R.id.container, mTab1Fragment, "TAB 1 FRAGMENT");

mFragmentTransaction.commit();

 }

@Override
public void onBackPressed() {

//Toast.makeText(this, "Calling back pressed", Toast.LENGTH_SHORT).show();

if (mTab1Fragment != null) {

    if (mTab1Fragment.webView.canGoBack()) {

        mTab1Fragment.webView.goBack();

    }

} else {

    super.onBackPressed();

}
}
}
</code>```

答:
This is your onCreateView method as per your need

```<code>@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.tab1_fragment, container, false);

    webView = (WebView) view.findViewById(R.id.webview);

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webView.setInitialScale(1);

    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);

    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(false);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.loadUrl("https://www.facebook.com/");
    webView.setWebViewClient(new WebViewClient());

    view.setFocusableInTouchMode(true);
    view.requestFocus();
    view.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int code, KeyEvent keyEvent) {

            if (code == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_UP) {

                //Here is logic to handle back press event

                return true;

            }

            return false;
        }
    });

    return view;
}
</code>```

Update to load previous page inside webview

Your onCreateView is same as you put in question. I made some simple change in Fragment.

Tab1 fragment will be like

```<code>public class Tab1Fragment extends Fragment {

Context mContext;

public WebView webView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.tab1_fragment, container, false);

    mContext = view.getContext();

    webView = (WebView) view.findViewById(R.id.webview);

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webView.setInitialScale(1);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    webView.setScrollbarFadingEnabled(false);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.loadUrl("https://www.facebook.com/");
    webView.setWebViewClient(new WebViewClient());

    return view;
}

}
</code>```

Now your Activity will be

```<code>public class SampleActivity extends AppCompatActivity {

Tab1Fragment mTab1Fragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sample);

    initialiseView();

}

private void initialiseView() {

    mTab1Fragment = new Tab1Fragment();

    FragmentManager mFragmentManager = getSupportFragmentManager();

    FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();

    mFragmentTransaction.replace(R.id.container, mTab1Fragment, "TAB 1 FRAGMENT");

    mFragmentTransaction.commit();

}

@Override
public void onBackPressed() {

    //Toast.makeText(this, "Calling back pressed", Toast.LENGTH_SHORT).show();

    if (mTab1Fragment != null) {

        if (mTab1Fragment.webView.canGoBack()) {

            mTab1Fragment.webView.goBack();

        }

    } else {

        super.onBackPressed();

    }
}
}
</code>```

NOTE: Here I kept webview public just for simplicity. Keep it private and use getter to access it. If you want to use more fragments then add TAG for each fragment and identify which fragment is visible.

Title: Make the onBackPressed in Fragment

Body:
How to change code below of activity to the code in Fragment? This is Android Studio code. My page now is Fragment, I want use this code and i want modified to fragment code. If who know, tell me, thanks. And I also put my current code in fragment and the activity connect with fragment.

Fragment Code:

public class Tab1Fragment extends Fragment {
Context mContext;

public WebView webView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tab1_fragment, container, false);
     mContext = view.getContext();
    webView = (WebView) view.findViewById(R.id.webview);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webView.setInitialScale(1);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(false);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.loadUrl("https://www.facebook.com/");
    webView.setWebViewClient(new WebViewClient());

    return view;

}
}

Activity code:

public class Schedule extends AppCompatActivity {

private static final String TAG = "Schedule";
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.schedule);
    Log.d(TAG, "onCreate: Starting.");
    initialiseView();
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
    setSupportActionBar(toolbar);
    toolbar.setTitle("SCHEDULE");
    mTitle.setText(toolbar.getTitle());
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    if(getSupportActionBar() !=null){
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    setupViewPager(mViewPager);
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

}
private void setupViewPager(ViewPager viewPager){
    SectionPageAdapter adapter = new SectionPageAdapter(getSupportFragmentManager());
    adapter.addFragment(new Tab1Fragment(), "4 Sept 2018");
    adapter.addFragment(new Tab2Fragment(), "5 Sept 2018");
    adapter.addFragment(new Tab3Fragment(), "6 Sept 2018");
    viewPager.setAdapter(adapter);
}
 private void initialiseView() {

mTab1Fragment = new Tab1Fragment();

FragmentManager mFragmentManager = getSupportFragmentManager();

FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();

mFragmentTransaction.replace(R.id.container, mTab1Fragment, "TAB 1 FRAGMENT");

mFragmentTransaction.commit();

 }

@Override
public void onBackPressed() {

//Toast.makeText(this, "Calling back pressed", Toast.LENGTH_SHORT).show();

if (mTab1Fragment != null) {

    if (mTab1Fragment.webView.canGoBack()) {

        mTab1Fragment.webView.goBack();

    }

} else {

    super.onBackPressed();

}
}
}

Body:
This is your onCreateView method as per your need

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.tab1_fragment, container, false);

    webView = (WebView) view.findViewById(R.id.webview);

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webView.setInitialScale(1);

    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);

    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(false);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.loadUrl("https://www.facebook.com/");
    webView.setWebViewClient(new WebViewClient());

    view.setFocusableInTouchMode(true);
    view.requestFocus();
    view.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int code, KeyEvent keyEvent) {

            if (code == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_UP) {

                //Here is logic to handle back press event

                return true;

            }

            return false;
        }
    });

    return view;
}

Update to load previous page inside webview

Your onCreateView is same as you put in question. I made some simple change in Fragment.

Tab1 fragment will be like

public class Tab1Fragment extends Fragment {

Context mContext;

public WebView webView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.tab1_fragment, container, false);

    mContext = view.getContext();

    webView = (WebView) view.findViewById(R.id.webview);

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webView.setInitialScale(1);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    webView.setScrollbarFadingEnabled(false);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.loadUrl("https://www.facebook.com/");
    webView.setWebViewClient(new WebViewClient());

    return view;
}

}

Now your Activity will be

public class SampleActivity extends AppCompatActivity {

Tab1Fragment mTab1Fragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sample);

    initialiseView();

}

private void initialiseView() {

    mTab1Fragment = new Tab1Fragment();

    FragmentManager mFragmentManager = getSupportFragmentManager();

    FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();

    mFragmentTransaction.replace(R.id.container, mTab1Fragment, "TAB 1 FRAGMENT");

    mFragmentTransaction.commit();

}

@Override
public void onBackPressed() {

    //Toast.makeText(this, "Calling back pressed", Toast.LENGTH_SHORT).show();

    if (mTab1Fragment != null) {

        if (mTab1Fragment.webView.canGoBack()) {

            mTab1Fragment.webView.goBack();

        }

    } else {

        super.onBackPressed();

    }
}
}

NOTE: Here I kept webview public just for simplicity. Keep it private and use getter to access it. If you want to use more fragments then add TAG for each fragment and identify which fragment is visible.


问:
Need help displaying min/max values of integers entered by user
I need help with a c++ program that:

"Prompts  users  for  N  integers  and  determines/displays  the  integer
with  the  highest  and  lowest  value  –  use  separate  functions  to  return  the  highest  and lowest value.  N is a random number from 5 to 10 (both inclusive)."

This is what I have so far:

```<code>#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

void randNumGenerator();
void smallestNum(int);
void largestNum(int);

int smallNum;
int largeNum;
int randomNum;
int num[10];

int main()
{
    smallestNum(smallNum);
    largestNum(largeNum);

    system("pause");
    return 0;
}

void randNumGenerator()
{
    srand(time(0));
    randomNum = 5 + (rand() % 10);

    for (int x = 1; x <= randomNum; x++) {
        cout << "Enter an integer: ";
        cin >> num[randomNum];
    }
}

void smallestNum(int smallNum)
{
    randNumGenerator();

    smallNum = num[randomNum];
    for (int i = 0; randomNum <= i; i++)
        if (num[randomNum] < smallNum)
        {
            smallNum = num[randomNum];
        }
    cout << "The smallest integer is: " << smallNum << endl;
}

void largestNum(int largeNum)
{
    randNumGenerator();

    largeNum = num[randomNum];
    for (int i = 0; i <= i; i++)
        if (num[randomNum] > largeNum)
        {
            largeNum = num[randomNum];
        }
    cout << "The largest integer is: " << largeNum << endl;
}
</code>```

But, my code is not working and I can't seem to figure out how to fix it. Any help would be appreciated, thanks!

答:
Try this,

```<code>#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

void randNumGenerator();
void smallestNum();
void largestNum();
void getInput();

int num[11];
int length;

int main(){
  smallestNum();
  largestNum();
  return 0;
}

void randNumGenerator(){
  int from = 5;
  int to = 10;
  srand(time(0));
  length = from + (rand() % (to - from));
}

void getInput(){
  for (int x = 1; x <= length; x++) {
    cout << "Enter the integer num[" << x << "]: ";
    cin >> num[x];
  }
}

void smallestNum(){
  cout << "Finding smallest integer\n";
  randNumGenerator();
  getInput();
  int smallNum = num[1];
  for (int i = 1; i <= length; i++)
    if (num[i] < smallNum)
      smallNum = num[i];
  cout << "The smallest integer is: " << smallNum << endl;
}

void largestNum(){
  cout << "Finding largest integer\n";
  randNumGenerator();
  getInput();
  int largeNum = num[1];
  for (int i = 1; i <= length; i++)
    if (num[i] > largeNum)
      largeNum = num[i];
  cout << "The largest integer is: " << largeNum << endl;
}
</code>```

With above code, I hope you will find your mistakes on your own :)

Body:
I need help with a c++ program that:

"Prompts  users  for  N  integers  and  determines/displays  the  integer
with  the  highest  and  lowest  value  –  use  separate  functions  to  return  the  highest  and lowest value.  N is a random number from 5 to 10 (both inclusive)."

This is what I have so far:

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

void randNumGenerator();
void smallestNum(int);
void largestNum(int);

int smallNum;
int largeNum;
int randomNum;
int num[10];

int main()
{
    smallestNum(smallNum);
    largestNum(largeNum);

    system("pause");
    return 0;
}

void randNumGenerator()
{
    srand(time(0));
    randomNum = 5 + (rand() % 10);

    for (int x = 1; x <= randomNum; x++) {
        cout << "Enter an integer: ";
        cin >> num[randomNum];
    }
}

void smallestNum(int smallNum)
{
    randNumGenerator();

    smallNum = num[randomNum];
    for (int i = 0; randomNum <= i; i++)
        if (num[randomNum] < smallNum)
        {
            smallNum = num[randomNum];
        }
    cout << "The smallest integer is: " << smallNum << endl;
}

void largestNum(int largeNum)
{
    randNumGenerator();

    largeNum = num[randomNum];
    for (int i = 0; i <= i; i++)
        if (num[randomNum] > largeNum)
        {
            largeNum = num[randomNum];
        }
    cout << "The largest integer is: " << largeNum << endl;
}

But, my code is not working and I can't seem to figure out how to fix it. Any help would be appreciated, thanks!

Body:
Try this,

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

void randNumGenerator();
void smallestNum();
void largestNum();
void getInput();

int num[11];
int length;

int main(){
  smallestNum();
  largestNum();
  return 0;
}

void randNumGenerator(){
  int from = 5;
  int to = 10;
  srand(time(0));
  length = from + (rand() % (to - from));
}

void getInput(){
  for (int x = 1; x <= length; x++) {
    cout << "Enter the integer num[" << x << "]: ";
    cin >> num[x];
  }
}

void smallestNum(){
  cout << "Finding smallest integer\n";
  randNumGenerator();
  getInput();
  int smallNum = num[1];
  for (int i = 1; i <= length; i++)
    if (num[i] < smallNum)
      smallNum = num[i];
  cout << "The smallest integer is: " << smallNum << endl;
}

void largestNum(){
  cout << "Finding largest integer\n";
  randNumGenerator();
  getInput();
  int largeNum = num[1];
  for (int i = 1; i <= length; i++)
    if (num[i] > largeNum)
      largeNum = num[i];
  cout << "The largest integer is: " << largeNum << endl;
}

With above code, I hope you will find your mistakes on your own :)


问:
java.lang.ArrayIndexOutOfBoundsException: 1 >= 1
What is happening?
the first time it runs everything goes well but if it is executed a second time it fails even if it meets the for condition:

```<code>private void actualizar_screen(){
        DefaultTableModel tabla = (DefaultTableModel) screen_table.getModel();
        int total_rows = tabla.getRowCount();
        int i=0;
        System.out.println("Total items: "+items);
        System.out.println("Total rows: "+total_rows);
        for(i=0;i<items;i++){
            System.out.println("i = "+i);
            tabla.removeRow(i);
        }
        System.out.println("Removidas "+i+" de items "+items);
}
</code>```

the console shows the following

```<code>Total items: 1
Total rows: 1
i = 0
Removidas 1 de items 1

Total items: 2
Total rows: 2
i = 0
i = 1

java.lang.ArrayIndexOutOfBoundsException: 1 >= 1
</code>```

答:
You have problem in loop to remove:

```<code>Total items: 2 --> items = 2
Total rows: 2 --> tabla.getRowCount() = 2, row index 0, 1 exist
i = 0 --> then remove row index 0, so tabla.getRowCount() = 1 -> row index 0 exist
i = 1 --> then remove row index 1 --> java.lang.ArrayIndexOutOfBoundsException: index >= length
</code>```

To fix your code, just use tabla.removeRow(0); to remove first row.
Or use while loop:

```<code>while(i < items) {
    System.out.println("i = "+ i++);
    tabla.removeRow(0);
}
</code>```

Body:
What is happening?
the first time it runs everything goes well but if it is executed a second time it fails even if it meets the for condition:

private void actualizar_screen(){
        DefaultTableModel tabla = (DefaultTableModel) screen_table.getModel();
        int total_rows = tabla.getRowCount();
        int i=0;
        System.out.println("Total items: "+items);
        System.out.println("Total rows: "+total_rows);
        for(i=0;i<items;i++){
            System.out.println("i = "+i);
            tabla.removeRow(i);
        }
        System.out.println("Removidas "+i+" de items "+items);
}

the console shows the following

Total items: 1
Total rows: 1
i = 0
Removidas 1 de items 1

Total items: 2
Total rows: 2
i = 0
i = 1

java.lang.ArrayIndexOutOfBoundsException: 1 >= 1

Body:
You have problem in loop to remove:

Total items: 2 --> items = 2
Total rows: 2 --> tabla.getRowCount() = 2, row index 0, 1 exist
i = 0 --> then remove row index 0, so tabla.getRowCount() = 1 -> row index 0 exist
i = 1 --> then remove row index 1 --> java.lang.ArrayIndexOutOfBoundsException: index >= length

To fix your code, just use tabla.removeRow(0); to remove first row.
Or use while loop:

while(i < items) {
    System.out.println("i = "+ i++);
    tabla.removeRow(0);
}


问:
Passing JSON objects to jq arguments
Data sample - sample.json (full sample: https://pastebin.com/KFkVmc2M)

```<code>    {
      "ip": 3301234701,
      "_shodan": {
        "options": {
          "referrer": "7ae15507-f5cc-4353-b72e-5cc0b1c34c5e"
        },
      },
      "hash": -1056085507,
      "os": null,
      "title": "WHM Login",
      "opts": {
        "vulns": ["!CVE-2014-0160"],
        "heartbleed": "2017/08/29 09:57:30 196.196.216.13:2087 - SAFE\
        }
      },
      "isp": "Fiber Grid Inc",
      "http": {
        "redirects": [],
        "title": "WHM Login",
        "robots": null,
        "favicon": null,
        "host": "196.196.216.13",
        "html":
}
</code>```

Script using jq which I hoped would work and haven't found a another solution yet.

```<code>   cat sample.json | jq \
   --arg key0   'Host' \
   --arg value0 '.host' \
   --arg key1   'Vulnerability' \
   --arg value1 '.opts.vulns[0]' \
   --arg key2   'ISP' \
   --arg value2 '.isp' \
   '. | .[$key0]= $value0 | .[$key1]=$value1 | .[$key2]=$value2' \
   <<<'{}'
</code>```

The end result I hoped, but not getting:

```<code>{
  "Host": "196.196.216.13",
  "Vulnerability": "!CVE-2014-0160",
  "ISP": "Fiber Grid Inc"
}
</code>```

Right now it just returns the object as a string and I've tried a lot of different ways to approach the problem. I am quite new to working with JSON and jq but based on what I've read so far, the solution might not be as simple as I'm wishing?

Simply put, why isn't the object being returned as a value of the sample.json object and what do I have to do, to make it work?

Thanks!

to: chepner

```<code>{
  "196.196.216.13":[
  "AS63119",
  "Fiber Grid Inc",
  "2017-08-29T06:57:22.546423",
  "!CVE-2014-0160"
],
"196.196.216.14":[
  "AS63119",
  "Fiber Grid Inc",
  "2017-08-29T06:57:22.546423",
  "!CVE-2014-0160"
]
}
</code>```

答:
jq does not support the evaluation of jq expressions in the
way that would be required for your attempt to work.  You could do some
kind of shell interpolation, but it would be better to use JSON paths,
e.g. rather than --arg value0 .host, you could write --arg value0 "host", etc.  In the following, I've used getpath/1.

There is no need to prepend the jq filter with '. |'

Anyway, assuming the JSON contents of the pastebin are in pastebin.json, you could write:

```<code>  jq \
   --arg key0        Host \
   --argjson value0  '["http","host"]' \
   --arg key1        Vulnerability \
   --argjson value1  '["opts", "vulns", 0]' \
   --arg key2        ISP \
   --argjson value2  '["isp"]' \
   '. as $in
    | {}
    | .[$key0] = ($in|getpath($value0))
    | .[$key1] = ($in|getpath($value1))
    | .[$key2] = ($in|getpath($value2))' \
   pastebin.json
</code>```

This would have the result:

```<code>{
  "Host": "196.196.216.13",
  "Vulnerability": "!CVE-2014-0160",
  "ISP": "Fiber Grid Inc"
}
</code>```

Title: Passing JSON objects to jq arguments

Body:
Data sample - sample.json (full sample: https://pastebin.com/KFkVmc2M)

    {
      "ip": 3301234701,
      "_shodan": {
        "options": {
          "referrer": "7ae15507-f5cc-4353-b72e-5cc0b1c34c5e"
        },
      },
      "hash": -1056085507,
      "os": null,
      "title": "WHM Login",
      "opts": {
        "vulns": ["!CVE-2014-0160"],
        "heartbleed": "2017/08/29 09:57:30 196.196.216.13:2087 - SAFE\
        }
      },
      "isp": "Fiber Grid Inc",
      "http": {
        "redirects": [],
        "title": "WHM Login",
        "robots": null,
        "favicon": null,
        "host": "196.196.216.13",
        "html":
}

Script using jq which I hoped would work and haven't found a another solution yet.

   cat sample.json | jq \
   --arg key0   'Host' \
   --arg value0 '.host' \
   --arg key1   'Vulnerability' \
   --arg value1 '.opts.vulns[0]' \
   --arg key2   'ISP' \
   --arg value2 '.isp' \
   '. | .[$key0]= $value0 | .[$key1]=$value1 | .[$key2]=$value2' \
   <<<'{}'

The end result I hoped, but not getting:

{
  "Host": "196.196.216.13",
  "Vulnerability": "!CVE-2014-0160",
  "ISP": "Fiber Grid Inc"
}

Right now it just returns the object as a string and I've tried a lot of different ways to approach the problem. I am quite new to working with JSON and jq but based on what I've read so far, the solution might not be as simple as I'm wishing?

Simply put, why isn't the object being returned as a value of the sample.json object and what do I have to do, to make it work?

Thanks!

to: chepner

{
  "196.196.216.13":[
  "AS63119",
  "Fiber Grid Inc",
  "2017-08-29T06:57:22.546423",
  "!CVE-2014-0160"
],
"196.196.216.14":[
  "AS63119",
  "Fiber Grid Inc",
  "2017-08-29T06:57:22.546423",
  "!CVE-2014-0160"
]
}

Body:
jq does not support the evaluation of jq expressions in the
way that would be required for your attempt to work.  You could do some
kind of shell interpolation, but it would be better to use JSON paths,
e.g. rather than --arg value0 .host, you could write --arg value0 "host", etc.  In the following, I've used getpath/1.

There is no need to prepend the jq filter with '. |'

Anyway, assuming the JSON contents of the pastebin are in pastebin.json, you could write:

  jq \
   --arg key0        Host \
   --argjson value0  '["http","host"]' \
   --arg key1        Vulnerability \
   --argjson value1  '["opts", "vulns", 0]' \
   --arg key2        ISP \
   --argjson value2  '["isp"]' \
   '. as $in
    | {}
    | .[$key0] = ($in|getpath($value0))
    | .[$key1] = ($in|getpath($value1))
    | .[$key2] = ($in|getpath($value2))' \
   pastebin.json

This would have the result:

{
  "Host": "196.196.216.13",
  "Vulnerability": "!CVE-2014-0160",
  "ISP": "Fiber Grid Inc"
}


问:
difference between JSF, RichFaces, PrimeFaces and IceFaces
I am new to jsf and want to know about the clear difference between JSF, Rich-/Prime-/IceFaces.

In JSF we create pages with .jsp extension and write java code in the backing beans.

But how exactly all "faces" are different and related to jsf.

答:
I will just give a general comparison among JSF and other Faces libraries.

JSF: Standard Framework based on component architecture from Oracle. It has Model-View-Controller Architecture. Model(ie: Backing Bean), Controller( ie: JSF Servlet) and View ( ie: JSP, XHTML ). So it can be used with JSP or XHTML.

RichFaces/PrimeFaces/ICEfaces: These all are the external component library for JSF, provide more customized components and additional features. So its better to use any one of these component library with JSF application to make life easier. For example JSF has a <h:dataTable></h:dataTable> component for displaying data in HTML table format. On the other hand Prime Faces Data Table

 provides more features and flexibility over JSF Data Table.

So if anyone wants to customize JSF components and create additional features or additional components, they can just make their own component libraries by extending JSF standard component library or use the existing component library available currently which are RichFaces/PrimeFaces/ICEfaces

Body:
I will just give a general comparison among JSF and other Faces libraries.

JSF: Standard Framework based on component architecture from Oracle. It has Model-View-Controller Architecture. Model(ie: Backing Bean), Controller( ie: JSF Servlet) and View ( ie: JSP, XHTML ). So it can be used with JSP or XHTML.

RichFaces/PrimeFaces/ICEfaces: These all are the external component library for JSF, provide more customized components and additional features. So its better to use any one of these component library with JSF application to make life easier. For example JSF has a <h:dataTable></h:dataTable> component for displaying data in HTML table format. On the other hand Prime Faces Data Table <p:dataTable></P:dataTable> provides more features and flexibility over JSF Data Table.

So if anyone wants to customize JSF components and create additional features or additional components, they can just make their own component libraries by extending JSF standard component library or use the existing component library available currently which are RichFaces/PrimeFaces/ICEfaces


问:
How to change controls simultaneously without repainting each one?
For example I need to disable two buttons in runtime. After I disabled first button it bacame gray, the second - it also became gray. But I do not know how to make the repainting simultaneous!

I need something like that:

freeze the Form (disable repainting)

disable first button

disable second button

Enable Form repainting

How to implement that?

答:
To Elias551:

LockWindowUpdate is probably not the best way to handle this since it is intended for drag and drop operations and can introduce subtle bugs when misused.

See http://blogs.msdn.com/b/oldnewthing/archive/2007/02/22/1742084.aspx

Instead use SendMessage(hwnd, WM_SETREDRAW, FALSE, 0)


问:
When one of the p tag is not empty, hide other p tag
I am having the structure like this JSFiddle.

What I want to do is that: When the class ("discount") is not empty, the other 3 p tags will be hidden. When the class ("discount") is empty, the other 3 p tags will be shown.

I have been trying

```<code>if($('.discount).is(':not("empty)'))
</code>```

or

```<code>.discount.innerHTML.length != 0
</code>```

But all are not working. Can anyone give me some solution of it?

答:
Try with :not() and :has() selector:

```<code>$(function(){

 if($('.discount').text().length != 0)
 {

   $("p:not(:has(>em))").hide();
    }
});
</code>```

Body:
I am having the structure like this JSFiddle.

What I want to do is that: When the class ("discount") is not empty, the other 3 p tags will be hidden. When the class ("discount") is empty, the other 3 p tags will be shown.

I have been trying

if($('.discount).is(':not("empty)'))

or

.discount.innerHTML.length != 0

But all are not working. Can anyone give me some solution of it?

Body:
Try with :not() and :has() selector:

$(function(){

 if($('.discount').text().length != 0)
 {

   $("p:not(:has(>em))").hide();
    }
});


问:
Do zombies exist ... in .NET?
I was having a discussion with a teammate about locking in .NET.  He's a really bright guy with an extensive background in both lower-level and higher-level programming, but his experience with lower level programming far exceeds mine.  Anyway, He argued that .NET locking should be avoided on critical systems expected to be under heavy-load if at all possible in order to avoid the admittedly small possibility of a "zombie thread" crashing a system.  I routinely use locking and I didn't know what a "zombie thread" was, so I asked.  The impression I got from his explanation is that a zombie thread is a thread that has terminated but somehow still holds onto some resources.  An example he gave of how a zombie thread could break a system was a thread begins some procedure after locking on some object, and then is at some point terminated before the lock can be released.  This situation has the potential to crash the system, because eventually, attempts to execute that method will result in the threads all waiting for access to an object that will never be returned, because the thread that is using the locked object is dead.

I think I got the gist of this, but if I'm off base, please let me know.  The concept made sense to me.  I wasn't completely convinced that this was a real scenario that could happen in .NET.  I've never previously heard of "zombies", but I do recognize that programmers who have worked in depth at lower levels tend to have a deeper understanding of computing fundamentals (like threading).  I definitely do see the value in locking, however, and I have seen many world class programmers leverage locking.  I also have limited ability to evaluate this for myself because I know that the lock(obj) statement is really just syntactic sugar for:

```<code>bool lockWasTaken = false;
var temp = obj;
try { Monitor.Enter(temp, ref lockWasTaken); { body } }
finally { if (lockWasTaken) Monitor.Exit(temp); }
</code>```

and because Monitor.Enter and Monitor.Exit are marked extern.  It seems conceivable that .NET does some kind of processing that protects threads from exposure to system components that could have this kind of impact, but that is purely speculative and probably just based on the fact that I've never heard of "zombie threads" before.  So, I'm hoping I can get some feedback on this here:

Is there a clearer definition of a "zombie thread" than what I've explained here?

Can zombie threads occur on .NET?  (Why/Why not?)

If applicable, How could I force the creation of a zombie thread in .NET?

If applicable, How can I leverage locking without risking a zombie thread scenario in .NET?

Update

I asked this question a little over two years ago.  Today this happened:

答:
I can make zombie threads easily enough.

```<code>var zombies = new List<Thread>();
while(true)
{
    var th = new Thread(()=>{});
    th.Start();
    zombies.Add(th);
}
</code>```

This leaks the thread handles (for Join()). It's just another memory leak as far as we are concerned in the managed world.

Now then, killing a thread in a way that it actually holds locks is a pain in the rear but possible. The other guy's ExitThread() does the job. As he found, the file handle got cleaned up by the gc but a lock around an object wouldn't. But why would you do that?

Title: Do zombies exist ... in .NET?

Body:
I was having a discussion with a teammate about locking in .NET.  He's a really bright guy with an extensive background in both lower-level and higher-level programming, but his experience with lower level programming far exceeds mine.  Anyway, He argued that .NET locking should be avoided on critical systems expected to be under heavy-load if at all possible in order to avoid the admittedly small possibility of a "zombie thread" crashing a system.  I routinely use locking and I didn't know what a "zombie thread" was, so I asked.  The impression I got from his explanation is that a zombie thread is a thread that has terminated but somehow still holds onto some resources.  An example he gave of how a zombie thread could break a system was a thread begins some procedure after locking on some object, and then is at some point terminated before the lock can be released.  This situation has the potential to crash the system, because eventually, attempts to execute that method will result in the threads all waiting for access to an object that will never be returned, because the thread that is using the locked object is dead.

I think I got the gist of this, but if I'm off base, please let me know.  The concept made sense to me.  I wasn't completely convinced that this was a real scenario that could happen in .NET.  I've never previously heard of "zombies", but I do recognize that programmers who have worked in depth at lower levels tend to have a deeper understanding of computing fundamentals (like threading).  I definitely do see the value in locking, however, and I have seen many world class programmers leverage locking.  I also have limited ability to evaluate this for myself because I know that the lock(obj) statement is really just syntactic sugar for:

bool lockWasTaken = false;
var temp = obj;
try { Monitor.Enter(temp, ref lockWasTaken); { body } }
finally { if (lockWasTaken) Monitor.Exit(temp); }

and because Monitor.Enter and Monitor.Exit are marked extern.  It seems conceivable that .NET does some kind of processing that protects threads from exposure to system components that could have this kind of impact, but that is purely speculative and probably just based on the fact that I've never heard of "zombie threads" before.  So, I'm hoping I can get some feedback on this here:

Is there a clearer definition of a "zombie thread" than what I've explained here?

Can zombie threads occur on .NET?  (Why/Why not?)

If applicable, How could I force the creation of a zombie thread in .NET?

If applicable, How can I leverage locking without risking a zombie thread scenario in .NET?

Update

I asked this question a little over two years ago.  Today this happened:

Body:
I can make zombie threads easily enough.

var zombies = new List<Thread>();
while(true)
{
    var th = new Thread(()=>{});
    th.Start();
    zombies.Add(th);
}

This leaks the thread handles (for Join()). It's just another memory leak as far as we are concerned in the managed world.

Now then, killing a thread in a way that it actually holds locks is a pain in the rear but possible. The other guy's ExitThread() does the job. As he found, the file handle got cleaned up by the gc but a lock around an object wouldn't. But why would you do that?


问:
How to apply watershed on grayscale image with opencv and python?
Based on a solution that I read at How to define the markers for Watershed in OpenCV?, I am trying apply watershed to grayscale data (not very visible but not all black), extracted from netcdf (precipitation data).

Here is a black and white version of the data (threshold at 0) so that you can see more easily, and the markers I want to use to define the different basins (basically just another threshold where precipitation is more intense).

The code I'm running is as follows:

```<code>import os,sys,string
from netCDF4 import Dataset as nc
import cv2
import numpy as np
import matplotlib.pyplot as mpl
import scipy.ndimage as ndimage
import scipy.spatial as spatial
from skimage import filter
from skimage.morphology import watershed
from scipy import ndimage

filename=["Cmorph-1999_01_03.nc"]

nc_data=nc(filename[0])
data=nc_data.variables["CMORPH"][23,0:250,250:750]
new_data=np.flipud(data)
ma_data=np.ma.masked_where(new_data<=0,new_data)
ma_conv=np.ma.masked_where(new_data<=2,new_data)

## Borders
tmp_data=ma_data.filled(0)
tmp_data[np.where(tmp_data!=0)]=255
bw_data=tmp_data.astype(np.uint8)
border = cv2.dilate(bw_data, None, iterations=5)
border = border - cv2.erode(border, None)

## Markers
tmp_conv=ma_conv.filled(0)
tmp_conv[np.where(tmp_conv!=0)]=255
bw_conv=tmp_conv.astype(np.uint8)
lbl, ncc = ndimage.label(bw_conv)
lbl = lbl * (255/ncc)
lbl[border == 255] = 255
lbl = lbl.astype(np.int32)

## Apply watershed
cv2.watershed(ma_data, lbl)

lbl[lbl == -1] = 0
lbl = lbl.astype(np.uint8)
result = 255 - lbl
</code>```

I have the following error for the watershed in opencv-2.4.11/modules/imgproc/src/segmentation.cpp:

```<code>error: (-210) Only 8-bit, 3-channel input images are supported in function cvWatershed
</code>```

For what I saw on the internet, this is due to the fact that the grayscale data is a 2D image and watershed needs a 3D image (from RGB). Indeed, I tried the script with a jpg image and I worked perfectly.
This problem is mentionned here but the answer given was finally rejected. And I can't find any more recent link answering the question.

To try to solve this, I created a 3D array from the 2D new_data:

```<code>new_data = new_data[..., np.newaxis]
test=np.append(new_data, new_data, axis=2)
test=np.append(new_data, test, axis=2)
</code>```

But, as expected, it didn't solve the problem (same error message).

I also tried to save the plot from matplotlib to get RGB data:

```<code>fig = mpl.figure()
fig.add_subplot(111)
fig.tight_layout(pad=0)
mpl.contourf(ma_data,levels=np.arange(0,255.1,0.1))
fig.canvas.draw()
test_data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
test_data = test_data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
</code>```

But the size of the test_data created is different from ma_data (+ I can't get rid of the labels).

So, I am stuck here. Ideally, I want to apply the watershed on the 2D grayscale image directly and/or limit the number of operations as much as possible.

答:
you can try changing your image fram gray to a BGR color space using

cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)

before passing your image to watershed algorithm

Body:
Based on a solution that I read at How to define the markers for Watershed in OpenCV?, I am trying apply watershed to grayscale data (not very visible but not all black), extracted from netcdf (precipitation data).

Here is a black and white version of the data (threshold at 0) so that you can see more easily, and the markers I want to use to define the different basins (basically just another threshold where precipitation is more intense).

The code I'm running is as follows:

import os,sys,string
from netCDF4 import Dataset as nc
import cv2
import numpy as np
import matplotlib.pyplot as mpl
import scipy.ndimage as ndimage
import scipy.spatial as spatial
from skimage import filter
from skimage.morphology import watershed
from scipy import ndimage

filename=["Cmorph-1999_01_03.nc"]

nc_data=nc(filename[0])
data=nc_data.variables["CMORPH"][23,0:250,250:750]
new_data=np.flipud(data)
ma_data=np.ma.masked_where(new_data<=0,new_data)
ma_conv=np.ma.masked_where(new_data<=2,new_data)

## Borders
tmp_data=ma_data.filled(0)
tmp_data[np.where(tmp_data!=0)]=255
bw_data=tmp_data.astype(np.uint8)
border = cv2.dilate(bw_data, None, iterations=5)
border = border - cv2.erode(border, None)

## Markers
tmp_conv=ma_conv.filled(0)
tmp_conv[np.where(tmp_conv!=0)]=255
bw_conv=tmp_conv.astype(np.uint8)
lbl, ncc = ndimage.label(bw_conv)
lbl = lbl * (255/ncc)
lbl[border == 255] = 255
lbl = lbl.astype(np.int32)

## Apply watershed
cv2.watershed(ma_data, lbl)

lbl[lbl == -1] = 0
lbl = lbl.astype(np.uint8)
result = 255 - lbl

I have the following error for the watershed in opencv-2.4.11/modules/imgproc/src/segmentation.cpp:

error: (-210) Only 8-bit, 3-channel input images are supported in function cvWatershed

For what I saw on the internet, this is due to the fact that the grayscale data is a 2D image and watershed needs a 3D image (from RGB). Indeed, I tried the script with a jpg image and I worked perfectly.
This problem is mentionned here but the answer given was finally rejected. And I can't find any more recent link answering the question.

To try to solve this, I created a 3D array from the 2D new_data:

new_data = new_data[..., np.newaxis]
test=np.append(new_data, new_data, axis=2)
test=np.append(new_data, test, axis=2)

But, as expected, it didn't solve the problem (same error message).

I also tried to save the plot from matplotlib to get RGB data:

fig = mpl.figure()
fig.add_subplot(111)
fig.tight_layout(pad=0)
mpl.contourf(ma_data,levels=np.arange(0,255.1,0.1))
fig.canvas.draw()
test_data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
test_data = test_data.reshape(fig.canvas.get_width_height()[::-1] + (3,))

But the size of the test_data created is different from ma_data (+ I can't get rid of the labels).

So, I am stuck here. Ideally, I want to apply the watershed on the 2D grayscale image directly and/or limit the number of operations as much as possible.


问:
Variable table name in Django
Can I use variable table name for db mapped objects? For example, there are n objects of the same structure and I want to store it in different tables, for raising performance on some operations.

Let's say I've got class defined as:

```<code>class Measurement(models.Model):
    slave_id = models.IntegerField()
    tag = models.CharField(max_length=40)
    value = models.CharField(max_length=16)
    timestamp = models.DateTimeField()

    class Meta:
        db_table = 'measurements'
</code>```

Now all objects are stored into table 'measurements'. I would like to make table name dependant on 'slave_id' value. For example, to handle data from tables 'measurements_00001', 'measurements_00002' etc...

Is it possible to achieve this using Django ORM model or the only solution is to drop to SQL level?

答:
In the vast majority of cases, this shouldn't buy you any performance advantage.  Any RDBMS worth its salt should handle immense tables effortlessly.

If it's needed, there could be some sharding of the table. Again, managed by the DB server; at SQL level (and ORM) it should be seen as a single table.  Ideally, the discrimination should be automatically handled; if not, most RDBMS let you specify it at table definition time (or sometimes tune with ALTER TABLE)

If you choose to define the sharding method, each RDBMS has it's own non-standard methods.  Best not to tie your Python code to that; do the tuning once on the DB server instead.

Title: Variable table name in Django

Body:
Can I use variable table name for db mapped objects? For example, there are n objects of the same structure and I want to store it in different tables, for raising performance on some operations.

Let's say I've got class defined as:

class Measurement(models.Model):
    slave_id = models.IntegerField()
    tag = models.CharField(max_length=40)
    value = models.CharField(max_length=16)
    timestamp = models.DateTimeField()

    class Meta:
        db_table = 'measurements'

Now all objects are stored into table 'measurements'. I would like to make table name dependant on 'slave_id' value. For example, to handle data from tables 'measurements_00001', 'measurements_00002' etc...

Is it possible to achieve this using Django ORM model or the only solution is to drop to SQL level?


问:
Matrix multiplication using vector
I'm trying to multiply matrices. This line A[i][j].emplace_back(i*j);cause this error:

IntelliSense: expression must have class type

What's wrong with this code? I also try push_back() function.

```<code>#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;
using matrix = vector<vector<double>>;

matrix multiple(matrix A, matrix B);
void initialize(matrix& A, matrix& B);

int _tmain(int argc, _TCHAR* argv[])
{
    matrix A;
    matrix B;
    initialize(A, B);
    matrix C = multiple(A, B);
    return 0;
}

matrix multiple(matrix A, matrix B)
{
    matrix C;
    for (int i = 0; i < A.size(); ){
        for (int j = 0; j < B.size(); ){
            for (int k = 0; k < A.size();k++)
                C[i][j] += A[i][k] * B[k][j];
        }
    }
    return C;
}

void initialize(matrix& A, matrix& B)
{
    for (int i = 0; i < A.size(); i++){
        for (int j = 0; j < B.size(); j++){
            A[i][j].emplace_back(i*j);
            B[i][j].emplace_back(i*j);
        }
    }
}
</code>```

答:
Here is a template class so vector can be int or double</p>

```<code>template <class T>
std::vector <std::vector<T>> Multiply(std::vector <std::vector<T>> &a, std::vector <std::vector<T>> &b)
{
    const int n = a.size();     // a rows
    const int m = a[0].size();  // a cols
    const int p = b[0].size();  // b cols

    std::vector <std::vector<T>> c(n, std::vector<T>(p, 0));
    for (auto j = 0; j < p; ++j)
    {
        for (auto k = 0; k < m; ++k)
        {
            for (auto i = 0; i < n; ++i)
            {
                c[i][j] += a[i][k] * b[k][j];
            }
        }
    }
    return c;
}

std::vector <std::vector<double>> a (2, std::vector<double>(2));
a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;
a[1][1] = 4;

std::vector <std::vector<double>> b(2, std::vector<double>(2));
b[0][0] = 5;
b[0][1] = 6;
b[1][0] = 7;
b[1][1] = 8;

auto c = Multiply(a, b);
</code>```

Title: Matrix multiplication using vector

Body:
I'm trying to multiply matrices. This line A[i][j].emplace_back(i*j);cause this error:

IntelliSense: expression must have class type

What's wrong with this code? I also try push_back() function.

#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;
using matrix = vector<vector<double>>;

matrix multiple(matrix A, matrix B);
void initialize(matrix& A, matrix& B);

int _tmain(int argc, _TCHAR* argv[])
{
    matrix A;
    matrix B;
    initialize(A, B);
    matrix C = multiple(A, B);
    return 0;
}

matrix multiple(matrix A, matrix B)
{
    matrix C;
    for (int i = 0; i < A.size(); ){
        for (int j = 0; j < B.size(); ){
            for (int k = 0; k < A.size();k++)
                C[i][j] += A[i][k] * B[k][j];
        }
    }
    return C;
}

void initialize(matrix& A, matrix& B)
{
    for (int i = 0; i < A.size(); i++){
        for (int j = 0; j < B.size(); j++){
            A[i][j].emplace_back(i*j);
            B[i][j].emplace_back(i*j);
        }
    }
}

Body:
Here is a template class so vector can be int or double

template <class T>
std::vector <std::vector<T>> Multiply(std::vector <std::vector<T>> &a, std::vector <std::vector<T>> &b)
{
    const int n = a.size();     // a rows
    const int m = a[0].size();  // a cols
    const int p = b[0].size();  // b cols

    std::vector <std::vector<T>> c(n, std::vector<T>(p, 0));
    for (auto j = 0; j < p; ++j)
    {
        for (auto k = 0; k < m; ++k)
        {
            for (auto i = 0; i < n; ++i)
            {
                c[i][j] += a[i][k] * b[k][j];
            }
        }
    }
    return c;
}

std::vector <std::vector<double>> a (2, std::vector<double>(2));
a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;
a[1][1] = 4;

std::vector <std::vector<double>> b(2, std::vector<double>(2));
b[0][0] = 5;
b[0][1] = 6;
b[1][0] = 7;
b[1][1] = 8;

auto c = Multiply(a, b);


问:
Thymeleaf - enum value cannot be bind
I have a problem with binding value to enum field in thymeleaf

```<code><input type="hidden" th:field="${petDto.rating.finalRating}" th:value="${T(net.azurewebsites.mypet.domain.ratings.Scale).COOL}" />
</code>```

I want to set enum value Scale.Cool to field finalRating which has type Scale.
But in this way its not working. Thymeleaf do not bind value from  th:value to th:field.
Any idea?

答:
th:field and th:value cannot work together in one input. th:field effectively replaces value, id and the name of the input. So your input is equivalent to

```<code><input type="hidden" id="rating.finalRating" name="rating.finalRating" th:value="${petDto.rating.finalRating}" />
</code>```

To achieve what you want, just omit th:field from the input.

Please refer to the documentation of thymeleaf inputs

Title: Thymeleaf - enum value cannot be bind

Body:
I have a problem with binding value to enum field in thymeleaf

<input type="hidden" th:field="${petDto.rating.finalRating}" th:value="${T(net.azurewebsites.mypet.domain.ratings.Scale).COOL}" />

I want to set enum value Scale.Cool to field finalRating which has type Scale.
But in this way its not working. Thymeleaf do not bind value from  th:value to th:field.
Any idea?

Body:
th:field and th:value cannot work together in one input. th:field effectively replaces value, id and the name of the input. So your input is equivalent to

<input type="hidden" id="rating.finalRating" name="rating.finalRating" th:value="${petDto.rating.finalRating}" />

To achieve what you want, just omit th:field from the input.

Please refer to the documentation of thymeleaf inputs