问:
Swift: I am not seeing all bonjour services list if my iphone not hocked to my laptop
I have a scanner class to scan list of all bonjour services available with an option for the user to search for all the devices in a certain bonjour service name.

Everything works great! except when I remove my iphone from the cable then I can't see all the bonjour services.

Any ideas y?

Note: My iphone any my laptop connected via wifi at the same network. But it seems that the iphone detects the bonjour services through my laptop.

here is my Class though I am sure its not about my class implementation.

```<code>class ScannerViewController: UIViewController {

@IBOutlet weak var serviceTextField: UITextField!
@IBOutlet weak var transportLayerTextField: UITextField!
@IBOutlet weak var domainTextField: UITextField!

@IBOutlet weak var tableView: UITableView!

@IBOutlet weak var allBonjourBtn: UIButton!
@IBOutlet weak var searchBtn: UIButton!

let searchForAllString = "_services._dns-sd._udp."

var services = [NetService](){
    didSet{
        self.tableView.reloadData()
    }
}

private lazy var serviceBrowser = NetServiceBrowser()

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.estimatedRowHeight = 150
    self.tableView.rowHeight = UITableViewAutomaticDimension

    self.serviceBrowser.delegate = self
    self.searchBtn.makeCircularEdges()
    self.allBonjourBtn.makeCircularEdges()
}

@IBAction func allBonjourPressed(_ sender: UIButton) {
    self.startBrowsing(all: true)
}

@IBAction func searchPressed(_ sender: UIButton) {
    self.startBrowsing(all: false)
}

func setBrowserObj() -> (serviceName: String, transportLayer: String, domain: String){

    let sName = (self.serviceTextField?.text ?? "").trim
    let tl = (self.transportLayerTextField?.text ?? "").trim

    let text = (self.domainTextField?.text ?? "").trim
    let domain = (text == "" ? text: "\(text).")
    print("\(sName).\(tl).", domain)
    return (serviceName: "_\(sName)", transportLayer: "_\(tl)", domain: "\(domain)")
}

func startBrowsing(all: Bool){
    self.hideKeyboard()
    self.serviceBrowser.stop()
    self.services = []
    let result = self.setBrowserObj()
    self.serviceBrowser.delegate = self
    if all {
        self.serviceBrowser.searchForServices(ofType: searchForAllString, inDomain: "\(result.domain)")
    }else{
        self.serviceBrowser.searchForServices(ofType: "\(result.serviceName).\(result.transportLayer).", inDomain: "\(result.domain)")
    }
}
}

extension ScannerViewController: UITableViewDelegate, UITableViewDataSource {

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.services.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") else{
        return UITableViewCell()
    }

    guard self.services.count > 0 else{
        return cell
    }
    let service = self.services[indexPath.row]
    cell.textLabel?.text = "Name: \(service.name)\nDomain: \(service.domain)\nPort: \(service.port)"
    return cell
}
}

extension ScannerViewController: UITextFieldDelegate {

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    let nextTag = textField.tag + 1
    if let nextTextField = textField.superview?.viewWithTag(nextTag) {
        nextTextField.becomeFirstResponder()
    }else{
        self.hideKeyboard()
    }
    return false
}

func hideKeyboard() {
    self.serviceTextField?.resignFirstResponder()
    self.transportLayerTextField?.resignFirstResponder()
    self.domainTextField?.resignFirstResponder()
}
}

extension ScannerViewController: NetServiceBrowserDelegate, NetServiceDelegate {

func netServiceBrowser(_ browser: NetServiceBrowser, didNotSearch errorDict: [String : NSNumber]) {
    print("Error serching for service")
    print("Errors: \(errorDict.keys)\n")
}

func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) {
    service.delegate = self
    self.services.append(service)
}

func netServiceBrowser(_ browser: NetServiceBrowser, didRemove service: NetService, moreComing: Bool) {
    service.delegate = nil
    self.removeServiceFromList(serviceObj: service)
}

///Removes the service from the current list.
func removeServiceFromList(serviceObj: NetService){
    for (index, sev) in self.services.enumerated() {
        if sev == serviceObj {
            self.services.remove(at: index)
        }
    }
}

}
</code>```

Update:

I am using the command line to check the available bonjour services and I have noticed:

Running dns-sd  -B  _services._dns-sd._udp  local. will list couple of services that I believe is brodcasted from my machine only.

Running dns-sd  -B  _ipp._tcp  local. or dns-sd  -B  _http._tcp  local. will list all things uses the ipp/http services.

The real question why the ipp or http service types did not appear when I used the command dns-sd  -B  _services._dns-sd._udp  local. ??? based on all my readings online everybody saying that this command should list all bonjour services availble and active on the network! But thats not what is happening with me.

Note: I am connected to the network via wifi and I can't use a cable since I do not have an adapter.

Attached a snapshot of the result.

Update 2

Finally I figured it out. I guess the issue was with the wifi network at work that was blocking the list of services. because when I tried it home I was able to see all the bonjour services with no issues.

答:
Finally I was able to figure it out and it was the wifi network at my work who was blocking this. When I tried it at home everything is working as expected.

Thanks for everyone helped me figure this out

Body:
I have a scanner class to scan list of all bonjour services available with an option for the user to search for all the devices in a certain bonjour service name.

Everything works great! except when I remove my iphone from the cable then I can't see all the bonjour services.

Any ideas y?

Note: My iphone any my laptop connected via wifi at the same network. But it seems that the iphone detects the bonjour services through my laptop.

here is my Class though I am sure its not about my class implementation.

class ScannerViewController: UIViewController {

@IBOutlet weak var serviceTextField: UITextField!
@IBOutlet weak var transportLayerTextField: UITextField!
@IBOutlet weak var domainTextField: UITextField!

@IBOutlet weak var tableView: UITableView!

@IBOutlet weak var allBonjourBtn: UIButton!
@IBOutlet weak var searchBtn: UIButton!

let searchForAllString = "_services._dns-sd._udp."

var services = [NetService](){
    didSet{
        self.tableView.reloadData()
    }
}

private lazy var serviceBrowser = NetServiceBrowser()

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.estimatedRowHeight = 150
    self.tableView.rowHeight = UITableViewAutomaticDimension

    self.serviceBrowser.delegate = self
    self.searchBtn.makeCircularEdges()
    self.allBonjourBtn.makeCircularEdges()
}

@IBAction func allBonjourPressed(_ sender: UIButton) {
    self.startBrowsing(all: true)
}

@IBAction func searchPressed(_ sender: UIButton) {
    self.startBrowsing(all: false)
}

func setBrowserObj() -> (serviceName: String, transportLayer: String, domain: String){

    let sName = (self.serviceTextField?.text ?? "").trim
    let tl = (self.transportLayerTextField?.text ?? "").trim

    let text = (self.domainTextField?.text ?? "").trim
    let domain = (text == "" ? text: "\(text).")
    print("\(sName).\(tl).", domain)
    return (serviceName: "_\(sName)", transportLayer: "_\(tl)", domain: "\(domain)")
}

func startBrowsing(all: Bool){
    self.hideKeyboard()
    self.serviceBrowser.stop()
    self.services = []
    let result = self.setBrowserObj()
    self.serviceBrowser.delegate = self
    if all {
        self.serviceBrowser.searchForServices(ofType: searchForAllString, inDomain: "\(result.domain)")
    }else{
        self.serviceBrowser.searchForServices(ofType: "\(result.serviceName).\(result.transportLayer).", inDomain: "\(result.domain)")
    }
}
}

extension ScannerViewController: UITableViewDelegate, UITableViewDataSource {

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.services.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") else{
        return UITableViewCell()
    }

    guard self.services.count > 0 else{
        return cell
    }
    let service = self.services[indexPath.row]
    cell.textLabel?.text = "Name: \(service.name)\nDomain: \(service.domain)\nPort: \(service.port)"
    return cell
}
}

extension ScannerViewController: UITextFieldDelegate {

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    let nextTag = textField.tag + 1
    if let nextTextField = textField.superview?.viewWithTag(nextTag) {
        nextTextField.becomeFirstResponder()
    }else{
        self.hideKeyboard()
    }
    return false
}

func hideKeyboard() {
    self.serviceTextField?.resignFirstResponder()
    self.transportLayerTextField?.resignFirstResponder()
    self.domainTextField?.resignFirstResponder()
}
}

extension ScannerViewController: NetServiceBrowserDelegate, NetServiceDelegate {

func netServiceBrowser(_ browser: NetServiceBrowser, didNotSearch errorDict: [String : NSNumber]) {
    print("Error serching for service")
    print("Errors: \(errorDict.keys)\n")
}

func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) {
    service.delegate = self
    self.services.append(service)
}

func netServiceBrowser(_ browser: NetServiceBrowser, didRemove service: NetService, moreComing: Bool) {
    service.delegate = nil
    self.removeServiceFromList(serviceObj: service)
}

///Removes the service from the current list.
func removeServiceFromList(serviceObj: NetService){
    for (index, sev) in self.services.enumerated() {
        if sev == serviceObj {
            self.services.remove(at: index)
        }
    }
}

}

Update:

I am using the command line to check the available bonjour services and I have noticed:

Running dns-sd  -B  _services._dns-sd._udp  local. will list couple of services that I believe is brodcasted from my machine only.

Running dns-sd  -B  _ipp._tcp  local. or dns-sd  -B  _http._tcp  local. will list all things uses the ipp/http services.

The real question why the ipp or http service types did not appear when I used the command dns-sd  -B  _services._dns-sd._udp  local. ??? based on all my readings online everybody saying that this command should list all bonjour services availble and active on the network! But thats not what is happening with me.

Note: I am connected to the network via wifi and I can't use a cable since I do not have an adapter.

Attached a snapshot of the result.

Update 2

Finally I figured it out. I guess the issue was with the wifi network at work that was blocking the list of services. because when I tried it home I was able to see all the bonjour services with no issues.


来源: stackexchange

问:
Jupyter notebook python crash on Windows 10
I have spent a week searching and trying different solutions with no luck. I've seen several others having the same problems going back over a year.

The issue:

Windows 10 Pro build 15063.674

I'm using the latest Anaconda 5 build with Python 3.6.2 and all the packages are updated to most recent.

Running Jupyter Notebook, after some time, python will crash with a dialog "python has stopped working". This seems to happen after the notebook has been open for awhile, but I haven't been able to pinpoint an exact time. It's longer than 15 minutes but I've had it crash after a couple hours too.

The crash happens whether or not the notebook is in use, but most of the time, it's been while it's idle.

The console contains several lines like this:

