问:
Convert a react class component to react hooks component
I want to convert this react class component into a react hooks component.
I converted most of the code and now I need help to convert the part of code that is between the render and the return functions.

Here is the class component:

```<code>class LoginGoogle extends React.Component {
    state = {
        loading: true,
        error: null,
        data: {},
    };

    componentDidMount() {
        fetch(`/api/auth/google/callback${this.props.location.search}`, { headers: new Headers({ accept: 'application/json' }) })
            .then((response) => {
                if (response.ok) {
                    return response.json();
                }
                throw new Error('Something went wrong!');
            })
            .then((data) => {
                this.setState({ loading: false, data });
            })
            .catch((error) => {
                this.setState({ loading: false, error });
                console.error(error);
            });
    }

    render() {
        const { loading, error, data } = this.state;
        if (loading) {
            return <Layout>Loading....</Layout>;
        }

        if (error) {
            return (
                <Layout>
                    <div>
                        <p>Error:</p>
                        <code className="Code-block">{error.toString()}</code>
                    </div>
                </Layout>
            );
        }

        return (
            <Layout>
                <div>
                    <details>
                        <summary>Welcome {data.user.name}</summary>
                        <p>Here is your info: </p>
                        <code className="Code-block">{JSON.stringify(data, null, 2)}</code>
                    </details>
                </div>
            </Layout>
        );
    }
}
</code>```

And this is the new react hooks component that I created. As I mentioned before it's still not finished yet.

```<code>function LoginGoogle (props) {

    const [start, setStart] = useState(
        {
        loading: true,
        error: null,
        data: {},
           }
    )

    useEffect(() => {
        fetch(`/api/auth/google/callback${props.location.search}`, { headers: new Headers({ accept: 'application/json' }) })
            .then((response) => {
                if (response.ok) {
                    return response.json();
                }
                throw new Error('Something went wrong!');
            })
            .then((data) => {
                setStart({ loading: false, data });
            })
            .catch((error) => {
                setStart({ loading: false, error });
                console.error(error);
            });
    })

        const { loading, error, data } = this.state;
        if (loading) {
            return <Layout>Loading....</Layout>;
        }

        if (error) {
            return (
                <Layout>
                    <div>
                        <p>Error:</p>
                        <code className="Code-block">{error.toString()}</code>
                    </div>
                </Layout>
            );
        }

        return (
            <Layout>
                <div>
                    <details>
                        <summary>Welcome {data.user.name}</summary>
                        <p>Here is your info: </p>
                        <code className="Code-block">{JSON.stringify(data, null, 2)}</code>
                    </details>
                </div>
            </Layout>
        );
    }
</code>```

These are the steps that I took to convert the code :
10 Steps to Convert React Class Component to React Functional Component with Hooks!

答:
Right now your fetch request is running on EVERY render, if you wanted to simulate componentDidMount behaviour, you would need to pass in an empty dependency array to the useEffect

```<code>useEffect(() => {
    fetch(`/api/auth/google/callback${props.location.search}`, { headers: new Headers({ accept: 'application/json' }) })
        .then((response) => {
            if (response.ok) {
                return response.json();
            }
            throw new Error('Something went wrong!');
        })
        .then((data) => {
            setStart({ loading: false, data });
        })
        .catch((error) => {
            setStart({ loading: false, error });
            console.error(error);
        });
}, []) // See the empty dependency array
</code>```

By adding an empty dependency list, it will run once.

const { loading, error, data } = this.state

becomes

const {loading, error, data} = start

Body:
I want to convert this react class component into a react hooks component.
I converted most of the code and now I need help to convert the part of code that is between the render and the return functions.

Here is the class component:

class LoginGoogle extends React.Component {
    state = {
        loading: true,
        error: null,
        data: {},
    };

    componentDidMount() {
        fetch(`/api/auth/google/callback${this.props.location.search}`, { headers: new Headers({ accept: 'application/json' }) })
            .then((response) => {
                if (response.ok) {
                    return response.json();
                }
                throw new Error('Something went wrong!');
            })
            .then((data) => {
                this.setState({ loading: false, data });
            })
            .catch((error) => {
                this.setState({ loading: false, error });
                console.error(error);
            });
    }

    render() {
        const { loading, error, data } = this.state;
        if (loading) {
            return <Layout>Loading....</Layout>;
        }

        if (error) {
            return (
                <Layout>

Error:

                        {error.toString()}

                </Layout>
            );
        }

        return (
            <Layout>

                        Welcome {data.user.name}

Here is your info:

                        {JSON.stringify(data, null, 2)}

            </Layout>
        );
    }
}

And this is the new react hooks component that I created. As I mentioned before it's still not finished yet.

function LoginGoogle (props) {

    const [start, setStart] = useState(
        {
        loading: true,
        error: null,
        data: {},
           }
    )

    useEffect(() => {
        fetch(`/api/auth/google/callback${props.location.search}`, { headers: new Headers({ accept: 'application/json' }) })
            .then((response) => {
                if (response.ok) {
                    return response.json();
                }
                throw new Error('Something went wrong!');
            })
            .then((data) => {
                setStart({ loading: false, data });
            })
            .catch((error) => {
                setStart({ loading: false, error });
                console.error(error);
            });
    })

        const { loading, error, data } = this.state;
        if (loading) {
            return <Layout>Loading....</Layout>;
        }

        if (error) {
            return (
                <Layout>

Error:

                        {error.toString()}

                </Layout>
            );
        }

        return (
            <Layout>

                        Welcome {data.user.name}

Here is your info:

                        {JSON.stringify(data, null, 2)}

            </Layout>
        );
    }

These are the steps that I took to convert the code :
10 Steps to Convert React Class Component to React Functional Component with Hooks!

Body:
Right now your fetch request is running on EVERY render, if you wanted to simulate componentDidMount behaviour, you would need to pass in an empty dependency array to the useEffect

useEffect(() => {
    fetch(`/api/auth/google/callback${props.location.search}`, { headers: new Headers({ accept: 'application/json' }) })
        .then((response) => {
            if (response.ok) {
                return response.json();
            }
            throw new Error('Something went wrong!');
        })
        .then((data) => {
            setStart({ loading: false, data });
        })
        .catch((error) => {
            setStart({ loading: false, error });
            console.error(error);
        });
}, []) // See the empty dependency array

By adding an empty dependency list, it will run once.

const { loading, error, data } = this.state

becomes

const {loading, error, data} = start


来源: stackexchange

问:
Why is the length of an array 0 after a assign a key/value pair? (JS)
```<code>var array = new Array()
array.name = 'peter'
console.log(array.length) //returns 0
console.log(array.name) //returns peter
</code>```

I would've expected the length to be 1 and not 0. Can anyone explain what is going on here?

答: That merely add a property name to instance of that array object.  To actually add item to the array to increase its size, you need to push item into it.  Something like, array.push('peter').</p>

ContentLicense: CC BY-SA 4.0

Body:
var array = new Array()
array.name = 'peter'
console.log(array.length) //returns 0
console.log(array.name) //returns peter

I would've expected the length to be 1 and not 0. Can anyone explain what is going on here?


问:
Should Firebase listeners be removed when a Native app is "backgrounded"?
It's considered good practice to remove listeners from Firebase databases (whether that be Cloud Firestore or Realtime Database) when the listening components are unmounted.

In a lot of applications, mine included (React Native app), this might not happen very often.

For example, when my user is authenticated (signed in), they are subscribed to a number of listeners on both RTDB and CFS. Things like notifications and messages and other "realtime" updates i want them to see app-wide - think notification "badges" for example or "unread messages".

Developers of Native applications will know that apps can remain "backgrounded" for long periods of time. And with auth refreshing, users will rarely log out of my application. This means that those components are never (or rarely) unmounted and thus, remain subscribed to updates - i think.

Should i be adding logic that removes those subscribers to realtime data when a user backgrounds the application, only to re-instate them when they foreground again?

答:
What you're asking is primarily a matter of opinion, which is off-topic for Stack Overflow.  That said, you should probably take some time to understand the ramifications of leaving listeners added indefinitely.

A listener that's not removed when the user isn't looking at your app still incurs the cost of downloading updates to the documents it's listening to.  Whether or not that's acceptable is entirely up to you.

The host OS will likely throttle the network access of app that can't be seen by the user after some time.  This is for the benefit of the user, so poorly implemented apps don't consume excess network and battery.  You can't depend on these listeners to work properly when this happens.  If you want listeners to stay active while the app isn't visible, you will need to tell the host OS what you want using whatever APIs it provides.  Even then, you don't have any guarantees, as the OS may simply kill an invisible app in order to reclaims resources.

You will have to decide for yourself when it makes sense add and remove listeners, after you understand the behavior apps on the given OS.


问:
How to spread a nested object in Javascript?
I've been trying to copy a nested object properties into another object by using the spread operator. But, I got an error.

So I tried to spread the nested object separately:

```<code>try {
  console.log(
    ...{
      autre_panne: { nbr_op_sav: 12, percentage_op_sav: 0 },
      fonctionnement_bluetooth: { nbr_op_sav: 13, percentage_op_sav: 0 },
      memoire_interne: { nbr_op_sav: 15, percentage_op_sav: 0 },
      non_precise: { nbr_op_sav: 15, percentage_op_sav: 0 },
      panne_audio: { nbr_op_sav: 68, percentage_op_sav: 0 },
      piece_aspect_mecanique: { nbr_op_sav: 78, percentage_op_sav: 0 },
      probleme_charge: { nbr_op_sav: 2, percentage_op_sav: 0 },
    }
  );
} catch (error) {
  console.log("Error spreading");
  console.log(error);
}
</code>```

I get this error:

Error spreading TypeError: Found non-callable @@iterator

      at Object. (C:\Users\Avempace\Desktop\Projects\playground\play.js:227:11)

      at Module._compile (internal/modules/cjs/loader.js:955:30)

      at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)

      at Module.load (internal/modules/cjs/loader.js:811:32)

      at Function.Module._load (internal/modules/cjs/loader.js:723:14)

      at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)

PS:
Similar questions mentioned in SO, do not answer my question:

1. How to use object spread with nested properties?

2. How to spread nested properties in Object?

答:
Not sure if this is an issue with the way you test your actual problem, but you need to spread your object into an object - in the console.log call I'm not sure what you want the end result to be but you if you spread into an object it should work:

```<code>try {
  console.log(
    {...{
      autre_panne: { nbr_op_sav: 12, percentage_op_sav: 0 },
      fonctionnement_bluetooth: { nbr_op_sav: 13, percentage_op_sav: 0 },
      memoire_interne: { nbr_op_sav: 15, percentage_op_sav: 0 },
      non_precise: { nbr_op_sav: 15, percentage_op_sav: 0 },
      panne_audio: { nbr_op_sav: 68, percentage_op_sav: 0 },
      piece_aspect_mecanique: { nbr_op_sav: 78, percentage_op_sav: 0 },
      probleme_charge: { nbr_op_sav: 2, percentage_op_sav: 0 },
    }}
  );
} catch (error) {
  console.log("Error spreading");
  console.log(error);
}
</code>```

By "it should work", I mean that you should be able to print the object (that is actually spread into a new object).

Body:
I've been trying to copy a nested object properties into another object by using the spread operator. But, I got an error.

So I tried to spread the nested object separately:

try {
  console.log(
    ...{
      autre_panne: { nbr_op_sav: 12, percentage_op_sav: 0 },
      fonctionnement_bluetooth: { nbr_op_sav: 13, percentage_op_sav: 0 },
      memoire_interne: { nbr_op_sav: 15, percentage_op_sav: 0 },
      non_precise: { nbr_op_sav: 15, percentage_op_sav: 0 },
      panne_audio: { nbr_op_sav: 68, percentage_op_sav: 0 },
      piece_aspect_mecanique: { nbr_op_sav: 78, percentage_op_sav: 0 },
      probleme_charge: { nbr_op_sav: 2, percentage_op_sav: 0 },
    }
  );
} catch (error) {
  console.log("Error spreading");
  console.log(error);
}

I get this error:

Error spreading TypeError: Found non-callable @@iterator

      at Object. (C:\Users\Avempace\Desktop\Projects\playground\play.js:227:11)

      at Module._compile (internal/modules/cjs/loader.js:955:30)

      at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)

      at Module.load (internal/modules/cjs/loader.js:811:32)

      at Function.Module._load (internal/modules/cjs/loader.js:723:14)

      at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)

PS:
Similar questions mentioned in SO, do not answer my question:

1. How to use object spread with nested properties?

2. How to spread nested properties in Object?

Body:
Not sure if this is an issue with the way you test your actual problem, but you need to spread your object into an object - in the console.log call I'm not sure what you want the end result to be but you if you spread into an object it should work:

try {
  console.log(
    {...{
      autre_panne: { nbr_op_sav: 12, percentage_op_sav: 0 },
      fonctionnement_bluetooth: { nbr_op_sav: 13, percentage_op_sav: 0 },
      memoire_interne: { nbr_op_sav: 15, percentage_op_sav: 0 },
      non_precise: { nbr_op_sav: 15, percentage_op_sav: 0 },
      panne_audio: { nbr_op_sav: 68, percentage_op_sav: 0 },
      piece_aspect_mecanique: { nbr_op_sav: 78, percentage_op_sav: 0 },
      probleme_charge: { nbr_op_sav: 2, percentage_op_sav: 0 },
    }}
  );
} catch (error) {
  console.log("Error spreading");
  console.log(error);
}

By "it should work", I mean that you should be able to print the object (that is actually spread into a new object).


问:
http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /
I'm really very new to this Tomcat stuff. I downloaded Tomcat 7.0 windows installer and installed it using the default configuration. After installing, I typed localhost:8080 in my browser to see if Tomcat is working. However,it showed error message like this: Access Error: 404 -- Not Found Cannot locate document: /  And there's nothing else show with Tomcat or Apache words in the page. It seems Tomcat not responding.

I googled and searched this forum, but so far the solutions people provided didn't work for me.

checked the server.xml file, 8080 is the HTTP connector port:

Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443"

I did run the Tomcat7.exe in the \bin folder. Something run in the command window and disappeared then. Nothing changed then.

I set some environment system variables like JAVA HOME, PATH, and CLASSPATH according to some tutorials online.

Still not work. Only things I'm suspicious are:
1. I have two JRE folder: jre6 and jre7 in the program files directory. Tomcat7 chose the jre7 one.
2. I installed anyother server called Wamp server, which I used to learn some PHP programming with SQL usage. There's Apache in the package. Not sure if it's using 8080 port.

Please help. I've already digged online more than 2hrs for this headache. Any comments are welcome.

答: For CentOS users (at least), one will also get a 404 error trying to access the server on port 8080 on a fresh install if the tomcat-webapps package is not installed.

ContentLicense: CC BY-SA 3.0


问:
TFS branching, what are the advantages
I am pretty new to TFS and source control. I unable to understand the advantage of branching. Since i can do the same stuff by creating 2 folder main and development, when I am done with development.I can  merge the code using any diff tool with the main branch.

Then whats the point of having branches ? I know there must a huge advantage but i am unable to understand.

答:
(UPDATE: TFS now supports git for version control so the rest of this answer no longer applies)

I would google branch-per-feature.

The main advantage of branching is that you can work on a feature and not be interrupted by anyone else's work. When you are ready, you can merge and see if many features work well together or not. This is usually done as the feature is developed but for small features can be done once the feature is complete.

The advantage is that you have a clear history of what you did to implement something. Without branches, you would have a whole lot of commits mixed together with other features' commits. If QA does not pass a certain feature, you have your work cut out for you to put together another build using just the commits for the other features. The other alternative is to try and fix your feature so that QA passes. This may not be doable on a Friday afternoon.

Feature toggles are another way to omit work but this increases the complexity of code and the toggles may themselves have bugs in them. This is something to be very weary of and see how this became an "acceptable" work-around.

Branches are also used to track changes to multiple versions of releases. Products that are consumed by multiple customers may be in a situation that one set of customers is using 1.0 of the product while others are already on 2.0. If you support both, you should track changes to each by branches that are designated to them. The previous points still apply to developing for these branches.

Having said that, TFS is not ideal at branch-per-feature for a number of reasons. The biggest is that it does not support 3-way merges - it only has what is called a baseless merge. The way history is tracked, TFS cannot show you a common ancestor between the feature branch and where you are trying to merge it to. This leaves you potentially solving a lot of conflicts. In general, a lot of people that use TFS shy away from branching for this reason.

3-way merges are great because they will show you what the common ancestor is, what your changes are and what the changes in the other branch are. This will allow you to make a very educated decision on how to resolve a conflict.

If you have to use TFS, I would suggest using git-tfs to be able to take advantage of 3-way merges and many other features. Some of them include: rerere, rebasing, disconnected model, local history, bisect, and many many more.

Rebase is very useful as it allows you to alter a feature to be based off of another starting point, omit commits, squash commits together, split commits, etc. Once ready you can them merge into an integration or release branch, depending on the workflow you decide upon.

Mercurial is also another one that may be easier to use, but will not be as powerful in the long run.

If you have the opportunity, I would highly recommend moving away from TFS for source control due to a lot of limitations when compared to modern day DVCS.

Here is a nice set of guidelines to follow if you want to effectively manage branching/merging:

http://dymitruk.com/blog/2012/02/05/branch-per-feature/

Hope this helps.

Title: TFS branching, what are the advantages


问:
Realm Swift: Object has been deleted or invalidated
I have a tableViewController (ArticlesVC) that displays an array of Articles that are fetched from an API. Each of these tableViewCell has a "more action" button that allows the user to save the article for later reading in the SavedVC. Note that only saved articles are written to Realm DB, the displaying of articles in the ArticlesVC are not written to Realm DB.

If the user has saved the article, I would show "Remove saved article", otherwise, I show "Save for later". I query Realm to conduct this check.

However, if I delete a saved article (or all saved articles) from Realm from SavedVC and go back to the ArticlesVC and start swiping the tableView, it crashes with the above error. This crash happens on an intermittent basis, making it pretty hard to pinpoint.

Code

```<code>//At ArticlesVC, where articles are fetched via API
func getArticles() {
    AF.request(apiUrl).responseJSON { (response) in
        //Error checks and decoding ...

        self.articles = try decoder.decode(Article.self, from: data)
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ArticleCell
    cell.article = articles[indexPath.row]
    cell.moreButton.tag = indexPath.row
    cell.moreButton.addTarget(self, action: #selector(moreButtonTapped(sender:)), for: .touchUpInside)
    return cell
}

@objc func moreButtonTapped(sender: UIButton) {
    let buttonTag = sender.tag
    let article = articles[buttonTag]

    let alert = UIAlertController(title: "More", message: nil, preferredStyle: .actionSheet)
    let action = getAction(article: article)
    alert.addActions([action, .cancelAction()])
    //present alert
}

func getAction(article: Article) -> UIAlertAction {

    do {
        let realm = try Realm()
        let articleInRealm = realm.objects(Article.self).filter("id == %@", article.id)

        if articleInRealm.isInvalidated {
            return UIAlertAction(title: "Save for later", style: .default, handler: {(_) in
                self.saveArticle(article: article)
            })
        } else {
            if articleInRealm.count == 0 {
                return UIAlertAction(title: "Save for later", style: .default, handler: {(_) in
                    self.saveArticle(article: article)
                })
            } else {
                return UIAlertAction(title: "Remove saved article", style: .destructive, handler: {(_) in
                    self.deleteArticle(article: articleInRealm)
                })
            }
        }

    } catch {
        Log("Err getting article: \(error.localizedDescription)")
        return UIAlertAction(title: "Save for later", style: .default, handler: {(_) in
            self.saveArticle(article: article)
        })
    }
}

func saveArticle(article: Article) {
    do {
        let realm = try Realm()

        try realm.write {
            realm.add(article, update: .modified)
        }

    } catch {
        Log("Err saving article: \(error.localizedDescription)")
    }
}

func deleteArticle(article: Results<Article>) {
    do {
        let realm = try Realm()

        try realm.write {
            realm.delete(article)
        }

    } catch {
        Log("Err saving article: \(error.localizedDescription)")
    }
}

//At SavedVC, which is another VC in the tabBarController.
//ArticlesVC is in tab1 and SavedVC is in tab2
var notificationToken: NotificationToken? = nil
var articles: Results<Article>?

override func viewDidLoad() {
    super.viewDidLoad()

    subscribeToRealmNotifications()
}

fileprivate func subscribeToRealmNotifications() {
    let realm = try! Realm()
    let results = realm.objects(Article.self)

    notificationToken = results.observe { [weak self] (changes: RealmCollectionChange) in

        guard let tableView = self?.tableView else { return }

        switch changes {
            case .initial:

                self?.articles = results

                tableView.reloadData()

            case .update(_, _, _, _):
                tableView.reloadData()

            case .error(let error):
                fatalError("Realm notif: \(error.localizedDescription)")
        }
    }
}
</code>```

