问:
Microsoft Outlook 365 (Windows Only) ADD-IN ERROR
I have been consistently receiving this ADD-IN ERROR which states: "ADD-IN ERROR This add-in could not be started. Close this dialog to ignore the problem or click "Restart" to try again."

This happens from the following very specific chain of events:

When I open the new email/compose screen

As soon as the screen loads I click on the ADD-IN and click a button on the toolbar associated with the ADD-IN

Microsoft Edge Dev Tools (not OWA) do not catch this error because essentially the new email/compose view is not able to be picked up even when I spam refresh. I can view it in Dev Tools only when I don't receive this error.

Outlook logs are hard to read, but I have found one error that might be a smoking gun: Unable to open volatile key. (0x80070005). This however doesn't have much documentation surrounding it.

Would anyone have insight on this issue, Thanks in advance!!

EDIT: ERROR Error: Uncaught (in promise): : {"status":"failed","error":{"name":"MissingExtendedPermissionsForAPIError","message":"Extended Permission missing for the API call.","code":9047}}

This seems to fire in reference to a manifest addition AppendOnSend Here are the docs on this: https://learn.microsoft.com/en-us/office/dev/add-ins/reference/manifest/extendedpermissions Why would this error out when clicking on a ribbon icon?

EDIT 2: Trying to validate the XML used in the addin I receive:

has invalid child element 'ExtendedPermissions'

even though I am following the documentation: https://learn.microsoft.com/en-us/office/dev/add-ins/reference/manifest/extendedpermission

答: The issue here happened to be with using the Microsoft Preview API. The Add-In will throw this error when you accidentally have AppendOnSend enabled while using a manifest that does not have Preview.</p>


来源: stackexchange

问:
How to update a file of base branch from current successor branch?
I have the following branch structure

```<code>-localproject
  -master
  -taskA
  -taskB
-remotes/origin
  -master
  -taskA
  -taskB
</code>```

Here is what I want to achieve:

The whole thing is for an assignment, so taskA and taskB are parts of the assignment that I need to push to the corresponding remote branch to get tested automatically. So initially I pull from master, which is the provided framework and create branch taskA.

I do my work in taskA and as soon as it is done, I push to the corresponding remote branch. It gets evaluated by the remote test system (gitlab CI / CD pipeline)

Perfect, taskA is working! Now I want to start taskB. This new task is based upon taskA so I create the new branch from it and start working.

Now working in taskB I realize that I could some things in my code to improve taskA. Let's say some files changed in taskB should now be committed to taskA.

The way I would do this now:
For each file, where I have changes I want to commit in taskA:

Manually copy the code while in taskB

checkout taskA

paste the code and commit the changes.

Is there a better way to do this? Can I somehow check files in taskB and copy/commit them over to taskA directly?

I hope I explained as clear as possible (at least I tried), however ask away if some things are not described in the best manner. While I generally understand git, I mostly use it for my private projects where not a lot of branching or anything out of the ordinary is involved...

答:
There are many different ways to manage this kind of work-flow in Git, because Git is a set of tools, rather than a particular solution.

When working with Git, keep all of these things in mind:

Git is really all about commits.  Commits (like all Git internal objects) are completely immutable once created.

Commits store snapshots of your files: not changes, just snapshots.  In some ways this doesn't really matter, but it makes it a lot easier to understand some weird Git corners.  Since the commits are immutable, so are the stored files.  These stored files are also compressed (sometimes in very fancy way) and de-duplicated, and not usable by anything other than Git itself.  They have to be extracted from a commit for you to use them (see below).

Each commit has a parent commit, or for merge commits, two (or potentially more) parents.  These are stored by hash IDs.

The hash ID of each commit is how Git actually retrieves the commit, so hash IDs are crucial here.  But hash IDs look random and are completely unsuitable for human use, therefore ...

Git gives us branch names, which simply store the hash ID of the last commit that we'd like Git to think of as being "on the branch".

A Git repository, then, is essentially just two databases.  One contains all the commits and supporting internal objects—all indexed by hash ID—and the other contains the name-to-hash-ID mapping.  The files that you work with, as you do your actual work, aren't in Git at all.  That is, they're not the ones that are in the repository database.  They are just in an auxiliary area.

This work area, where you work on files, is your working tree or work-tree.  If you use git clone to make your repository, Git creates the work-tree for you.  If you build your own work-tree before you create a .git with git init, you have already set up the work-tree, and the git init step just creates a new empty repository—two empty databases, one for commits and the other for names.

When you check out some particular commit—whether that's by an explicit check out historical commit so I can view it or implied by check out some branch by name so that I can do new work—Git will extract the saved snapshot into your work-tree.  But apart from this and other Git commands that explicitly tell Git do something with my work-tree file(s), these files are now yours to do with as you will.

There's one more wrinkle here.  When you go to make a new commit, Git does not use the files in your work-tree.  Instead, Git uses hidden copies—technically these aren't exactly copies, but it works to think of them like that—of the frozen-format files that get stored in commits.  These "copies" live in what Git calls, variously, the index, or the staging area, or—rarely these days—the cache.

The index has multiple roles, but you can think of it as containing the proposed next snapshot.  It starts out matching the current snapshot, as extracted into your work-tree.  The git diff --staged and git status commands don't show you the index copies of the files because they're the same as the snapshot's copy of the files.  When you use git add, you're telling Git: Copy my work-tree copy of the file back into the index, replacing the old copy, or putting an all-new file into the index.  Now that the index copy doesn't match the current-commit copy, git status and git diff --cached will show you that file.  Change it back—to match the committed copy—and they'll stop showing the file again.

Since your work-tree is yours, you can create files that never get into Git at all.  These are your untracked files.  To help ensure you don't accidentally put the untracked files into the repository, you can list files or name-patterns in .gitignore.  Note that once a file is tracked, listing it in .gitignore has no effect.

A file in your work-tree is tracked if and only if that file exists right now in Git's index.  While this definition is very short and simple, it has a long shadow:  Since Git fills in its index from a commit—via git checkout or git switch—this means that a file that exists in commit X but not in commit Y can switch from being tracked to untracked, or vice versa, just by changing which commit you have checked out.  You can also modify, create, or remove specific files within the index yourself, with git add and git rm.  Whenever you do this, you're changing the proposed next commit.  None of this has any effect until you actually run git commit.

With the above in mind, we're ready to tackle your particular case

Let's jump right to step 3:

Perfect, taskA is working! Now I want to start taskB. This new task is based upon taskA so I create the new branch from it and start working.

Since commits refer back to earlier commits, let's draw this.  Suppose the hash ID of the last commit in your taskA branch (which now exists) is H, where H stands in for the real Git hash ID.  Then the name taskA is a way for Git to remember hash ID H for you.  Commit H itself has a parent, with another big ugly hash ID, but we'll call that parent G.  G has a parent, too, which we'll call F, and so on:

```<code>... <-F <-G <-H   <--taskA
</code>```

The name taskA selects commit H (for now).  The name taskB does not even exist yet.

Now you create taskB.  I'm going to switch from drawing the internal arrows, which point backwards from each commit, to lines because the arrow drawing character set for posting here on StackOverflow is poor, but this just adds another name, taskB, that also selects commit H:

```<code>...--F--G--H   <-- taskA, taskB (HEAD)
</code>```

We now need to know which name we're using, as well as which commit, so we'll attach the special name HEAD to one of these two branch names.

Now working in taskB I realize that I could some things in my code to improve taskA. Let's say some files changed in taskB should now be committed to taskA.

This is where you suddenly get a lot of options.

My favorite one for descriptive purposes is git worktree, specifically git worktree add.  But git worktree was new in Git 2.5, and had a nasty bug finally fixed in 2.15, so unless your Git is reasonably modern, you might want to avoid it.  It's also going to create a little bit of extra work for you, if you go this way, but it's a very general solution.

What git worktree add does is let you add a second work-tree to your existing repository.  Each added work-tree gets:

its own HEAD, so that it can (and in fact must) have a different branch checked out;

its own index, i.e., proposed next commit; and

of course, its own work-tree full of files.

So you can use git worktree add to make two independent work areas, each of which is "on" a different branch.  You can then just take this moment to:

open a new window on (or push directories to) the work-tree in which you're working on taskA;

modify the files there, however you like—up to and including copying them from the work-tree where you are working on taskB—and git add and git commit.

Let's say you do make a new commit in this added work-tree.  We can draw that.  We start with this:

```<code>...--F--G--H   <-- taskA (HEAD), taskB
</code>```

and modify some files, git add, and run git commit.  This makes a new commit—which gets a new big ugly hash ID; we'll call it I—and makes the name taskA point to this new commit:

```<code>             I   <-- taskA (HEAD)
            /
...--F--G--H   <-- taskB
</code>```

If we switch back to the taskB window / work-tree, where taskB is the HEAD, we have:

```<code>             I   <-- taskA
            /
...--F--G--H   <-- taskB (HEAD)
</code>```

The files in the work-tree here—the original one, not the added one—match those of commit H, except for any changes you've made so far.  The files in the index for this work-tree match those for commit H.  Any new commit you make now will update the name taskB like this:

```<code>             I   <-- taskA
            /
...--F--G--H
            \
             J   <-- taskB (HEAD)
</code>```

Again, the new snapshot comes from the index.  The commits have not changed: we've merely added some new ones.  The parent of new commit I is existing commit H.  The parent of new commit J is existing commit H.  Commits up through and including H are on both branches, but the branches now diverge.

What if you don't want to use git worktree add

Remember that Git makes each new commit from the index, not from your work-tree.  Suppose we have:

```<code>...--F--G--H   <-- taskA, taskB (HEAD)
</code>```

but the index matches commit H.  Git will let you switch back to taskA without disturbing the index and work-tree content at all.  (This is not always true, but it is true given our suppositions and setup here.  For the gory details, see Checkout another branch when there are uncommitted changes on the current branch.)  So let's say we do that:

```<code>git checkout taskA              # or git switch taskA

...--F--G--H   <-- taskA (HEAD), taskB
</code>```