```<code>Assertion failed: Connection reset by peer (bundled\zeromq\src\signaler.cpp:298)
</code>```

I had been using everything with no issues, on a daily basis for months prior to this. I honestly have no idea what could have changed other than Windows Automatic updates.

What I've tried:

updating anaconda

updating all packages

updating python

full clean removal then reinstall of anaconda, python, and all packages

updating everything again

removing pyzmq and Jupyter then reinstalling

disabling Windows Defender

attempted to revert pyzmq on a long shot to 13.1.0 but the build failed

I've also tried using both conda and pip for installing/removing

Threads I've read:

https://github.com/zeromq/libzmq/issues/1808

https://github.com/ipython/ipython/issues/9975

https://github.com/ipython/ipython/issues/9236

https://github.com/zeromq/libzmq/issues/1108

https://github.com/zeromq/libzmq/issues/1573

Why python raised an AssertionError on some failed assumption in a ZeroMQ client?

Python.exe crashes while running Jupyter notebook sever

Why Does Jupyter Notebook Crashes?

Any suggestions on fixing this?

答:
The solution was to uninstall a program called Networx.

I don't understand the error myself but the person I got the solution from linked this post: https://github.com/Microsoft/WSL/issues/1554#issuecomment-339743927

ContentLicense: CC BY-SA 3.0

Body:
I have spent a week searching and trying different solutions with no luck. I've seen several others having the same problems going back over a year.

The issue:

Windows 10 Pro build 15063.674

I'm using the latest Anaconda 5 build with Python 3.6.2 and all the packages are updated to most recent.

Running Jupyter Notebook, after some time, python will crash with a dialog "python has stopped working". This seems to happen after the notebook has been open for awhile, but I haven't been able to pinpoint an exact time. It's longer than 15 minutes but I've had it crash after a couple hours too.

The crash happens whether or not the notebook is in use, but most of the time, it's been while it's idle.

The console contains several lines like this:

Assertion failed: Connection reset by peer (bundled\zeromq\src\signaler.cpp:298)

I had been using everything with no issues, on a daily basis for months prior to this. I honestly have no idea what could have changed other than Windows Automatic updates.

What I've tried:

updating anaconda

updating all packages

updating python

full clean removal then reinstall of anaconda, python, and all packages

updating everything again

removing pyzmq and Jupyter then reinstalling

disabling Windows Defender

attempted to revert pyzmq on a long shot to 13.1.0 but the build failed

I've also tried using both conda and pip for installing/removing

Threads I've read:

https://github.com/zeromq/libzmq/issues/1808

https://github.com/ipython/ipython/issues/9975

https://github.com/ipython/ipython/issues/9236

https://github.com/zeromq/libzmq/issues/1108

https://github.com/zeromq/libzmq/issues/1573

Why python raised an AssertionError on some failed assumption in a ZeroMQ client?

Python.exe crashes while running Jupyter notebook sever

Why Does Jupyter Notebook Crashes?

Any suggestions on fixing this?


问:
I'm having trouble understanding this for loop and what its returning
```<code>def double_char(str):
    result = ''
    for char in str:
        result += char + char
    return result
</code>```

this is the function, and when i call it, say:

```<code>double_char(dog)
</code>```

it returns: 'ddoogg'

but on line 4 it's saying result = result + char + char wouldn't that yield ''dogdog? I'm really confused and I think I just dont understand the basics of for loops

答:
You could change your method like this to get what you want.

```<code>def double_char(str):
    result = str + str
    return result
</code>```

for char in str: loops through every character in str. First time is 'd', second is 'o', third is 'g'. Each of these gets doubled and added to the result. In other words, the first value is not just 'dog' as a whole.

result then looks like this after every iteration

```<code>''
'dd'
'ddoo'
'ddoogg'
</code>```

Body:
def double_char(str):
    result = ''
    for char in str:
        result += char + char
    return result

this is the function, and when i call it, say:

double_char(dog)

it returns: 'ddoogg'

but on line 4 it's saying result = result + char + char wouldn't that yield ''dogdog? I'm really confused and I think I just dont understand the basics of for loops

Body:
You could change your method like this to get what you want.

def double_char(str):
    result = str + str
    return result

for char in str: loops through every character in str. First time is 'd', second is 'o', third is 'g'. Each of these gets doubled and added to the result. In other words, the first value is not just 'dog' as a whole.

result then looks like this after every iteration

''
'dd'
'ddoo'
'ddoogg'


问:
Getting the location from an IP address
I want to retrieve information like the city, state, and country of a visitor from their IP address, so that I can customize my web page according to their location. Is there a good and reliable way to do this in PHP? I am using JavaScript for client-side scripting, PHP for server-side scripting, and MySQL for the database.</p>

答:
I run the service at IPLocate.io, which you can hook into for free with one easy call:

```<code><?php
$res = file_get_contents('https://www.iplocate.io/api/lookup/8.8.8.8');
$res = json_decode($res);

echo $res->country; // United States
echo $res->continent; // North America
echo $res->latitude; // 37.751
echo $res->longitude; // -97.822

var_dump($res);
</code>```

The $res object will contain your geolocation fields like country, city, etc.

Check out the docs for more information.

OwnerDisplayName: krishna Kant

Title: Getting the location from an IP address

Body:
I run the service at IPLocate.io, which you can hook into for free with one easy call:

<?php
$res = file_get_contents('https://www.iplocate.io/api/lookup/8.8.8.8');
$res = json_decode($res);

echo $res->country; // United States
echo $res->continent; // North America
echo $res->latitude; // 37.751
echo $res->longitude; // -97.822

var_dump($res);

The $res object will contain your geolocation fields like country, city, etc.

Check out the docs for more information.


问:
Python File Reading & Writing
So I need to write a program that reads a text file, and copies its contents to another file. I then have to add a column at the end of the text file, and populate that column with an int that is calculated using the function calc_bill. I can get it to copy the contents of the original file to the new one, but I cannot seem to get my program to read in the ints necessary for calc_bill to run.
Any help would be greatly appreciated.

Here are the first 3 lines of the text file I am reading from:

```<code>CustomerID  Title   FirstName   MiddleName  LastName    Customer Type
1   Mr. Orlando N.  Gee Residential     297780  302555
2   Mr. Keith   NULL    Harris  Residential     274964  278126
</code>```

It is copying the file exactly as it is supposed to to the new file. What is not working is writing the bill_amount (calc_bill)/ billVal(main) to the new file in a new column. Here is the expected output to the new file:

```<code>CustomerID  Title   FirstName   MiddleName  LastName    Customer Type   Company Name    Start Reading   End Reading  BillVal
1   Mr. Orlando N.  Gee Residential     297780  302555       some number
2   Mr. Keith   NULL    Harris  Residential     274964  278126    some number
</code>```

And here is my code:

```<code>def main():
    file_in = open("water_supplies.txt", "r")
    file_in.readline()
    file_out = input("Please enter a file name for the output:")
    output_file = open(file_out, 'w')
    lines = file_in.readlines()
    for line in lines:
        lines = [line.split('\t')]
        #output_file.write(str(lines)+ "\n")
        billVal = 0
        c_type = line[5]
        start = int(line[7])
        end = int(line[8])
        billVal = calc_bill(c_type, start, end)
        output_file.write(str(lines)+ "\t" + str(billVal) + "\n")

def calc_bill(customer_type, start_reading, end_reading):
    price_per_gallon = 0

    if customer_type == "Residential":
        price_per_gallon = .012

    elif customer_type == "Commercial":
        price_per_gallon = .011

    elif customer_type == "Industrial":
        price_per_gallon = .01

    if start_reading >= end_reading:
        print("Error: please try again")

    else:
        reading = end_reading - start_reading

    bill_amount = reading * price_per_gallon
    return bill_amount
main()
</code>```

答:
There are a couple things. The inconsistent spacing in your column names makes counting the actual columns a bit confusing, but I believe there are 9 column names there. However, each of your rows of data have only 8 elements, so it looks like you've got an extra column name (maybe "CompanyName"). So get rid of that, or fix the data.

Then your "start" and "end" variables are pointing to indexes 7 and 8, respectively. However, since there are only 8 elements in the row, I think the indexes should be 6 and 7.

Another problem could be that inside your for-loop through "lines", you set "lines" to the elements in that line. I would suggest renaming the second "lines" variable inside the for-loop to something else, like "elements".

Aside from that, I'd just caution you about naming consistency. Some of your column names are camel-case and others have spaces. Some of your variables are separated by underscores and others are camel-case.

Hopefully that helps. Let me know if you have any other questions.

Title: Python File Reading & Writing

Body:
So I need to write a program that reads a text file, and copies its contents to another file. I then have to add a column at the end of the text file, and populate that column with an int that is calculated using the function calc_bill. I can get it to copy the contents of the original file to the new one, but I cannot seem to get my program to read in the ints necessary for calc_bill to run.
Any help would be greatly appreciated.

Here are the first 3 lines of the text file I am reading from:

CustomerID  Title   FirstName   MiddleName  LastName    Customer Type
1   Mr. Orlando N.  Gee Residential     297780  302555
2   Mr. Keith   NULL    Harris  Residential     274964  278126

It is copying the file exactly as it is supposed to to the new file. What is not working is writing the bill_amount (calc_bill)/ billVal(main) to the new file in a new column. Here is the expected output to the new file:

CustomerID  Title   FirstName   MiddleName  LastName    Customer Type   Company Name    Start Reading   End Reading  BillVal
1   Mr. Orlando N.  Gee Residential     297780  302555       some number
2   Mr. Keith   NULL    Harris  Residential     274964  278126    some number

And here is my code:

def main():
    file_in = open("water_supplies.txt", "r")
    file_in.readline()
    file_out = input("Please enter a file name for the output:")
    output_file = open(file_out, 'w')
    lines = file_in.readlines()
    for line in lines:
        lines = [line.split('\t')]
        #output_file.write(str(lines)+ "\n")
        billVal = 0
        c_type = line[5]
        start = int(line[7])
        end = int(line[8])
        billVal = calc_bill(c_type, start, end)
        output_file.write(str(lines)+ "\t" + str(billVal) + "\n")

def calc_bill(customer_type, start_reading, end_reading):
    price_per_gallon = 0

    if customer_type == "Residential":
        price_per_gallon = .012

    elif customer_type == "Commercial":
        price_per_gallon = .011

    elif customer_type == "Industrial":
        price_per_gallon = .01

    if start_reading >= end_reading:
        print("Error: please try again")

    else:
        reading = end_reading - start_reading

    bill_amount = reading * price_per_gallon
    return bill_amount
main()