My guess is that because I have deleted the articles in SavedVC but ArticlesVC is still pointing to those Realm objects which no longer exist and therefore crashed.

I have read multiple SO posts that suggest to do a check on obj.isInvalidated, which I did and have included a condition for it. But this still crashes.

Other attempts includes:

using realm.create() instead of realm.add()

答:
Here's the issue: You've saving an unmanaged object (article) into realm

```<code>func getAction(article: Article)
    ...
    self.saveArticle(article: article)
</code>```

which then makes it a managed object.

If it's deleted from Realm,

```<code>realm.delete(article)
</code>```

it will also be removed from the results object that contains it

```<code>articles[indexPath.row]
</code>```

Which will then make your app crash as it's scrolling as the dataSource and tableView are out of sync.

I have a feeling you don't want it to actually be removed from the master list of articles.

My suggestion is to save any articles you want to read later by their id which will have no effect on the master list of articles as they are added and removed from realm.

In other words your master list of articles stays the same but in Realm, you have a table of id's which are strings for example. So when you want to track what they want to read

```<code>self.saveArticleId(article: article.id)
</code>```

and then when it's time to delete it from their saved reading list

```<code>self.deleteArticleBy(articleId: artical.id)
</code>```

Body:
I have a tableViewController (ArticlesVC) that displays an array of Articles that are fetched from an API. Each of these tableViewCell has a "more action" button that allows the user to save the article for later reading in the SavedVC. Note that only saved articles are written to Realm DB, the displaying of articles in the ArticlesVC are not written to Realm DB.

If the user has saved the article, I would show "Remove saved article", otherwise, I show "Save for later". I query Realm to conduct this check.

However, if I delete a saved article (or all saved articles) from Realm from SavedVC and go back to the ArticlesVC and start swiping the tableView, it crashes with the above error. This crash happens on an intermittent basis, making it pretty hard to pinpoint.

Code

//At ArticlesVC, where articles are fetched via API
func getArticles() {
    AF.request(apiUrl).responseJSON { (response) in
        //Error checks and decoding ...

        self.articles = try decoder.decode(Article.self, from: data)
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ArticleCell
    cell.article = articles[indexPath.row]
    cell.moreButton.tag = indexPath.row
    cell.moreButton.addTarget(self, action: #selector(moreButtonTapped(sender:)), for: .touchUpInside)
    return cell
}

@objc func moreButtonTapped(sender: UIButton) {
    let buttonTag = sender.tag
    let article = articles[buttonTag]

    let alert = UIAlertController(title: "More", message: nil, preferredStyle: .actionSheet)
    let action = getAction(article: article)
    alert.addActions([action, .cancelAction()])
    //present alert
}

func getAction(article: Article) -> UIAlertAction {

    do {
        let realm = try Realm()
        let articleInRealm = realm.objects(Article.self).filter("id == %@", article.id)

        if articleInRealm.isInvalidated {
            return UIAlertAction(title: "Save for later", style: .default, handler: {(_) in
                self.saveArticle(article: article)
            })
        } else {
            if articleInRealm.count == 0 {
                return UIAlertAction(title: "Save for later", style: .default, handler: {(_) in
                    self.saveArticle(article: article)
                })
            } else {
                return UIAlertAction(title: "Remove saved article", style: .destructive, handler: {(_) in
                    self.deleteArticle(article: articleInRealm)
                })
            }
        }

    } catch {
        Log("Err getting article: \(error.localizedDescription)")
        return UIAlertAction(title: "Save for later", style: .default, handler: {(_) in
            self.saveArticle(article: article)
        })
    }
}

func saveArticle(article: Article) {
    do {
        let realm = try Realm()

        try realm.write {
            realm.add(article, update: .modified)
        }

    } catch {
        Log("Err saving article: \(error.localizedDescription)")
    }
}

func deleteArticle(article: Results
) {
    do {
        let realm = try Realm()

        try realm.write {
            realm.delete(article)
        }

    } catch {
        Log("Err saving article: \(error.localizedDescription)")
    }
}

//At SavedVC, which is another VC in the tabBarController.
//ArticlesVC is in tab1 and SavedVC is in tab2
var notificationToken: NotificationToken? = nil
var articles: Results
?

override func viewDidLoad() {
    super.viewDidLoad()

    subscribeToRealmNotifications()
}

fileprivate func subscribeToRealmNotifications() {
    let realm = try! Realm()
    let results = realm.objects(Article.self)

    notificationToken = results.observe { [weak self] (changes: RealmCollectionChange) in

        guard let tableView = self?.tableView else { return }

        switch changes {
            case .initial:

                self?.articles = results

                tableView.reloadData()

            case .update(_, _, _, _):
                tableView.reloadData()

            case .error(let error):
                fatalError("Realm notif: \(error.localizedDescription)")
        }
    }
}

My guess is that because I have deleted the articles in SavedVC but ArticlesVC is still pointing to those Realm objects which no longer exist and therefore crashed.

I have read multiple SO posts that suggest to do a check on obj.isInvalidated, which I did and have included a condition for it. But this still crashes.

Other attempts includes:

using realm.create() instead of realm.add()

Body:
Here's the issue: You've saving an unmanaged object (article) into realm

func getAction(article: Article)
    ...
    self.saveArticle(article: article)

which then makes it a managed object.

If it's deleted from Realm,

realm.delete(article)

it will also be removed from the results object that contains it

articles[indexPath.row]

Which will then make your app crash as it's scrolling as the dataSource and tableView are out of sync.

I have a feeling you don't want it to actually be removed from the master list of articles.

My suggestion is to save any articles you want to read later by their id which will have no effect on the master list of articles as they are added and removed from realm.

In other words your master list of articles stays the same but in Realm, you have a table of id's which are strings for example. So when you want to track what they want to read

self.saveArticleId(article: article.id)

and then when it's time to delete it from their saved reading list

self.deleteArticleBy(articleId: artical.id)


问:
Error in kinship2 creating of pedigree object
I am trying to plot very simple pedigrees with kinship2. I only have one generations but lots of different families.

```<code>id <- sample(1:100, 50, replace=F)
dadid <- sample(100:110, 50, replace=T)
momid <- sample(111:121, 50, replace=T)
sex <- sample(1:3, 50, replace=T)

df <- data.frame(cbind(dadid, momid, id, sex))

df<- df %>% mutate(famid = group_indices(., momid, dadid))
</code>```

When I try and convert my data into a pedigree() object:

```<code>pedAll <- pedigree(
  id = id,
  dadid = dadid,
  momid = momid,
  sex = sex,
  famid = famid)
</code>```

I get the following error:

```<code>Error in pedigree(id = id, dadid = dadid, momid = momid, sex = sex, famid = famid) :
  Value of 'dadid' not found in the id list 1/101 5/100 5/103 11/103 11/107
</code>```

Any ideas why? I have been doing round in circles for ages and there is not much out there using this package.

答:
I just started to learn how to use this library some days ago.
In your dataframe you need to have a row for each individual present (mother and father included) with either both parents specified or none.
You can either adding them by hand or use the function fixParent() of kinship2. This function will add the missing parents, fix genders problems and add second parents for children for whom only one parent id is given.

```<code>df_fixed <- with(df,fixParents(
  id = id,
  dadid = dadid,
  momid = momid,
  sex = sex))
</code>```

This new dataframe can then be use to create your pedigree.

```<code>pedAll <- with(df_fixed,pedigree(
  id = id,
  dadid = dadid,
  momid = momid,
  sex = sex))
plot(pedAll)
</code>```

However I don't quite understand what you want to do with the 'mutate' function. If you subdivide your dataframe in family, be sure that every individual inside each family has its own row (that doesn't seems to be the case with your code).

Body:
I am trying to plot very simple pedigrees with kinship2. I only have one generations but lots of different families.

id <- sample(1:100, 50, replace=F)
dadid <- sample(100:110, 50, replace=T)
momid <- sample(111:121, 50, replace=T)
sex <- sample(1:3, 50, replace=T)

df <- data.frame(cbind(dadid, momid, id, sex))

df<- df %>% mutate(famid = group_indices(., momid, dadid))

When I try and convert my data into a pedigree() object:

pedAll <- pedigree(
  id = id,
  dadid = dadid,
  momid = momid,
  sex = sex,
  famid = famid)

I get the following error:

Error in pedigree(id = id, dadid = dadid, momid = momid, sex = sex, famid = famid) :
  Value of 'dadid' not found in the id list 1/101 5/100 5/103 11/103 11/107

Any ideas why? I have been doing round in circles for ages and there is not much out there using this package.

Body:
I just started to learn how to use this library some days ago.
In your dataframe you need to have a row for each individual present (mother and father included) with either both parents specified or none.
You can either adding them by hand or use the function fixParent() of kinship2. This function will add the missing parents, fix genders problems and add second parents for children for whom only one parent id is given.

df_fixed <- with(df,fixParents(
  id = id,
  dadid = dadid,
  momid = momid,
  sex = sex))

This new dataframe can then be use to create your pedigree.

pedAll <- with(df_fixed,pedigree(
  id = id,
  dadid = dadid,
  momid = momid,
  sex = sex))
plot(pedAll)

However I don't quite understand what you want to do with the 'mutate' function. If you subdivide your dataframe in family, be sure that every individual inside each family has its own row (that doesn't seems to be the case with your code).