Now we just git add the one or two files you would like to be different—which copies them into the index, ready for the next commit—and then run git commit.  Since we're using the index files, not the work-tree files, updated you made but did not git add do not go into the new snapshot.

We get:

```<code>             I   <-- taskA (HEAD)
            /
...--F--G--H   <-- taskB
</code>```

exactly as before.  The name taskB does not move.

When we now git checkout taskB, Git sees that the files we just updated are different in commits H and I.  So Git will copy H's copy of those files out of the commit, into Git's index (so that they match H) and your work-tree, and the changes you just made for taskA are gone.  But we can bring them back into the work-tree:

```<code>git checkout taskA -- file1 file2
</code>```

or (since Git 2.23):

```<code>...--F--G--H   <-- taskA, taskB (HEAD)
</code>```0

which tells Git: reach into the commit identified by the name taskA—commit I—and pull out these two files and copy them into the index and my work-tree.  So now you're back to having the updated files, along with all the other undisturbed files.  The updated files are already changes staged for commit, as git status will say, as they're in the proposed next commit in the index.

You can now finish up the stuff you were doing, git add, and git commit as needed, giving:

```<code>...--F--G--H   <-- taskA, taskB (HEAD)
</code>```1

exactly as before.

You may now want to rebase taskB

However you got to this point, you now have taskB extending from commit H, rather than from commit I as you might wish.

No commit can ever be changed, but any commit can be copied.  What if we copy commit J to a new-and-improved commit—let's call it J'—where the snapshot in J' matches the snapshot in J, plus any changes from H-to-I if needed?  (They're already in J so they are not needed, but Git would put them in if they were.)

We can get this by using git cherry-pick.  We first create a new temporary branch temp, pointing to commit I:

```<code>...--F--G--H   <-- taskA, taskB (HEAD)
</code>```2

Now we tell Git: copy commit J to where we are now:

```<code>git cherry-pick taskB
</code>```

which produces:

```<code>               J'  <-- temp (HEAD)
              /
             I   <-- taskA
            /
...--F--G--H
            \
             J   <-- taskB
</code>```

Note that, yet again, we have not changed any existing commit at all.  We have just added a new commit J' whose parent is I.

Now that we have copied all the taskB commits (all one of them) to new-and-improved commits, we just need to tell Git: Take that name taskB and move it in a way such that we'll forget all about the old commit J.  Specifically, force taskB to point to the current commit.  We do this with:

```<code>git branch -f taskB HEAD
</code>```

which results in:

```<code>               J'  <-- taskB, temp (HEAD)
              /
             I   <-- taskA
            /
...--F--G--H
            \
             J   ???
</code>```

Note that there is now no name by which to find existing commit J.  So when you have Git list out the commits it can find by branch names, commit J does not show up at all.  A new and different hash ID—that of J'—does.  Now we just switch back to branch taskB and delete the temporary name and we have:

```<code>               J'  <-- taskB (HEAD)
              /
             I   <-- taskA
            /
...--F--G--H
</code>```

as if we had been clever enough to make commit I first all along.

We don't need to use four separate Git commands—create temp branch name, cherry-pick commits to make new-and-improved-copies, forcibly move old branch name, delete temp branch name—because git rebase does that for us.  That's what git rebase is really about.

The one drawback to rebasing: if someone else has the commit(s)

You did not mention doing a git push -u origin taskB above, but if you had done that, you would have sent a request to another Git, the one over at origin, to take any new commits you have that they don't, that they need, and then to create, in their Git repository, their branch name taskB, pointing to whichever commit your name taskB points to.

When you use git rebase you tell your Git: Copy some commits to a new place, then throw out the old commits in favor of the new-and-improved copies.  Your Git obeys.  If you now have your Git ask their Git to update their taskB name:

```<code>git push origin taskB
</code>```

they will sometimes say no!  In particular, they will see whether this action will drop some commit(s) from their taskB.  If that's the case, they will reject the push with the error non-fast-forward.  But of course that's just what you would want in this case: you made some commits, then you made new-and-improved commits and they should lose the old ones.  To get them to do that, you will need a more forceful git push.

Whenever a branch gets rebased regularly, all users of any shared Git repository should be aware of this.  That's because ... well, suppose Alice pushes a commit.  Then Bob gets Alice's commit from the shared repository, and starts building his own additional commits.  Then Alice changes her mind and rebases, throwing out the old commits in favor of new-and-improved ones.  But Bob still has, and has based his commits on, the old ones!  Alice and Bob are in effect fighting over which commits are the good ones.

This is not all that hard to deal with technically, usually.  For instance, here, Bob just needs to rebase his commits on Alice's new ones, dropping Alice's old ones.  If everyone agrees in advance that this sort of thing happens, and knows how to deal with it, that's no problem.

If the origin repository is private (so there are not separate users Alice and Bob), or your branch on origin is private (same condition), or everyone agrees that rebasing happens (Alice and Bob are both ready to check these things), there is no problem here.  Just be aware of the pitfalls.  Consider using git push --force-with-lease as a safety check, too.

ContentLicense: CC BY-SA 4.0

Body:
I have the following branch structure

-localproject
  -master
  -taskA
  -taskB
-remotes/origin
  -master
  -taskA
  -taskB

Here is what I want to achieve:

The whole thing is for an assignment, so taskA and taskB are parts of the assignment that I need to push to the corresponding remote branch to get tested automatically. So initially I pull from master, which is the provided framework and create branch taskA.

I do my work in taskA and as soon as it is done, I push to the corresponding remote branch. It gets evaluated by the remote test system (gitlab CI / CD pipeline)

Perfect, taskA is working! Now I want to start taskB. This new task is based upon taskA so I create the new branch from it and start working.

Now working in taskB I realize that I could some things in my code to improve taskA. Let's say some files changed in taskB should now be committed to taskA.

The way I would do this now:
For each file, where I have changes I want to commit in taskA:

Manually copy the code while in taskB

checkout taskA

paste the code and commit the changes.

Is there a better way to do this? Can I somehow check files in taskB and copy/commit them over to taskA directly?

I hope I explained as clear as possible (at least I tried), however ask away if some things are not described in the best manner. While I generally understand git, I mostly use it for my private projects where not a lot of branching or anything out of the ordinary is involved...

Body:
There are many different ways to manage this kind of work-flow in Git, because Git is a set of tools, rather than a particular solution.

When working with Git, keep all of these things in mind:

Git is really all about commits.  Commits (like all Git internal objects) are completely immutable once created.

Commits store snapshots of your files: not changes, just snapshots.  In some ways this doesn't really matter, but it makes it a lot easier to understand some weird Git corners.  Since the commits are immutable, so are the stored files.  These stored files are also compressed (sometimes in very fancy way) and de-duplicated, and not usable by anything other than Git itself.  They have to be extracted from a commit for you to use them (see below).

Each commit has a parent commit, or for merge commits, two (or potentially more) parents.  These are stored by hash IDs.

The hash ID of each commit is how Git actually retrieves the commit, so hash IDs are crucial here.  But hash IDs look random and are completely unsuitable for human use, therefore ...

Git gives us branch names, which simply store the hash ID of the last commit that we'd like Git to think of as being "on the branch".

A Git repository, then, is essentially just two databases.  One contains all the commits and supporting internal objects—all indexed by hash ID—and the other contains the name-to-hash-ID mapping.  The files that you work with, as you do your actual work, aren't in Git at all.  That is, they're not the ones that are in the repository database.  They are just in an auxiliary area.

This work area, where you work on files, is your working tree or work-tree.  If you use git clone to make your repository, Git creates the work-tree for you.  If you build your own work-tree before you create a .git with git init, you have already set up the work-tree, and the git init step just creates a new empty repository—two empty databases, one for commits and the other for names.

When you check out some particular commit—whether that's by an explicit check out historical commit so I can view it or implied by check out some branch by name so that I can do new work—Git will extract the saved snapshot into your work-tree.  But apart from this and other Git commands that explicitly tell Git do something with my work-tree file(s), these files are now yours to do with as you will.

There's one more wrinkle here.  When you go to make a new commit, Git does not use the files in your work-tree.  Instead, Git uses hidden copies—technically these aren't exactly copies, but it works to think of them like that—of the frozen-format files that get stored in commits.  These "copies" live in what Git calls, variously, the index, or the staging area, or—rarely these days—the cache.

The index has multiple roles, but you can think of it as containing the proposed next snapshot.  It starts out matching the current snapshot, as extracted into your work-tree.  The git diff --staged and git status commands don't show you the index copies of the files because they're the same as the snapshot's copy of the files.  When you use git add, you're telling Git: Copy my work-tree copy of the file back into the index, replacing the old copy, or putting an all-new file into the index.  Now that the index copy doesn't match the current-commit copy, git status and git diff --cached will show you that file.  Change it back—to match the committed copy—and they'll stop showing the file again.

Since your work-tree is yours, you can create files that never get into Git at all.  These are your untracked files.  To help ensure you don't accidentally put the untracked files into the repository, you can list files or name-patterns in .gitignore.  Note that once a file is tracked, listing it in .gitignore has no effect.

A file in your work-tree is tracked if and only if that file exists right now in Git's index.  While this definition is very short and simple, it has a long shadow:  Since Git fills in its index from a commit—via git checkout or git switch—this means that a file that exists in commit X but not in commit Y can switch from being tracked to untracked, or vice versa, just by changing which commit you have checked out.  You can also modify, create, or remove specific files within the index yourself, with git add and git rm.  Whenever you do this, you're changing the proposed next commit.  None of this has any effect until you actually run git commit.

With the above in mind, we're ready to tackle your particular case

Let's jump right to step 3:

Perfect, taskA is working! Now I want to start taskB. This new task is based upon taskA so I create the new branch from it and start working.

Since commits refer back to earlier commits, let's draw this.  Suppose the hash ID of the last commit in your taskA branch (which now exists) is H, where H stands in for the real Git hash ID.  Then the name taskA is a way for Git to remember hash ID H for you.  Commit H itself has a parent, with another big ugly hash ID, but we'll call that parent G.  G has a parent, too, which we'll call F, and so on:

... <-F <-G <-H   <--taskA