问:
How do I do two has_many/belongs_to relationships between two models?
I've got a Project model, and a Contact model. The Project model has an owner and a client, both of which are Contacts. I've obviously got something ambiguous going on, because if I have a contact and ask for its projects, Rails won't know whether I'm asking for it's projects where it's the client or where it's the owner. So far I've got this:

```<code>class Contact < ActiveRecord::Base
  has_many :projects
end

class Project < ActiveRecord::Base
  belongs_to :owner, :class_name => 'Contact', :foreign_key => 'owner_id'
  belongs_to :client, :class_name => 'Contact', :foreign_key => 'client_id'
end
</code>```

How do I make two relationships here?

答:
You should try to use a single table inheritance on the Contact table. All you need to do for this to work is to implement a 'type' column (string). Rails will handle the rest</p>

```<code>class Contact < ActiveRecord::Base
   # implement a type column
   has_many :projects
end

class OwnerContact < Contact
end

class ClientContact < Contact
end

class Project < ActiveRecord::Base
  belongs_to :owner, :class_name => 'OwnerContact'
  belongs_to :client, :class_name => 'ClientContact'
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've got a Project model, and a Contact model. The Project model has an owner and a client, both of which are Contacts. I've obviously got something ambiguous going on, because if I have a contact and ask for its projects, Rails won't know whether I'm asking for it's projects where it's the client or where it's the owner. So far I've got this:

class Contact < ActiveRecord::Base
  has_many :projects
end

class Project < ActiveRecord::Base
  belongs_to :owner, :class_name => 'Contact', :foreign_key => 'owner_id'
  belongs_to :client, :class_name => 'Contact', :foreign_key => 'client_id'
end

How do I make two relationships here?

Body:
You should try to use a single table inheritance on the Contact table. All you need to do for this to work is to implement a 'type' column (string). Rails will handle the rest

class Contact < ActiveRecord::Base
   # implement a type column
   has_many :projects
end

class OwnerContact < Contact
end

class ClientContact < Contact
end

class Project < ActiveRecord::Base
  belongs_to :owner, :class_name => 'OwnerContact'
  belongs_to :client, :class_name => 'ClientContact'
end


问:
"GSSException Defective token detected" - when trying to Authenticate to Tomcat running on Windows using Kerberos
I am struggling to authenticate to a Java web container (I've tried both Tomcat and Jetty) when running on Windows 2012.

Every time I try the Negotiate auth scheme I get an error: org.ietf.jgss.GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)

Steps to reproduce

Start out by setting up a Windows Server 2012 or 2016 instance and install active directory domain services.

In my example, I created:

NETBIOS Domain: NICKIS

Dns domain: nickis.life

Create the kerberos subject user on Active Directory

IMPORTANT: MAKE SURE THAT THE FIRST NAME, LAST NAME AND FULL NAME ARE THE SAME!

The new user in my case is:

DN = CN=kerberos500,CN=Users,DC=nickis,DC=life

login+domain = kerberos500@nickis.life

NETBIOS\samAccountName = NICKIS\kerberos500

Run the setspn command from the Windows Active Directory Server

```<code>setspn -A HTTP/nickis.life@NICKIS.LIFE kerberos500
</code>```

Example output:

```<code>C:\Users\Administrator>setspn -A HTTP/nickis.life kerberos500
Checking domain DC=nickis,DC=life
Registering ServicePrincipalNames for CN=kerberos500,CN=Users,DC=nickis,DC=life
        HTTP/kerberos500.nickis.life
Updated object
</code>```

Run the ktpass command from the Windows Active Directory Server

```<code>ktpass -out c:\Users\Administrator\kerberos500.keytab -princ HTTP/nickis.life@NICKIS.LIFE -mapUser kerberos500 -mapOp set -pass XXXXpasswordforkerberos500userXXXX -crypto DES-CBC-MD5 -pType KRB5_NT_PRINCIPAL +DesOnly
</code>```

Example output:

```<code>C:\Users\Administrator>ktpass -out c:\Users\Administrator\kerberos500.keytab -princ HTTP/nickis.life@NICKIS.LIFE -mapUser kerberos500 -mapOp set -pass xxxxxxxx -crypto DES-CBC-MD5 -pType KRB5_NT_PRINCIPAL +DesOnly
Targeting domain controller: WIN-OVV6VHBGIB8.nickis.life
Using legacy password setting method
Successfully mapped HTTP/kerberos500.nickis.life to kerberos500.
Key created.
Output keytab to c:\Users\Administrator\kerberos500.keytab:
Keytab version: 0x502
keysize 71 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 3 etype 0x3 (DES-CBC-MD5) keylength 8 (0xcd07200bea625d20)
Account kerberos500 has been set for DES-only encryption.
</code>```

At this point, you will now have a keytab file:

```<code>c:\Users\Administrator\kerberos500.keytab
</code>```

And a user principal:

```<code>HTTP/kerberos500.nickis.life@NICKIS.LIFE
</code>```

These are the 2 inputs that are needed to provide to the GSSApi to get single sign on with Kerberos.

So I deployed those inputs to my web container's kerberos security realm in the Hadoop security module.

Curl test I tried unsuccessfully to use curl to test it:

curl --negotiate -u : http://nickis.life:8080/my/webapp

Internet Explorer test I also tried using Internet Explorer. I added nickis.life domain to the Trusted Roles in Internet Explorer. Then I launch the site in internet explorer: http://nickis.life:8080

Either way, I get the error below:

```<code>org.apache.hadoop.security.authentication.client.AuthenticationException: GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)
    at org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler.authenticate(KerberosAuthenticationHandler.java:398) ~[hadoop-auth-2.7.1.jar:?]

...

Caused by: org.ietf.jgss.GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)
    at sun.security.jgss.GSSHeader.<init>(Unknown Source) ~[?:1.8.0_131]
    at sun.security.jgss.GSSContextImpl.acceptSecContext(Unknown Source) ~[?:1.8.0_131]
    at sun.security.jgss.GSSContextImpl.acceptSecContext(Unknown Source) ~[?:1.8.0_131]
    at org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler$2.run(KerberosAuthenticationHandler.java:365) ~[hadoop-auth-2.7.1.jar:?]
    at org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler$2.run(KerberosAuthenticationHandler.java:347) ~[hadoop-auth-2.7.1.jar:?]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_131]
    at javax.security.auth.Subject.doAs(Unknown Source) ~[?:1.8.0_131]
    at org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler.authenticate(KerberosAuthenticationHandler.java:347) ~[hadoop-auth-2.7.1.jar:?]