答:
You need to push value to array.

array.push({name:'peter'});

Title: Why is the length of an array 0 after a assign a key/value pair? (JS)


问:
Pass a buildType from android app/library module to java only gradle module
Gradle Module A is an android module which defines several custom build types

```<code>android {
  buildTypes {
    debug {
      buildConfigField 'boolean', 'DEV', 'true'
    }
    internal {
      buildConfigField 'boolean', 'INTERNAL', 'true'
    }
    external {
      buildConfigField 'boolean', 'EXTERNAL', 'true'
    }
    release {
      buildConfigField 'boolean', 'RELEASE', 'true'
    }
  }
}

dependencies {
  implementation project(":module-b")
}

</code>```

Gradle Module B is a kotlin/java only module:

```<code>apply plugin: 'kotlin'
apply plugin: 'com.android.lint'

dependencies {
}
</code>```

Module A depends on module B:

```<code>// Module A build.gradle
dependencies {
  implementation project(":module-b")
}
</code>```

In Module B sources I need to know how exactly is it consumed by Module A, what is the current buildType of Module A: is it 'debug', 'internal', 'external' or 'release'?

Ideally I'd like to have BuildConfig.java in Module B similar to one provided by an Android Gradle Plugin, but if this is not possible I'd like to have at least some way of figuring out the build type in non-android modules.

EDIT Another example to put this into perspective: let's say there's one 'app' module and 10 java-only modules. When I execute 'app:assembleExternal' task, then in all 10 java-only modules I want to know that it is "external" build type being built.

答:
I think this would work:</p>

```<code>api project(":module-b")
</code>```

Body:
Gradle Module A is an android module which defines several custom build types

android {
  buildTypes {
    debug {
      buildConfigField 'boolean', 'DEV', 'true'
    }
    internal {
      buildConfigField 'boolean', 'INTERNAL', 'true'
    }
    external {
      buildConfigField 'boolean', 'EXTERNAL', 'true'
    }
    release {
      buildConfigField 'boolean', 'RELEASE', 'true'
    }
  }
}

dependencies {
  implementation project(":module-b")
}

Gradle Module B is a kotlin/java only module:

apply plugin: 'kotlin'
apply plugin: 'com.android.lint'

dependencies {
}

Module A depends on module B:

// Module A build.gradle
dependencies {
  implementation project(":module-b")
}

In Module B sources I need to know how exactly is it consumed by Module A, what is the current buildType of Module A: is it 'debug', 'internal', 'external' or 'release'?

Ideally I'd like to have BuildConfig.java in Module B similar to one provided by an Android Gradle Plugin, but if this is not possible I'd like to have at least some way of figuring out the build type in non-android modules.

EDIT Another example to put this into perspective: let's say there's one 'app' module and 10 java-only modules. When I execute 'app:assembleExternal' task, then in all 10 java-only modules I want to know that it is "external" build type being built.

Body:
I think this would work:

api project(":module-b")


问:
Retrieve/use G suite Default Routing rules programatically
I am only looking for read-only access.

I'd like to develop either a small web app, or maybe a script embedded in Google Sheets, that allows my users can look up which Google Admin default routing rules they are involved in.

To do that, I'll need an API to go through the rules and tabulate the information in the way I need it.

Can I do that with Admin SDK, which is soon-to-be deprecated? Is there a replacement product that can do what I want?

More details:

I currently use default routing for a few purposes. I have about 15 rules, and each one changes the route of a simple Match Rule by adding extra recipients. Some of these are to catch emails sent to ex-employees.

Others are to handle certain general email addresses like sales@example.com. Rather than using a sales group, we have a sales user account. And rather than putting forwarding rules in that users' settings, we use Default routing.

答: I had a similar problem where I needed the routing rules.... a bit different case since I just wanted a one time access to see what was going on - not necessarily something for users. I could not find anywhere else that helped me even retrieve the rules (Other than open each one up individually). I ended up finding that I could just scrape the HTML of the routing rules page to a CSV and filter for lines with an '@' character. The rules have a bunch of t/f that presumably can be matched back to their function - I didn't need all that and didn't spend the time to figure it out. This probably doesn't help the for the original post case, but perhaps my finding can help the next person looking for a way to do this.</p>


问:
How to output to txt (Programming in Python with Processing 3)
I'm currently working on a project and a part of the project is to output something to the project directory in a sepereate .txt file, I have completed that but I have a problem, everything works GREAT but I don't want to create a new file every single time but I want to have everything and all records stored in only one file and that they just keep adding up, can someone help me?

Here's a part of the code I've came up with, don't bother about the "%d" etc. I just need help with output :

```<code>output = createWriter("rekordi.txt")
            output.print("Tvoj zadnji rekord je " + str(millis()/1000-sekunde) + " sekund || ob " + str(datum.strftime("%I:" + "%M" + " %p" + " na " + "%d." + "%b"))) # Write the date to the file
            output.flush()# Writes the remaining data to the file
            output.close()# Finishes the file
</code>```

答:
```<code>with open("rekordi.txt", "a", buffering=0) as f:
      f.write("write some data")
</code>```

file mode "a" will append all data to the file
buffering=0 means that data will be written directly to the file (just like using flush() )

Body:
I'm currently working on a project and a part of the project is to output something to the project directory in a sepereate .txt file, I have completed that but I have a problem, everything works GREAT but I don't want to create a new file every single time but I want to have everything and all records stored in only one file and that they just keep adding up, can someone help me?

Here's a part of the code I've came up with, don't bother about the "%d" etc. I just need help with output :

output = createWriter("rekordi.txt")
            output.print("Tvoj zadnji rekord je " + str(millis()/1000-sekunde) + " sekund || ob " + str(datum.strftime("%I:" + "%M" + " %p" + " na " + "%d." + "%b"))) # Write the date to the file
            output.flush()# Writes the remaining data to the file
            output.close()# Finishes the file

Body:
with open("rekordi.txt", "a", buffering=0) as f:
      f.write("write some data")

file mode "a" will append all data to the file
buffering=0 means that data will be written directly to the file (just like using flush() )


问:
Swift - Dictionary Fetching API
I am creating a simple iOS app where i fetch data from API ( open Source ) using the below function :

```<code>    private func fetchCurrencies() {
    if let url = URL(string: "http://data.fixer.io/api/latest?access_key=a5b8f8bd7583e32252946741********"){
        let session = URLSession(configuration: .default)
        let task = session.dataTask(with: url) { data, response, error in
            guard error == nil else{
                return
            }

            if let data = data {
                let decoder = JSONDecoder()
                do {
                    let decodedData = try decoder.decode(Rates.self, from: data)
                    let array = decodedData.rates
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                } catch {
                    print("error decoding")
                }

            }
        }
        task.resume()
    }
}
</code>```

and the data model is :

```<code> struct Rates: Codable {
    let rates: [String: Double]
 }
</code>```

Below is part of my API Data :

```<code>"success": true,
"timestamp": 1590762665,
"base": "EUR",
"date": "2020-05-29",
"rates": {
    "AED": 4.08666,
    "AFN": 85.22449,
    "ALL": 124.556499,
    "AMD": 538.156223,
    "ANG": 1.996181,
    "AOA": 645.803727,
    "ARS": 76.250753,
    "AUD": 1.672917,
    "AWG": 2.002692,
    "AZN": 1.896163,
    "BAM": 1.95413,
    "BBD": 2.245466,
    "BDT": 94.371782,
    // and so on .....
</code>```

Fetching data is working fine and i receive the rates but i can't figure out how to publish these data inside my table view ( for example : cell text the currency & cell details text as rate ) also i feel my model is not structured as supposed to be, so what is the proper way should be to fetch the rates data & publish them inside my table view as modeling the data, fetching them & table cell data insertion .

Below is part of what appears when i print array into the console :

```<code> ▿ 168 elements
  ▿ 0 : 2 elements
   - key : "HKD"
   - value : 8.615716
  ▿ 1 : 2 elements
   - key : "IMP"
   - value : 0.900216
 ▿ 2 : 2 elements
   - key : "ZWL"
   - value : 357.865214
 ▿ 3 : 2 elements
   - key : "LBP"
   - value : 1676.38247
</code>```

I hope i made myself clear ,

Thank you in advance,

答:
Use this code to combine all dictionaries to a single one

```<code>let flattenedArray = array
.flatMap { $0 }
.reduce([String:String]()) { (var dict, tuple) in
    dict.updateValue(tuple.1, forKey: tuple.0)
    return dict
}
</code>```

next, you can use flattenedArray like I do below

```<code>            var i: Int = 0
            //use i as a counter
            while i < 168 {

            self.arrayOfRates.append(Array(flattenedArray)[i].value)
            self.arrayOfCurrency.append(Array(flattenedArray)[i].key)
                i = i + 1

            }
</code>```

then set up your tableView using arrayOfRates as cell details, and arrayOfCurrency as cell text.

if you need help setting up tableView watch this video https://www.youtube.com/watch?v=cJUmrdfgbbA