The name taskA selects commit H (for now).  The name taskB does not even exist yet.

Now you create taskB.  I'm going to switch from drawing the internal arrows, which point backwards from each commit, to lines because the arrow drawing character set for posting here on StackOverflow is poor, but this just adds another name, taskB, that also selects commit H:

...--F--G--H   <-- taskA, taskB (HEAD)

We now need to know which name we're using, as well as which commit, so we'll attach the special name HEAD to one of these two branch names.

Now working in taskB I realize that I could some things in my code to improve taskA. Let's say some files changed in taskB should now be committed to taskA.

This is where you suddenly get a lot of options.

My favorite one for descriptive purposes is git worktree, specifically git worktree add.  But git worktree was new in Git 2.5, and had a nasty bug finally fixed in 2.15, so unless your Git is reasonably modern, you might want to avoid it.  It's also going to create a little bit of extra work for you, if you go this way, but it's a very general solution.

What git worktree add does is let you add a second work-tree to your existing repository.  Each added work-tree gets:

its own HEAD, so that it can (and in fact must) have a different branch checked out;

its own index, i.e., proposed next commit; and

of course, its own work-tree full of files.

So you can use git worktree add to make two independent work areas, each of which is "on" a different branch.  You can then just take this moment to:

open a new window on (or push directories to) the work-tree in which you're working on taskA;

modify the files there, however you like—up to and including copying them from the work-tree where you are working on taskB—and git add and git commit.

Let's say you do make a new commit in this added work-tree.  We can draw that.  We start with this:

...--F--G--H   <-- taskA (HEAD), taskB

and modify some files, git add, and run git commit.  This makes a new commit—which gets a new big ugly hash ID; we'll call it I—and makes the name taskA point to this new commit:

             I   <-- taskA (HEAD)
            /
...--F--G--H   <-- taskB

If we switch back to the taskB window / work-tree, where taskB is the HEAD, we have:

             I   <-- taskA
            /
...--F--G--H   <-- taskB (HEAD)

The files in the work-tree here—the original one, not the added one—match those of commit H, except for any changes you've made so far.  The files in the index for this work-tree match those for commit H.  Any new commit you make now will update the name taskB like this:

             I   <-- taskA
            /
...--F--G--H
            \
             J   <-- taskB (HEAD)

Again, the new snapshot comes from the index.  The commits have not changed: we've merely added some new ones.  The parent of new commit I is existing commit H.  The parent of new commit J is existing commit H.  Commits up through and including H are on both branches, but the branches now diverge.

What if you don't want to use git worktree add

Remember that Git makes each new commit from the index, not from your work-tree.  Suppose we have:

...--F--G--H   <-- taskA, taskB (HEAD)

but the index matches commit H.  Git will let you switch back to taskA without disturbing the index and work-tree content at all.  (This is not always true, but it is true given our suppositions and setup here.  For the gory details, see Checkout another branch when there are uncommitted changes on the current branch.)  So let's say we do that:

git checkout taskA              # or git switch taskA

...--F--G--H   <-- taskA (HEAD), taskB

Now we just git add the one or two files you would like to be different—which copies them into the index, ready for the next commit—and then run git commit.  Since we're using the index files, not the work-tree files, updated you made but did not git add do not go into the new snapshot.

We get:

             I   <-- taskA (HEAD)
            /
...--F--G--H   <-- taskB

exactly as before.  The name taskB does not move.

When we now git checkout taskB, Git sees that the files we just updated are different in commits H and I.  So Git will copy H's copy of those files out of the commit, into Git's index (so that they match H) and your work-tree, and the changes you just made for taskA are gone.  But we can bring them back into the work-tree:

git checkout taskA -- file1 file2

or (since Git 2.23):

git restore -s taskA -i -w file1 file2

which tells Git: reach into the commit identified by the name taskA—commit I—and pull out these two files and copy them into the index and my work-tree.  So now you're back to having the updated files, along with all the other undisturbed files.  The updated files are already changes staged for commit, as git status will say, as they're in the proposed next commit in the index.

You can now finish up the stuff you were doing, git add, and git commit as needed, giving:

             I   <-- taskA
            /
...--F--G--H
            \
             J   <-- taskB (HEAD)

exactly as before.

You may now want to rebase taskB

However you got to this point, you now have taskB extending from commit H, rather than from commit I as you might wish.

No commit can ever be changed, but any commit can be copied.  What if we copy commit J to a new-and-improved commit—let's call it J'—where the snapshot in J' matches the snapshot in J, plus any changes from H-to-I if needed?  (They're already in J so they are not needed, but Git would put them in if they were.)

We can get this by using git cherry-pick.  We first create a new temporary branch temp, pointing to commit I:

             I   <-- taskA, temp (HEAD)
            /
...--F--G--H
            \
             J   <-- taskB

Now we tell Git: copy commit J to where we are now:

git cherry-pick taskB

which produces:

               J'  <-- temp (HEAD)
              /
             I   <-- taskA
            /
...--F--G--H
            \
             J   <-- taskB

Note that, yet again, we have not changed any existing commit at all.  We have just added a new commit J' whose parent is I.

Now that we have copied all the taskB commits (all one of them) to new-and-improved commits, we just need to tell Git: Take that name taskB and move it in a way such that we'll forget all about the old commit J.  Specifically, force taskB to point to the current commit.  We do this with:

git branch -f taskB HEAD

which results in:

               J'  <-- taskB, temp (HEAD)
              /
             I   <-- taskA
            /
...--F--G--H
            \
             J   ???

Note that there is now no name by which to find existing commit J.  So when you have Git list out the commits it can find by branch names, commit J does not show up at all.  A new and different hash ID—that of J'—does.  Now we just switch back to branch taskB and delete the temporary name and we have:

               J'  <-- taskB (HEAD)
              /
             I   <-- taskA
            /
...--F--G--H

as if we had been clever enough to make commit I first all along.

We don't need to use four separate Git commands—create temp branch name, cherry-pick commits to make new-and-improved-copies, forcibly move old branch name, delete temp branch name—because git rebase does that for us.  That's what git rebase is really about.

The one drawback to rebasing: if someone else has the commit(s)

You did not mention doing a git push -u origin taskB above, but if you had done that, you would have sent a request to another Git, the one over at origin, to take any new commits you have that they don't, that they need, and then to create, in their Git repository, their branch name taskB, pointing to whichever commit your name taskB points to.

When you use git rebase you tell your Git: Copy some commits to a new place, then throw out the old commits in favor of the new-and-improved copies.  Your Git obeys.  If you now have your Git ask their Git to update their taskB name:

git push origin taskB

they will sometimes say no!  In particular, they will see whether this action will drop some commit(s) from their taskB.  If that's the case, they will reject the push with the error non-fast-forward.  But of course that's just what you would want in this case: you made some commits, then you made new-and-improved commits and they should lose the old ones.  To get them to do that, you will need a more forceful git push.

Whenever a branch gets rebased regularly, all users of any shared Git repository should be aware of this.  That's because ... well, suppose Alice pushes a commit.  Then Bob gets Alice's commit from the shared repository, and starts building his own additional commits.  Then Alice changes her mind and rebases, throwing out the old commits in favor of new-and-improved ones.  But Bob still has, and has based his commits on, the old ones!  Alice and Bob are in effect fighting over which commits are the good ones.

This is not all that hard to deal with technically, usually.  For instance, here, Bob just needs to rebase his commits on Alice's new ones, dropping Alice's old ones.  If everyone agrees in advance that this sort of thing happens, and knows how to deal with it, that's no problem.

If the origin repository is private (so there are not separate users Alice and Bob), or your branch on origin is private (same condition), or everyone agrees that rebasing happens (Alice and Bob are both ready to check these things), there is no problem here.  Just be aware of the pitfalls.  Consider using git push --force-with-lease as a safety check, too.


问:
Inventory design approach (inheritance vs generics)
Greetings!
I am trying to decide on which is the best approach to implement a following scenario:

Vehicle and Part are both "entites" which can be an Item in an Inventory.
Vehicle has the usual VIN, Year, Make, Model, Type, etc, etc... while Part has PartNumber, QuantityOnHand, IsPartOfSet, Vendor...
When "stocked" in an Inventory as an Item, both have RetailPrice, PurchasePrice, PurchaseDate but at the same time they have a lot of other properties that are not in common
(e.g Vehicle has CurrentMileage, NewOrUsed, etc... etc.. while Part has TreshholdCount, LastCountDate, etc, etc..)
So as you can see both Part and Vehicle can be in Inventory, but they have very few properties that are share (more that they don't)...

With scenario above, I am trying to decide between several approaches:

Option 1 - Separate classes for everything (no inheritance)

Vehicle - common vehicle properties (VIN, year, make, model, etc, etc)

VehicleInventoryItem - has a reference to Vehicle and contains other inventory specific properties (pricing, warranties, status)

VehicleInventoryManager - singleton with business logic add, remove, notify, etc, etc

Part

PartInventoryItem

PartInventoryManager

I think this approach is most flexible while it suffers for some property repetition. Managers also can have very different methods...

Option 2 - Base class simple inheritance

Vehicle - same as option 1

Part - same as option 1

InventoryItem  - base class

VehicleInventoryItem - extends InventoryItem, references Vehicle

PartInventoryItem - extends InventoryItem, references Part

InventoryManager - all methods accept InventoryItem as parameters

With this approach, I am worried about InventoryManager being polluted with different operations needed for parts vs vehicles

Option 3 - Generics

Item - where T will be part or vehicle (I can even go more specific then, e.g. - VehicleItem : Item)

Inventory - holds reference to Item

InventoryManager - singleton that operates on T

In this approach, there is less classes but again I am worried about InventoryManager

Recap

Vehicle and Part share very few properties when "stocked" in Inventory.

Inventory management for Vehicle and Part will also be mostly different (parts are "reordered" when qty on hand is low, when vehicle is sold similar one may be purchased but it is unique)

In my scenario there will be no other objects/models that will be "stockable" (being in Inventory of any kind)

Questions

What does community think? Is there another approach (perhaps interfaces?)
If 2 domain objects share at least 1 property (e.g. PurchasePrice), should that warrant having some sort of inheritance (e.g. option 2 or 3)

答:
From a brief look at your description I would like to suggest putting the Inventory related methods on the items in an Interface. If you need a relationship between vehicles and parts, you can always have a property on your parts to reference the vehicle they come from, or the other way around (or possibly both, if you need to do lookups both ways). This seems to separate the concern of dealing with inventory related tasks into a specific class.
Hope that helps.</p>

ContentLicense: CC BY-SA 3.0


问:
How to extract partial text information from a label tag using Selenium and Python
I am trying to loop through different checkboxes and check them if the text is present in the list then click if not then move on.

the html element that I have been able to extract is below:

```<code><label>
 <input type ="checkbox" value = "pf29">
 <span> BNN Bloomberg </span>
 <span> class='count'>(16)</span>
<label>
</code>```

when I do element.text it gives me BNN Bloomberg (16). Is there a way to restrict the text output to only BNN Bloomberg?

There are roughly 33 different tags so I cant use any of the string methods to limit the number of characters.

Fairly new to html and selenium so excuse my wording.

Currently this is what my code looks like

```<code>element_list = (driver.find_elements_by_css_selector("div[class='modal-dialog-padded-body'] label"))
source = element_list[3].text
print(source)
</code>```

print(source) gives me BNN Bloomberg (16)

Edit: I have to loop through 21 different elements and look at the text to see what the source is and check the checkbox accordingly.

答:
You were pretty close enough.
To retrieve the text BNN Bloomberg you need to traverse one step deeper till the first  tag and youyou can use either of the following Locator Strategies:

Using css_selector and get_attribute():

```<code>print(driver.find_element_by_css_selector("div.modal-dialog-padded-body label span:not(.count)").get_attribute("innerHTML"))
</code>```

Using xpath and text attribute:

```<code>print(driver.find_element_by_xpath("//div[@class='modal-dialog-padded-body']//label//span[not(contains(@class,'count'))]").text)
</code>```

Best practices

To print the first title you have to induce WebDriverWait for thevisibility_of_element_located() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR and text attribute::

```<code>print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.modal-dialog-padded-body label span:not(.count)"))).text)
</code>```

Using XPATH and get_attribute():

```<code>print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='modal-dialog-padded-body']//label//span[not(contains(@class,'count'))]"))).get_attribute("innerHTML"))
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Reference

You can find a couple of relevant discussions in:

Protractor - Check if a radio-button is checked or not

Body:
I am trying to loop through different checkboxes and check them if the text is present in the list then click if not then move on.

the html element that I have been able to extract is below:

 <input type ="checkbox" value = "pf29">
  BNN Bloomberg
  class='count'>(16)

when I do element.text it gives me BNN Bloomberg (16). Is there a way to restrict the text output to only BNN Bloomberg?

There are roughly 33 different tags so I cant use any of the string methods to limit the number of characters.

Fairly new to html and selenium so excuse my wording.

Currently this is what my code looks like

element_list = (driver.find_elements_by_css_selector("div[class='modal-dialog-padded-body'] label"))
source = element_list[3].text
print(source)

print(source) gives me BNN Bloomberg (16)

Edit: I have to loop through 21 different elements and look at the text to see what the source is and check the checkbox accordingly.

Body:
You were pretty close enough.
To retrieve the text BNN Bloomberg you need to traverse one step deeper till the first <span> tag and youyou can use either of the following Locator Strategies:

Using css_selector and get_attribute():

print(driver.find_element_by_css_selector("div.modal-dialog-padded-body label span:not(.count)").get_attribute("innerHTML"))

Using xpath and text attribute:

print(driver.find_element_by_xpath("//div[@class='modal-dialog-padded-body']//label//span[not(contains(@class,'count'))]").text)

Best practices

To print the first title you have to induce WebDriverWait for thevisibility_of_element_located() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR and text attribute::

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.modal-dialog-padded-body label span:not(.count)"))).text)

Using XPATH and get_attribute():

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='modal-dialog-padded-body']//label//span[not(contains(@class,'count'))]"))).get_attribute("innerHTML"))

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Reference

You can find a couple of relevant discussions in:

Protractor - Check if a radio-button is checked or not


问:
i stack over and over in djjango
i watched few videos to learn how to use Django. a lot of them coming older version of Django and because im a beginner in Django so it makes it harder. the problem is that in urls.py file they are showing how to make it with "url" way and i have the newer version of Django which is showing me with "path" way. what i did wrong here that it does not showing me:

```<code>from django.contrib import admin
from django.urls import path

from adoptions import views

urlpatterns = [

    path('admin/', admin.site.urls),

    path("", views.home, name = "home"),

    path("adoptions/(\d+)/", views.pet_detail, name = "pet_detail"),

]
</code>```

cause what i actually did, i looked on the tutorial and implemented on the path. maybe i did it wrong i dont know. and this is not the first time that i stack on the same place.

答:
if you want to use id of the cat use it like below

```<code>path("adoptions/<int:id>", views.pet_detail, name = "pet_detail"),
</code>```

or slug

```<code>path("adoptions/<slug:slug>", views.pet_detail, name = "pet_detail"),
</code>```

Best way to start Django is the official documentation first app. It will fix your mindset easily. Though the versions of Django are not so much different than each other.

Title: i stack over and over in djjango

Body:
i watched few videos to learn how to use Django. a lot of them coming older version of Django and because im a beginner in Django so it makes it harder. the problem is that in urls.py file they are showing how to make it with "url" way and i have the newer version of Django which is showing me with "path" way. what i did wrong here that it does not showing me:

from django.contrib import admin
from django.urls import path

from adoptions import views

urlpatterns = [

    path('admin/', admin.site.urls),

    path("", views.home, name = "home"),

    path("adoptions/(\d+)/", views.pet_detail, name = "pet_detail"),

]

cause what i actually did, i looked on the tutorial and implemented on the path. maybe i did it wrong i dont know. and this is not the first time that i stack on the same place.

Body:
if you want to use id of the cat use it like below

path("adoptions/<int:id>", views.pet_detail, name = "pet_detail"),

or slug

path("adoptions/<slug:slug>", views.pet_detail, name = "pet_detail"),

Best way to start Django is the official documentation first app. It will fix your mindset easily. Though the versions of Django are not so much different than each other.


问:
What is the best way to trigger actions on successful authentication in ASP.NET MVC Core?
When multiple authentication schemes are registered there can be many different paths that a successful authentication can take. I'm looking for a way to register a single handler which will trigger actions that should be taken upon any successful auth.</p>

答:
The simplest and most robust solution I've found is to subclass SignInManager and override the SignInAsync or SignInWithClaimsAsync method:

```<code>public class CustomSignInManager<TUser> : SignInManager<TUser> where TUser : class
{
    public CustomSignInManager(UserManager<TUser> userManager, IHttpContextAccessor contextAccessor, IUserClaimsPrincipalFactory<TUser> claimsFactory, IOptions<IdentityOptions> optionsAccessor, ILogger<SignInManager<TUser>> logger, IAuthenticationSchemeProvider schemes)
        : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes, new DefaultUserConfirmation<TUser>()) { }

    public override async Task SignInWithClaimsAsync(TUser user, AuthenticationProperties authenticationProperties, IEnumerable<Claim> additionalClaims)
    {
        await base.SignInWithClaimsAsync(user, authenticationProperties, additionalClaims);

        // Trigger custom actions
    }
}
</code>```

Then register the custom SignInManager in ConfigureServices:

```<code>services.AddSignInManager<CustomSignInManager<TUser>>();
</code>```

Body:
The simplest and most robust solution I've found is to subclass SignInManager and override the SignInAsync or SignInWithClaimsAsync method:

public class CustomSignInManager<TUser> : SignInManager<TUser> where TUser : class
{
    public CustomSignInManager(UserManager<TUser> userManager, IHttpContextAccessor contextAccessor, IUserClaimsPrincipalFactory<TUser> claimsFactory, IOptions<IdentityOptions> optionsAccessor, ILogger<SignInManager<TUser>> logger, IAuthenticationSchemeProvider schemes)
        : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes, new DefaultUserConfirmation<TUser>()) { }

    public override async Task SignInWithClaimsAsync(TUser user, AuthenticationProperties authenticationProperties, IEnumerable<Claim> additionalClaims)
    {
        await base.SignInWithClaimsAsync(user, authenticationProperties, additionalClaims);

        // Trigger custom actions
    }
}

Then register the custom SignInManager in ConfigureServices:

services.AddSignInManager<CustomSignInManager<TUser>>();


问:
Output stdio and stderr from pytest.main()
Is there a way to get the output from a test that you run via pytest, using the call to main?

```<code>string = "-x mytests.py"
pytest.main(string)
print(????????)
</code>```

If this was a process I could get the output using communicate() but I can't find the equivalent for pytest when running it as function from Python3, instead than run it as standalone from terminal.

EDIT:
I did try to use sys.stdout but it didn't work either...I am fundamentally stuck since I can't get the pytest output in any way; beside in my output IDE window. Any suggestion or workaround would be really appreciated.

答:
As of Python 3.4 (per the docs), there is an easier way to accomplish what you are trying to do:</p>

```<code>from io import StringIO
from contextlib import redirect_stdout

temp_stdout = StringIO()
with redirect_stdout(temp_stdout):
    result = pytest.main(sys.argv)