</code>```

I am stumped. NOTE: I have found several links around here and there but none of them were all inclusive on the steps that were followed like I have summed up here, and none of the solutions provided within worked for me.

I am attempting kerberos login from a different machine on the domain than the server is running on

I have tried all sorts of combinations of keytab generation variations none have worked.

There is no duplicate SPN.

I tried setting up the DNS in the domain server as an A record.

I wonder maybe if there's some kerberos windows server setup steps and Microsoft employee verified that this should not be the case here: https://social.msdn.microsoft.com/Forums/sharepoint/en-US/db15ad96-e269-436e-952f-fe9dfb39da8a/setting-up-a-test-windows-server-active-directory-for-kerberos-testing?forum=winserverDS

Can anyone trace what I am screwing up here?

UPDATE:

I have AD server with domain set to fusionis.life, and the AD server is WIN-OVV6VHBGIB8.fusionis.life

I moved the tomcat server to another windows machine in the domain. DESKTOP-VTPBE99.fusionis.life

I opened dnsmgmt.msc and added a "Forward Lookup Zone" with "kerberos500.nickis.life" with A HOST set to the IP of the DESKTOP-VTPBE99.fusionis.life box.

I deleted the AD account, recreated it, then re-generated the keytab again as suggested in one of the answers on the ticket.

C:\Users\Administrator>ktpass -out c:\Users\Administrator\kerberos500.keytab -princ HTTP/kerberos500.nickis.life@NICKIS.LIFE -mapUser kerberos500 -mapOp set -pass xxxxxxxxx -crypto ALL -pType KRB5_NT_PRINCIPAL
Targeting domain controller: WIN-OVV6VHBGIB8.fusionis.life
Using legacy password setting method
Successfully mapped HTTP/kerberos500.nickis.life to kerberos500.
Key created.
Key created.
Key created.
Key created.
Key created.
Output keytab to c:\Users\Administrator\kerberos500.keytab:
Keytab version: 0x502
keysize 67 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x1 (DES-CBC-CRC) keylength 8 (0x04e30b9183ba8389)
keysize 67 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x3 (DES-CBC-MD5) keylength 8 (0x04e30b9183ba8389)
keysize 75 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x17 (RC4-HMAC) keylength 16 (0xe39a141de38abd8750bf9c0bf49fd1c5)
keysize 91 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x12 (AES256-SHA1) keylength 32 (0xe368a1b060cfe4816f522c1c5f62ca07fe201ed96c6d018054dfbd5b86251892)
keysize 75 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x11 (AES128-SHA1) keylength 16 (0x1b1a548fa2893a78c6f4c7f9c482b614)

I saved the keytab updated file on the server, then updated the Service Principal to HTTP/kerberos500.nickis.life@NICKIS.LIFE

I logged into tomcat machine as a domain user, added http://kerberos500.nickis.life to the trusted sites, then navigated to http://kerberos500.nickis.life:8764

I checked all combinations of the encryption check boxes in the kerberos500 AD "account" tab.

Now i'm getting a new error...

GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos credentails)

UPDATE:

Resolved finally. I got this final error because I needed fusionis.life to be on the same host as nickis.life

答:
The error “Defective token detected” likely means that an ntlm token was detected.  That’s what the Negotiate mechanism uses inside popular web browsers if kerberos fails - when not instructed by the web server otherwise.  On windows operating systems, the IE web browser on it (and Firefox, if configured correctly) basically says, if you won’t do Kerberos, I’m going to send you an NTLM token.  And the server replies “no way” I don’t even know NTLM so I’m calling what you sent me defective.  Since you seem to be setting this up for the first time, you likely did not configure any fallback mechanism (such as NTLM) for when Kerberos fails, therefore, that error message.  We solve this by understanding why Kerberos is failing.  I think I see the reason for the failure in your question, in two places, related to SPNs and Trusted Sites.  Even if you resolve those two items, there is a third reason and fourth reason why it could continue to fail, related to encryption.

The spn for the HTTP service does not match the URL entered by the browser.   These need to match, otherwise Kerberos will fail.  To work, the browser should be using: http://kerberos500.nickis.life:8080, not http://nickis.life:8080.  I say that based on what I saw in your keytab creation syntax.  In that you’ve coded the SPN as such:  HTTP/kerberos500.nickis.life@NICKIS.LIFE.  That’s why you need to use http://kerberos500.nickis.life:8080. The browser won’t know how to get to your web service when you tell it to go to http://nickis.life:8080.  With that top URL, the browser assumes it needs to find a web service running on your Active Directorydomaincontroller (anything with just nickis.life is assumed to run on the Domain Controller).  DCs should never run web servers for security reasons.

You’ll need to add http://kerberos500.nickis.life as a Trusted Site under IE settings.  Alternatively, *.nickis.life would work as well.   (You called it Trusted Roles, when it’s actually called Trusted Sites).

You are restricting the Kerberos encryption type to DES-CBC-MD5.  Starting with Windows Server 2008 Active Directory R2, DES is disabled by default.  DES is an outdated and generally insecure encryption type these days.  Much better to use AES128 or even better, AES256.  You can fix that by re-generating the keytab per my example below.

In the AD user account kerberos500, go to the Account tab, scroll to the bottom, and check all the boxes for DES, AES 128, and AES 256, and OK you’re way out of the dialog boxes.  You must check these boxes even if you did everything right above, or else Kerberos authentication will still fail.

How to properly re-generate the keytab: You should not run the setspn -a command to add an SPN to an AD user whenever you are planning to make a keytab associated with that user account.  The reason why is because the keytab creation command adds the SPN to the user account as part of the command.  If your scenario doesn’t work after following my advice above, then you’ll need to remove the SPN via setspn -D like below:

```<code>setspn -D HTTP/nickis.life@NICKIS.LIFE kerberos500
</code>```

And the re-generate the keytab afterwards, my only change is that I told it to use all encryption types.  The client and server will agree on the strongest common one during the authentication process.

```<code>ktpass -out c:\Users\Administrator\kerberos500.keytab -princ HTTP/nickis.life@NICKIS.LIFE -mapUser kerberos500 -mapOp set -pass XXXXpasswordforkerberos500userXXXX -crypto ALL -pType KRB5_NT_PRINCIPAL
</code>```

Then replace the old keytab with the new one.  For additional in-depth information on keytabs, you can read more from my technical article on how to create Kerberos keytabs here:  Kerberos Keytabs – Explained.  I frequently go back and edit it based on questions I see here in this forum.

By the way, HTTP/kerberos500.nickis.life is a service principal, not a user principal as you wrote in your question.   I only use web browsers to test Kerberos in HTTP scenarios like this one, I don’t use cURL.

I am positive if you diligently go through all four points I’ve highlighted above, you will resolve this problem.

EDIT1: This answer assumes you have an HTTP service running  on a host with the fully-qualified domain name of kerberos500.nickis.life.  If you don't have such a host with that name, my answer will slightly change.  Please let me know if any.

EDIT2: To achieve the objective of authentication using the URL of http://nickis.life:8080, then you may keep on using the same keytab you already created.

On the AD account NICKIS\kerberos500, go to the Account tab, scroll to the bottom, and check the box for "Use Kerberos DES encryption types for this account".

Then enable DES encryption itself at the AD domain level via Group Policy.  To do that, conduct the following:

Open up Group Policy Management Console (GPMC).

Edit Default Domain Policy GPO.  (Its safer to create a new domain-level GPO instead and edit that, but that's up to you).

Navigate to Computer Configuration > Policies > Windows Settings > Security Settings > Local Policies > Security Options > “Network Security: Configure Encryption types allowed for Kerberos” and check the both checkboxes for DES_CBC_MD5 and DES_CBC_MD5.  IMPORTANT:  In that same Group Policy, also ensure the checkboxes for RC4,  AES128, and AES256 are also checked.  Those encryption types won't be used for tickets to your web site, but they will for everything else in the domain. and OK you're way out of the dialog boxes and close the GPMC.

Run the 'gpupdate /force' command on both the DC server and the client.

Run 'klist purge' on the client to purge all Kerberos tickets.

In the web browser, clear the cache and delete all cookies.

Ensure that the DC server allows port 8080 TCP inbound.

Try it again.

Reference: Windows Configurations for Kerberos Supported Encryption Type

EDIT 3: Avoid running Kerberos KDC (the DC), client and server on the same machine.  That is a classic recipe for getting the "Defective token error" even if you've done everything else right.

EDIT 4: (Final update which was verified by the OP):  Looked at the new ktpass keytab creation output, and I saw this: Targeting domain controller: WIN-OVV6VHBGIB8.fusionis.life. Now, the defined SPN in the keytab is HTTP/kerberos500.nickis.life. The AD domain name is different from the SPN you defined, so this is not going to work unless you have some kind of trust setup between these domains. If you don't have a trust, you need to use an SPN of HTTP/kerberos500.fusionis.life instead.

Body:
I am struggling to authenticate to a Java web container (I've tried both Tomcat and Jetty) when running on Windows 2012.

Every time I try the Negotiate auth scheme I get an error: org.ietf.jgss.GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)

Steps to reproduce

Start out by setting up a Windows Server 2012 or 2016 instance and install active directory domain services.

In my example, I created:

NETBIOS Domain: NICKIS

Dns domain: nickis.life

Create the kerberos subject user on Active Directory

IMPORTANT: MAKE SURE THAT THE FIRST NAME, LAST NAME AND FULL NAME ARE THE SAME!

The new user in my case is:

DN = CN=kerberos500,CN=Users,DC=nickis,DC=life

login+domain = kerberos500@nickis.life

NETBIOS\samAccountName = NICKIS\kerberos500

Run the setspn command from the Windows Active Directory Server

setspn -A HTTP/nickis.life@NICKIS.LIFE kerberos500

Example output:

C:\Users\Administrator>setspn -A HTTP/nickis.life kerberos500
Checking domain DC=nickis,DC=life
Registering ServicePrincipalNames for CN=kerberos500,CN=Users,DC=nickis,DC=life
        HTTP/kerberos500.nickis.life
Updated object

Run the ktpass command from the Windows Active Directory Server

ktpass -out c:\Users\Administrator\kerberos500.keytab -princ HTTP/nickis.life@NICKIS.LIFE -mapUser kerberos500 -mapOp set -pass XXXXpasswordforkerberos500userXXXX -crypto DES-CBC-MD5 -pType KRB5_NT_PRINCIPAL +DesOnly

Example output:

C:\Users\Administrator>ktpass -out c:\Users\Administrator\kerberos500.keytab -princ HTTP/nickis.life@NICKIS.LIFE -mapUser kerberos500 -mapOp set -pass xxxxxxxx -crypto DES-CBC-MD5 -pType KRB5_NT_PRINCIPAL +DesOnly
Targeting domain controller: WIN-OVV6VHBGIB8.nickis.life
Using legacy password setting method
Successfully mapped HTTP/kerberos500.nickis.life to kerberos500.
Key created.
Output keytab to c:\Users\Administrator\kerberos500.keytab:
Keytab version: 0x502
keysize 71 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 3 etype 0x3 (DES-CBC-MD5) keylength 8 (0xcd07200bea625d20)
Account kerberos500 has been set for DES-only encryption.

At this point, you will now have a keytab file:

c:\Users\Administrator\kerberos500.keytab

And a user principal:

HTTP/kerberos500.nickis.life@NICKIS.LIFE

These are the 2 inputs that are needed to provide to the GSSApi to get single sign on with Kerberos.

So I deployed those inputs to my web container's kerberos security realm in the Hadoop security module.

Curl test I tried unsuccessfully to use curl to test it:

curl --negotiate -u : http://nickis.life:8080/my/webapp

Internet Explorer test I also tried using Internet Explorer. I added nickis.life domain to the Trusted Roles in Internet Explorer. Then I launch the site in internet explorer: http://nickis.life:8080

Either way, I get the error below:

org.apache.hadoop.security.authentication.client.AuthenticationException: GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)
    at org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler.authenticate(KerberosAuthenticationHandler.java:398) ~[hadoop-auth-2.7.1.jar:?]

...

Caused by: org.ietf.jgss.GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)
    at sun.security.jgss.GSSHeader.<init>(Unknown Source) ~[?:1.8.0_131]
    at sun.security.jgss.GSSContextImpl.acceptSecContext(Unknown Source) ~[?:1.8.0_131]
    at sun.security.jgss.GSSContextImpl.acceptSecContext(Unknown Source) ~[?:1.8.0_131]
    at org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler$2.run(KerberosAuthenticationHandler.java:365) ~[hadoop-auth-2.7.1.jar:?]
    at org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler$2.run(KerberosAuthenticationHandler.java:347) ~[hadoop-auth-2.7.1.jar:?]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_131]
    at javax.security.auth.Subject.doAs(Unknown Source) ~[?:1.8.0_131]
    at org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler.authenticate(KerberosAuthenticationHandler.java:347) ~[hadoop-auth-2.7.1.jar:?]

I am stumped. NOTE: I have found several links around here and there but none of them were all inclusive on the steps that were followed like I have summed up here, and none of the solutions provided within worked for me.

I am attempting kerberos login from a different machine on the domain than the server is running on

I have tried all sorts of combinations of keytab generation variations none have worked.

There is no duplicate SPN.

I tried setting up the DNS in the domain server as an A record.

I wonder maybe if there's some kerberos windows server setup steps and Microsoft employee verified that this should not be the case here: https://social.msdn.microsoft.com/Forums/sharepoint/en-US/db15ad96-e269-436e-952f-fe9dfb39da8a/setting-up-a-test-windows-server-active-directory-for-kerberos-testing?forum=winserverDS

Can anyone trace what I am screwing up here?

UPDATE:

I have AD server with domain set to fusionis.life, and the AD server is WIN-OVV6VHBGIB8.fusionis.life

I moved the tomcat server to another windows machine in the domain. DESKTOP-VTPBE99.fusionis.life

I opened dnsmgmt.msc and added a "Forward Lookup Zone" with "kerberos500.nickis.life" with A HOST set to the IP of the DESKTOP-VTPBE99.fusionis.life box.

I deleted the AD account, recreated it, then re-generated the keytab again as suggested in one of the answers on the ticket.

C:\Users\Administrator>ktpass -out c:\Users\Administrator\kerberos500.keytab -princ HTTP/kerberos500.nickis.life@NICKIS.LIFE -mapUser kerberos500 -mapOp set -pass xxxxxxxxx -crypto ALL -pType KRB5_NT_PRINCIPAL
Targeting domain controller: WIN-OVV6VHBGIB8.fusionis.life
Using legacy password setting method
Successfully mapped HTTP/kerberos500.nickis.life to kerberos500.
Key created.
Key created.
Key created.
Key created.
Key created.
Output keytab to c:\Users\Administrator\kerberos500.keytab:
Keytab version: 0x502
keysize 67 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x1 (DES-CBC-CRC) keylength 8 (0x04e30b9183ba8389)
keysize 67 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x3 (DES-CBC-MD5) keylength 8 (0x04e30b9183ba8389)
keysize 75 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x17 (RC4-HMAC) keylength 16 (0xe39a141de38abd8750bf9c0bf49fd1c5)
keysize 91 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x12 (AES256-SHA1) keylength 32 (0xe368a1b060cfe4816f522c1c5f62ca07fe201ed96c6d018054dfbd5b86251892)
keysize 75 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x11 (AES128-SHA1) keylength 16 (0x1b1a548fa2893a78c6f4c7f9c482b614)

I saved the keytab updated file on the server, then updated the Service Principal to HTTP/kerberos500.nickis.life@NICKIS.LIFE

I logged into tomcat machine as a domain user, added http://kerberos500.nickis.life to the trusted sites, then navigated to http://kerberos500.nickis.life:8764

I checked all combinations of the encryption check boxes in the kerberos500 AD "account" tab.

Now i'm getting a new error...

GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos credentails)

UPDATE:

Resolved finally. I got this final error because I needed fusionis.life to be on the same host as nickis.life

Body:
The error “Defective token detected” likely means that an ntlm token was detected.  That’s what the Negotiate mechanism uses inside popular web browsers if kerberos fails - when not instructed by the web server otherwise.  On windows operating systems, the IE web browser on it (and Firefox, if configured correctly) basically says, if you won’t do Kerberos, I’m going to send you an NTLM token.  And the server replies “no way” I don’t even know NTLM so I’m calling what you sent me defective.  Since you seem to be setting this up for the first time, you likely did not configure any fallback mechanism (such as NTLM) for when Kerberos fails, therefore, that error message.  We solve this by understanding why Kerberos is failing.  I think I see the reason for the failure in your question, in two places, related to SPNs and Trusted Sites.  Even if you resolve those two items, there is a third reason and fourth reason why it could continue to fail, related to encryption.

The spn for the HTTP service does not match the URL entered by the browser.   These need to match, otherwise Kerberos will fail.  To work, the browser should be using: http://kerberos500.nickis.life:8080, not http://nickis.life:8080.  I say that based on what I saw in your keytab creation syntax.  In that you’ve coded the SPN as such:  HTTP/kerberos500.nickis.life@NICKIS.LIFE.  That’s why you need to use http://kerberos500.nickis.life:8080. The browser won’t know how to get to your web service when you tell it to go to http://nickis.life:8080.  With that top URL, the browser assumes it needs to find a web service running on your Active Directorydomaincontroller (anything with just nickis.life is assumed to run on the Domain Controller).  DCs should never run web servers for security reasons.

You’ll need to add http://kerberos500.nickis.life as a Trusted Site under IE settings.  Alternatively, *.nickis.life would work as well.   (You called it Trusted Roles, when it’s actually called Trusted Sites).

You are restricting the Kerberos encryption type to DES-CBC-MD5.  Starting with Windows Server 2008 Active Directory R2, DES is disabled by default.  DES is an outdated and generally insecure encryption type these days.  Much better to use AES128 or even better, AES256.  You can fix that by re-generating the keytab per my example below.

In the AD user account kerberos500, go to the Account tab, scroll to the bottom, and check all the boxes for DES, AES 128, and AES 256, and OK you’re way out of the dialog boxes.  You must check these boxes even if you did everything right above, or else Kerberos authentication will still fail.

How to properly re-generate the keytab: You should not run the setspn -a command to add an SPN to an AD user whenever you are planning to make a keytab associated with that user account.  The reason why is because the keytab creation command adds the SPN to the user account as part of the command.  If your scenario doesn’t work after following my advice above, then you’ll need to remove the SPN via setspn -D like below:

setspn -D HTTP/nickis.life@NICKIS.LIFE kerberos500

And the re-generate the keytab afterwards, my only change is that I told it to use all encryption types.  The client and server will agree on the strongest common one during the authentication process.

ktpass -out c:\Users\Administrator\kerberos500.keytab -princ HTTP/nickis.life@NICKIS.LIFE -mapUser kerberos500 -mapOp set -pass XXXXpasswordforkerberos500userXXXX -crypto ALL -pType KRB5_NT_PRINCIPAL

Then replace the old keytab with the new one.  For additional in-depth information on keytabs, you can read more from my technical article on how to create Kerberos keytabs here:  Kerberos Keytabs – Explained.  I frequently go back and edit it based on questions I see here in this forum.

By the way, HTTP/kerberos500.nickis.life is a service principal, not a user principal as you wrote in your question.   I only use web browsers to test Kerberos in HTTP scenarios like this one, I don’t use cURL.

I am positive if you diligently go through all four points I’ve highlighted above, you will resolve this problem.

EDIT1: This answer assumes you have an HTTP service running  on a host with the fully-qualified domain name of kerberos500.nickis.life.  If you don't have such a host with that name, my answer will slightly change.  Please let me know if any.

EDIT2: To achieve the objective of authentication using the URL of http://nickis.life:8080, then you may keep on using the same keytab you already created.

On the AD account NICKIS\kerberos500, go to the Account tab, scroll to the bottom, and check the box for "Use Kerberos DES encryption types for this account".

Then enable DES encryption itself at the AD domain level via Group Policy.  To do that, conduct the following:

Open up Group Policy Management Console (GPMC).

Edit Default Domain Policy GPO.  (Its safer to create a new domain-level GPO instead and edit that, but that's up to you).

Navigate to Computer Configuration > Policies > Windows Settings > Security Settings > Local Policies > Security Options > “Network Security: Configure Encryption types allowed for Kerberos” and check the both checkboxes for DES_CBC_MD5 and DES_CBC_MD5.  IMPORTANT:  In that same Group Policy, also ensure the checkboxes for RC4,  AES128, and AES256 are also checked.  Those encryption types won't be used for tickets to your web site, but they will for everything else in the domain. and OK you're way out of the dialog boxes and close the GPMC.

Run the 'gpupdate /force' command on both the DC server and the client.

Run 'klist purge' on the client to purge all Kerberos tickets.

In the web browser, clear the cache and delete all cookies.

Ensure that the DC server allows port 8080 TCP inbound.

Try it again.

Reference: Windows Configurations for Kerberos Supported Encryption Type

EDIT 3: Avoid running Kerberos KDC (the DC), client and server on the same machine.  That is a classic recipe for getting the "Defective token error" even if you've done everything else right.

EDIT 4: (Final update which was verified by the OP):  Looked at the new ktpass keytab creation output, and I saw this: Targeting domain controller: WIN-OVV6VHBGIB8.fusionis.life. Now, the defined SPN in the keytab is HTTP/kerberos500.nickis.life. The AD domain name is different from the SPN you defined, so this is not going to work unless you have some kind of trust setup between these domains. If you don't have a trust, you need to use an SPN of HTTP/kerberos500.fusionis.life instead.


答:
You are looping over each character in the string. Imagine it was just:

```<code>for char in str:
    print char