Title: Swift - Dictionary Fetching API

Body:
I am creating a simple iOS app where i fetch data from API ( open Source ) using the below function :

    private func fetchCurrencies() {
    if let url = URL(string: "http://data.fixer.io/api/latest?access_key=a5b8f8bd7583e32252946741********"){
        let session = URLSession(configuration: .default)
        let task = session.dataTask(with: url) { data, response, error in
            guard error == nil else{
                return
            }

            if let data = data {
                let decoder = JSONDecoder()
                do {
                    let decodedData = try decoder.decode(Rates.self, from: data)
                    let array = decodedData.rates
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                } catch {
                    print("error decoding")
                }

            }
        }
        task.resume()
    }
}

and the data model is :

 struct Rates: Codable {
    let rates: [String: Double]
 }

Below is part of my API Data :

"success": true,
"timestamp": 1590762665,
"base": "EUR",
"date": "2020-05-29",
"rates": {
    "AED": 4.08666,
    "AFN": 85.22449,
    "ALL": 124.556499,
    "AMD": 538.156223,
    "ANG": 1.996181,
    "AOA": 645.803727,
    "ARS": 76.250753,
    "AUD": 1.672917,
    "AWG": 2.002692,
    "AZN": 1.896163,
    "BAM": 1.95413,
    "BBD": 2.245466,
    "BDT": 94.371782,
    // and so on .....

Fetching data is working fine and i receive the rates but i can't figure out how to publish these data inside my table view ( for example : cell text the currency & cell details text as rate ) also i feel my model is not structured as supposed to be, so what is the proper way should be to fetch the rates data & publish them inside my table view as modeling the data, fetching them & table cell data insertion .

Below is part of what appears when i print array into the console :

 ▿ 168 elements
  ▿ 0 : 2 elements
   - key : "HKD"
   - value : 8.615716
  ▿ 1 : 2 elements
   - key : "IMP"
   - value : 0.900216
 ▿ 2 : 2 elements
   - key : "ZWL"
   - value : 357.865214
 ▿ 3 : 2 elements
   - key : "LBP"
   - value : 1676.38247

I hope i made myself clear ,

Thank you in advance,

Body:
Use this code to combine all dictionaries to a single one

let flattenedArray = array
.flatMap { $0 }
.reduce([String:String]()) { (var dict, tuple) in
    dict.updateValue(tuple.1, forKey: tuple.0)
    return dict
}

next, you can use flattenedArray like I do below

            var i: Int = 0
            //use i as a counter
            while i < 168 {

            self.arrayOfRates.append(Array(flattenedArray)[i].value)
            self.arrayOfCurrency.append(Array(flattenedArray)[i].key)
                i = i + 1

            }

then set up your tableView using arrayOfRates as cell details, and arrayOfCurrency as cell text.

if you need help setting up tableView watch this video https://www.youtube.com/watch?v=cJUmrdfgbbA


问:
Tree View structure in web form using Django
I want to create a webform in Tree view using Django. I am completely new to it and could not able to understand how to make it.

I tried the following code in html

```<code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
ul, #myUL {
  list-style-type: none;
}

#myUL {
  margin: 0;
  padding: 0;
}

.caret {
  cursor: pointer;
  -webkit-user-select: none; /* Safari 3.1+ */
  -moz-user-select: none; /* Firefox 2+ */
  -ms-user-select: none; /* IE 10+ */
  user-select: none;
}

.caret::before {
  content: "\25B6";
  color: black;
  display: inline-block;
  margin-right: 6px;
}

.caret-down::before {
  -ms-transform: rotate(90deg); /* IE 9 */
  -webkit-transform: rotate(90deg); /* Safari */'
  transform: rotate(90deg);
}

.nested {
  display: none;
}

.active {
  display: block;
}
</style>
</head>
<body>

<h2>Tree View</h2>
<p>A tree view represents a hierarchical view of information, where each item can have a number of subitems.</p>
<p>Click on the arrow(s) to open or close the tree branches.</p>

<ul id="myUL">
  <li><span class="caret">Beverages</span>
    <ul class="nested">
      <li>Water</li>
      <li>Coffee</li>
      <li><span class="caret">Tea</span>
        <ul class="nested">
          <li>Black Tea</li>
          <li>White Tea</li>
          <li><span class="caret">Green Tea</span>
            <ul class="nested">
              <li>Sencha</li>
              <li>Gyokuro</li>
              <li>Matcha</li>
              <li>Pi Lo Chun</li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<script>
var toggler = document.getElementsByClassName("caret");
var i;

for (i = 0; i < toggler.length; i++) {
  toggler[i].addEventListener("click", function() {
    this.parentElement.querySelector(".nested").classList.toggle("active");
    this.classList.toggle("caret-down");
  });
}
</script>

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

but how to make it in Django? need to represent the same. Tried some github examples but couldn't succeed in getting. can someone suggest me a simple example

答:
First, you can use a framework like semantic-UI or bootstrap. it will be easier.
In your case, you can replace any
 with <form>. after that to be more realistic and more sense you can use ajax to submit a form without reloading the page. the idea here not in Django itself the problem is how to do that in HTML, CSS, and JS. if you do that with them Django side will be easy.

Body:
I want to create a webform in Tree view using Django. I am completely new to it and could not able to understand how to make it.

I tried the following code in html

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Tree View

A tree view represents a hierarchical view of information, where each item can have a number of subitems.

Click on the arrow(s) to open or close the tree branches.

Beverages

Water

Coffee

Tea

Black Tea

White Tea

Green Tea

Sencha

Gyokuro

Matcha

Pi Lo Chun

but how to make it in Django? need to represent the same. Tried some github examples but couldn't succeed in getting. can someone suggest me a simple example

Body:
First, you can use a framework like semantic-UI or bootstrap. it will be easier.
In your case, you can replace any <ul> with <form>. after that to be more realistic and more sense you can use ajax to submit a form without reloading the page. the idea here not in Django itself the problem is how to do that in HTML, CSS, and JS. if you do that with them Django side will be easy.


问:
Open a hyperlink to a pdf file from excel
I inserted a hyperlink to a pdf file in my excel table using Spreadsheet::WriteExcel; write_url() method. But when I want to open the link, it displays the pdf file as text rather than an image. Any ideas of how to open the link with original pdf image? Thanks.

答:
Your problem sounds very much like the one I posted a couple of days ago - except mine was trying to hyperlink from excel to .jpgs in my website. You click on the Hyperlink and instead of getting an image you get a long page full of characters. This started to happen about March this year. Except it is fine with Firefox and Explorer.
I have spent most of my afternoon first with Mac - Safari and then with MS Excel group. Their conclusion is that it is a known bug between XL and Mac and they are still working on it.
I uploaded a .PDF to my web site (link is:  http://www.hkirbydesigns.com/PIDB/RocknGrass.pdf) and I was able to view the image with firefox but not with Safari - I got the characters with Safari. So, MS said to use a different browser until they have fixed the bug.
Hope this is useful.</p>


问:
Error in classes - missing 1 required positional argument
I am actually learning python3 and not able to figure it why it is so

```<code>class Load():
    def __init__(self):
        print("Starting Now")
        self.player = []
    def player_Stats(self,filename):
        with open(filename) as my_names:
            names = my_names.readlines()
            for one in names:
                one.replace("\n","")
                self.player.append(one.split[":"][0])
                print(player)

print(Load.player_Stats("players.txt"))
</code>```

It is giving me an error

Traceback (most recent call last):
  File "test.py", line 56, in <module>
    print(Load.player_Stats("players.txt"))
TypeError: player_Stats() missing 1 required positional argument: 'filename'
```

and I am not getting it why.

答:
You need to create a new instance of Load in order to use the player_Stats method:

load = Load()
print(load.player_Stats("players.txt"))
```

<p>Also, there are some other errors in your code:</p>

<pre class="lang-py prettyprint-override"><code>self.player.append(one.split[":"][0])
# should be
self.player.append(one.split(":")[0])

print(player)
# should be
print(self.player)
</code>```

Body:
I am actually learning python3 and not able to figure it why it is so

class Load():
    def __init__(self):
        print("Starting Now")
        self.player = []
    def player_Stats(self,filename):
        with open(filename) as my_names:
            names = my_names.readlines()
            for one in names:
                one.replace("\n","")
                self.player.append(one.split[":"][0])
                print(player)

print(Load.player_Stats("players.txt"))

It is giving me an error

Traceback (most recent call last):
  File "test.py", line 56, in <module>
    print(Load.player_Stats("players.txt"))
TypeError: player_Stats() missing 1 required positional argument: 'filename'

and I am not getting it why.

Body:
You need to create a new instance of Load in order to use the player_Stats method:

load = Load()
print(load.player_Stats("players.txt"))

Also, there are some other errors in your code:

self.player.append(one.split[":"][0])
# should be
self.player.append(one.split(":")[0])

print(player)
# should be
print(self.player)


问:
Plugin already initialized
I am doing plugin for teleport between servers in bungeecord. Suddenly, i don't know how, but error starts occur. Can you tell me, where is the problem? Thank you for your response.

Full Stacktrace:

org.bukkit.plugin.InvalidPluginException: java.lang.IllegalArgumentException: Plugin already initialized!
        at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:139) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:334) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:253) [spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at org.bukkit.craftbukkit.v1_15_R1.CraftServer.loadPlugins(CraftServer.java:351) [spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at net.minecraft.server.v1_15_R1.DedicatedServer.init(DedicatedServer.java:203) [spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at net.minecraft.server.v1_15_R1.MinecraftServer.run(MinecraftServer.java:784) [spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at java.lang.Thread.run(Thread.java:830) [?:?]
Caused by: java.lang.IllegalArgumentException: Plugin already initialized!
        at org.bukkit.plugin.java.PluginClassLoader.initialize(PluginClassLoader.java:178) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at org.bukkit.plugin.java.JavaPlugin.(JavaPlugin.java:52) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at pl.piotrek.main.Main.(Main.java:9) ~[?:?]
        at jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:?]
        at jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[?:?]
        at jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[?:?]
        at java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500) ~[?:?]
        at java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:166) ~[?:?]
        at jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:404) ~[?:?]
        at java.lang.Class.newInstance(Class.java:591) ~[?:?]
        at org.bukkit.plugin.java.PluginClassLoader.(PluginClassLoader.java:72) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:135) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        ... 6 more