stdout_str = temp_stdout.getvalue()
# or whatever you want to do with it
print(stdout_str.upper())
</code>```

Body:
Is there a way to get the output from a test that you run via pytest, using the call to main?

string = "-x mytests.py"
pytest.main(string)
print(????????)

If this was a process I could get the output using communicate() but I can't find the equivalent for pytest when running it as function from Python3, instead than run it as standalone from terminal.

EDIT:
I did try to use sys.stdout but it didn't work either...I am fundamentally stuck since I can't get the pytest output in any way; beside in my output IDE window. Any suggestion or workaround would be really appreciated.

Body:
As of Python 3.4 (per the docs), there is an easier way to accomplish what you are trying to do:

from io import StringIO
from contextlib import redirect_stdout

temp_stdout = StringIO()
with redirect_stdout(temp_stdout):
    result = pytest.main(sys.argv)
stdout_str = temp_stdout.getvalue()
# or whatever you want to do with it
print(stdout_str.upper())


问:
Calling the variable property directly vs getter/setters - OOP Design
I know this is probably subjective but I read this optimization page from Google for PHP and they suggest use the variable property directly without the need of getters and setters. Understandably I see the performance gain in this but is this really a good design practice to follow?

Their Example using getter/setter:

```<code>class dog {
  public $name = '';

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

$rover = new dog();
$rover->setName('rover');
echo $rover->getName();
</code>```

Suggested Optimization:

```<code>$rover = new dog();
$rover->name = 'rover';
echo $rover->name;
</code>```

This would be a welcome change in my design process as I see the need for getters/setters going away, but what other hurdles/benefits might occur in doing this?

答:
This would be a welcome change in my
  design process as I see the need for
  getters/setters going away, but what
  other hurdles/benefits might occur in
  doing this?

You lose the ability to implement special get/set logic on a particular property. For properties that are scalars (strings, integers, booleans) maybe this is no problem. But what if you have a property that is a lazy-loaded class instance?

```<code>class Document
{
    protected $_createdBy;

    public function getCreatedBy()
    {
        if (is_integer($this->_createdBy)) {
            $this->_createdBy = UserFactory::loadUserById($this->_createdBy);
        }
        return $this->_createdBy;
    }
}
</code>```

That trick only works in a method. You could use __get and __set for this logic but as you add properties you end up with a big nasty switch() block:

```<code>public function __get($name)
{
    switch ($name) {
        case 'createdBy':
            // blah blah blah
        case 'createdDate':
            // more stuff
        // more case statements until you scream
    }
}
</code>```

If you just want to avoid or put off writing getters and setters, use the __call magic method to trap method calls that follow the getProperty() and setProperty() naming convention. You can put all the default get/set logic in __call and never touch it again:

```<code>abstract class Object
{
    public function __call($method, $args)
    {
        $key = '_' . strtolower(substr($method, 3, 1)) . substr($method, 4);
        $value = isset($args[0]) ? $args[0] : null;
        switch (substr($method, 0, 3)) {
            case 'get':
                if (property_exists($this, $key)) {
                    return $this->$key;
                }
                break;

            case 'set':
                if (property_exists($this, $key)) {
                    $this->$key = $value;
                    return $this;
                }
                break;

            case 'has':
                return property_exists($this, $key);
                break;
        }

        throw new Exception('Method "' . $method . '" does not exist and was not trapped in __call()');
    }
}
</code>```

This approach is very fast from a development standpoint because you can just extend the Object class, define some properties, and you're off to the races:

```<code>class Foo extends Object
{
    protected $_bar = 12345;
}

$foo = new Foo();
echo $foo->getBar();  // outputs '12345'
$foo->setBar(67890);  // next call to getBar() returns 67890
$foo->getBaz();       // oops! 'baz' doesn't exist, exception for you
</code>```

It's slow from an execution standpoint because magic methods are damned slow, but you can mitigate that later by defining explicit getBar() and setBar() methods (because __call is only invoked when you calling a method that isn't defined). But if a particular property doesn't get accessed very often, maybe you don't care how slow it is. The point is, it's easy to add special get/set methods later on and the rest of your code never knows the difference.

I cribbed this approach from Magento and I find it to be very developer-friendly. Throwing an exception when calling the get/set for a property that doesn't exist helps you avoid phantom bugs caused by typos. Keeping property-specific logic in its own get/set methods makes code easier to maintain. But you don't have to write all the accessor methods at the start, you can easily go back and add them without refactoring all your other code.

The question is, what are you trying to optimize? Developer time or code speed? If you want to optimize code speed, make sure you know where your bottlenecks are before building your code around them. Premature optimization is the root of all evil.

Body:
I know this is probably subjective but I read this optimization page from Google for PHP and they suggest use the variable property directly without the need of getters and setters. Understandably I see the performance gain in this but is this really a good design practice to follow?

Their Example using getter/setter:

class dog {
  public $name = '';

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

$rover = new dog();
$rover->setName('rover');
echo $rover->getName();

Suggested Optimization:

$rover = new dog();
$rover->name = 'rover';
echo $rover->name;

This would be a welcome change in my design process as I see the need for getters/setters going away, but what other hurdles/benefits might occur in doing this?

Body:
This would be a welcome change in my
  design process as I see the need for
  getters/setters going away, but what
  other hurdles/benefits might occur in
  doing this?

You lose the ability to implement special get/set logic on a particular property. For properties that are scalars (strings, integers, booleans) maybe this is no problem. But what if you have a property that is a lazy-loaded class instance?

class Document
{
    protected $_createdBy;

    public function getCreatedBy()
    {
        if (is_integer($this->_createdBy)) {
            $this->_createdBy = UserFactory::loadUserById($this->_createdBy);
        }
        return $this->_createdBy;
    }
}

That trick only works in a method. You could use __get and __set for this logic but as you add properties you end up with a big nasty switch() block:

public function __get($name)
{
    switch ($name) {
        case 'createdBy':
            // blah blah blah
        case 'createdDate':
            // more stuff
        // more case statements until you scream
    }
}

If you just want to avoid or put off writing getters and setters, use the __call magic method to trap method calls that follow the getProperty() and setProperty() naming convention. You can put all the default get/set logic in __call and never touch it again:

abstract class Object
{
    public function __call($method, $args)
    {
        $key = '_' . strtolower(substr($method, 3, 1)) . substr($method, 4);
        $value = isset($args[0]) ? $args[0] : null;
        switch (substr($method, 0, 3)) {
            case 'get':
                if (property_exists($this, $key)) {
                    return $this->$key;
                }
                break;

            case 'set':
                if (property_exists($this, $key)) {
                    $this->$key = $value;
                    return $this;
                }
                break;

            case 'has':
                return property_exists($this, $key);
                break;
        }

        throw new Exception('Method "' . $method . '" does not exist and was not trapped in __call()');
    }
}

This approach is very fast from a development standpoint because you can just extend the Object class, define some properties, and you're off to the races:

class Foo extends Object
{
    protected $_bar = 12345;
}

$foo = new Foo();
echo $foo->getBar();  // outputs '12345'
$foo->setBar(67890);  // next call to getBar() returns 67890
$foo->getBaz();       // oops! 'baz' doesn't exist, exception for you

It's slow from an execution standpoint because magic methods are damned slow, but you can mitigate that later by defining explicit getBar() and setBar() methods (because __call is only invoked when you calling a method that isn't defined). But if a particular property doesn't get accessed very often, maybe you don't care how slow it is. The point is, it's easy to add special get/set methods later on and the rest of your code never knows the difference.

I cribbed this approach from Magento and I find it to be very developer-friendly. Throwing an exception when calling the get/set for a property that doesn't exist helps you avoid phantom bugs caused by typos. Keeping property-specific logic in its own get/set methods makes code easier to maintain. But you don't have to write all the accessor methods at the start, you can easily go back and add them without refactoring all your other code.

The question is, what are you trying to optimize? Developer time or code speed? If you want to optimize code speed, make sure you know where your bottlenecks are before building your code around them. Premature optimization is the root of all evil.


问:
Angular 9 routing to child component in lazy loaded module
I have problem with routing setup to child component in a lazy loaded module.

app.routing.ts

```<code>export const routes: Routes = [
    {
        path: 'admin',
        loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),
    },
];
</code>```

admin.routing.ts

```<code>export const routes: Routes = [
    {
        path: '',
        component: AdminPanelComponent,

        children: [
            {
                path: '',
                redirectTo: 'user/list',
                pathMatch: 'full'
            },
            {
                path: 'user/list',
                canActivate: [AdminGuard],
                component: UserListComponent,
            },
            {
                path: 'user/new',
                canActivate: [AdminGuard],
                component: UserComponent,
            }
        ]
    }

];
</code>```

When I go to https://localhost/admin app is not redirected to https://localhost/admin/user/list as expected but to https://localhost.

AdminPanelComponent is a UI layout component for admin module.

Any suggestions?

UPDATE:
Same problem with lazy loaded module without child components

app.routing.ts

```<code>export const routes: Routes = [
    {
        path: 'agent',
        loadChildren: () => import('./agent/agent.module').then(m => m.AgentModule),
    },
];
</code>```

agent.routing.ts

```<code>export const routes: Routes = [
    {
        path: '',
        component: AgentPanelComponent,
    },

];
</code>```

When I go to https://localhost/agent app is redirected to https://localhost.

UPDATE:
I found a problem and fixed it but can't explain why it was not working.

app.routing.ts

```<code>export const routes: Routes = [
        {
            path: 'auth',
            loadChildren: () => import('./auth/auth.module').then(m => m.AuthModule),
        },
        {
            path: 'admin',
            loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),
        },
        {
            path: 'agent',
            loadChildren: () => import('./agent/agent.module').then(m => m.AgentModule),
        },

    ];
</code>```

Both admin and agent modules are using auth module.

auth.routing.ts

```<code>export const routes: Routes = [
    {
        path: '',
        canActivate: [RedirectIfLoggedInGuard],
        component: LoginPageComponent
    },
    {
        path: 'password-reset',
        canActivate: [RedirectIfLoggedInGuard],
        component: LoginPasswordResetComponent
    },
];
</code>```

In auth.routing.ts I've changed path from this

```<code>{
            path: '',
            canActivate: [RedirectIfLoggedInGuard],
            component: LoginPageComponent
        },
</code>```

to this

```<code>{
            path: 'login',
            canActivate: [RedirectIfLoggedInGuard],
            component: LoginPageComponent
        },