</code>```

you go 'd', 'o', 'g' resulting in "dog". Now do the same but 2 times:

```<code>for char in str:
    print char
    print char
</code>```

you are going 'd', 'd', 'o', 'o' ... resulting in "ddoogg". You are doing the same but constructing the string, then printing it.

Title: I'm having trouble understanding this for loop and what its returning

Body:
You are looping over each character in the string. Imagine it was just:

for char in str:
    print char

you go 'd', 'o', 'g' resulting in "dog". Now do the same but 2 times:

for char in str:
    print char
    print char

you are going 'd', 'd', 'o', 'o' ... resulting in "ddoogg". You are doing the same but constructing the string, then printing it.


答:
You have two errors in handling your variables, both in the same line:

```<code>    lines = [line.split()]
</code>```

You put this into your lines variable, which is the entire file contents.  You just lost the rest of your input data.

You made a new list-of-list from the return of split.

Try this line:

```<code>    line = line.split()
</code>```

I got reasonable output with that change, once I make a couple of assumptions about your placement of tabs.

Also, consider not overwriting a variable with a different data semantic; it confuses the usage.  For instance:

```<code>    for record in lines:
    line = record.split()
</code>```

Title: Python File Reading & Writing

Body:
You have two errors in handling your variables, both in the same line:

    lines = [line.split()]

You put this into your lines variable, which is the entire file contents.  You just lost the rest of your input data.

You made a new list-of-list from the return of split.

Try this line:

    line = line.split()

I got reasonable output with that change, once I make a couple of assumptions about your placement of tabs.

Also, consider not overwriting a variable with a different data semantic; it confuses the usage.  For instance:

    for record in lines:
    line = record.split()


问:
How to use PactJS with Angular 2/4/5 to tests services
I'm trying to use PactJS to test some of my Angular Services.  I'm using:

```<code>"@pact-foundation/karma-pact": "^2.1.1",
"pact": "^4.2.1",
"pact-web": "^4.2.1",
</code>```

I can't get the test to run successfully.  Without using async the subscribe callback never gets hit and if I do use async then Pact fails.  This is my code:

```<code>import { TestBed, async, inject } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { ApiService } from '../index';
import { HttpParams } from '@angular/common/http';
import { Group } from '../../grouping/model';
let Pact = require('pact-web');

describe('ApiService', () => {

  let provider;

  beforeAll((done) => {
    provider = Pact({
      consumer: 'client',
      provider: 'server',
      web: true
    });

    // required for slower CI environments
    setTimeout(done, 2000);

    // Required if run with `singleRun: false`
    provider.removeInteractions();
  });

  afterAll((done) => {
    provider.finalize().then(done, e => done.fail(e));
  });

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      providers: [
        ApiService
      ]
    });
  }));

  afterEach((done) => {
    provider.verify().then(done, e => done.fail(e));
  });

  describe('Get all Groups', () => {

    beforeAll((done) => {
      provider.addInteraction({
        given: 'groups exist',
        uponReceiving: 'a request to get groups',
        withRequest: {
          method: 'GET',
          path: '/api/groups'
        },
        willRespondWith: {
          status: 200,
          headers: {'Content-Type': 'application/json'},
          body: [{
            id: Pact.Matchers.somethingLike(1),
            name: Pact.Matchers.somethingLike('a group name'),
            disabled: Pact.Matchers.somethingLike(false),
          }]
        }
      }).then(done, e => done.fail(e));
    });

    it('should return all groups from API', (done) => {

      const apiService: ApiService = TestBed.get(ApiService);
      const groups: Group[] = [{
        id: 1,
        name: false,
        disabled: false
      }];

      apiService.getGroups().subscribe((response: Group[]) => {
        expect(response).toEqual(groups);
        done()
      });
    });
  });
});
</code>```

And the errors I get:

```<code>Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