Caused by: java.lang.IllegalStateException: Initial initialization
        at org.bukkit.plugin.java.PluginClassLoader.initialize(PluginClassLoader.java:181) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at org.bukkit.plugin.java.JavaPlugin.(JavaPlugin.java:52) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at pl.piotrek.main.Main.(Main.java:9) ~[?:?]
        at jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:?]
        at jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[?:?]
        at jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[?:?]
        at java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500) ~[?:?]
        at java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:166) ~[?:?]
        at jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:404) ~[?:?]
        at java.lang.Class.newInstance(Class.java:591) ~[?:?]
        at org.bukkit.plugin.java.PluginClassLoader.(PluginClassLoader.java:72) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:135) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        ... 6 more

Main class:

```<code>package pl.piotrek.main;

import org.bukkit.plugin.java.JavaPlugin;
import pl.piotrek.commands.ServersCommand;
import pl.piotrek.events.ServersGuiListener;
import pl.piotrek.gui.Gui;
import pl.piotrek.message.channel.PluginMessagingListener;
import pl.piotrek.message.command.ConnectCommand;

public class Main extends JavaPlugin {
    private static Main instance;
    public static Main getInstance() { return instance; }
    public void setInstance(Main instance) { Main.instance = instance; }
    public Gui gui;
    @Override
    public void onEnable() {
        System.out.println("Enabled TeleportationUtils v1.0.0");
        setInstance(this);
        registerCommands();
        registerListener();
        this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
        this.getServer().getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new PluginMessagingListener());
        gui = new Gui();
    }
    public void registerCommands() {
        getCommand("connect").setExecutor(new ConnectCommand());
        getCommand("servers").setExecutor(new ServersCommand());
    }
    public void registerListener() {
        this.getServer().getPluginManager().registerEvents(new ServersGuiListener(), this);
    }
}
</code>```

Plugin.yml:

```<code>name: TeleportationUtils
version: 1.0.0
main: pl.piotrek.main.Main
api-version: 1.15
commands:
  connect:
    aliases: [cnt]
    description: Connect to another sevrer command
  servers:
    aliases: [svr]
    description: Server menu command for teleport between servers
permissions:
  commands:
   connect:
</code>```

答:
Your stack trace shows that your plugin is initially initialized at pl.piotrek.main.Main.<init>(Main.java:9) and then it's trying to be initialized again at the same point. It is very likely that you have the same plugin twice in your plugins folder, probably under a different name.

Have a look through your server's plugin folder and find the duplicate.

Title: Plugin already initialized

Body:
I am doing plugin for teleport between servers in bungeecord. Suddenly, i don't know how, but error starts occur. Can you tell me, where is the problem? Thank you for your response.

Full Stacktrace:

org.bukkit.plugin.InvalidPluginException: java.lang.IllegalArgumentException: Plugin already initialized!
        at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:139) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:334) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:253) [spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at org.bukkit.craftbukkit.v1_15_R1.CraftServer.loadPlugins(CraftServer.java:351) [spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at net.minecraft.server.v1_15_R1.DedicatedServer.init(DedicatedServer.java:203) [spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at net.minecraft.server.v1_15_R1.MinecraftServer.run(MinecraftServer.java:784) [spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at java.lang.Thread.run(Thread.java:830) [?:?]
Caused by: java.lang.IllegalArgumentException: Plugin already initialized!
        at org.bukkit.plugin.java.PluginClassLoader.initialize(PluginClassLoader.java:178) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at org.bukkit.plugin.java.JavaPlugin.(JavaPlugin.java:52) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at pl.piotrek.main.Main.(Main.java:9) ~[?:?]
        at jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:?]
        at jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[?:?]
        at jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[?:?]
        at java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500) ~[?:?]
        at java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:166) ~[?:?]
        at jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:404) ~[?:?]
        at java.lang.Class.newInstance(Class.java:591) ~[?:?]
        at org.bukkit.plugin.java.PluginClassLoader.(PluginClassLoader.java:72) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:135) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        ... 6 more
Caused by: java.lang.IllegalStateException: Initial initialization
        at org.bukkit.plugin.java.PluginClassLoader.initialize(PluginClassLoader.java:181) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at org.bukkit.plugin.java.JavaPlugin.(JavaPlugin.java:52) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at pl.piotrek.main.Main.(Main.java:9) ~[?:?]
        at jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:?]
        at jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[?:?]
        at jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[?:?]
        at java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500) ~[?:?]
        at java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:166) ~[?:?]
        at jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:404) ~[?:?]
        at java.lang.Class.newInstance(Class.java:591) ~[?:?]
        at org.bukkit.plugin.java.PluginClassLoader.(PluginClassLoader.java:72) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:135) ~[spigot-1.15.2.jar:git-Spigot-800b93f-8160e29]
        ... 6 more

Main class:

package pl.piotrek.main;

import org.bukkit.plugin.java.JavaPlugin;
import pl.piotrek.commands.ServersCommand;
import pl.piotrek.events.ServersGuiListener;
import pl.piotrek.gui.Gui;
import pl.piotrek.message.channel.PluginMessagingListener;
import pl.piotrek.message.command.ConnectCommand;

public class Main extends JavaPlugin {
    private static Main instance;
    public static Main getInstance() { return instance; }
    public void setInstance(Main instance) { Main.instance = instance; }
    public Gui gui;
    @Override
    public void onEnable() {
        System.out.println("Enabled TeleportationUtils v1.0.0");
        setInstance(this);
        registerCommands();
        registerListener();
        this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
        this.getServer().getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new PluginMessagingListener());
        gui = new Gui();
    }
    public void registerCommands() {
        getCommand("connect").setExecutor(new ConnectCommand());
        getCommand("servers").setExecutor(new ServersCommand());
    }
    public void registerListener() {
        this.getServer().getPluginManager().registerEvents(new ServersGuiListener(), this);
    }
}

Plugin.yml:

name: TeleportationUtils
version: 1.0.0
main: pl.piotrek.main.Main
api-version: 1.15
commands:
  connect:
    aliases: [cnt]
    description: Connect to another sevrer command
  servers:
    aliases: [svr]
    description: Server menu command for teleport between servers
permissions:
  commands:
   connect:


问:
Django and ajax request: ValueError: Cannot assign must be a instance
I'm trying to integrate in my django modal an ajax call to modify directly the value of my data.
In other words I have the following views.py

```<code>class UpdateCrudUser(View):
    def  get(self, request):
        id1 = request.GET.get('id', None)
        conto1 = request.GET.get('conto', None)

        obj = Materiale.objects.get(id=id1)
        obj.conto = conto1
        obj.save()

        element = {
                'id':obj.id,
                'conto':obj.conto}

        data = {
            'element': element}
        return JsonResponse(data)
</code>```

After that I have build before my table as following:

```<code>{% for element in elements %}
  <tr id="element-{{element.id}}">
  <td class="elementConto userData" name="conto">{{element.conto}}</td>
  </tr>
{% endfor %}
</code>```

...
 And after that the modal:

```<code><form id="updateUser">
              <div class="modal-body">
                  <input class="form-control" id="form-id" type="hidden" name="formId"/>

                  <label for="conto">Conto</label>
                  <input class="form-control" id="form-conto" name="formConto"/>
</code>```

Finally the script with the ajax call:

```<code>function editUser(id) {
  if (id) {
    tr_id = $("#element-" + id);
    conto = $(tr_id).find(".elementConto").text();

    $('#form-id').val(id);
    $('#form-conto').val(conto);
  }
}

$("form#updateUser").submit(function() {
    var idInput = $('input[name="formId"]').val();
    var contoInput = $('input[name="formConto"]').val();
    if (contoInput && tipologiaInput ) {
        // Create Ajax Call
        $.ajax({
            url: '{% url "crud_ajax_update" %}',
            data: {
                'id': idInput,
                'conto': contoInput,
            },
            dataType: 'json',
            success: function (data) {
                if (data.element) {
                  updateToUserTabel(data.element);
                }
            }
        });
       } else {
        alert("Vediamo se funziona.");
    }
    $('form#updateUser').trigger("reset");
    $('#myModal').modal('hide');
    return false;
});
</code>```

But If I try to modify using the modal my data, django give me the following error:

```<code>ValueError: Cannot assign "'Materia Prima'": "Materiale.conto" must be a "Conto" instance.
</code>```

It's possible that this error arises from the model?Becouse conto is a foreingKey:

```<code>class Materiale(models.Model):
    conto = models.ForeignKey(Conto, on_delete=models.CASCADE, null=True)

class Conto(models.Model):
    nome=models.CharField('Nome Conto', max_length=30, blank=True, default="")
    def __str__(self):
        return  self.nome
</code>```

In this case how could I overcome that problem?

答:
In your UpdateCrudUser, the variable conto1 has been assign to be a string, more precisely when you do this: conto1 = request.GET.get('conto', None).

Then, when you instantiate the Materiale model (through the obj object), you're attempting to set that string to its conto field, which expects an object of the Conto model, rather than a string.

How to overcome this? Instead of assigning that string to obj.conto directly, first make a query to get a Conto object by its field nome. Something like this in your UpdateCrudUser view:

```<code>obj = Materiale.objects.get(id=id1)
conto_obj, created = Conto.objects.get_or_create(nome=conto1)

obj.conto = conto_obj
</code>```