</code>```

And it's working fine now.

答: What you probably did and created the infinite recursion is you imported AuthModule inside the AdminModule which in turn mounted the routes for the login in the admin module. To confirm the issue try navigating to /admin/login. You will see that it will load up the LoginComponent which is not what you expected to happen. The reason you probably created the infinite recursion is because your guard is now running both on /login routes and /admin routes which tries to redirect to itself.</p>

Body:
I have problem with routing setup to child component in a lazy loaded module.

app.routing.ts

export const routes: Routes = [
    {
        path: 'admin',
        loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),
    },
];

admin.routing.ts

export const routes: Routes = [
    {
        path: '',
        component: AdminPanelComponent,

        children: [
            {
                path: '',
                redirectTo: 'user/list',
                pathMatch: 'full'
            },
            {
                path: 'user/list',
                canActivate: [AdminGuard],
                component: UserListComponent,
            },
            {
                path: 'user/new',
                canActivate: [AdminGuard],
                component: UserComponent,
            }
        ]
    }

];

When I go to https://localhost/admin app is not redirected to https://localhost/admin/user/list as expected but to https://localhost.

AdminPanelComponent is a UI layout component for admin module.

Any suggestions?

UPDATE:
Same problem with lazy loaded module without child components

app.routing.ts

export const routes: Routes = [
    {
        path: 'agent',
        loadChildren: () => import('./agent/agent.module').then(m => m.AgentModule),
    },
];

agent.routing.ts

export const routes: Routes = [
    {
        path: '',
        component: AgentPanelComponent,
    },

];

When I go to https://localhost/agent app is redirected to https://localhost.

UPDATE:
I found a problem and fixed it but can't explain why it was not working.

app.routing.ts

export const routes: Routes = [
        {
            path: 'auth',
            loadChildren: () => import('./auth/auth.module').then(m => m.AuthModule),
        },
        {
            path: 'admin',
            loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),
        },
        {
            path: 'agent',
            loadChildren: () => import('./agent/agent.module').then(m => m.AgentModule),
        },

    ];

Both admin and agent modules are using auth module.

auth.routing.ts

export const routes: Routes = [
    {
        path: '',
        canActivate: [RedirectIfLoggedInGuard],
        component: LoginPageComponent
    },
    {
        path: 'password-reset',
        canActivate: [RedirectIfLoggedInGuard],
        component: LoginPasswordResetComponent
    },
];

In auth.routing.ts I've changed path from this

{
            path: '',
            canActivate: [RedirectIfLoggedInGuard],
            component: LoginPageComponent
        },

to this

{
            path: 'login',
            canActivate: [RedirectIfLoggedInGuard],
            component: LoginPageComponent
        },

And it's working fine now.


问:
Send emails where the box is checked
I'd like to have the possibility to send ID emails using the button "Envoyer ID" only to the rows which are checked: user2, user4 & user5.

Thank you.

```<code> function EnvoiIDCourriel() {

  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Liste").activate();
  var SS = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var LR = SS.getLastRow()

  var TemplateTexte = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();
  //Permet d'utiliser le corps du courriel qui se trouve dans l'onglet Template

  //Logger.log(NomCandidat);

  //Cette ligne permet de passer à travers de toutes les lignes inscrites
  for (var i = 2;i<=LR;i++){

       var CurrentEmail = SS.getRange(i, 4).getValue();
       var ID = SS.getRange(i, 3).getValue();
       var NomCandidat = SS.getRange(i, 2).getValue();
       var Processus = SS.getRange(i, 5).getValue();
       //var Img = DriveApp.getFileById(1pRBZnWRZcKMFll1OouC8eer2V97e8tT6).getBlob();
       //Logger.log(Img);

       var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
       var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne"

       //Logger.log(ObjetCourriel);

       GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage)

    }

}
</code>```

答:
How about this modification?

Modification points:

In your script, the values are retrieved from Spreadsheet in the for loop. In order to reduce the process cost, in this modification, at first, the values are retrieved from the cells "A2:E", and the email is sent using the retrieved values.

When the value of checkbox is retrieved by getValue and getValues, the value type is the boolean type.

When above points are reflected to your script, it becomes as follows.

Modified script:

From:

```<code>for (var i = 2;i<=LR;i++){

     var CurrentEmail = SS.getRange(i, 4).getValue();
     var ID = SS.getRange(i, 3).getValue();
     var NomCandidat = SS.getRange(i, 2).getValue();
     var Processus = SS.getRange(i, 5).getValue();
     //var Img = DriveApp.getFileById(1pRBZnWRZcKMFll1OouC8eer2V97e8tT6).getBlob();
     //Logger.log(Img);

     var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
     var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne"

     //Logger.log(ObjetCourriel);

     GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage)

  }
</code>```

To:

```<code>var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
  if (check === true) {
    var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
    var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
    GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage);
  }
});
</code>```

References:

getValues()

forEach()

Title: Send emails where the box is checked

Body:
I'd like to have the possibility to send ID emails using the button "Envoyer ID" only to the rows which are checked: user2, user4 & user5.

Thank you.

 function EnvoiIDCourriel() {

  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Liste").activate();
  var SS = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var LR = SS.getLastRow()

  var TemplateTexte = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();
  //Permet d'utiliser le corps du courriel qui se trouve dans l'onglet Template

  //Logger.log(NomCandidat);

  //Cette ligne permet de passer à travers de toutes les lignes inscrites
  for (var i = 2;i<=LR;i++){

       var CurrentEmail = SS.getRange(i, 4).getValue();
       var ID = SS.getRange(i, 3).getValue();
       var NomCandidat = SS.getRange(i, 2).getValue();
       var Processus = SS.getRange(i, 5).getValue();
       //var Img = DriveApp.getFileById(1pRBZnWRZcKMFll1OouC8eer2V97e8tT6).getBlob();
       //Logger.log(Img);

       var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
       var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne"

       //Logger.log(ObjetCourriel);

       GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage)

    }

}

Body:
How about this modification?

Modification points:

In your script, the values are retrieved from Spreadsheet in the for loop. In order to reduce the process cost, in this modification, at first, the values are retrieved from the cells "A2:E", and the email is sent using the retrieved values.

When the value of checkbox is retrieved by getValue and getValues, the value type is the boolean type.

When above points are reflected to your script, it becomes as follows.

Modified script:

From:

for (var i = 2;i<=LR;i++){

     var CurrentEmail = SS.getRange(i, 4).getValue();
     var ID = SS.getRange(i, 3).getValue();
     var NomCandidat = SS.getRange(i, 2).getValue();
     var Processus = SS.getRange(i, 5).getValue();
     //var Img = DriveApp.getFileById(1pRBZnWRZcKMFll1OouC8eer2V97e8tT6).getBlob();
     //Logger.log(Img);

     var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
     var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne"

     //Logger.log(ObjetCourriel);

     GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage)

  }

To:

var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
  if (check === true) {
    var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
    var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
    GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage);
  }
});

References:

getValues()

forEach()


问:
MS access Query with in and parameter
I need to create a query in MS access where the parameter is a list (given by me).

This works In ("2209487";"2102669";"2727930";"3727550"), but if I try to put a parameter inside the "IN" like this: In ([NUM]) It doesn't return a result!

I write 2209487";"2102669";"2727930";"3727550 when the parameter window appears.

PS: my laptop is in European Portuguese so I use the ";"

答:
Thanks to all!!!!

i've redone the query and logic of the database) in another way.

Title: MS access Query with in and parameter


问:
Find the closest pair of points in a given set of points
Q) Find the closest pair of points in a given set of points.

Expected time complexity: O(nlog2(n)) / O(nlog(n))

i was reading up this problem from here. However i am unable to understand a few things:

what do we achieve by sorting points by Y which are already sorted by X?

when we take a point as mid from one of the halves, dont we miss out on a few cases?
i.e. how does taking a mid point ensure that the strip formed
includes all the points that are candidates for a distance less than the distance returned by the two recursive calls?

even if the above point is proved, shouldnt we take the mid point of both halves i.e. m of left half and (m+1) of right half?

答:
If I understand this correctly, the following point is actually a bit misleading:

3) Recursively find the smallest distances in both subarrays. [...]

I think it should say: Split the subarrays recursively until they contain a small number of points (maybe 2 or 3? It doesn't say) and then find the smallest distance in each of this small strips. Then we proceed with 4)-7) and apply a y-strip search for every border between all subarrays that we created.

Here is my understanding of what happens, it doesn't mention array splitting because I think this only confuses what is going on:

1) Sort all points by x. Walk over the sorted array and calculate the distance for each consecutive pair of points, ie. each point and the one that follows it. We get a minimum distance 'd'.

2) Sort all point by y. Again, for each point we calculate the distance to its direct following neighbor(s) in the sorted array. Unlike '1)', we do not only consider the direct neighbors, but all neighbors that are less than 'd' ahead of the current point.
When we find a pair with distance smaller 'd', we use this new distance as our new 'd' from this moment on.

This should give us the smallest d.

Basically, splitting an array recursively until only pairs remain (which is what I guess they imply) is in effect the same as simply walking over the array and comparing each consecutive point pair.
There is one difference in my step 1) though: they only calculate the x-distance of every 2nd point to its successor (there is a subarray border after every 2nd point). This may help (because they are doing only half the work) or be detrimental (because they may no get the best d from this first pass).

I haven't verified this, please let me know if I understood this wrong or if there are problems with my 'translated' approach.


问:
Events not flowing to Application Insights when using secrets.json in localhost
I used this Application Insights getting started guide for setting up my application. I'm running VS2017 version 15.5.7 and my application is using AspNetCore 2.0.0.

When I F5 debug my application using IIS Express from Visual Studio, I see Application Insights events within the debugger Events window. However, the same events are not flowing to Application Insights in Azure; I've configured the InstrumentationKey within secrets.json as you can see below. I've confirmed the key is loaded into my application configuration by setting a breakpoint.

As another debugging data point, I've confirmed events do successfully flow to Application Insights when running in a Azure Web App. This test uses the exact same code. Instead of loading the InstrumentationKey from secrets.json, however, I've configured APPINSIGHTS_INSTRUMENTATIONKEY environment variable to have the key (via ApplicationSettings pane of the Web App in the portal).

I'm at a loss for why my events are not flowing to Application Insights via localhost debugger, but they are when deployed to a Web App.

Program.cs

```<code>public static void Main( string[] args )
{
    BuildWebHost( args ).Run();
}