Failed: Actual interactions do not match expected interactions for mock MockService.

Missing requests:
    GET /api/groups

See standard out/err for details.
</code>```

I have been following these two projects

https://paucls.wordpress.com/2017/08/04/pact-consumer-driven-contract-implementation-in-angular/

https://github.com/koelec/angular-pact-example

Has anyone managed to successfully implement PactJS with Angular or what am I missing to get this working?

答:
The error that's being specified here is specifically because one of your tests timed out (default is 10 seconds), the verify then failed afterwards because of that timed out test.  My suggestion is to look at your own code, the ApiService specifically, because it seems like your subscribe callback never gets called:

```<code>apiService.getGroups().subscribe((response: Group[]) => {
        expect(response).toEqual(groups);
        done()
      });
</code>```

Maybe something fails in getGroups() and isn't caught or that subscribe actually doesn't work.  Either way, that function never called the endpoint (as per the verify) and the callback never called, hence the timeout since done() was never called.

Body:
I'm trying to use PactJS to test some of my Angular Services.  I'm using:

"@pact-foundation/karma-pact": "^2.1.1",
"pact": "^4.2.1",
"pact-web": "^4.2.1",

I can't get the test to run successfully.  Without using async the subscribe callback never gets hit and if I do use async then Pact fails.  This is my code:

import { TestBed, async, inject } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { ApiService } from '../index';
import { HttpParams } from '@angular/common/http';
import { Group } from '../../grouping/model';
let Pact = require('pact-web');

describe('ApiService', () => {

  let provider;

  beforeAll((done) => {
    provider = Pact({
      consumer: 'client',
      provider: 'server',
      web: true
    });

    // required for slower CI environments
    setTimeout(done, 2000);

    // Required if run with `singleRun: false`
    provider.removeInteractions();
  });

  afterAll((done) => {
    provider.finalize().then(done, e => done.fail(e));
  });

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      providers: [
        ApiService
      ]
    });
  }));

  afterEach((done) => {
    provider.verify().then(done, e => done.fail(e));
  });

  describe('Get all Groups', () => {

    beforeAll((done) => {
      provider.addInteraction({
        given: 'groups exist',
        uponReceiving: 'a request to get groups',
        withRequest: {
          method: 'GET',
          path: '/api/groups'
        },
        willRespondWith: {
          status: 200,
          headers: {'Content-Type': 'application/json'},
          body: [{
            id: Pact.Matchers.somethingLike(1),
            name: Pact.Matchers.somethingLike('a group name'),
            disabled: Pact.Matchers.somethingLike(false),
          }]
        }
      }).then(done, e => done.fail(e));
    });

    it('should return all groups from API', (done) => {

      const apiService: ApiService = TestBed.get(ApiService);
      const groups: Group[] = [{
        id: 1,
        name: false,
        disabled: false
      }];

      apiService.getGroups().subscribe((response: Group[]) => {
        expect(response).toEqual(groups);
        done()
      });
    });
  });
});

And the errors I get:

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

Failed: Actual interactions do not match expected interactions for mock MockService.

Missing requests:
    GET /api/groups

See standard out/err for details.

I have been following these two projects

https://paucls.wordpress.com/2017/08/04/pact-consumer-driven-contract-implementation-in-angular/

https://github.com/koelec/angular-pact-example

Has anyone managed to successfully implement PactJS with Angular or what am I missing to get this working?

Body:
The error that's being specified here is specifically because one of your tests timed out (default is 10 seconds), the verify then failed afterwards because of that timed out test.  My suggestion is to look at your own code, the ApiService specifically, because it seems like your subscribe callback never gets called:

apiService.getGroups().subscribe((response: Group[]) => {
        expect(response).toEqual(groups);
        done()
      });

Maybe something fails in getGroups() and isn't caught or that subscribe actually doesn't work.  Either way, that function never called the endpoint (as per the verify) and the callback never called, hence the timeout since done() was never called.


问:
HTML5 Canvas - Fill circle with image
How can I draw an image inside a circle? If I do:

```<code>context.beginPath();
context.arc((e.pageX),(e.pageY),161,0,Math.PI*2,true);
context.closePath();
</code>```

How can I then use fill() to fill it with my drawn image?

答:
Not sure if you are still looking for the answer, but here's how:

```<code>var ctx = document.getElementById('your_canvas').getContext("2d");
//ctx.lineWidth = 13;
//ctx.strokeStyle = 'rgba(0,0,0,1)';
//ctx.fillStyle="rgba(0,0,0,0)" // if using this, make sure alpha < 1

ctx.arc(100,100, 50, 0, Math.PI*2,true); // you can use any shape
ctx.clip();

var img = new Image();
img.addEventListener('load', function(e) {
    ctx.drawImage(this, 0, 0, 200, 300);
    //ctx.fill();
//ctx.stroke();
}, true);
img.src="/path/to/image.jpg";
</code>```

You can also do this with pattern, but you get less image placement flexibility

```<code>ctx.arc(100,100, 70, 0, Math.PI*2,true);
ctx.clip();

img = new Image()
img.addEventListener('load', function(e) {
    ctx.fillStyle = ctx.createPattern(this, 'no-repeat')
    ctx.fill();
}, true);
img.src="/path/to/image.jpg"
</code>```

Title: HTML5 Canvas - Fill circle with image

Body:
How can I draw an image inside a circle? If I do:

context.beginPath();
context.arc((e.pageX),(e.pageY),161,0,Math.PI*2,true);
context.closePath();

How can I then use fill() to fill it with my drawn image?

Body:
Not sure if you are still looking for the answer, but here's how:

var ctx = document.getElementById('your_canvas').getContext("2d");
//ctx.lineWidth = 13;
//ctx.strokeStyle = 'rgba(0,0,0,1)';
//ctx.fillStyle="rgba(0,0,0,0)" // if using this, make sure alpha < 1

ctx.arc(100,100, 50, 0, Math.PI*2,true); // you can use any shape
ctx.clip();

var img = new Image();
img.addEventListener('load', function(e) {
    ctx.drawImage(this, 0, 0, 200, 300);
    //ctx.fill();
//ctx.stroke();
}, true);
img.src="/path/to/image.jpg";

You can also do this with pattern, but you get less image placement flexibility

ctx.arc(100,100, 70, 0, Math.PI*2,true);
ctx.clip();

img = new Image()
img.addEventListener('load', function(e) {
    ctx.fillStyle = ctx.createPattern(this, 'no-repeat')
    ctx.fill();
}, true);
img.src="/path/to/image.jpg"


问:
convert a string to a list of object using Java 8
I have a string

```<code>"Red apple, blue banana, orange".
</code>```

How could I split it by ", " first then add "_" between two words (such as Red_apple but not orange) and capitalize all letters. I read a few posts and found a solution but it only has the split part and how could I also add "_" and capitalize all letters? :

```<code>   Pattern pattern = Pattern.compile(", ");
   List<Fruit> f = pattern.splitAsStream(fruitString)
  .map(Fruit::valueOf)
  .collect(Collectors.toList());
</code>```

Fruit is a enum object. So basically if I am able to convert a string to a certain format and I am able get a Enum object based on a Enum name.

答:
Here is another sample:

```<code>f = pattern.splitAsStream(fruitString)
        .map(s -> Arrays.stream(s.split(" ")).map(String::toUpperCase).collect(Collectors.joining("_")))
        .map(Fruit::valueOf).collect(Collectors.toList());
</code>```

Or by StreamEx:

```<code>StreamEx.split(fruitString, ", ")
        .map(s -> StreamEx.split(s, " ").map(String::toUpperCase).joining("_"))
        .map(Fruit::valueOf).toList();