Note that I used the get_or_create() method because in case that the user's input for Conto name doesn't match any existent object, this will create a new Conto object that then can be assign to the Materiale instance that you want to update.

Body:
I'm trying to integrate in my django modal an ajax call to modify directly the value of my data.
In other words I have the following views.py

class UpdateCrudUser(View):
    def  get(self, request):
        id1 = request.GET.get('id', None)
        conto1 = request.GET.get('conto', None)

        obj = Materiale.objects.get(id=id1)
        obj.conto = conto1
        obj.save()

        element = {
                'id':obj.id,
                'conto':obj.conto}

        data = {
            'element': element}
        return JsonResponse(data)

After that I have build before my table as following:

{% for element in elements %}

  {{element.conto}}

{% endfor %}

...
 And after that the modal:

<form id="updateUser">

                  <input class="form-control" id="form-id" type="hidden" name="formId"/>

                  Conto
                  <input class="form-control" id="form-conto" name="formConto"/>

Finally the script with the ajax call:

function editUser(id) {
  if (id) {
    tr_id = $("#element-" + id);
    conto = $(tr_id).find(".elementConto").text();

    $('#form-id').val(id);
    $('#form-conto').val(conto);
  }
}

$("form#updateUser").submit(function() {
    var idInput = $('input[name="formId"]').val();
    var contoInput = $('input[name="formConto"]').val();
    if (contoInput && tipologiaInput ) {
        // Create Ajax Call
        $.ajax({
            url: '{% url "crud_ajax_update" %}',
            data: {
                'id': idInput,
                'conto': contoInput,
            },
            dataType: 'json',
            success: function (data) {
                if (data.element) {
                  updateToUserTabel(data.element);
                }
            }
        });
       } else {
        alert("Vediamo se funziona.");
    }
    $('form#updateUser').trigger("reset");
    $('#myModal').modal('hide');
    return false;
});

But If I try to modify using the modal my data, django give me the following error:

ValueError: Cannot assign "'Materia Prima'": "Materiale.conto" must be a "Conto" instance.

It's possible that this error arises from the model?Becouse conto is a foreingKey:

class Materiale(models.Model):
    conto = models.ForeignKey(Conto, on_delete=models.CASCADE, null=True)

class Conto(models.Model):
    nome=models.CharField('Nome Conto', max_length=30, blank=True, default="")
    def __str__(self):
        return  self.nome

In this case how could I overcome that problem?

Body:
In your UpdateCrudUser, the variable conto1 has been assign to be a string, more precisely when you do this: conto1 = request.GET.get('conto', None).

Then, when you instantiate the Materiale model (through the obj object), you're attempting to set that string to its conto field, which expects an object of the Conto model, rather than a string.

How to overcome this? Instead of assigning that string to obj.conto directly, first make a query to get a Conto object by its field nome. Something like this in your UpdateCrudUser view:

obj = Materiale.objects.get(id=id1)
conto_obj, created = Conto.objects.get_or_create(nome=conto1)

obj.conto = conto_obj

Note that I used the get_or_create() method because in case that the user's input for Conto name doesn't match any existent object, this will create a new Conto object that then can be assign to the Materiale instance that you want to update.


问:
Primeng p-chart not displaying data from array
I have a Primeng 9 p-chart that I'm trying to display and it's not working when I pass an array of data that's being parsed from JSON. When I manually enter the data the lines appear but for some reason an array is bust.

Is there a certain formatting this takes that I'm missing?

Chart

```<code>qData = [];
for(let i = 0; i < 6; i++){
      this.qData.push(5);
}

this.data = {
      labels: this.getXAxis(),
      datasets: [
        {
          label: 'First Dataset',
          data: [28, 48, 40, 19, 86], <--Line appears
          fill: false,
          borderColor: '#565656'
        },
        {
          label: 'Second',
          data: this.qData, <-- Array is populated but no lines
          fill: false,
          borderColor: '#4f81bd'
        },
...
</code>```

答: Data wasn't being loaded in time. Added a setTimeout(() => {...chart display...}, 1500); after my data calls and the chart is rendering now.

Body:
I have a Primeng 9 p-chart that I'm trying to display and it's not working when I pass an array of data that's being parsed from JSON. When I manually enter the data the lines appear but for some reason an array is bust.

Is there a certain formatting this takes that I'm missing?

Chart

qData = [];
for(let i = 0; i < 6; i++){
      this.qData.push(5);
}

this.data = {
      labels: this.getXAxis(),
      datasets: [
        {
          label: 'First Dataset',
          data: [28, 48, 40, 19, 86], <--Line appears
          fill: false,
          borderColor: '#565656'
        },
        {
          label: 'Second',
          data: this.qData, <-- Array is populated but no lines
          fill: false,
          borderColor: '#4f81bd'
        },
...


问:
c# datatable Cannot update. Database or object is read-only
```<code>private void Form1_Load(object sender, EventArgs e)
        {
            GetDataTable(@"C:\Documents and Settings\agordon\Desktop\ACTIVITYEX.log");
        }
        public System.Data.DataTable GetDataTable(string strFileName)
        {
            System.Data.OleDb.OleDbConnection conn =
                new System.Data.OleDb.OleDbConnection
                    ("Provider=Microsoft.Jet.OleDb.4.0; Data Source = "
                    + System.IO.Path.GetDirectoryName(strFileName)
                    + ";Extended Properties = \"Text;HDR=YES;FMT=TabDelimited\"");
            conn.Open();
            string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(strFileName) + "]";
            System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(strQuery, conn);
            System.Data.DataTable ds = new System.Data.DataTable("CSV File");
            adapter.Fill(ds);
            return ds;
        }
</code>```

when THE SAME file is named .csv it does not give me an error; however when i rename it to .log it says Cannot update.  Database or object is read-only. on adapter.Fill

is this a compiler error?

答: *.log is disabled extension, AFAIK only way is registry change on machine that will run this code, see MS Knowledge base article</p>

Body:
private void Form1_Load(object sender, EventArgs e)
        {
            GetDataTable(@"C:\Documents and Settings\agordon\Desktop\ACTIVITYEX.log");
        }
        public System.Data.DataTable GetDataTable(string strFileName)
        {
            System.Data.OleDb.OleDbConnection conn =
                new System.Data.OleDb.OleDbConnection
                    ("Provider=Microsoft.Jet.OleDb.4.0; Data Source = "
                    + System.IO.Path.GetDirectoryName(strFileName)
                    + ";Extended Properties = \"Text;HDR=YES;FMT=TabDelimited\"");
            conn.Open();
            string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(strFileName) + "]";
            System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(strQuery, conn);
            System.Data.DataTable ds = new System.Data.DataTable("CSV File");
            adapter.Fill(ds);
            return ds;
        }

when THE SAME file is named .csv it does not give me an error; however when i rename it to .log it says Cannot update.  Database or object is read-only. on adapter.Fill

is this a compiler error?


问:
Swift - HTTP digest auth
I am currently in the process of reverse engineering a home automation API. I want to manage all settings with my own app - because there is really no current home automation app of the company.

Anyway - I already managed the authentication with my SmartHome device. To not make it too complicated: I need http digest authentication for final communication.
I have already been able to connect to my device through the command line with curl - unfortunately this doesn't work in Swift as planned.

```<code>curl -X POST -d '{"key": "value"}' https://192.168.0.0:1/action -k -s --digest --user username:password
</code>```

Translated to Swift:

(1) Using Alamofire

```<code>import Alamofire
let data: [String: any] = ["key": "value"]
let request = Alamofire.request("https://192.168.0.0:1/action", method: HTTPMethod.post, parameters: data);
request.authenticate(user: "username", password: "password")
request.responseJSON { response in
    // leads to error because of invalid self signed certificate of the smart home device ("https:")
}
</code>```

Note to Alamofire: I guess using an external libary such as AF does not make much sense in this case - there are some unresolved issues that wont let such code as above work. (Self signed ceritficates makes problems, using custom manager instances overriding internal stuff leads also to problems) - I've already spent hours believe me.

(2) Using not Alamofire :)

```<code>extension ViewController: URLSessionDelegate {
    public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
        completionHandler(.useCredential, urlCredential)
    }
}

let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

do {
    let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
    request.httpBody = jsonData;
    let task = session.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            return
        }
        let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
        if let responseJSON = responseJSON as? [String: Any] {
        // success
        }
    }
    task.resume()
} catch { }
</code>```

The code above seems to work fine - the problem is that I've not implemented the digest authentication yet - because I do not find any method how to do this.

It would be super helpful if somebody to get some tips how generate the Auth header based on username and password

Edit

Curl uses this Authorization header:

```<code>> Digest username="username",
realm="XTV",
nonce="MTU5MDcNc2UxNjQ3OTo1YzMwYjc3YjIxMzAAAGQ5Nzg2NzUzMmRkZGU1ZVVlYw==",
uri="/action",
cnonce="MTExOTZlZmI1MjBlYWU0MTIzMDBmNDE0YTkWzJl1MDk=",
nc=00000001,
qop=auth,
response="2ba89269645e2aa24ac6f117d85e190c",
algorithm="MD5"
</code>```

Is there the possibility to generate this header in Swift?

答:
Digest authentication is supported automatically by URLSession and Alamofire through URLCredential (which is what authenticate() uses in Alamofire) when the server properly returns the WWW-Authenticate header with the proper digest settings.

You can generate the header manually, though I wouldn't recommend it due to the complexity of the digest process. I've found the wikipedia page to be thorough enough to implement the standard manually.

Title: Swift - HTTP digest auth

Body:
I am currently in the process of reverse engineering a home automation API. I want to manage all settings with my own app - because there is really no current home automation app of the company.

Anyway - I already managed the authentication with my SmartHome device. To not make it too complicated: I need http digest authentication for final communication.
I have already been able to connect to my device through the command line with curl - unfortunately this doesn't work in Swift as planned.

curl -X POST -d '{"key": "value"}' https://192.168.0.0:1/action -k -s --digest --user username:password

Translated to Swift:

(1) Using Alamofire

import Alamofire
let data: [String: any] = ["key": "value"]
let request = Alamofire.request("https://192.168.0.0:1/action", method: HTTPMethod.post, parameters: data);
request.authenticate(user: "username", password: "password")
request.responseJSON { response in
    // leads to error because of invalid self signed certificate of the smart home device ("https:")
}

Note to Alamofire: I guess using an external libary such as AF does not make much sense in this case - there are some unresolved issues that wont let such code as above work. (Self signed ceritficates makes problems, using custom manager instances overriding internal stuff leads also to problems) - I've already spent hours believe me.

(2) Using not Alamofire :)