public static IWebHost BuildWebHost( string[] args ) =>
    WebHost.CreateDefaultBuilder( args )
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .Build();
</code>```

Startup.cs

```<code>var configurationBuilder = new ConfigurationBuilder()
    .SetBasePath( hostingEnvironment.ContentRootPath )
    .AddJsonFile( $"appsettings.{hostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true );

if ( hostingEnvironment.IsDevelopment() )
{
    configurationBuilder.AddUserSecrets<Startup>( optional: true );
}

this.Configuration = configurationBuilder
    .AddEnvironmentVariables()
    .Build();
</code>```

secrets.json

```<code>{
    "ApplicationInsights": {
        "InstrumentationKey": "omitted for StackOverflow"
    }
}
</code>```

my.csproj

```<code><PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.1.1" />
<PackageReference Include="Microsoft.ApplicationInsights.Web" Version="2.5.1" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.0.0" />
</code>```

launchSettings.json

```<code>{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
        "applicationUrl": "http://localhost:2322/",
        "sslPort": 44330
    }
  },
  "profiles": {
    "IIS Express": {
        "commandName": "IISExpress",
        "launchBrowser": true,
        "launchUrl": "https://localhost:44330/",
        "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        }
    },
    "FrontDoor": {
        "commandName": "Project",
        "launchBrowser": true,
        "launchUrl": "https://localhost:44330/api/config",
        "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        },
        "applicationUrl": "http://localhost:2323"
    }
  }
}
</code>```

答:
This is a known limitation, being fixed in the coming beta.
https://github.com/microsoft/ApplicationInsights-dotnet/issues/1882

Until then workaround is to use the AddApplicationInsights(IConfiguration) overlaod.

Body:
I used this Application Insights getting started guide for setting up my application. I'm running VS2017 version 15.5.7 and my application is using AspNetCore 2.0.0.

When I F5 debug my application using IIS Express from Visual Studio, I see Application Insights events within the debugger Events window. However, the same events are not flowing to Application Insights in Azure; I've configured the InstrumentationKey within secrets.json as you can see below. I've confirmed the key is loaded into my application configuration by setting a breakpoint.

As another debugging data point, I've confirmed events do successfully flow to Application Insights when running in a Azure Web App. This test uses the exact same code. Instead of loading the InstrumentationKey from secrets.json, however, I've configured APPINSIGHTS_INSTRUMENTATIONKEY environment variable to have the key (via ApplicationSettings pane of the Web App in the portal).

I'm at a loss for why my events are not flowing to Application Insights via localhost debugger, but they are when deployed to a Web App.

Program.cs

public static void Main( string[] args )
{
    BuildWebHost( args ).Run();
}

public static IWebHost BuildWebHost( string[] args ) =>
    WebHost.CreateDefaultBuilder( args )
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .Build();

Startup.cs

var configurationBuilder = new ConfigurationBuilder()
    .SetBasePath( hostingEnvironment.ContentRootPath )
    .AddJsonFile( $"appsettings.{hostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true );

if ( hostingEnvironment.IsDevelopment() )
{
    configurationBuilder.AddUserSecrets<Startup>( optional: true );
}

this.Configuration = configurationBuilder
    .AddEnvironmentVariables()
    .Build();

secrets.json

{
    "ApplicationInsights": {
        "InstrumentationKey": "omitted for StackOverflow"
    }
}

my.csproj

<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.1.1" />
<PackageReference Include="Microsoft.ApplicationInsights.Web" Version="2.5.1" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.0.0" />

launchSettings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
        "applicationUrl": "http://localhost:2322/",
        "sslPort": 44330
    }
  },
  "profiles": {
    "IIS Express": {
        "commandName": "IISExpress",
        "launchBrowser": true,
        "launchUrl": "https://localhost:44330/",
        "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        }
    },
    "FrontDoor": {
        "commandName": "Project",
        "launchBrowser": true,
        "launchUrl": "https://localhost:44330/api/config",
        "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        },
        "applicationUrl": "http://localhost:2323"
    }
  }
}


问:
How do I add URL to code below? I have mysql_fetch_array creating a row wrapped with td
Here's the row that outputs the data in td format:

```<code>echo "<td style='border: 1px solid black; text-align:left; padding: 3px 3px 3px 3px; width:100px; font-family: arial, helvetica, sans-serif; font-size: 15px; text-align: center'>" . $row['redtagnum'] . "</td>";
</code>```

var myurl = "update_ncr.php"
How do create link for redtagnum to become URL pointing to myurl variable?
Everything I find is not wrapped with the td.

答:
If I understand your question correctly you want to create a link to  $myurl wrapped in the  tags with the text $row["redtagnum"]

You need to put an  tag inside of the  tag

```<code>echo "<td style='...'>";
echo "<a href='".$myurl."'>";
echo $row["redtagnum"];
echo "</a>";
echo "</td>";
</code>```

Body:
Here's the row that outputs the data in td format:

echo "" . $row['redtagnum'] . "	";

var myurl = "update_ncr.php"
How do create link for redtagnum to become URL pointing to myurl variable?
Everything I find is not wrapped with the td.

Body:
If I understand your question correctly you want to create a link to  $myurl wrapped in the <td> tags with the text $row["redtagnum"]

You need to put an <a> tag inside of the <td> tag

echo "<td style='...'>";
echo "<a href='".$myurl."'>";
echo $row["redtagnum"];
echo "</a>";
echo "</td>";


问:
Tensorflow throwing distributed_function error
I am new to ML and tensorflow and trying to train and use a standard text generation model. When I go to train the model I get this error:

```<code>Train for 155 steps
Epoch 1/5
  2/155 [..............................] - ETA: 4:49 - loss: 2.5786
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-133-d70c02ff4270> in <module>()
----> 1 model.fit(dataset, epochs=epochs, callbacks=[checkpoint_callback])

11 frames
/usr/local/lib/python3.6/dist-packages/six.py in raise_from(value, from_value)

InvalidArgumentError: 2 root error(s) found.
  (0) Invalid argument:  indices[58,87] = 63 is not in [0, 63)
     [[node sequential_12/embedding_12/embedding_lookup (defined at <ipython-input-131-d70c02ff4270>:1) ]]
     [[VariableShape/_24]]
  (1) Invalid argument:  indices[58,87] = 63 is not in [0, 63)
     [[node sequential_12/embedding_12/embedding_lookup (defined at <ipython-input-131-d70c02ff4270>:1) ]]
0 successful operations.
0 derived errors ignored. [Op:__inference_distributed_function_95797]

Errors may have originated from an input operation.
Input Source operations connected to node sequential_12/embedding_12/embedding_lookup:
 sequential_12/embedding_12/embedding_lookup/92192 (defined at /usr/lib/python3.6/contextlib.py:81)

Input Source operations connected to node sequential_12/embedding_12/embedding_lookup:
 sequential_12/embedding_12/embedding_lookup/92192 (defined at /usr/lib/python3.6/contextlib.py:81)

Function call stack:
distributed_function -> distributed_function
</code>```

Data

```<code>data['title'] = [['Sentence'],['Sentence2'], ...]
</code>```

Data Prep

```<code>tokenizer = keras.preprocessing.text.Tokenizer(num_words=209, lower=False, char_level=True)
tokenizer.fit_on_texts(df['title'])
df['encoded_with_keras'] = tokenizer.texts_to_sequences(df['title'])

dataset = df['encoded_with_keras']
dataset = tf.keras.preprocessing.sequence.pad_sequences(dataset, padding='post')

dataset = dataset.flatten()

dataset = tf.data.Dataset.from_tensor_slices(dataset)

sequences = dataset.batch(seq_len+1, drop_remainder=True)

def create_seq_targets(seq):
    input_txt = seq[:-1]
    target_txt = seq[1:]
    return input_txt, target_txt

dataset = sequences.map(create_seq_targets)

batch_size = 128

buffer_size = 10000

dataset = dataset.shuffle(buffer_size).batch(batch_size, drop_remainder=True)
</code>```

Model:

```<code>vocab_size = len(tokenizer.word_index)
embed_dim = 128
rnn_neurons = 256

epochs = 5

# Directory where the checkpoints will be saved
checkpoint_dir = './training_checkpoints'
# Name of the checkpoint files
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}")

checkpoint_callback=tf.keras.callbacks.ModelCheckpoint(
    filepath=checkpoint_prefix,
    save_weights_only=True)

def create_model(vocab_size, embed_dim, rnn_neurons, batch_size):
    model = Sequential()
    model.add(Embedding(vocab_size, embed_dim, batch_input_shape=[batch_size, None], mask_zero=True))
    model.add(LSTM(rnn_neurons, return_sequences=True, stateful=True))
    model.add(Dropout(0.2))
    model.add(LSTM(rnn_neurons, return_sequences=True, stateful=True))
    model.add(Dropout(0.2))
    model.compile(optimizer='adam', loss="sparse_categorical_crossentropy")
    return model