</code>```

Body:
I have a string

"Red apple, blue banana, orange".

How could I split it by ", " first then add "_" between two words (such as Red_apple but not orange) and capitalize all letters. I read a few posts and found a solution but it only has the split part and how could I also add "_" and capitalize all letters? :

   Pattern pattern = Pattern.compile(", ");
   List<Fruit> f = pattern.splitAsStream(fruitString)
  .map(Fruit::valueOf)
  .collect(Collectors.toList());

Fruit is a enum object. So basically if I am able to convert a string to a certain format and I am able get a Enum object based on a Enum name.

Body:
Here is another sample:

f = pattern.splitAsStream(fruitString)
        .map(s -> Arrays.stream(s.split(" ")).map(String::toUpperCase).collect(Collectors.joining("_")))
        .map(Fruit::valueOf).collect(Collectors.toList());

Or by StreamEx:

StreamEx.split(fruitString, ", ")
        .map(s -> StreamEx.split(s, " ").map(String::toUpperCase).joining("_"))
        .map(Fruit::valueOf).toList();


问:
Can a view be updated/inserted/deleted? If Yes under what conditions?
I googled above question and got the following answers

YES--> If it is in the case of simple view (which consists only one base table).

NO---->If it is in the case of complex view( which consists multiple base tables, and joins).

However, there is an indirect way of performing DML operations on Complex views, by using "Instead Of trigger". In the body of Instead of trigger we will use co-relational identifiers, and DML statements to perform DML operations indirectly on the complex view. Then that changes will reflect in base tables of that particular complex view.

here my question is does changes applied to view will have any effect on original tables?

If a View on a single base table is manipulated will the changes be reflected on the base table?

can any one give me example for the above cases?

答:
In Oracle you can update a view under these conditions:

from: Oracle database SQL Reference

Notes on Updatable Views

An updatable view is one you can use to insert, update, or delete

  base table rows. You can create a view to be inherently updatable, or
  you can create an INSTEAD OF trigger on any view to make it

  updatable.

To learn whether and in what ways the columns of an inherently

  updatable view can be modified, query the USER_UPDATABLE_COLUMNS data
  dictionary view. The information displayed by this view is meaningful
  only for inherently updatable views. For a view to be inherently

  updatable, the following conditions must be met:

Each column in the view must map to a column of a single table. For      example, if a view column maps to the output of a TABLE clause (an

  unnested collection), then the view is not inherently updatable.

The view must not contain any of the following constructs:

A set operator

A DISTINCT operator

An aggregate or analytic function

A GROUP BY, ORDER BY, MODEL, CONNECT BY, or START WITH clause

A collection expression in a SELECT list

A subquery in a SELECT list

A subquery designated WITH READ ONLY

Joins, with some exceptions, as documented in Oracle Database
  Administrator's Guide

In addition, if an inherently updatable view contains pseudocolumns      or expressions, then you cannot update base table rows with an UPDATE
  statement that refers to any of these pseudocolumns or expressions.

If you want a join view to be updatable, then all of the following       conditions must be true:

The DML statement must affect only one table underlying the join.

For an INSERT statement, the view must not be created WITH CHECK
  OPTION, and all columns into which values are inserted must come from
  a key-preserved table. A key-preserved table is one for which every
  primary key or unique key value in the base table is also unique in
  the join view.

For an UPDATE statement, all columns updated must be extracted from
  a key-preserved table. If the view was created WITH CHECK OPTION, then
  join columns and columns taken from tables that are referenced more
  than once in the view must be shielded from UPDATE.

For a DELETE statement, if the join results in more than one    key-preserved table, then Oracle Database deletes from the first

  table named in the FROM clause, whether or not the view was created

  WITH CHECK OPTION.

In SQL Server, you can insert, update, and delete rows in a view, subject to the following limitations, Source

If the view contains joins between multiple tables, you can only    insert and update one table in the view, and you can't delete rows.

You can't directly modify data in views based on union queries. You      can't modify data in views that use GROUP BY or DISTINCT statements.

All columns being modified are subject to the same restrictions as if    the statements were being executed directly against the base
  table.

Text and image columns can't be modified through views.

There is no checking of view criteria. For example, if the view       selects all customers who live in Paris, and data is modified to

  either add or edit a row that does not have City = 'Paris', the data

  will be modified in the base table but not shown in the view, unless

  WITH CHECK OPTION is used when defining the view.


问:
How to know when the Draft.js plugins are ready?
I am using Draft.js plugin Linkify.

I am trying to load the content from the local storage and then linkify it.

Now I have to use setTimeout to wait linkifyPlugin ready. If not, the content loaded will be pure text which is not linkified.

Is there any way like event I can use to know when plugin is ready?

```<code>class MyComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      editorState: EditorState.createEmpty()
    };
  }

  componentDidMount() {
    // ...
    if (hasDraft) this.loadEditor(draftFromLocalStorage);
  }

  loadEditor = rawContent => {
    // here I have to use setTimeout to wait linkifyPlugin ready
    setTimeout(() => {
      const editorState = EditorState.push(this.state.editorState, convertFromRaw(rawContent));
      this.setState({ editorState });
    }, 5);
  };

  render() {
    return (
      <Editor
        editorState={editorState}
        plugins={[linkifyPlugin]}
        onChange={this.onEditorChange} />
    );
  }
}
</code>```

答:
Try using a Promise

```<code>loadEditor(rawContent){
  return new Promise((resolve, reject) => {
    let editorState = EditorState.push(this.state.editorState, convertFromRaw(rawContent));
    resolve(editorState);
  });
}
//call it after component has mounted
componentDidMount(){
  this.loadEditor(draftFromLocalStorage).then(data => this.setState({ editorState: data }));
}
</code>```

Body:
I am using Draft.js plugin Linkify.

I am trying to load the content from the local storage and then linkify it.

Now I have to use setTimeout to wait linkifyPlugin ready. If not, the content loaded will be pure text which is not linkified.

Is there any way like event I can use to know when plugin is ready?

class MyComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      editorState: EditorState.createEmpty()
    };
  }

  componentDidMount() {
    // ...
    if (hasDraft) this.loadEditor(draftFromLocalStorage);
  }

  loadEditor = rawContent => {
    // here I have to use setTimeout to wait linkifyPlugin ready
    setTimeout(() => {
      const editorState = EditorState.push(this.state.editorState, convertFromRaw(rawContent));
      this.setState({ editorState });
    }, 5);
  };

  render() {
    return (
      <Editor
        editorState={editorState}
        plugins={[linkifyPlugin]}
        onChange={this.onEditorChange} />
    );
  }
}

Body:
Try using a Promise

loadEditor(rawContent){
  return new Promise((resolve, reject) => {
    let editorState = EditorState.push(this.state.editorState, convertFromRaw(rawContent));
    resolve(editorState);
  });
}
//call it after component has mounted
componentDidMount(){
  this.loadEditor(draftFromLocalStorage).then(data => this.setState({ editorState: data }));
}


答:
In python when you run for loop on element like string,

You actually iterate over its characters.

That's why in your example you get each characters twice.

For 'dogdog' use: result = 2*'dog'

Body:
def double_char(str):
    result = ''
    for char in str:
        result += char + char
    return result

this is the function, and when i call it, say:

double_char(dog)

it returns: 'ddoogg'

but on line 4 it's saying result = result + char + char wouldn't that yield ''dogdog? I'm really confused and I think I just dont understand the basics of for loops


问:
angular ui grid save and restore state
I need to know how to implement save and restore state in angularui grid without using any buttons. I need to save the state automatically when ever we do any changes in the grid. We have to auto restore the saved state also. Even if we refresh the page the saved state should be restored</p>

答:
it's relatively easy to save the state using Angular $cookies

```<code>    function saveState() {
  var state = $scope.gridApi.saveState.save();
        $cookies.put('gridState', JSON.stringify(state));
}
</code>```

Then, to restore:

```<code>$scope.restoreState = function() {
     $timeout(function() {
    var state = JSON.parse($cookies.get('gridState'));
    if (state) {
        $scope.gridApi.saveState.restore($scope, state);
}
</code>```

Title: angular ui grid save and restore state

Body:
it's relatively easy to save the state using Angular $cookies

    function saveState() {
  var state = $scope.gridApi.saveState.save();
        $cookies.put('gridState', JSON.stringify(state));
}

Then, to restore:

$scope.restoreState = function() {
     $timeout(function() {
    var state = JSON.parse($cookies.get('gridState'));
    if (state) {
        $scope.gridApi.saveState.restore($scope, state);
}


问:
How to filter an array inside of an array of objects?
I have this array that I want to check the days that has the job done inside.(In this case Monday)</p>

```<code>const done = [
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "done"]},
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "done", "done"]},
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "not yet"]},
]

 const freeTime = done
  .filter((event) => event.job === 'done')
console.log(freeTime) // I get nothing here?
</code>```

答:
To check which day has 'done' in all three objects you need to look at them all and build a map that will give you true or false for each day. You can do that like this:

const done = [
    {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "done"]},
    {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "done", "done"]},
    {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "not yet"]},
   ]

var map = done.reduce((a, c ) => {
    c.days.forEach((day, i) => {
        a[day] =  ((a[day] == undefined || a[day] ) && c.job[i] === "done") || false
    })
    return a
}, {})

console.log(map)```

This will result in on abject for true or false for each day. Is that what you'r after?

Body:
I have this array that I want to check the days that has the job done inside.(In this case Monday)

const done = [
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "done"]},
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "done", "done"]},
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "not yet"]},
]

 const freeTime = done
  .filter((event) => event.job === 'done')
console.log(freeTime) // I get nothing here?

Body:
To check which day has 'done' in all three objects you need to look at them all and build a map that will give you true or false for each day. You can do that like this:

const done = [
    {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "done"]},
    {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "done", "done"]},
    {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "not yet"]},
   ]

var map = done.reduce((a, c ) => {
    c.days.forEach((day, i) => {
        a[day] =  ((a[day] == undefined || a[day] ) && c.job[i] === "done") || false
    })
    return a
}, {})

console.log(map)

This will result in on abject for true or false for each day. Is that what you'r after?


问:
How do I read a file using NUnit 3+ (use data from an Excel sheet for my tests)?
I can read the Excel file perfectly, but not pass the parameters to the test.

```<code>[TestFixture]
public class MyTests
{
    [Test, TestCaseSource(typeof(MyDataClass), "TestCases")]
    public int DivideTest(int n, int d)
    {
        return n / d;
    }
}

public class MyDataClass
{
    public static IEnumerable TestCases
    {
        get
        {
            yield return new TestCaseData(12, 3).Returns(4);
            yield return new TestCaseData(12, 2).Returns(6);
            yield return new TestCaseData(12, 4).Returns(3);
        }
    }
}
</code>```

That way you can pass data through IEnumerable. How did you date from an Excel file?

答: If you can read the Excel file already, you are almost there. All you need to do is loop through the rows in the spreadsheet, construct a TestCaseData object using the values from the columns of each row and then yield return the object.

ContentLicense: CC BY-SA 4.0

Body:
I can read the Excel file perfectly, but not pass the parameters to the test.

[TestFixture]
public class MyTests
{
    [Test, TestCaseSource(typeof(MyDataClass), "TestCases")]
    public int DivideTest(int n, int d)
    {
        return n / d;
    }
}

public class MyDataClass
{
    public static IEnumerable TestCases
    {
        get
        {
            yield return new TestCaseData(12, 3).Returns(4);
            yield return new TestCaseData(12, 2).Returns(6);
            yield return new TestCaseData(12, 4).Returns(3);
        }
    }
}

That way you can pass data through IEnumerable. How did you date from an Excel file?


问:
How do I read a text file as a list of lists in python
I have a large text file like this separated into different lines:

35 4 23 12 8 \n
23 6 78 3 5 \n
27 4 9 10 \n
73 5 \n

I need to convert it to a list of lists, each line a separate element like this:

[[35, 4, 23, 12, 8], [23, 6, 78, 3, 5], [27, 4, 9, 10], [73, 5], .......]

答:
You might just be able to use the genfromtxt method in numpy to do so.

```<code>from numpy import genfromtxt
lol = genfromtxt('myFile.csv', delimiter=' ')
</code>```

Find more information here.

Body:
You might just be able to use the genfromtxt method in numpy to do so.

from numpy import genfromtxt
lol = genfromtxt('myFile.csv', delimiter=' ')

Find more information here.


问:
How to avoid use of Thread.Sleep
I never gave the use of Thread.Sleep much thought, until I downloaded the latest version of Netbeans.  Netbeans now warns you not to use Thread.Sleep.  So I did some research on the topic and found people stating that you only need to use Thread.Sleep for debugging/testing purposes and that if you use it at any other time you have poorly written code.

So my question is how can I keep from using Thread.Sleep in the following situation.

I have written a server application that interfaces with another application.  The server has two threads:

Handles the data coming over the socket and sends back other information or just plain acknoledgements.

This is the main thread.  After kicking off the socket thread it going into an indefinite while loop.  Within this while loop I check to make sure the socket thread is still active and that the user hasn't asked to exit the application via a TrayIcon interface.  Then I sleep and continue this while loop.

With this application, the TrayIcon is the only UI.

Here is the snippet I'm referencing:

```<code>// continues running as long as the exitth file is not present and
// the tray icon is not in a safe to exit status.

while(doNotExit())
{

    if (getPrimaryThread() == null || !getPrimaryThread().isAlive())
        resetsThreadAndSocket();

    try
    {
        // check to see if the socket threads are still active, if not create new ones.
        if ((getPrimaryThread() == null || !getPrimaryThread().isAlive()))
            createSocketThread();

        // check right before sleeping that the user does not want to exit.
        if(getTrayIcon().isExiting())
            break;

        // puts the main Thread to sleep for 3 seconds
           Thread.sleep(3000);
    }
    catch(SQLException ex)
    {
        _log.error(ex.getMessage(), ex);
        restartDatabase();
    }
}
</code>```

答:
Instead of your Thread.sleep(3000) do:

```<code>getPrimaryThread().join(3000)
</code>```

This will wait for the thread to exit for 3 seconds.

Title: How to avoid use of Thread.Sleep

Body:
I never gave the use of Thread.Sleep much thought, until I downloaded the latest version of Netbeans.  Netbeans now warns you not to use Thread.Sleep.  So I did some research on the topic and found people stating that you only need to use Thread.Sleep for debugging/testing purposes and that if you use it at any other time you have poorly written code.

So my question is how can I keep from using Thread.Sleep in the following situation.

I have written a server application that interfaces with another application.  The server has two threads:

Handles the data coming over the socket and sends back other information or just plain acknoledgements.

This is the main thread.  After kicking off the socket thread it going into an indefinite while loop.  Within this while loop I check to make sure the socket thread is still active and that the user hasn't asked to exit the application via a TrayIcon interface.  Then I sleep and continue this while loop.

With this application, the TrayIcon is the only UI.

Here is the snippet I'm referencing:

// continues running as long as the exitth file is not present and
// the tray icon is not in a safe to exit status.

while(doNotExit())
{

    if (getPrimaryThread() == null || !getPrimaryThread().isAlive())
        resetsThreadAndSocket();

    try
    {
        // check to see if the socket threads are still active, if not create new ones.
        if ((getPrimaryThread() == null || !getPrimaryThread().isAlive()))
            createSocketThread();

        // check right before sleeping that the user does not want to exit.
        if(getTrayIcon().isExiting())
            break;

        // puts the main Thread to sleep for 3 seconds
           Thread.sleep(3000);
    }
    catch(SQLException ex)
    {
        _log.error(ex.getMessage(), ex);
        restartDatabase();
    }
}

Body:
Instead of your Thread.sleep(3000) do:

getPrimaryThread().join(3000)

This will wait for the thread to exit for 3 seconds.


问:
Custom v-on:click.prevent functionality
I've no idea what to call this so I don't know what to search for. I've looked around the directives but not sure this is what it is either, basically, I want to be able to do:

```<code>v-on:click.validate="runCode"
</code>```

Where validate is a custom method that runs before runCode is called (much in the same way .prevent works.

Can someone point me to some docs / an example?

More Context: I've written some custom form components that feed validation data into my state. These form components can be used as and when i.e

```<code><msp-input
          v-model="form.username"
          :validation="{ required, email }"
          float-label="Email Address"
          type="email"
        />
</code>```

I want to be able to write a button on any of the forms that causes the validation popup to show if the state shows some validation has failed. I could have an <msp-button> component to do it but thought it would be nice to have an inline .validate.

答:
Using the example v-on:click.validate, validate is called a modifier, and click is an argument to the v-on directive. This is covered in the documentation for custom directives.

There is no way currently to add your own custom modifiers to built in directives (this is covered in several issues on the github repo). You could potentially write your own directive and handle arguments and modifiers as you see fit.

Otherwise your other approach sounds fine.

Title: Custom v-on:click.prevent functionality

Body:
I've no idea what to call this so I don't know what to search for. I've looked around the directives but not sure this is what it is either, basically, I want to be able to do:

v-on:click.validate="runCode"

Where validate is a custom method that runs before runCode is called (much in the same way .prevent works.

Can someone point me to some docs / an example?

More Context: I've written some custom form components that feed validation data into my state. These form components can be used as and when i.e

<msp-input
          v-model="form.username"
          :validation="{ required, email }"
          float-label="Email Address"
          type="email"
        />

I want to be able to write a button on any of the forms that causes the validation popup to show if the state shows some validation has failed. I could have an <msp-button> component to do it but thought it would be nice to have an inline .validate.


问:
How to redirect php forms to different urls?
I want the user to pick and option from a dropdown, and be redirected to a page based on their selection. Option 1 redirecting to Page 1, Option 2 redirecting to Page 2, etc.

When I try to look this up, I get results for how to redirect a user to a url no matter what they enter or select on the form. A form completion redirect.

So I am looking for an example of how to redirect based on selection from a dropdown with each selection having a different redirect.

答:
You could try us JavaScript, something like the below code?  </p>

```<code><form name="store" id="form" method="post" action="">
<select name="formID">
<option value="/stores/form1.php">6</option>
<option value="/stores/form2.php">10</option>
</select>
</form>

<script>
document.getElementById('form').formID.onchange = function() {
    var newaction = this.value;
    document.getElementById('form').action = newaction;
};

</script>
</code>```

<p>You can find more info here too. </p>

Body:
You could try us JavaScript, something like the below code?

<form name="store" id="form" method="post" action="">
<select name="formID">
<option value="/stores/form1.php">6</option>
<option value="/stores/form2.php">10</option>
</select>
</form>

<script>
document.getElementById('form').formID.onchange = function() {
    var newaction = this.value;
    document.getElementById('form').action = newaction;
};

</script>

You can find more info here too.


问:
Return a dictionary with keys that are the first letter of a word and lists of those words?
I want to write a function that takes a list of words and keys and outputs those keys as dictionary keys with any words starting with that letter attached.
How could this be achieved using simple python 3 code?

eg. takes (['apples', 'apple', 'bananna', 'fan'], 'fad')

returns {'a' : ['apple', 'apples'], 'f' : ['fan']}

so far i have tried:

```<code>def dictionary(words, char_keys)
char_keys = remove_duplicates(char_keys)
ret = {}
keys_in_dict = []
words = sorted(words)
for word in words:
    if word[0] in char_keys and word[0] not in keys_in_dict:
        ret[word[0]] = word
        keys_in_dict.append(word[0])
    elif word[0] in keys_in_dict:
        ret[word[0]] += (word)
return ret
</code>```

This gives kinda the right output but it the output is in a single string rather than a list of strings.(the def is not indented properly i know)

答:
Not sure if your list of inputs are consisted with only strings or it can also include sub-lists of strings (and I'm not so sure why "fad" disappeared in your example). Obviously, in the latter scenario it will need some more effort. For simplicity I assume if contains only strings and here's a piece of code which hopefully points the direction:</p>

```<code>d = {}
for elem in input_list[0]:
    if elem[0] in input_list[1]
        lst = d.get(elem[0], [])
        lst.append(elem)
        d[elem] = lst
</code>```

Body:
I want to write a function that takes a list of words and keys and outputs those keys as dictionary keys with any words starting with that letter attached.
How could this be achieved using simple python 3 code?

eg. takes (['apples', 'apple', 'bananna', 'fan'], 'fad')

returns {'a' : ['apple', 'apples'], 'f' : ['fan']}

so far i have tried:

def dictionary(words, char_keys)
char_keys = remove_duplicates(char_keys)
ret = {}
keys_in_dict = []
words = sorted(words)
for word in words:
    if word[0] in char_keys and word[0] not in keys_in_dict:
        ret[word[0]] = word
        keys_in_dict.append(word[0])
    elif word[0] in keys_in_dict:
        ret[word[0]] += (word)
return ret

This gives kinda the right output but it the output is in a single string rather than a list of strings.(the def is not indented properly i know)

Body:
Not sure if your list of inputs are consisted with only strings or it can also include sub-lists of strings (and I'm not so sure why "fad" disappeared in your example). Obviously, in the latter scenario it will need some more effort. For simplicity I assume if contains only strings and here's a piece of code which hopefully points the direction:

d = {}
for elem in input_list[0]:
    if elem[0] in input_list[1]
        lst = d.get(elem[0], [])
        lst.append(elem)
        d[elem] = lst


问:
ANT & MSBUILD - build process won't fail if errors
When running msbuild.exe with ANT's exec task, errors in the .net code do not result in the build process failing.

Why would this be?

答:
What do you let the msbuild task do ?

When I used NAnt previously, I used the  task to build a VS.NET solution.

Right now, I'm not using NAnt anymore, I use msbuild instead. :)

OwnerDisplayName: Bert Vandamme

OwnerDisplayName: Frederik Gheysels


问:
I'm having trouble understanding this for loop and what its returning
```<code>def double_char(str):
    result = ''
    for char in str:
        result += char + char
    return result
</code>```

this is the function, and when i call it, say:

```<code>double_char(dog)
</code>```

it returns: 'ddoogg'

but on line 4 it's saying result = result + char + char wouldn't that yield ''dogdog? I'm really confused and I think I just dont understand the basics of for loops

答:
Let's try running the function:

```<code>def double_char(string):
    result = ''
    for char in string:
        result += char + char
    return result

print(double_char('dog'))
</code>```

It returns:

```<code>ddoogg
</code>```

So, what this function is doing is defining an emptry string (result).  Many programs do this, they have a temporary empty string.  Then that string gets filled up with new information generated by a loop (for char in string:).  This loop loops through every character in the string, so d, o, and g.  However, there is a twist.  This code adds two of the same character for every character inside of the string so, it goes result += 'd' + 'd' on the first iteration.  And then result += 'o' + 'o'.  The += operater is simply squishing two strings together, like dd from the first iteration with oo from the second iteration.  From there, we get ddoo. And it continues until the end of the string.  Finally, we use the return statement to send out the new temporary string we created, result.

Body:
Let's try running the function:

def double_char(string):
    result = ''
    for char in string:
        result += char + char
    return result

print(double_char('dog'))

It returns:

ddoogg

So, what this function is doing is defining an emptry string (result).  Many programs do this, they have a temporary empty string.  Then that string gets filled up with new information generated by a loop (for char in string:).  This loop loops through every character in the string, so d, o, and g.  However, there is a twist.  This code adds two of the same character for every character inside of the string so, it goes result += 'd' + 'd' on the first iteration.  And then result += 'o' + 'o'.  The += operater is simply squishing two strings together, like dd from the first iteration with oo from the second iteration.  From there, we get ddoo. And it continues until the end of the string.  Finally, we use the return statement to send out the new temporary string we created, result.