extension ViewController: URLSessionDelegate {
    public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
        completionHandler(.useCredential, urlCredential)
    }
}

let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

do {
    let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
    request.httpBody = jsonData;
    let task = session.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            return
        }
        let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
        if let responseJSON = responseJSON as? [String: Any] {
        // success
        }
    }
    task.resume()
} catch { }

The code above seems to work fine - the problem is that I've not implemented the digest authentication yet - because I do not find any method how to do this.

It would be super helpful if somebody to get some tips how generate the Auth header based on username and password

Edit

Curl uses this Authorization header:

> Digest username="username",
realm="XTV",
nonce="MTU5MDcNc2UxNjQ3OTo1YzMwYjc3YjIxMzAAAGQ5Nzg2NzUzMmRkZGU1ZVVlYw==",
uri="/action",
cnonce="MTExOTZlZmI1MjBlYWU0MTIzMDBmNDE0YTkWzJl1MDk=",
nc=00000001,
qop=auth,
response="2ba89269645e2aa24ac6f117d85e190c",
algorithm="MD5"

Is there the possibility to generate this header in Swift?


问:
SignalR .Net Core 3.1 Web Application not working on local IIS
Trying to create a chat based on an online example using ASP.Net Core 3.1 and Angular.

The following works perfectly well on IIS Express, but not on local IIS.

Error Message:
WebSocketTransport.js:85 WebSocket connection to 'ws://localhost/MyCoreAPI/ChatHub' failed: Error during WebSocket handshake: Unexpected response code: 400

Startup:

```<code>    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR();
    }
    public void Configure(IApplicationBuilder app,
                          IWebHostEnvironment env,
                          ApplicationDbContext context)
    {

        app.UseCors("EnableCORS");
        app.UseMiddleware<ErrorHandlingMiddleware>();
        app.UseMiddleware<TokenServiceMiddleware>();

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(route =>
        {
            route.MapHub<ChatHub>("/ChatHub");
        });
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=auth}/{action}/");

        });

        app.Run(async (c) =>
        {
            await c.Response.WriteAsync("My Core Web API");
        });
    }
</code>```

ChatHub:

```<code>public class ChatHub : Hub
{
    public Task SendMessageToAll(Message message) =>
         Clients.All.SendAsync("receiveMessage", message);
}
</code>```

Client:

```<code>export class ChatService {

  receiveMessage = new EventEmitter<Message>();
  connectionEstablished = new EventEmitter<Boolean>();

  private connectionIsEstablished = false;
  private _hubConnection: HubConnection;

  constructor() {
    this.createConnection();
    this.registerOnServerEvents();
    this.startConnection();
  }

  async sendMessage(message: Message) {
    console.log(message);
    await this._hubConnection.invoke('SendMessageToAll', message);
  }

  private createConnection() {
    this._hubConnection = new HubConnectionBuilder()
      .configureLogging(LogLevel.Debug)
      .withUrl('http://localhost/MyCoreAPI/ChatHub', {
        skipNegotiation:true,
        transport:HttpTransportType.WebSockets
      })
      .build();
  }

  private startConnection(): void {
    this._hubConnection
      .start()
      .then(() => {
        this.connectionIsEstablished = true;
        console.log('Hub connection started');
        this.connectionEstablished.emit(true);
      })
      .catch(err => {
        console.log('Error while establishing connection, retrying...');
        setTimeout(function () { this.startConnection(); }, 5000);
      });
  }

  private registerOnServerEvents(): void {
    this._hubConnection.on('receiveMessage', (data: any) => {
      console.log(data);
      this.receiveMessage.emit(data);
    });
  }
}

  }
</code>```

On IIS Express using 'http://localhost:59235/ChatHub' everything works. When I switch to local IIS using 'http://localhost/MyCoreAPI/ChatHub' I get the error.

答:
Can you check if WebSockets Protocol is enabled in IIS. </p>

<p>"Turn Windows features on or off" -> Internet Information Services ->World Wide Web Services -> Application Development Features -> WebSocket Protocol </p>

Body:
Trying to create a chat based on an online example using ASP.Net Core 3.1 and Angular.

The following works perfectly well on IIS Express, but not on local IIS.

Error Message:
WebSocketTransport.js:85 WebSocket connection to 'ws://localhost/MyCoreAPI/ChatHub' failed: Error during WebSocket handshake: Unexpected response code: 400

Startup:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR();
    }
    public void Configure(IApplicationBuilder app,
                          IWebHostEnvironment env,
                          ApplicationDbContext context)
    {

        app.UseCors("EnableCORS");
        app.UseMiddleware<ErrorHandlingMiddleware>();
        app.UseMiddleware<TokenServiceMiddleware>();

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(route =>
        {
            route.MapHub<ChatHub>("/ChatHub");
        });
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=auth}/{action}/");

        });

        app.Run(async (c) =>
        {
            await c.Response.WriteAsync("My Core Web API");
        });
    }

ChatHub:

public class ChatHub : Hub
{
    public Task SendMessageToAll(Message message) =>
         Clients.All.SendAsync("receiveMessage", message);
}

Client:

export class ChatService {

  receiveMessage = new EventEmitter<Message>();
  connectionEstablished = new EventEmitter<Boolean>();

  private connectionIsEstablished = false;
  private _hubConnection: HubConnection;

  constructor() {
    this.createConnection();
    this.registerOnServerEvents();
    this.startConnection();
  }

  async sendMessage(message: Message) {
    console.log(message);
    await this._hubConnection.invoke('SendMessageToAll', message);
  }

  private createConnection() {
    this._hubConnection = new HubConnectionBuilder()
      .configureLogging(LogLevel.Debug)
      .withUrl('http://localhost/MyCoreAPI/ChatHub', {
        skipNegotiation:true,
        transport:HttpTransportType.WebSockets
      })
      .build();
  }

  private startConnection(): void {
    this._hubConnection
      .start()
      .then(() => {
        this.connectionIsEstablished = true;
        console.log('Hub connection started');
        this.connectionEstablished.emit(true);
      })
      .catch(err => {
        console.log('Error while establishing connection, retrying...');
        setTimeout(function () { this.startConnection(); }, 5000);
      });
  }

  private registerOnServerEvents(): void {
    this._hubConnection.on('receiveMessage', (data: any) => {
      console.log(data);
      this.receiveMessage.emit(data);
    });
  }
}

  }

On IIS Express using 'http://localhost:59235/ChatHub' everything works. When I switch to local IIS using 'http://localhost/MyCoreAPI/ChatHub' I get the error.

Body:
Can you check if WebSockets Protocol is enabled in IIS.

"Turn Windows features on or off" -> Internet Information Services ->World Wide Web Services -> Application Development Features -> WebSocket Protocol


问:
Mapping different column and table names for Laravel Authentication without re-writing all of the auth classes
We store our authentication information in a different table and column names than Laravel uses by default. It's still stored in MySQL. When doing research, in the documentation it says that we have to write completely different authentication handlers.

Is there really not any way to just remap the table and column names in a central place?

If not is there a better way to handle this? Should we just create a new table using the authentication information?

答:
You can change your table/model name for authentication purposes inside the config\auth.php file.

```<code>'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],
</code>```

Now, when it comes to changing column name by default Laravel using email field which you can change by putting a function username() which will return the field to be used for authentication inside LoginController.php.

```<code>public function username()
{
    return 'username';
}
</code>```

Hopefully this helps.

Body:
You can change your table/model name for authentication purposes inside the config\auth.php file.

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],

Now, when it comes to changing column name by default Laravel using email field which you can change by putting a function username() which will return the field to be used for authentication inside LoginController.php.

public function username()
{
    return 'username';
}

Hopefully this helps.


问:
Manipulate Data Across Multiple Sheets
I am trying to use a simple formula across multiple worksheets (within the same workbook) to effectively consolidate data.

Current Formula: =COUNTIF('5-01-20:5-29-20'!A:A, "Laptop")

Basically, look at all of the cells in the 'A' columns on sheet named '5-01-20' through sheet named '5-29-20' and count the cell if it contains the word 'Laptop'

This formula returns a #Value error, as does the same formula using a named range.  A quick Google search suggests that the CountIF function cannot use this type of range.  Is there another solution I can try that isn't combining all of the data onto a single worksheet?

I have also tried a PIVOT Table, but was unable to get it to contain more than one Table/Worksheet.

答:
You will need to create a list of the worksheets then refer to that list using INDIRECT() and wrap the whole in SUMPRODUCT.  So for example if your list of sheet names is in Z1:Z29:</p>

```<code>=SuMPRODUCT(COUNTIFS(INDIRECT("'"&Z1:Z29&"'!A:A"),"Laptop"))
</code>```

Title: Manipulate Data Across Multiple Sheets

Body:
You will need to create a list of the worksheets then refer to that list using INDIRECT() and wrap the whole in SUMPRODUCT.  So for example if your list of sheet names is in Z1:Z29:

=SuMPRODUCT(COUNTIFS(INDIRECT("'"&Z1:Z29&"'!A:A"),"Laptop"))