model.fit(dataset, epochs=epochs, callbacks=[checkpoint_callback])
</code>```

I have tried changing almost all model settings, and playing around with custom tokenization and data prep. But this starts training and on the 2nd step of 155 I get this error. I'm not sure where to start any help is appreciated

答: Try changing the batch_size to something like 32, 16 or 8 . Apparently, for rtx 2060/70/80 there’s a tensorflow bug that makes it run out of memory.</p>

Body:
I am new to ML and tensorflow and trying to train and use a standard text generation model. When I go to train the model I get this error:

Train for 155 steps
Epoch 1/5
  2/155 [..............................] - ETA: 4:49 - loss: 2.5786
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-133-d70c02ff4270> in <module>()
----> 1 model.fit(dataset, epochs=epochs, callbacks=[checkpoint_callback])

11 frames
/usr/local/lib/python3.6/dist-packages/six.py in raise_from(value, from_value)

InvalidArgumentError: 2 root error(s) found.
  (0) Invalid argument:  indices[58,87] = 63 is not in [0, 63)
     [[node sequential_12/embedding_12/embedding_lookup (defined at <ipython-input-131-d70c02ff4270>:1) ]]
     [[VariableShape/_24]]
  (1) Invalid argument:  indices[58,87] = 63 is not in [0, 63)
     [[node sequential_12/embedding_12/embedding_lookup (defined at <ipython-input-131-d70c02ff4270>:1) ]]
0 successful operations.
0 derived errors ignored. [Op:__inference_distributed_function_95797]

Errors may have originated from an input operation.
Input Source operations connected to node sequential_12/embedding_12/embedding_lookup:
 sequential_12/embedding_12/embedding_lookup/92192 (defined at /usr/lib/python3.6/contextlib.py:81)

Input Source operations connected to node sequential_12/embedding_12/embedding_lookup:
 sequential_12/embedding_12/embedding_lookup/92192 (defined at /usr/lib/python3.6/contextlib.py:81)

Function call stack:
distributed_function -> distributed_function

Data

data['title'] = [['Sentence'],['Sentence2'], ...]

Data Prep

tokenizer = keras.preprocessing.text.Tokenizer(num_words=209, lower=False, char_level=True)
tokenizer.fit_on_texts(df['title'])
df['encoded_with_keras'] = tokenizer.texts_to_sequences(df['title'])

dataset = df['encoded_with_keras']
dataset = tf.keras.preprocessing.sequence.pad_sequences(dataset, padding='post')

dataset = dataset.flatten()

dataset = tf.data.Dataset.from_tensor_slices(dataset)

sequences = dataset.batch(seq_len+1, drop_remainder=True)

def create_seq_targets(seq):
    input_txt = seq[:-1]
    target_txt = seq[1:]
    return input_txt, target_txt

dataset = sequences.map(create_seq_targets)

batch_size = 128

buffer_size = 10000

dataset = dataset.shuffle(buffer_size).batch(batch_size, drop_remainder=True)

Model:

vocab_size = len(tokenizer.word_index)
embed_dim = 128
rnn_neurons = 256

epochs = 5

# Directory where the checkpoints will be saved
checkpoint_dir = './training_checkpoints'
# Name of the checkpoint files
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}")

checkpoint_callback=tf.keras.callbacks.ModelCheckpoint(
    filepath=checkpoint_prefix,
    save_weights_only=True)

def create_model(vocab_size, embed_dim, rnn_neurons, batch_size):
    model = Sequential()
    model.add(Embedding(vocab_size, embed_dim, batch_input_shape=[batch_size, None], mask_zero=True))
    model.add(LSTM(rnn_neurons, return_sequences=True, stateful=True))
    model.add(Dropout(0.2))
    model.add(LSTM(rnn_neurons, return_sequences=True, stateful=True))
    model.add(Dropout(0.2))
    model.compile(optimizer='adam', loss="sparse_categorical_crossentropy")
    return model

model.fit(dataset, epochs=epochs, callbacks=[checkpoint_callback])

I have tried changing almost all model settings, and playing around with custom tokenization and data prep. But this starts training and on the 2nd step of 155 I get this error. I'm not sure where to start any help is appreciated


问:
Using reduce to remap an array with child arrays
I'm struggling to work out how to remap the below array.

I have tried to use the reduce function built into JS but to no avail.

The furthest I have got it creating the function:

```<code>var comb = []
var setEle = []
var setEle = []
input.forEach(a => {
  a.productVariations.forEach(element => {
    if (comb.indexOf(element.variationName) === -1) {
      comb.push(element.variationName)

      let group = element.variationOptions.reduce((r, a) => {
        r['variationName'] = element.variationName
        r['variationOptions'] = [...(r[a.name] || []), a]

        return r
      }, {})

      group['linked'] = []
      setEle.push(group)
    }
  })

})
</code>```

How do I remap the array as below and get my reduce function working?

```<code>var input = [
  {
    companyName: 'ABC',
    productVariations: [
      {
        variationName: 'Colour',
        variationOptions: [
          {
            name: 'Blue'
          },
          {
            name: 'Red'
          }
        ]
      },
      {
        variationName: 'Pattern',
        variationOptions: [
          {
            name: 'Bold'
          },
          {
            name: 'Spotted'
          }
        ]
      }
    ]
  },
  {
    companyName: 'BBC',
    productVariations: [
      {
        variationName: 'Colour',
        variationOptions: [
          {
            name: 'Blue'
          },
          {
            name: 'Red'
          },
          {
            name: 'Purple '
          }
        ]
      }
    ]
  }
]
</code>```

I would like the output to look like this:

```<code>var output = [
  {
    variationName: 'Colour',
    variationOptions: [
      {
        name: 'Blue'
      },
      {
        name: 'Purple'
      },
      {
        name: 'Red'
      },
    ],
    linked: [
      {
        companyName: 'BBC'
      },
      {
        companyName: 'ABC'
      }
    ]
  },
  {
    variationName: 'Pattern',
    variationOptions: [
      {
        name: 'Bold'
      },
      {
        name: 'Spotted'
      },
    ],
    linked: [
      {
        companyName: 'ABC',
      }
    ]
  }
]
</code>```

The output array, groups the variationOptions by variationName and adds the relevant companyName to the linked child array.

答:
Like this:

const input = [
  {
    companyName: 'ABC',
    productVariations: [
      {
        variationName: 'Colour',
        variationOptions: [{ name: 'Blue' }, { name: 'Red' }],
      },
      {
        variationName: 'Pattern',
        variationOptions: [{ name: 'Bold' }, { name: 'Spotted' }],
      },
    ],
  },
  {
    companyName: 'BBC',
    productVariations: [
      {
        variationName: 'Colour',
        variationOptions: [{ name: 'Blue' }, { name: 'Red' }, { name: 'Purple' }],
      },
    ],
  },
];

const output = input.reduce((currentOutput, company) => {
  company.productVariations.forEach(variation => {
    const variationIndex = currentOutput.findIndex(
      outputVariation => variation.variationName === outputVariation.variationName,
    );
    if (variationIndex === -1) {
      // if this variation does not yet exist in the output create it
      currentOutput.push({
        variationName: variation.variationName,
        variationOptions: variation.variationOptions,
        linked: [{ companyName: company.companyName }],
      });
    } else {
      // if it already exists go through all options and add the ones that are not there yet
      variation.variationOptions.forEach(variationOption => {
        if (
          !currentOutput[variationIndex].variationOptions.some(
            outputVariationOption => variationOption.name === outputVariationOption.name,
          )
        ) {
          currentOutput[variationIndex].variationOptions.push(variationOption);
        }
      });
      // link the company
      currentOutput[variationIndex].linked.push({ companyName: company.companyName });
    }
  });
  return currentOutput;
}, []);

document.getElementById('output').innerHTML = JSON.stringify(output, null, 2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id="output" /></code>```

Body:
I'm struggling to work out how to remap the below array.

I have tried to use the reduce function built into JS but to no avail.

The furthest I have got it creating the function:

var comb = []
var setEle = []
var setEle = []
input.forEach(a => {
  a.productVariations.forEach(element => {
    if (comb.indexOf(element.variationName) === -1) {
      comb.push(element.variationName)

      let group = element.variationOptions.reduce((r, a) => {
        r['variationName'] = element.variationName
        r['variationOptions'] = [...(r[a.name] || []), a]

        return r
      }, {})

      group['linked'] = []
      setEle.push(group)
    }
  })

})

How do I remap the array as below and get my reduce function working?

var input = [
  {
    companyName: 'ABC',
    productVariations: [
      {
        variationName: 'Colour',
        variationOptions: [
          {
            name: 'Blue'
          },
          {
            name: 'Red'
          }
        ]
      },
      {
        variationName: 'Pattern',
        variationOptions: [
          {
            name: 'Bold'
          },
          {
            name: 'Spotted'
          }
        ]
      }
    ]
  },
  {
    companyName: 'BBC',
    productVariations: [
      {
        variationName: 'Colour',
        variationOptions: [
          {
            name: 'Blue'
          },
          {
            name: 'Red'
          },
          {
            name: 'Purple '
          }
        ]
      }
    ]
  }
]

I would like the output to look like this:

var output = [
  {
    variationName: 'Colour',
    variationOptions: [
      {
        name: 'Blue'
      },
      {
        name: 'Purple'
      },
      {
        name: 'Red'
      },
    ],
    linked: [
      {
        companyName: 'BBC'
      },
      {
        companyName: 'ABC'
      }
    ]
  },
  {
    variationName: 'Pattern',
    variationOptions: [
      {
        name: 'Bold'
      },
      {
        name: 'Spotted'
      },
    ],
    linked: [
      {
        companyName: 'ABC',
      }
    ]
  }
]

The output array, groups the variationOptions by variationName and adds the relevant companyName to the linked child array.

Body:
Like this:

const input = [
  {
    companyName: 'ABC',
    productVariations: [
      {
        variationName: 'Colour',
        variationOptions: [{ name: 'Blue' }, { name: 'Red' }],
      },
      {
        variationName: 'Pattern',
        variationOptions: [{ name: 'Bold' }, { name: 'Spotted' }],
      },
    ],
  },
  {
    companyName: 'BBC',
    productVariations: [
      {
        variationName: 'Colour',
        variationOptions: [{ name: 'Blue' }, { name: 'Red' }, { name: 'Purple' }],
      },
    ],
  },
];

const output = input.reduce((currentOutput, company) => {
  company.productVariations.forEach(variation => {
    const variationIndex = currentOutput.findIndex(
      outputVariation => variation.variationName === outputVariation.variationName,
    );
    if (variationIndex === -1) {
      // if this variation does not yet exist in the output create it
      currentOutput.push({
        variationName: variation.variationName,
        variationOptions: variation.variationOptions,
        linked: [{ companyName: company.companyName }],
      });
    } else {
      // if it already exists go through all options and add the ones that are not there yet
      variation.variationOptions.forEach(variationOption => {
        if (
          !currentOutput[variationIndex].variationOptions.some(
            outputVariationOption => variationOption.name === outputVariationOption.name,
          )
        ) {
          currentOutput[variationIndex].variationOptions.push(variationOption);
        }
      });
      // link the company
      currentOutput[variationIndex].linked.push({ companyName: company.companyName });
    }
  });
  return currentOutput;
}, []);

document.getElementById('output').innerHTML = JSON.stringify(output, null, 2);

<pre id="output" />