问:
I have two git commits that appear the same after a pushed amend
I have a git branch that I am working on locally.  After editing some code and doing a commit and a push to a remote repo, I noticed that I had an error in my commit message.  I used amend to correct this.  First I tried to push, but this was not allowed,  So I did a pull and then a push.  Everything appeared to work.  When I look at the repo, I can see two commits, one for each message (both correct and incorrect, so I guess my correction was useless lol.)  Then I noticed that both commits contained the same code changes.  This seems strange, because I don't think that both should contain code changes.  Does this mean that the changes are applied twice?  Is this a problem that could cause issues later?  Does this need to be fixed?  If so, how do I fix this?

=====

commands

(IDE) Changes made, added and committed

git push -u origin BRANCH_NAME

(IDE) Amend performed

git push (error: failed to push some refs)

git pull

git push

答:
As matt said, you can't actually change a commit.  What git commit --amend does is make a new commit that doesn't extend the current branch.

I think more people get this when they can see, visually, what this means.  But this means you first need to learn to draw commit graphs.  Since you are using an IDE, perhaps you have already learned this—but you don't mention which IDE (and I don't normally use any IDE anyway myself).  Also, it's very hard to type graphics into a StackOverflow posting. :-) So consider this text version of a drawing of a commit graph:

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

What we have here is a series of commits, all in a nice neat line, with the commit whose hash is H—H here stands in for some big ugly Git hash ID—being last in the chain.  Some IDEs draw this vertically, with commit H at the top:

```<code>H  <commit subject line>
|
G  <commit subject line>
|
:
</code>```

but for StackOverflow purposes I like the horizontal drawings.

Note how each commit "points back" to its immediate parent commit.  Internally, this means that each commit stores the full hash ID of its parent, because Git actually finds commits by their hash IDs.

To find commit H specifically (and quickly), Git needs to have its hash ID stored somewhere too.  Git can use H to find G's hash ID, and then can use G to find F's hash ID, and so on, but Git needs to start with H's hash ID.  The place Git finds H's hash ID is your branch name:

```<code>...--F--G--H   <-- branch (HEAD)
</code>```

The branch name lets Git find H easily, because the branch name itself contains the raw commit hash ID.  Then commit H lets Git find G easily, which lets Git find F easily, and so on.  That's our backwards-looking chain of commits.

Note how when you have multiple branches, they tend to rejoin somewhere in the past:

```<code>          I--J   <-- branch1
         /
...--G--H   <-- master
         \
          K--L   <-- branch2 (HEAD)
</code>```

Here, we made branch1 have two commits that aren't on master yet, and made branch2 have two commits that aren't on master yet either.  The commits up through H are on all three branches.  The name master specifically means commit H, but also—whenever necessary—means all commits up to and including H.  The name branch1 means commits up to and including J, or just J, depending on context; and the name branch2 means commits up through H plus K-L, or just L, depending on context.

I've drawn the name HEAD in here attached to branch2 to show that we have branch2, and hence commit L, checked out at the moment.  The general idea with Git is this:

Git will resolve HEAD to a commit, by finding the branch name and following the branch name's arrow to the commit.

That's the current commit and is the one you have checked out.

Each commit finds a previous (parent) commit, which defines the chain of commits that we call "the branch".

But the word branch is ambiguous, because sometimes it means the branch name, sometimes it means the commit at the tip of the branch as pointed to by the name, and sometimes it means the tip commit plus some or all previous commits.

When people use the word branch, sometimes they mean a series of commits up to and including a commit that's not identified by a branch name, too.  Besides regular branch names, Git has tag names, and remote-tracking names like origin/master and origin/branch1 and so on.  All of these names ultimately just point to one specific commit—just like a branch name—but only branch names have the feature of letting HEAD attach to them.

Consider now how adding a commit normally works

Suppose we have:

```<code>...--G--H   <-- branch (HEAD)
</code>```

We have the files from commit H checked out, because H is the current commit.  We make some changes to those files, git add the updated files to copy the changes over top of the copies of those files in Git's index or staging area, and run git commit.  Git now freezes the files that are in its index, add the right metadata—our name and email address, our log message, the parent hash ID H, and so on—and thereby creates a new commit, which gets a new unique big ugly hash ID but we'll just call it I:

```<code>...--G--H   <-- branch (HEAD)
         \
          I
</code>```

Since I is now the last commit, Git now does the one trick that makes branch names different from any other kind of name: Git stores I's hash ID into the name branch, because that's the name to which HEAD is attached.  We get:

```<code>...--G--H
         \
          I   <-- branch (HEAD)
</code>```

which we can straighten out now:

```<code>...--G--H--I   <-- branch (HEAD)
</code>```

So this is how git commit works:

It freezes, for all time, all the files that are in Git's index (aka the staging area).  The fact that Git makes commits from its ready-to-freeze copies in its staging area, rather than the ordinary files you have in your work-tree, is why you have to git add files all the time.  These frozen files become the new snapshot in the new commit.

It adds the appropriate metadata: your name, your email address, the current date-and-time, and so forth.

It sets the new commit's parent hash ID to the current commit's hash ID.

It writes out the actual commit (which gains a new, unique hash ID).

Last, it writes the new commit's hash ID into the current branch name so that the name continues to point to the last commit in the chain.

Having written out the new commit, the current commit changes—the hash ID that HEAD means is now commit I instead of commit H—but once again the current commit snapshot matches the files in Git's index, which—if you git add-ed everything—also match the files in your work-tree.

Now we can see how git commit --amend works

When you use git commit --amend, Git goes through all the same steps as for any commit, with one exception: the new commit's parent (or parents, plural, if the current commit is a merge commit) are taken from the current commit instead of being the current commit.  That is, rather than doing:

```<code>...--G--H--I--J   <-- branch (HEAD)
</code>```

with new commit J pointing back to existing commit I, Git does this:

```<code>          I   ???
         /
...--G--H--J   <-- branch (HEAD)
</code>```

In effect, the then-current commit I has now been "shoved out of the way" to place the new commit at the end of the chain without making the chain any longer.

The existing commit I still exists.  It just no longer has a name.

When you involve another Git repository, you exchange commits with them

Git is, at its heart, really all about commits.  You make new commits, and then you have your Git call up another Git and send it your commits.  Or, you call up that other Git repository—whether or not you yourself have made any new commits—and get any new commits that they have, that you don't.

One of these two commands is git fetch.  That's the one that calls up their Git and finds which commits they have that you don't: it fetches their commits into your own Git repository.

The other command is git push: with git push you have your Git call up their Git and send commits.  These two are not quite symmetric, though.  Let's look at git fetch first, because it's where remote-tracking names like origin/master and origin/branch come from.

We've already seen that Git finds commits by taking a name—maybe a branch name—to find the last commit, and then working backwards.  Meanwhile, your Git is calling up some other Git.  That other Git has branch names B1, B2, B3, ..., each of which specify the last commit's hash ID, for that Git's branches.

Those are their branches, not your branches.  You may or may not have branches with the same name, but those are their names, pointing to their last commits.  Your git fetch doesn't touch your branch names.

Suppose, for instance, that we start with:

```<code>H  <commit subject line>
|
G  <commit subject line>
|
:
</code>```0

but that we got commit H from origin.  Then we really have:

```<code>H  <commit subject line>
|
G  <commit subject line>
|
:
</code>```1

That is, in their Git repository, their name master also selects commit H.  So our Git has recorded their Git's name master as our origin/master; then we made our master from their origin/master, and now both names point to existing commit H.

If we now make our own new commit I, our master now points to commit I.  Our origin/master still points to H as before:

```<code>H  <commit subject line>
|
G  <commit subject line>
|
:
</code>```2

Meanwhile, suppose that they—whoever they are—make their own new commit.  It will get some big ugly unique hash ID; we'll just call it J.  Their commit J is in their repository:

```<code>H  <commit subject line>
|
G  <commit subject line>
|
:
</code>```3

We run git fetch, and our Git calls up their Git and finds that they have a new commit that we have never seen before.  Our Git gets it from their Git and puts it into our repository.  To remember J's hash ID, our Git updates our own origin/master:

```<code>H  <commit subject line>
|
G  <commit subject line>
|
:
</code>```4

(I put ours up top just for aesthetics—I like the letters to be more in alphabetical order here).

Now we have a problem, of sorts.  Our commit I and their commit J form two branches, depending on just what we mean by the word branch:

```<code>H  <commit subject line>
|
G  <commit subject line>
|
:
</code>```5

We'll need to combine these somehow, at some point.  We can do that with git merge, or we can use git rebase to copy our existing commit I to a new and improved commit—let's call it I'—that extends their J:

```<code>H  <commit subject line>
|
G  <commit subject line>
|
:
</code>```6

We abandon our I in favor of our new-and-improved I', which adds on to their existing commits.  We can now git push origin master.  Or, we use git merge to combine work into a new commit, with a snapshot made by a slightly complicated process involving comparing commit H's snapshot to each of the two snapshots in I and J:

```<code>H  <commit subject line>
|
G  <commit subject line>
|
:
</code>```7

Once again we can now git push origin master.

Why push is not symmetric with fetch

Let's say we have just this:

```<code>H  <commit subject line>
|
G  <commit subject line>
|
:
</code>```8

In other words, we have not yet rebased or merged.  Our name master points to commit I; our name origin/master, representing the master over on origin, points to commit J.  We can try to run:

```<code>H  <commit subject line>
|
G  <commit subject line>
|
:
</code>```9

which will call up their Git, send them our commit I—they don't have it yet because we have not given it to them before—and then ask them to set their master to point to commit I.

Remember that their master currently points to (shared, copied into both Gits) commit J.  If they do what we ask, they will end up with:

```<code>...--F--G--H   <-- branch (HEAD)
</code>```0

That is, they will lose commit J entirely.  Git finds commits by starting from a branch name like master and working backwards.  Their master used to find J; and if they take our request, to set their master to point to I instead, they won't be able to find J any more.

This is why they just refuse our polite request, saying not a fast forward.  We fix this problem by using git rebase or git merge, to make I' or some merge commit.  Then we either send them I' and ask them to set their master to point to I', which is OK because I' comes after J and therefore keeps commit J in the picture; or, we send them M (and I again, if they dropped it), and ask them to set their master to point to M, which is OK because both I and J come before M, so that they can still find J.

Sometimes we really want them to throw out a commit

When we use git commit --amend, we take a chain like this:

```<code>...--F--G--H   <-- branch (HEAD)
</code>```1

and turn it into this:

```<code>...--F--G--H   <-- branch (HEAD)
</code>```2

which makes commit I appear to go away.  It actually sticks around for a while—at least a month or so—in case we want it back, through a mechanism that Git calls reflogs.  But it's gone from the everyday view, as there's no name that points directly to it, and no other name that points to some commit that eventually points back to I either.

But what if we sent commit I to some other Git?  What if, in particular, we ran:

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

so that we now have:

```<code>       I   <-- origin/branch
      /
...--H--J   <-- branch (HEAD)
</code>```

where our origin/branch represents origin's branch, which now points to our old commit I?

If we just run:

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

this tells their Git: Here: have a new commit J.  Now please, if it's OK, set your branch to remember commit J.  They will say no, for the same reason they said no to our other example: this will lose commit I, in their Git repository.

But that's exactly what we want.  We want them to lose commit I off their branch branch.  To make that happen, we send the same sort of operation—another git push—but we change our last polite request, into a more forceful command.

We have two options:

We can say: Set your name branch to point to commit J!  This just tells them drop all commits that might be dropped this way, even if that's now I and K too.

Or, we can say: I think your branch identifies commit <hash-of-I>.  If so, change it to identify commit J instead.  In any case, let me know what happened.

The first is a simple git push --force.  The second is git push --force-with-lease.  Our Git will fill in the "I think" commit I hash part from our origin/branch, and of course get commit J's hash ID in the same way as always.

The danger of any git push --force, with or without the -with-lease part, is that we're telling some other Git throw out some commits.  That's what we want, of course, so it's not that dangerous, as long as we know that we're asking for commits to be thrown out.  But if we're git push-ing to a GitHub repository, are there other people who use that GitHub repository to git fetch from?  Maybe they have picked up our commit I and are using it.  They could put commit I back.  Or, maybe we are making extra work for them, such that they'll have to rework their commits to use commit J instead of commit I.

We should arrange in advance with other users of this origin Git, so that they know which branches might have commits removed like this.

Your own case

In your case, you did a git push that failed, then a git pull.  The git pull command means run git fetch, then run a second Git command.  That second command is git merge by default.

So, let's say you started with:

```<code>...--G--H   <-- master, origin/master, branch (HEAD)
</code>```

then added commit I:

```<code>...--G--H   <-- master, origin/master
         \
          I   <-- branch (HEAD)
</code>```

You then ran (successfully) git push -u origin branch which resulted in:

```<code>          I   <-- branch (HEAD), origin/branch
         /
...--G--H   <-- master, origin/master
</code>```

(again I just put I on top this time for aesthetics).

Next, you used git commit --amend, which made a new commit J that doesn't have I as its parent:

```<code>          I   <-- origin/branch
         /
...--G--H   <-- master, origin/master
         \
          J   <-- branch (HEAD)
</code>```

You tried a regular git push, which failed with not a fast forward: their Git told your Git that this push would lose commits (I in particular).

Then you ran git pull:

This ran git fetch, which did nothing because you already have commits H and I and there are no changes to make to any of your origin/* names.

Then it ran git merge to merge I and J into a new merge commit.

I'll stop drawing the names master and origin/master as they get in the way, but this did just what we'd now expect:

```<code>          I--J   <-- branch1
         /
...--G--H   <-- master
         \
          K--L   <-- branch2 (HEAD)
</code>```0

and then you ran git push, which sent them commits J and M to add on to their branch.  They said OK to that, so your Git updated your origin/branch:

```<code>          I--J   <-- branch1
         /
...--G--H   <-- master
         \
          K--L   <-- branch2 (HEAD)
</code>```1

and this is what you now see in your repository.

You can, if you like, force your name branch to point to commit J directly again, then use git push --force-with-lease to ask the other Git to discard both commits M and I.

To force your current (HEAD) branch to point to one specific commit, use git reset.  In this case, you might first make sure you have nothing else that git reset --hard will destroy, and use git reset --hard HEAD~1 to move to the first parent of M.  See side note on first parent below.

(To move a branch that you're not on, use git branch -f, which needs two arguments: the branch name, and the commit to move-to.  Since git reset operations on the branch that you are on, git reset just takes the commit specifier.)

Side note: --first-parent

There's a tricky bit that is not shown well in my horizontal graph drawings.  Whenever you make a new merge commit like M, Git makes sure that the first of the multiple parents coming out of M points back to the commit that was the tip of your branch before.  In this case, that means the first parent of M is J, not I.

You can have git log, and other Git commands, only look at the first parent of each merge when viewing commits.  If you do this, the picture looks like this:

```<code>          I--J   <-- branch1
         /
...--G--H   <-- master
         \
          K--L   <-- branch2 (HEAD)
</code>```2

In fact, M still points back to I too, as its second parent.

This --first-parent option is mainly useful to look at a branch like master when features are always developed on their own branches:

```<code>          I--J   <-- branch1
         /
...--G--H   <-- master
         \
          K--L   <-- branch2 (HEAD)
</code>```3

Looking at master with --first-parent drops all those incoming side connections, so that one sees only the solid bullet commits.  But the notion itself matters whenever you are dealing with a merge commit: M^1 means the first parent of M and M^2 means the second parent of M.  The tilde suffix notation counts backwards through first-parent links only, so that M~1 means step back one first-parent link.

Body:
As matt said, you can't actually change a commit.  What git commit --amend does is make a new commit that doesn't extend the current branch.

I think more people get this when they can see, visually, what this means.  But this means you first need to learn to draw commit graphs.  Since you are using an IDE, perhaps you have already learned this—but you don't mention which IDE (and I don't normally use any IDE anyway myself).  Also, it's very hard to type graphics into a StackOverflow posting. :-) So consider this text version of a drawing of a commit graph:

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

What we have here is a series of commits, all in a nice neat line, with the commit whose hash is H—H here stands in for some big ugly Git hash ID—being last in the chain.  Some IDEs draw this vertically, with commit H at the top:

H  <commit subject line>
|
G  <commit subject line>
|
:

but for StackOverflow purposes I like the horizontal drawings.

Note how each commit "points back" to its immediate parent commit.  Internally, this means that each commit stores the full hash ID of its parent, because Git actually finds commits by their hash IDs.

To find commit H specifically (and quickly), Git needs to have its hash ID stored somewhere too.  Git can use H to find G's hash ID, and then can use G to find F's hash ID, and so on, but Git needs to start with H's hash ID.  The place Git finds H's hash ID is your branch name:

...--F--G--H   <-- branch (HEAD)

The branch name lets Git find H easily, because the branch name itself contains the raw commit hash ID.  Then commit H lets Git find G easily, which lets Git find F easily, and so on.  That's our backwards-looking chain of commits.

Note how when you have multiple branches, they tend to rejoin somewhere in the past:

          I--J   <-- branch1
         /
...--G--H   <-- master
         \
          K--L   <-- branch2 (HEAD)

Here, we made branch1 have two commits that aren't on master yet, and made branch2 have two commits that aren't on master yet either.  The commits up through H are on all three branches.  The name master specifically means commit H, but also—whenever necessary—means all commits up to and including H.  The name branch1 means commits up to and including J, or just J, depending on context; and the name branch2 means commits up through H plus K-L, or just L, depending on context.

I've drawn the name HEAD in here attached to branch2 to show that we have branch2, and hence commit L, checked out at the moment.  The general idea with Git is this:

Git will resolve HEAD to a commit, by finding the branch name and following the branch name's arrow to the commit.

That's the current commit and is the one you have checked out.

Each commit finds a previous (parent) commit, which defines the chain of commits that we call "the branch".

But the word branch is ambiguous, because sometimes it means the branch name, sometimes it means the commit at the tip of the branch as pointed to by the name, and sometimes it means the tip commit plus some or all previous commits.

When people use the word branch, sometimes they mean a series of commits up to and including a commit that's not identified by a branch name, too.  Besides regular branch names, Git has tag names, and remote-tracking names like origin/master and origin/branch1 and so on.  All of these names ultimately just point to one specific commit—just like a branch name—but only branch names have the feature of letting HEAD attach to them.

Consider now how adding a commit normally works

Suppose we have:

...--G--H   <-- branch (HEAD)

We have the files from commit H checked out, because H is the current commit.  We make some changes to those files, git add the updated files to copy the changes over top of the copies of those files in Git's index or staging area, and run git commit.  Git now freezes the files that are in its index, add the right metadata—our name and email address, our log message, the parent hash ID H, and so on—and thereby creates a new commit, which gets a new unique big ugly hash ID but we'll just call it I:

...--G--H   <-- branch (HEAD)
         \
          I

Since I is now the last commit, Git now does the one trick that makes branch names different from any other kind of name: Git stores I's hash ID into the name branch, because that's the name to which HEAD is attached.  We get:

...--G--H
         \
          I   <-- branch (HEAD)

which we can straighten out now:

...--G--H--I   <-- branch (HEAD)

So this is how git commit works:

It freezes, for all time, all the files that are in Git's index (aka the staging area).  The fact that Git makes commits from its ready-to-freeze copies in its staging area, rather than the ordinary files you have in your work-tree, is why you have to git add files all the time.  These frozen files become the new snapshot in the new commit.

It adds the appropriate metadata: your name, your email address, the current date-and-time, and so forth.

It sets the new commit's parent hash ID to the current commit's hash ID.

It writes out the actual commit (which gains a new, unique hash ID).

Last, it writes the new commit's hash ID into the current branch name so that the name continues to point to the last commit in the chain.

Having written out the new commit, the current commit changes—the hash ID that HEAD means is now commit I instead of commit H—but once again the current commit snapshot matches the files in Git's index, which—if you git add-ed everything—also match the files in your work-tree.

Now we can see how git commit --amend works

When you use git commit --amend, Git goes through all the same steps as for any commit, with one exception: the new commit's parent (or parents, plural, if the current commit is a merge commit) are taken from the current commit instead of being the current commit.  That is, rather than doing:

...--G--H--I--J   <-- branch (HEAD)

with new commit J pointing back to existing commit I, Git does this:

          I   ???
         /
...--G--H--J   <-- branch (HEAD)

In effect, the then-current commit I has now been "shoved out of the way" to place the new commit at the end of the chain without making the chain any longer.

The existing commit I still exists.  It just no longer has a name.

When you involve another Git repository, you exchange commits with them

Git is, at its heart, really all about commits.  You make new commits, and then you have your Git call up another Git and send it your commits.  Or, you call up that other Git repository—whether or not you yourself have made any new commits—and get any new commits that they have, that you don't.

One of these two commands is git fetch.  That's the one that calls up their Git and finds which commits they have that you don't: it fetches their commits into your own Git repository.

The other command is git push: with git push you have your Git call up their Git and send commits.  These two are not quite symmetric, though.  Let's look at git fetch first, because it's where remote-tracking names like origin/master and origin/branch come from.

We've already seen that Git finds commits by taking a name—maybe a branch name—to find the last commit, and then working backwards.  Meanwhile, your Git is calling up some other Git.  That other Git has branch names B1, B2, B3, ..., each of which specify the last commit's hash ID, for that Git's branches.

Those are their branches, not your branches.  You may or may not have branches with the same name, but those are their names, pointing to their last commits.  Your git fetch doesn't touch your branch names.

Suppose, for instance, that we start with:

...--G--H   <-- master (HEAD)

but that we got commit H from origin.  Then we really have:

...--G--H   <-- master (HEAD), origin/master

That is, in their Git repository, their name master also selects commit H.  So our Git has recorded their Git's name master as our origin/master; then we made our master from their origin/master, and now both names point to existing commit H.

If we now make our own new commit I, our master now points to commit I.  Our origin/master still points to H as before:

...--G--H   <-- origin/master
         \
          I   <-- master (HEAD)

Meanwhile, suppose that they—whoever they are—make their own new commit.  It will get some big ugly unique hash ID; we'll just call it J.  Their commit J is in their repository:

...--G--H--J   <-- master [in their Git]

We run git fetch, and our Git calls up their Git and finds that they have a new commit that we have never seen before.  Our Git gets it from their Git and puts it into our repository.  To remember J's hash ID, our Git updates our own origin/master:

          I   <-- master (HEAD)
         /
...--G--H--J   <-- origin/master

(I put ours up top just for aesthetics—I like the letters to be more in alphabetical order here).

Now we have a problem, of sorts.  Our commit I and their commit J form two branches, depending on just what we mean by the word branch:

          I   <-- master (HEAD)
         /
...--G--H
         \
          J   <-- origin/master

We'll need to combine these somehow, at some point.  We can do that with git merge, or we can use git rebase to copy our existing commit I to a new and improved commit—let's call it I'—that extends their J:

          I   ??? [abandoned]
         /
...--G--H--J   <-- origin/master
            \
             I'  <-- master (HEAD)

We abandon our I in favor of our new-and-improved I', which adds on to their existing commits.  We can now git push origin master.  Or, we use git merge to combine work into a new commit, with a snapshot made by a slightly complicated process involving comparing commit H's snapshot to each of the two snapshots in I and J:

          I
         / \
...--G--H   M   <-- master (HEAD)
         \ /
          J   <-- origin/master

Once again we can now git push origin master.

Why push is not symmetric with fetch

Let's say we have just this:

          I   <-- master (HEAD)
         /
...--G--H
         \
          J   <-- origin/master

In other words, we have not yet rebased or merged.  Our name master points to commit I; our name origin/master, representing the master over on origin, points to commit J.  We can try to run:

git push origin master

which will call up their Git, send them our commit I—they don't have it yet because we have not given it to them before—and then ask them to set their master to point to commit I.

Remember that their master currently points to (shared, copied into both Gits) commit J.  If they do what we ask, they will end up with:

          I   <-- master
         /
...--G--H
         \
          J   ??? [abandoned]

That is, they will lose commit J entirely.  Git finds commits by starting from a branch name like master and working backwards.  Their master used to find J; and if they take our request, to set their master to point to I instead, they won't be able to find J any more.

This is why they just refuse our polite request, saying not a fast forward.  We fix this problem by using git rebase or git merge, to make I' or some merge commit.  Then we either send them I' and ask them to set their master to point to I', which is OK because I' comes after J and therefore keeps commit J in the picture; or, we send them M (and I again, if they dropped it), and ask them to set their master to point to M, which is OK because both I and J come before M, so that they can still find J.

Sometimes we really want them to throw out a commit

When we use git commit --amend, we take a chain like this:

...--H--I   <-- branch (HEAD)

and turn it into this:

       I   ??? [abandoned]
      /
...--H--J   <-- branch (HEAD)

which makes commit I appear to go away.  It actually sticks around for a while—at least a month or so—in case we want it back, through a mechanism that Git calls reflogs.  But it's gone from the everyday view, as there's no name that points directly to it, and no other name that points to some commit that eventually points back to I either.

But what if we sent commit I to some other Git?  What if, in particular, we ran:

git push origin branch

so that we now have:

       I   <-- origin/branch
      /
...--H--J   <-- branch (HEAD)

where our origin/branch represents origin's branch, which now points to our old commit I?

If we just run:

git push origin branch

this tells their Git: Here: have a new commit J.  Now please, if it's OK, set your branch to remember commit J.  They will say no, for the same reason they said no to our other example: this will lose commit I, in their Git repository.

But that's exactly what we want.  We want them to lose commit I off their branch branch.  To make that happen, we send the same sort of operation—another git push—but we change our last polite request, into a more forceful command.

We have two options:

We can say: Set your name branch to point to commit J!  This just tells them drop all commits that might be dropped this way, even if that's now I and K too.

Or, we can say: I think your branch identifies commit <hash-of-I>.  If so, change it to identify commit J instead.  In any case, let me know what happened.

The first is a simple git push --force.  The second is git push --force-with-lease.  Our Git will fill in the "I think" commit I hash part from our origin/branch, and of course get commit J's hash ID in the same way as always.

The danger of any git push --force, with or without the -with-lease part, is that we're telling some other Git throw out some commits.  That's what we want, of course, so it's not that dangerous, as long as we know that we're asking for commits to be thrown out.  But if we're git push-ing to a GitHub repository, are there other people who use that GitHub repository to git fetch from?  Maybe they have picked up our commit I and are using it.  They could put commit I back.  Or, maybe we are making extra work for them, such that they'll have to rework their commits to use commit J instead of commit I.

We should arrange in advance with other users of this origin Git, so that they know which branches might have commits removed like this.

Your own case

In your case, you did a git push that failed, then a git pull.  The git pull command means run git fetch, then run a second Git command.  That second command is git merge by default.

So, let's say you started with:

...--G--H   <-- master, origin/master, branch (HEAD)

then added commit I:

...--G--H   <-- master, origin/master
         \
          I   <-- branch (HEAD)

You then ran (successfully) git push -u origin branch which resulted in:

          I   <-- branch (HEAD), origin/branch
         /
...--G--H   <-- master, origin/master

(again I just put I on top this time for aesthetics).

Next, you used git commit --amend, which made a new commit J that doesn't have I as its parent:

          I   <-- origin/branch
         /
...--G--H   <-- master, origin/master
         \
          J   <-- branch (HEAD)

You tried a regular git push, which failed with not a fast forward: their Git told your Git that this push would lose commits (I in particular).

Then you ran git pull:

This ran git fetch, which did nothing because you already have commits H and I and there are no changes to make to any of your origin/* names.

Then it ran git merge to merge I and J into a new merge commit.

I'll stop drawing the names master and origin/master as they get in the way, but this did just what we'd now expect:

          I   <-- origin/branch
         / \
...--G--H   M   <-- branch (HEAD)
         \ /
          J

and then you ran git push, which sent them commits J and M to add on to their branch.  They said OK to that, so your Git updated your origin/branch:

          I
         / \
...--G--H   M   <-- branch (HEAD), origin/branch
         \ /
          J

and this is what you now see in your repository.

You can, if you like, force your name branch to point to commit J directly again, then use git push --force-with-lease to ask the other Git to discard both commits M and I.

To force your current (HEAD) branch to point to one specific commit, use git reset.  In this case, you might first make sure you have nothing else that git reset --hard will destroy, and use git reset --hard HEAD~1 to move to the first parent of M.  See side note on first parent below.

(To move a branch that you're not on, use git branch -f, which needs two arguments: the branch name, and the commit to move-to.  Since git reset operations on the branch that you are on, git reset just takes the commit specifier.)

Side note: --first-parent

There's a tricky bit that is not shown well in my horizontal graph drawings.  Whenever you make a new merge commit like M, Git makes sure that the first of the multiple parents coming out of M points back to the commit that was the tip of your branch before.  In this case, that means the first parent of M is J, not I.

You can have git log, and other Git commands, only look at the first parent of each merge when viewing commits.  If you do this, the picture looks like this:

...--G--H--J--M   <-- branch (HEAD), origin/branch

In fact, M still points back to I too, as its second parent.

This --first-parent option is mainly useful to look at a branch like master when features are always developed on their own branches:

                  o--o--o   <-- feature2
                 /       \
 ...--●---------●---------●--...   <-- master
       \       /
        o--o--o   <-- feature1

Looking at master with --first-parent drops all those incoming side connections, so that one sees only the solid bullet commits.  But the notion itself matters whenever you are dealing with a merge commit: M^1 means the first parent of M and M^2 means the second parent of M.  The tilde suffix notation counts backwards through first-parent links only, so that M~1 means step back one first-parent link.


来源: stackexchange

问:
Aggregate (Summarize) multiple Time Series Data by Month in .r
I have hundreds of daily weather data with a .txt extension, with comma (",") as separators in common folders. Each file has the same data structure with different file names. The following is an example of the data structure:

```<code>$ year         : int  1980 1980 1980 1980 1980 1980 1980 1980 1980 1980 ...
$ month        : int  1 1 1 1 1 1 1 1 1 1 ...
$ day          : int  1 2 3 4 5 6 7 8 9 10 ...
$ V1           : num  18.4 22.9 19.9 22.9 23.4 9.8 13.9 17.5 20.3 22.7 ...
$ V2           : num  30.8 31.5 31.4 31.3 31.5 29.8 30.1 30.6 30.5 31.1 ...
$ V3           : num  23.4 23.7 23.2 23.3 23.4 22.9 23 23.4 23.1 23.2 ...
$ V4           : num  2.2 0 0 0 0.9 3.6 3.5 3.7 1.2 0 ...
$ V5           : num  0.93 0.86 0.88 0.87 0.87 0.98 1 0.96 0.96 0.91 ...
$ V6           : num  1.6 3.5 5.2 5.5 3.9 4.2 4.2 4.9 4.9 4.4 ...
</code>```

I need to make a summary of the total monthly of one of the variables, (let say V4) from each file. And the desired output data structure of each file is like this (first column is year, the second column is month, the third column is total of the daily value of V4):

```<code>Year 1  Month 1 22.1
Year 1  Month 2 82.4
Year 1  Month 3 142.8
Year 1  Month …etc  314
Year 2  Month 1 48.9
Year 2  Month 2 173.6
Year 2  Month 3 76.2
Year 2  Month …etc  517.4
Year 3  Month 1 117.8
Year 3  Month 2 20.1
Year 3  Month 3 169.8
Year 3  Month …etc  191.5
</code>```

Then i need export the results to be a unique .txt file from all files, with the name of the new file according to the original file (example: before_file1.txt into result_file1.txt) for each file.
I have a script using Purrr, but nothing seems to be happening. Please if you were willing to help me improve the script with the right method. Thank you

```<code># Load packages
library(tidyverse)
library(dplyr)
library(purrr)

# Setting working directory
workingdirectory <- "D:/Directory"
setwd(workingdirectory)

# Listing the files in the folder with .txt extension
FilesList <- list.files(workingdirectory, pattern = "\\.txt$", full.names = TRUE)

# Looping per files
purrr::map(FilesList, ~{
 .x %>%
    # Read csv file
    read.csv(sep = ",", header = FALSE, stringsAsFactors = FALSE) %>%
    # select variables
    variables <- c("year", "month", "day", "V4") %>%
    # summarize monthly of V4
    group_by(month, year) %>%
    summarise(monthly = sum(V4)) %>%

})

# Write the data back
write.csv(paste0('Result_', basename(.x)), sep = ",", row.names = FALSE)
</code>```

I have edited the script, but there is an error. Please help to fix it. Thanks

```<code>Error: unexpected '}' in:
"
}"
>
> # Write the data back
> write.csv(paste0('TM_', basename(.x)), sep = ",", row.names = FALSE)
Error in basename(.x) : object '.x' not found
In addition: Warning message:
In write.csv(paste0("TM_", basename(.x)), sep = ",", row.names = FALSE) :
  attempt to set 'sep' ignored
</code>```

答:
I think you're already in the right direction. My suggested workaround to this would be to define the function prior to running the purrr::map function.

Therefore, the code should look something like this:

```<code># Load packages
library(tidyverse)
library(dplyr)
library(purrr)

# Setting working directory
workingdirectory <- "D:/Directory"
setwd(workingdirectory)

# Listing the files in the folder with .txt extension
FilesList <- list.files(workingdirectory, pattern = "\\.txt$", full.names = TRUE)
columnNames <- c("year", "month", "day", "pcp_day")
# define function
processing <- function(x){
  x %>% read.csv(sep = "", header = FALSE, stringsAsFactors = FALSE) %>% rename_at(c(1,2,3,7), ~columnNames) %>% filter(month != 2 | day != 29) %>% group_by(month, year) %>% summarise(monthly = sum(pcp_day))
}
# Looping per files and # Write the data back
purrr::map(FilesList, ~processing(.x) %>% write.csv(paste0('Result_', basename(.x)), row.names = FALSE))
</code>```

If run successfully, you can find the outputs in the working directory you work in.

ContentLicense: CC BY-SA 4.0

Body:
I have hundreds of daily weather data with a .txt extension, with comma (",") as separators in common folders. Each file has the same data structure with different file names. The following is an example of the data structure:

$ year         : int  1980 1980 1980 1980 1980 1980 1980 1980 1980 1980 ...
$ month        : int  1 1 1 1 1 1 1 1 1 1 ...
$ day          : int  1 2 3 4 5 6 7 8 9 10 ...
$ V1           : num  18.4 22.9 19.9 22.9 23.4 9.8 13.9 17.5 20.3 22.7 ...
$ V2           : num  30.8 31.5 31.4 31.3 31.5 29.8 30.1 30.6 30.5 31.1 ...
$ V3           : num  23.4 23.7 23.2 23.3 23.4 22.9 23 23.4 23.1 23.2 ...
$ V4           : num  2.2 0 0 0 0.9 3.6 3.5 3.7 1.2 0 ...
$ V5           : num  0.93 0.86 0.88 0.87 0.87 0.98 1 0.96 0.96 0.91 ...
$ V6           : num  1.6 3.5 5.2 5.5 3.9 4.2 4.2 4.9 4.9 4.4 ...

I need to make a summary of the total monthly of one of the variables, (let say V4) from each file. And the desired output data structure of each file is like this (first column is year, the second column is month, the third column is total of the daily value of V4):

Year 1  Month 1 22.1
Year 1  Month 2 82.4
Year 1  Month 3 142.8
Year 1  Month …etc  314
Year 2  Month 1 48.9
Year 2  Month 2 173.6
Year 2  Month 3 76.2
Year 2  Month …etc  517.4
Year 3  Month 1 117.8
Year 3  Month 2 20.1
Year 3  Month 3 169.8
Year 3  Month …etc  191.5

Then i need export the results to be a unique .txt file from all files, with the name of the new file according to the original file (example: before_file1.txt into result_file1.txt) for each file.
I have a script using Purrr, but nothing seems to be happening. Please if you were willing to help me improve the script with the right method. Thank you

# Load packages
library(tidyverse)
library(dplyr)
library(purrr)

# Setting working directory
workingdirectory <- "D:/Directory"
setwd(workingdirectory)

# Listing the files in the folder with .txt extension
FilesList <- list.files(workingdirectory, pattern = "\\.txt$", full.names = TRUE)

# Looping per files
purrr::map(FilesList, ~{
 .x %>%
    # Read csv file
    read.csv(sep = ",", header = FALSE, stringsAsFactors = FALSE) %>%
    # select variables
    variables <- c("year", "month", "day", "V4") %>%
    # summarize monthly of V4
    group_by(month, year) %>%
    summarise(monthly = sum(V4)) %>%

})

# Write the data back
write.csv(paste0('Result_', basename(.x)), sep = ",", row.names = FALSE)

I have edited the script, but there is an error. Please help to fix it. Thanks

Error: unexpected '}' in:
"
}"
>
> # Write the data back
> write.csv(paste0('TM_', basename(.x)), sep = ",", row.names = FALSE)
Error in basename(.x) : object '.x' not found
In addition: Warning message:
In write.csv(paste0("TM_", basename(.x)), sep = ",", row.names = FALSE) :
  attempt to set 'sep' ignored

Body:
I think you're already in the right direction. My suggested workaround to this would be to define the function prior to running the purrr::map function.

Therefore, the code should look something like this:

# Load packages
library(tidyverse)
library(dplyr)
library(purrr)

# Setting working directory
workingdirectory <- "D:/Directory"
setwd(workingdirectory)

# Listing the files in the folder with .txt extension
FilesList <- list.files(workingdirectory, pattern = "\\.txt$", full.names = TRUE)
columnNames <- c("year", "month", "day", "pcp_day")
# define function
processing <- function(x){
  x %>% read.csv(sep = "", header = FALSE, stringsAsFactors = FALSE) %>% rename_at(c(1,2,3,7), ~columnNames) %>% filter(month != 2 | day != 29) %>% group_by(month, year) %>% summarise(monthly = sum(pcp_day))
}
# Looping per files and # Write the data back
purrr::map(FilesList, ~processing(.x) %>% write.csv(paste0('Result_', basename(.x)), row.names = FALSE))

If run successfully, you can find the outputs in the working directory you work in.


问:
Stub private methods in class under test in junit 5, PowerMock not working with JUnit5
I want to stub a private method in the class under test. I am using junit 5. I have used before powermock to achieve this. Unfortunately junit 5 does not work with powermock.

I have simplified the example to better explain the problem. I have class that has has private helper method that is called inside public methods. Like below:

public class Service {
    private Repository repository;

    public Object findById(String id) {
        Object object = repository.findById(id);
        object = verify(object);
        return object;
    }

    private Object verify(Object object) {
        //removed for simplicity
        return object;
    }
}
```

<p>Now I want to unit test the method <code>findById</code> of <code>Service</code>.  I have used junit 5 with mockito to implement unit test for the Service class.</p>

<pre class="lang-java prettyprint-override"><code>public class ServiceUTest {
    @InjectMocks
    private Service service;
    @Mock
    private Repository repository;

    @BeforeEach
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testFindById() {
        when(repository.findById(Mockito.any())).thenReturn(new Object());
        //how to stub verify method
    }
}
</code>```

I would appreciate any help and guide to solve this problem.

Regards,

答:
You can spy service and use PowerMockito to define the behavior for verify() method.

```<code>public class ServiceUTest {

    @InjectMocks
    private Service service;

    @Mock
    private Repository repository;

    @BeforeEach
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testFindById() {
        // Arrange
        Service spyService = spy(service);
        when(repository.findById(Mockito.any())).thenReturn(new Object());
        PowerMockito.when(spyService, "verify", any()).thenReturn(expectedObjectReturn);

        // Act
        Object actual = spyService.findById("id");

        // Assert
    }
}
</code>```

Body:
I want to stub a private method in the class under test. I am using junit 5. I have used before powermock to achieve this. Unfortunately junit 5 does not work with powermock.

I have simplified the example to better explain the problem. I have class that has has private helper method that is called inside public methods. Like below:

public class Service {
    private Repository repository;

    public Object findById(String id) {
        Object object = repository.findById(id);
        object = verify(object);
        return object;
    }

    private Object verify(Object object) {
        //removed for simplicity
        return object;
    }
}

Now I want to unit test the method findById of Service.  I have used junit 5 with mockito to implement unit test for the Service class.

public class ServiceUTest {
    @InjectMocks
    private Service service;
    @Mock
    private Repository repository;

    @BeforeEach
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testFindById() {
        when(repository.findById(Mockito.any())).thenReturn(new Object());
        //how to stub verify method
    }
}

I would appreciate any help and guide to solve this problem.

Regards,

Body:
You can spy service and use PowerMockito to define the behavior for verify() method.

public class ServiceUTest {

    @InjectMocks
    private Service service;

    @Mock
    private Repository repository;

    @BeforeEach
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testFindById() {
        // Arrange
        Service spyService = spy(service);
        when(repository.findById(Mockito.any())).thenReturn(new Object());
        PowerMockito.when(spyService, "verify", any()).thenReturn(expectedObjectReturn);

        // Act
        Object actual = spyService.findById("id");

        // Assert
    }
}


问:
AWS CDK - role and policy creation
How can I translate this CloudFormation to CDK (JavaScript or Java)? I was trying to do it, but this is the first time that I work with CDK and I'm not sure how to do it.</p>
```<code>FargateTaskExecutionServiceRole:
Type: AWS::IAM::Role
Properties:
  AssumeRolePolicyDocument:
    Statement:
    - Effect: Allow
      Principal:
        Service:
          - ecs-tasks.amazonaws.com
      Action:
        - sts:AssumeRole
  Policies:
    - PolicyName: AmazonECSTaskExecutionRolePolicy
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
        - Effect: Allow
          Action:
            - 'ecr:GetAuthorizationToken'
            - 'ecr:BatchCheckLayerAvailability'
            - 'ecr:GetDownloadUrlForLayer'
            - 'ecr:BatchGetImage'
            - 'logs:CreateLogStream'
            - 'logs:PutLogEvents'
          Resource: '*'
</code>```

答:
You should refer to API reference document to get a clear picture. There are examples for such use cases.

However, since you have already asked here and my hands has been itchy to provide you with an answer, so here goes the TypeScript implementation of just the IAM part:

import {
   ManagedPolicy,
   Role,
   ServicePrincipal,
   PolicyStatement,
   Effect
} from '@aws-cdk/aws-iam';

....
....

const ecsFargateServiceRole = new Role(this, 'FargateTaskExecutionServiceRole', {
  assumedBy: new ServicePrincipal('ecs-tasks.amazonaws.com')
});

// Add a policy to a Role
ecsFargateServiceRole.addToPolicy(
  new PolicyStatement({
    effect: Effect.ALLOW,
    resources: ['*'],
    actions: [
      'ecr:GetAuthorizationToken',
      'ecr:BatchCheckLayerAvailability',
      'ecr:GetDownloadUrlForLayer',
      'ecr:BatchGetImage',
      'logs:CreateLogStream',
      'logs:PutLogEvents'
    ]
  })
);

// Add a managed policy to a role you can use
ecsFargateServiceRole.addManagedPolicy(
    ManagedPolicy.fromAwsManagedPolicyName('AmazonECSTaskExecutionRolePolicy')
);

....
....
```
<p>UPDATE:</p>
<p>When you are adding an AWS managed policy to a role, you can get the managed policy as a reference by its name or by its ARN. The important part is that if an AWS Managed policy is used as above by its name or ARN, then you will not need to use the policy statement explicitly. From my answer above, you can use the managed policy approach rather than using the policy statement.</p>
<p>An easy way to define the role now would be:</p>
<pre class="lang-js prettyprint-override"><code>const ecsFargateServiceRole = new Role(this, 'FargateTaskExecutionServiceRole', {
  assumedBy: new ServicePrincipal('ecs-tasks.amazonaws.com'),
  managedPolicies: [
    ManagedPolicy.fromAwsManagedPolicyName('AmazonECSTaskExecutionRolePolicy')
  ]
});
</code>```

Note that I have excluded the constructor for the Construct for brevity.

UPDATE: (from comments)

With version 2 of CDK you have to add service-role/ to managed policy. So it looks like this:

ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonECSTaskExecutionRolePolicy')
```

Title: AWS CDK - role and policy creation

Body:
How can I translate this CloudFormation to CDK (JavaScript or Java)? I was trying to do it, but this is the first time that I work with CDK and I'm not sure how to do it.

FargateTaskExecutionServiceRole:
Type: AWS::IAM::Role
Properties:
  AssumeRolePolicyDocument:
    Statement:
    - Effect: Allow
      Principal:
        Service:
          - ecs-tasks.amazonaws.com
      Action:
        - sts:AssumeRole
  Policies:
    - PolicyName: AmazonECSTaskExecutionRolePolicy
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
        - Effect: Allow
          Action:
            - 'ecr:GetAuthorizationToken'
            - 'ecr:BatchCheckLayerAvailability'
            - 'ecr:GetDownloadUrlForLayer'
            - 'ecr:BatchGetImage'
            - 'logs:CreateLogStream'
            - 'logs:PutLogEvents'
          Resource: '*'

Body:
You should refer to API reference document to get a clear picture. There are examples for such use cases.

However, since you have already asked here and my hands has been itchy to provide you with an answer, so here goes the TypeScript implementation of just the IAM part:

import {
   ManagedPolicy,
   Role,
   ServicePrincipal,
   PolicyStatement,
   Effect
} from '@aws-cdk/aws-iam';

....
....

const ecsFargateServiceRole = new Role(this, 'FargateTaskExecutionServiceRole', {
  assumedBy: new ServicePrincipal('ecs-tasks.amazonaws.com')
});

// Add a policy to a Role
ecsFargateServiceRole.addToPolicy(
  new PolicyStatement({
    effect: Effect.ALLOW,
    resources: ['*'],
    actions: [
      'ecr:GetAuthorizationToken',
      'ecr:BatchCheckLayerAvailability',
      'ecr:GetDownloadUrlForLayer',
      'ecr:BatchGetImage',
      'logs:CreateLogStream',
      'logs:PutLogEvents'
    ]
  })
);

// Add a managed policy to a role you can use
ecsFargateServiceRole.addManagedPolicy(
    ManagedPolicy.fromAwsManagedPolicyName('AmazonECSTaskExecutionRolePolicy')
);

....
....

UPDATE:

When you are adding an AWS managed policy to a role, you can get the managed policy as a reference by its name or by its ARN. The important part is that if an AWS Managed policy is used as above by its name or ARN, then you will not need to use the policy statement explicitly. From my answer above, you can use the managed policy approach rather than using the policy statement.

An easy way to define the role now would be:

const ecsFargateServiceRole = new Role(this, 'FargateTaskExecutionServiceRole', {
  assumedBy: new ServicePrincipal('ecs-tasks.amazonaws.com'),
  managedPolicies: [
    ManagedPolicy.fromAwsManagedPolicyName('AmazonECSTaskExecutionRolePolicy')
  ]
});

Note that I have excluded the constructor for the Construct for brevity.

UPDATE: (from comments)

With version 2 of CDK you have to add service-role/ to managed policy. So it looks like this:

ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonECSTaskExecutionRolePolicy')


问:
Replace lm with jsgf file in python
Using this pocketsphinx command  with python , how can i use jsgf instead of lm ? ( i have created my own model with arabic/french words and i don't know how to use it now with python ..)

```<code>speech = LiveSpeech(
verbose=False,
sampling_rate=16000,
buffer_size=2048,
no_search=False,
full_utt=False,
hmm=os.path.join(model_path, 'mymodel.ci_cont'),
lm=os.path.join(model_path, 'xxxx'),
dic=os.path.join(model_path, 'mymodel.dict')
)
</code>```

答:
Simply change

```<code>jsgf=os.path.join(model_path, 'file.jsgf'),
</code>```

instead of

```<code>lm=os.path.join(model_path, 'xxxx'),
</code>```

Title: Replace lm with jsgf file in python

Body:
Using this pocketsphinx command  with python , how can i use jsgf instead of lm ? ( i have created my own model with arabic/french words and i don't know how to use it now with python ..)

speech = LiveSpeech(
verbose=False,
sampling_rate=16000,
buffer_size=2048,
no_search=False,
full_utt=False,
hmm=os.path.join(model_path, 'mymodel.ci_cont'),
lm=os.path.join(model_path, 'xxxx'),
dic=os.path.join(model_path, 'mymodel.dict')
)

Body:
Simply change

jsgf=os.path.join(model_path, 'file.jsgf'),

instead of

lm=os.path.join(model_path, 'xxxx'),


问:
Unit Testing Monorail's RedirectToReferrer()
I am trying to write a unit test for an action method which calls the Controller.RedirectToReferrer() method, but am getting a "No referrer available" message.

How can I isolate and mock this method?

答: Have you thought about creating a test double?</p>

OwnerDisplayName: rauchy

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Chris Canal

ContentLicense: CC BY-SA 2.5


问:
How to hide the Dock icon
I want to make a preference for hiding the Dock icon and showing an NSStatusItem.
I can create the StatusItem but I don't know how to remove the icon from Dock. :-/

Any ideas?

答:
I think you are looking for the LSUIElement in the Info.plist

LSUIElement (String). If this key is set to “1”, Launch Services runs the application as an agent application. Agent applications do not appear in the Dock or in the Force Quit window. Although they typically run as background applications, they can come to the foreground to present a user interface if desired.

See a short discussion here about turning it on/off

OwnerDisplayName: xPablo

Title: How to hide the Dock icon

OwnerDisplayName: epatel


问:
Single Sign On (SSO) Standard Web Admin Application
Spring Security, JOSSO, CAS, etc, cares about authentication and authorization.
In most cases admin applications are very similar.

There are schemas for JDBC data sources, but there arent front-ends.

For example:
http://www.josso.org/confluence/display/JOSSO1/Database+Setup or http://static.springsource.org/spring-security/site/docs/3.0.x/reference/springsecurity-single.html#appendix-schema

Does anybody know a beautiful and tested third part web admin app to CRUD users and roles on Single Sign On?

答:
Would the Central Authentication Service project (CAS) fit the bill?  It is a Java server that enables single server authentication in large multi-server application environments.  It has a documented protocol that allows multiple servers to share the same authentication environment.

It includes a number of integration points.  Servers in the authentication environment can use spring security integration to obtain the current authentication credentials from a CAS server.  The CAS server itself can provide a login service.  The CAS server can also integrate into common user databases such as LDAP/ActiveDirectory.


问:
Why isn't button changing from x to y in react?
I am trying to make a button that toggles between x and y. However, the following code isn't working. Why isn't this working? Sorry if it is an easy solution, I am new to react.

Right now, all that is appearing is a button that says X, and when I try to click it, nothing changes.

```<code>  constructor(props) {
    super(props);
    this.myValue = 2
  }

  buttonIsClicked() {
    this.myValue+=1
    this.render()
  }

  render() {
    switch(this.myValue%2) {
      case 0:
        return(
        <button className = "myButton" onClick={() => this.buttonIsClicked()}>X</button>
        );
      case 1:
        return(
        <button className = "myButton" onClick={() => this.buttonIsClicked()}>Y</button>
        );
    }
  }
</code>```

答: Check this as to why this.render() doesn't actually trigger a re-render. A better way to see this in action would be to move the variable to the state and then call this.setState()

Body:
I am trying to make a button that toggles between x and y. However, the following code isn't working. Why isn't this working? Sorry if it is an easy solution, I am new to react.

Right now, all that is appearing is a button that says X, and when I try to click it, nothing changes.

  constructor(props) {
    super(props);
    this.myValue = 2
  }

  buttonIsClicked() {
    this.myValue+=1
    this.render()
  }

  render() {
    switch(this.myValue%2) {
      case 0:
        return(
        <button className = "myButton" onClick={() => this.buttonIsClicked()}>X</button>
        );
      case 1:
        return(
        <button className = "myButton" onClick={() => this.buttonIsClicked()}>Y</button>
        );
    }
  }


问:
How to import string from a .txt file C#
I am working on a password generator, that uses elements of an array to generate a word-based password.

I currently am working with four arrays, with a lot of elements, and I have to hardcode them individually. I want to automate that process, because writing in a .txt file is both easier and cleaner than writing it on the code itself, and as I plan on distributing this program to my friends, I want to be able to make libraries for the arrays.

Simply put, the .txt file will have four lines, each for one of the arrays.

All I need to know currently is how to import each the lines of the text as a single string, which will be individually formatted into the arrays.

So, for example, the .txt file would have this:

```<code>a,b,c,d,e,f,g
d,e,f,g,h,i,j
g,h,i,j,k,l,m
j,k,l,m,n,o,p
</code>```

And after the "fetching", four different strings would contain each of the lines:

```<code>string a = "a,b,c,d,e,f,g"
string b = "d,e,f,g,h,i,j"
string c = "g,h,i,j,k,l,m"
string d = "j,k,l,m,n,o,p"
</code>```

I will then process it by this, for each string, to break them down into elements.

```<code>String pattern = @"\-";
String[] elements = System.Text.RegularExpressions.Regex.Split(passKey, pattern);
</code>```

答:
You can use this:

```<code>System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("c:\\file.txt");
</code>```

To put them in an array specifically, use:

```<code>string[] lines = File.ReadLines("c:\\file.txt").ToArray();
</code>```

Body:
I am working on a password generator, that uses elements of an array to generate a word-based password.

I currently am working with four arrays, with a lot of elements, and I have to hardcode them individually. I want to automate that process, because writing in a .txt file is both easier and cleaner than writing it on the code itself, and as I plan on distributing this program to my friends, I want to be able to make libraries for the arrays.

Simply put, the .txt file will have four lines, each for one of the arrays.

All I need to know currently is how to import each the lines of the text as a single string, which will be individually formatted into the arrays.

So, for example, the .txt file would have this:

a,b,c,d,e,f,g
d,e,f,g,h,i,j
g,h,i,j,k,l,m
j,k,l,m,n,o,p

And after the "fetching", four different strings would contain each of the lines:

string a = "a,b,c,d,e,f,g"
string b = "d,e,f,g,h,i,j"
string c = "g,h,i,j,k,l,m"
string d = "j,k,l,m,n,o,p"

I will then process it by this, for each string, to break them down into elements.

String pattern = @"\-";
String[] elements = System.Text.RegularExpressions.Regex.Split(passKey, pattern);

Body:
You can use this:

System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("c:\\file.txt");

To put them in an array specifically, use:

string[] lines = File.ReadLines("c:\\file.txt").ToArray();


问:
Using regex replacement in Sublime 3
I am trying to use replace in Sublime using regular expressions but I'm stuck. I tried various combinations but don't seem to be getting there.

This is the input and my desired output:

Input: N_BBP_c_46137_n

Output : BBP

I tried combinations of:

```<code>[^BBP]+\b
\*BBP*+\g
</code>```

But none of the above (and many others) don't seem to work.

答:
To turn N_BBP_c_46137_n into BBP and according to the comment just want that entire long name such as N_BBP_ to be replaced by only BBP* you might also use a capture group to keep BBP.

```<code>\bN_(BBP)_\S*
</code>```

\bN_ Match N preceded by a word boundary

(BBP) Capture group 1, match BBP (or use [A-Z]+ to match 1+ uppercase chars)

_\S* Match _ followed by 0+ times a non whitespace char

In the replacement use the first capturing group $1

Regex demo

Title: Using regex replacement in Sublime 3

Body:
I am trying to use replace in Sublime using regular expressions but I'm stuck. I tried various combinations but don't seem to be getting there.

This is the input and my desired output:

Input: N_BBP_c_46137_n

Output : BBP

I tried combinations of:

[^BBP]+\b
\*BBP*+\g

But none of the above (and many others) don't seem to work.

Body:
To turn N_BBP_c_46137_n into BBP and according to the comment just want that entire long name such as N_BBP_ to be replaced by only BBP* you might also use a capture group to keep BBP.

\bN_(BBP)_\S*

\bN_ Match N preceded by a word boundary

(BBP) Capture group 1, match BBP (or use [A-Z]+ to match 1+ uppercase chars)

_\S* Match _ followed by 0+ times a non whitespace char

In the replacement use the first capturing group $1

Regex demo


问:
AWS provide proxy for Elasticsearch VPC domain
We created a VPC Elasticsearch domain.

We would like to be able to access the logs (kibana) from the Internet. I found this question: AWS Elasticsearch VPC connectivity

The answer suggests an nginx proxy facing the Internet and sitting on the VPC subnet. I got that working. But the response from the ES backend is that the user does not have the rights.

{"Message":"User: anonymous is not authorized to perform:
  es:ESHttpGet"}

Looks like I have to create the right policy. But I am stuck there.

I have created a role. But how to assign the role to the user, or even to the proxy so it is able to access the ES VPC endpoint?

答:
I finally got something well working for us following @jordanm 's cue using aws-es-proxy.

I initially just installed aws-es-proxy  on my local machine. I obviously had not understood how it works. Needless to say, it was timing out - essentially it was like I was accessing the VPC Endpoint from the Internet.

I then realized I had to install the proxy on a machine with access to the cluster (VPC / Subnet).

And finally I realized that I now needed an ssh tunnel to that machine in order to access it from localhost:9200.

Of course this is not what I myself was asking in the question - which I asked because I was freakin and did not understand all this AWS/VPC/ES stuff. I thought that if I'd create a public Internet proxy it would be easier.

Now I learnt quite a big deal and actually...access everything via a local tunnel is much safer.


问:
Which file is an anonymous memory mapping mapped to in linux?
My question is, when we create an anonymous memory mapping, what is the file that is being mapped into the address space of the process. I know that an anonymous mapping is guaranteed to be filled with zeros. Is it then the /dev/zero file? From what I understand, Inter Process Communication is not possible until there is some file that is being mapped inside the participating processes' address spaces ... be it a file in tmpfs or in the normal file system. I am new to Inter Process Communication, if you find any flaw in my understanding, please rectify.

答:
My question is, when we create an anonymous memory mapping, what is the file that is being mapped into the address space of the process.

There is no file.

I know that an anonymous mapping is guaranteed to be filled with zeros. Is it then the /dev/zero file?

No.

Historically, though, the MAP_ANONYMOUS flag is a newer invention than mmap itself.  Prior to that, if you wanted a chunk of memory filled with zeros and not backed by any regular file, you would indeed open /dev/zero and mmap it.  This was handled as a special case by the OS and would effectively give you an anonymous mapping; different processes creating mappings of /dev/zero wouldn't see each others' data, even if they used MAP_SHARED.  I believe the MAP_ANONYMOUS flag was introduced to simplify this process and avoid the extra system calls for opening and closing /dev/zero.

From what I understand, Inter Process Communication is not possible until there is some file that is being mapped inside the participating processes' address spaces ... be it a file in tmpfs or in the normal file system.

Well, that's not true; MAP_ANONYMOUS | MAP_SHARED is a counterexample to that. If your process creates a mapping with MAP_ANONYMOUS | MAP_SHARED, then any children created with fork() after that point (and their children, and so on) will inherit the mapping, and the memory will be shared between all of them and the parent.  Any writes to that memory by any of those processes will be seen by all of them.

This does mean you can only use this for IPC between "related" processes, descendants of the common ancestor who created the mapping (unless there are clever tricks I'm not aware of to give access to unrelated processes).  Mapping an actual file (other than /dev/zero) doesn't have this restriction.

And of course there are other IPC mechanisms that don't involve files at all, e.g. POSIX shared memory (shmget and friends).


问:
How to decrement like $dec?
In the Meteor leaderboard example there is this line:

```<code>  Players.update(Session.get("selected_player"), {$inc: {score: 5}});
</code>```

How can I gracefully decrement the same field? Sadly, there is no $dec.

答:
There is no need of something like $dec.
A negative value effectively decrements the specified field. For example using (-value):

```<code>Players.update(Session.get("selected_player"), {$inc: {score: -value}});
</code>```

Title: How to decrement like $dec?

Body:
In the Meteor leaderboard example there is this line:

  Players.update(Session.get("selected_player"), {$inc: {score: 5}});

How can I gracefully decrement the same field? Sadly, there is no $dec.

Body:
There is no need of something like $dec.
A negative value effectively decrements the specified field. For example using (-value):

Players.update(Session.get("selected_player"), {$inc: {score: -value}});


问:
Fortran if displays all and not selected
Good evening! I'm trying to create a virtual timeline in fortran with Force 2.0
I want to do an if with accept the "a" value, that is the year, and with the if you display the facts that happened that year
I wrote this code:

```<code>  program Calc
  real :: a
  print *, "Inserisci la data"
  print *, "Type the first number: "
  read *, a
  if a = 1900
  print *, "London arrives to 4 milion inhabitants"
  if a = 1901
  print *, "First trans-oceanic radio transmission"
  read *
  end program Calc
</code>```

but every input I insert it displays all the outputs, not the selected ones.
For example, if I input "1900" it displays both the 1900 and the 1901 facts", but it is not what I wanted. You know what can I do? Thxxx

答:
As I said in the comments to your question, the select case construct might be neater in your case:

```<code>program test
    implicit none
    integer:: year

    write(*,*) "Type the first number: "
    read(*,*) year

    select case(year)
        case(:1899)
            write(*,*) "I guess something happened before 1900"
        case(1900)
            write(*,*) "I am sure at least one cat was born in 1900"
        case(1901:1905)
            write(*,*) "I am sure something happened between 1901 and 1905"
        case(1906:)
            write(*,*) "Everything past 1906"
        case default
            write(*,*) "default case"
    end select

    read(*,*)
end program test
</code>```

Here is an explanation with flowchart. Note that I have changed the type of the year to an integer.

Body:
Good evening! I'm trying to create a virtual timeline in fortran with Force 2.0
I want to do an if with accept the "a" value, that is the year, and with the if you display the facts that happened that year
I wrote this code:

  program Calc
  real :: a
  print *, "Inserisci la data"
  print *, "Type the first number: "
  read *, a
  if a = 1900
  print *, "London arrives to 4 milion inhabitants"
  if a = 1901
  print *, "First trans-oceanic radio transmission"
  read *
  end program Calc

but every input I insert it displays all the outputs, not the selected ones.
For example, if I input "1900" it displays both the 1900 and the 1901 facts", but it is not what I wanted. You know what can I do? Thxxx

Body:
As I said in the comments to your question, the select case construct might be neater in your case:

program test
    implicit none
    integer:: year

    write(*,*) "Type the first number: "
    read(*,*) year

    select case(year)
        case(:1899)
            write(*,*) "I guess something happened before 1900"
        case(1900)
            write(*,*) "I am sure at least one cat was born in 1900"
        case(1901:1905)
            write(*,*) "I am sure something happened between 1901 and 1905"
        case(1906:)
            write(*,*) "Everything past 1906"
        case default
            write(*,*) "default case"
    end select

    read(*,*)
end program test

Here is an explanation with flowchart. Note that I have changed the type of the year to an integer.


问:
Joining 2 tables for value comparision
I have 2 tables which contain data as follows:

```<code>Table1-
Col1.  Col2
A1.     B1
A1.     B2

Table2-
Col1.  Col2
A1.     C1
A1.     C2
</code>```

Now when I am joining these 2 tables to compare col2, sometimes I get the output like A1-B1-C1;A1-B2-C2 and some time I get it as A1-B1-C2;A1-B2-C1.
But I don't want it to come in the second form ever.can anyone suggest any query which will help me achieve this.
Thanks in advance

答:
The most obvious join is on col1 column which returns 4 rows:

```<code>SQL> with
  2  t1 (col1, col2) as
  3    (select 'A1', 'B1' from dual union all
  4     select 'A1', 'B2' from dual
  5    ),
  6  t2 (col1, col2) as
  7    (select 'A1', 'C1' from dual union all
  8     select 'A1', 'C2' from dual
  9    )
 10  select a.col1, a.col2 a_col2, b.col2 b_col2
 11  from t1 a join t2 b on a.col1 = b.col1
 12  order by a.col1, a.col2, b.col2;

COL1    A_COL2  B_COL2
------- ------- -------
A1      B1      C1
A1      B1      C2
A1      B2      C1
A1      B2      C2

SQL>
</code>```

These are all combinations you named, so - how do you "sometimes" get only two of them, and "sometimes" another two? What's wrong with another two results (as you said you don't want them to show at all)?

Title: Joining 2 tables for value comparision

Body:
I have 2 tables which contain data as follows:

Table1-
Col1.  Col2
A1.     B1
A1.     B2

Table2-
Col1.  Col2
A1.     C1
A1.     C2

Now when I am joining these 2 tables to compare col2, sometimes I get the output like A1-B1-C1;A1-B2-C2 and some time I get it as A1-B1-C2;A1-B2-C1.
But I don't want it to come in the second form ever.can anyone suggest any query which will help me achieve this.
Thanks in advance

Body:
The most obvious join is on col1 column which returns 4 rows:

SQL> with
  2  t1 (col1, col2) as
  3    (select 'A1', 'B1' from dual union all
  4     select 'A1', 'B2' from dual
  5    ),
  6  t2 (col1, col2) as
  7    (select 'A1', 'C1' from dual union all
  8     select 'A1', 'C2' from dual
  9    )
 10  select a.col1, a.col2 a_col2, b.col2 b_col2
 11  from t1 a join t2 b on a.col1 = b.col1
 12  order by a.col1, a.col2, b.col2;

COL1    A_COL2  B_COL2
------- ------- -------
A1      B1      C1
A1      B1      C2
A1      B2      C1
A1      B2      C2

SQL>

These are all combinations you named, so - how do you "sometimes" get only two of them, and "sometimes" another two? What's wrong with another two results (as you said you don't want them to show at all)?


问:
Adding a sequence
I have a dataframe that (simplified) looks something like this:

```<code>Index     Studio Event
1
2          MovieStart
3
4
5
6
7           MovieEnd
8
9
10          MovieStart
11
12
13
14
15          MovieEnd
</code>```

I would like to create a third column that creates a sequence from 0 and increment of 50 that begins when the StudioEvent = MovieStart and ends when StudioEvent = MovieEnd. So something like this:

```<code>Index     Studio Event    Sequence
1
2          MovieStart      0
3                          50
4                          100
5                          150
6                          200
7           MovieEnd       250
8
9
10          MovieStart     0
11                         50
12                         100
13                         150
14                         200
15          MovieEnd       250
</code>```

Any idea how I can do it? Thank you in advance.

答:
You could try this, it worked for me.

```<code>n<-data.frame(index= seq(1:15),
   studio=c(NA,"MS",NA,NA,NA,NA,"ME",NA,NA,"MS",NA,NA,NA,NA,"ME"))

n$studio2<-0   #New column
n$studio2[n$studio=="MS"]<-1 ; n$studio2[n$studio=="ME"]<-2

n$seq<-0      #New column sequence
j<-1          #counter

k1<- which(n$studio=="MS")  #where movie starts
k2<- which(n$studio=="ME")  #where movie ends
</code>```

Loop

```<code>  for(i in 1:length(n$studio2))
{
    if(n$studio2[i]==1)
   {
      k<- k2[j]-k1[j]
      w<-seq(0,k*50,by=50)
      n$seq[k1[j]:k2[j]]<-w
      j<-j+1
    }
}
</code>```

Title: Adding a sequence

Body:
I have a dataframe that (simplified) looks something like this:

Index     Studio Event
1
2          MovieStart
3
4
5
6
7           MovieEnd
8
9
10          MovieStart
11
12
13
14
15          MovieEnd

I would like to create a third column that creates a sequence from 0 and increment of 50 that begins when the StudioEvent = MovieStart and ends when StudioEvent = MovieEnd. So something like this:

Index     Studio Event    Sequence
1
2          MovieStart      0
3                          50
4                          100
5                          150
6                          200
7           MovieEnd       250
8
9
10          MovieStart     0
11                         50
12                         100
13                         150
14                         200
15          MovieEnd       250

Any idea how I can do it? Thank you in advance.

Body:
You could try this, it worked for me.

n<-data.frame(index= seq(1:15),
   studio=c(NA,"MS",NA,NA,NA,NA,"ME",NA,NA,"MS",NA,NA,NA,NA,"ME"))

n$studio2<-0   #New column
n$studio2[n$studio=="MS"]<-1 ; n$studio2[n$studio=="ME"]<-2

n$seq<-0      #New column sequence
j<-1          #counter

k1<- which(n$studio=="MS")  #where movie starts
k2<- which(n$studio=="ME")  #where movie ends

Loop

  for(i in 1:length(n$studio2))
{
    if(n$studio2[i]==1)
   {
      k<- k2[j]-k1[j]
      w<-seq(0,k*50,by=50)
      n$seq[k1[j]:k2[j]]<-w
      j<-j+1
    }
}


问:
How to get a numeric sum for a "character number" within a string in Excel
I have 4 character cells that contain a "number" in positions 1 and 4, and a character in positions 2 and 3.  I want to get a numeric sum of the numbers for positions 1 and 4 for the range of cells.

My cells look like this:

I have tried SUM(MID(VALUE(B4:B21,1,1)) which gives me an invalid type error

Also tried SUM(MID(B4:B21,1,1)*1) which works with a single cell but not for a range.

答:
SUMPRODUCT of LEFT and RIGHT

```<code>=SUMPRODUCT(VALUE(LEFT(B4:B21,1)))+SUMPRODUCT(VALUE(RIGHT(B4:B21,1)))
</code>```

With error handling included, but possibly (Excel 2019) confirming with CTRL+SHIFT+ENTER:

```<code>=SUMPRODUCT(IFERROR(VALUE(LEFT(B4:B21,1)),0))+SUMPRODUCT(IFERROR(VALUE(RIGHT(B4:B21,1)),))
</code>```

Body:
SUMPRODUCT of LEFT and RIGHT

=SUMPRODUCT(VALUE(LEFT(B4:B21,1)))+SUMPRODUCT(VALUE(RIGHT(B4:B21,1)))

With error handling included, but possibly (Excel 2019) confirming with CTRL+SHIFT+ENTER:

=SUMPRODUCT(IFERROR(VALUE(LEFT(B4:B21,1)),0))+SUMPRODUCT(IFERROR(VALUE(RIGHT(B4:B21,1)),))


问:
No such element: Unable to locate element with ID in Python/Selenium
I am getting the following error when using Selenium in Python to enter text into a search field on the USPS careers website:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="WD40"]"}

The URL is: https://wp1-ext.usps.gov/sap/bc/webdynpro/sap/hrrcf_a_unreg_job_search#

```<code>driver = webdriver.Chrome("C:/Users/NAME/Downloads/chromedriver_win32/chromedriver.exe")
driver.get("https://wp1-ext.usps.gov/sap/bc/webdynpro/sap/hrrcf_a_unreg_job_search#")
elem = driver.find_element_by_name("WD40")
elem.send_keys("denver")
</code>```

When I dive into the selectors, the following is in the input field.

```<code><input id="WD40" ct="I" lsdata="{29:'WD3E'}" lsevents="{Change:[{ResponseData:'delta',EnqueueCardinality:'single'},{}]}" type="text" tabindex="0" ti="0" class="lsField__input" autocomplete="off" autocorrect="off" name="WD40" style="width:350px;" title="">
</code>```

So I should be able to enter the ID of 'WD40' into the ID field, but I am still getting that error.

Please send help.

答:
The desired element is a dynamic element so to locate/click() on the element using Selenium you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>driver.get("https://wp1-ext.usps.gov/sap/bc/webdynpro/sap/hrrcf_a_unreg_job_search#")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.lsField__input"))).send_keys("denver")
</code>```

Using XPATH:

```<code>driver.get("https://wp1-ext.usps.gov/sap/bc/webdynpro/sap/hrrcf_a_unreg_job_search#")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='lsField__input']"))).send_keys("denver")
</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>```

Browser Snapshot:

Body:
I am getting the following error when using Selenium in Python to enter text into a search field on the USPS careers website:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="WD40"]"}

The URL is: https://wp1-ext.usps.gov/sap/bc/webdynpro/sap/hrrcf_a_unreg_job_search#

driver = webdriver.Chrome("C:/Users/NAME/Downloads/chromedriver_win32/chromedriver.exe")
driver.get("https://wp1-ext.usps.gov/sap/bc/webdynpro/sap/hrrcf_a_unreg_job_search#")
elem = driver.find_element_by_name("WD40")
elem.send_keys("denver")

When I dive into the selectors, the following is in the input field.

<input id="WD40" ct="I" lsdata="{29:'WD3E'}" lsevents="{Change:[{ResponseData:'delta',EnqueueCardinality:'single'},{}]}" type="text" tabindex="0" ti="0" class="lsField__input" autocomplete="off" autocorrect="off" name="WD40" style="width:350px;" title="">

So I should be able to enter the ID of 'WD40' into the ID field, but I am still getting that error.

Please send help.

Body:
The desired element is a dynamic element so to locate/click() on the element using Selenium you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

driver.get("https://wp1-ext.usps.gov/sap/bc/webdynpro/sap/hrrcf_a_unreg_job_search#")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.lsField__input"))).send_keys("denver")

Using XPATH:

driver.get("https://wp1-ext.usps.gov/sap/bc/webdynpro/sap/hrrcf_a_unreg_job_search#")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='lsField__input']"))).send_keys("denver")

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

Browser Snapshot:


答:
In React, you cannot use object properties as a component state.

```<code>  constructor(props) {
    super(props);
    this.state = { counter: 0 };
  }

  buttonIsClicked() {
    this.setState({ counter: this.state.counter + 1 });
  }

  render() {
    switch(this.state.counter%2) {
      case 0:
        return(
        <button className = "myButton" onClick={() => this.buttonIsClicked()}>X</button>
        );
      case 1:
        return(
        <button className = "myButton" onClick={() => this.buttonIsClicked()}>Y</button>
        );
    }
  }
</code>```

Also, you cannot call lifecycle methods directly (render for example).

If I were you, I'd start by reading React's documentation to avoid similar mistakes.

Title: Why isn't button changing from x to y in react?

Body:
In React, you cannot use object properties as a component state.

  constructor(props) {
    super(props);
    this.state = { counter: 0 };
  }

  buttonIsClicked() {
    this.setState({ counter: this.state.counter + 1 });
  }

  render() {
    switch(this.state.counter%2) {
      case 0:
        return(
        <button className = "myButton" onClick={() => this.buttonIsClicked()}>X</button>
        );
      case 1:
        return(
        <button className = "myButton" onClick={() => this.buttonIsClicked()}>Y</button>
        );
    }
  }

Also, you cannot call lifecycle methods directly (render for example).

If I were you, I'd start by reading React's documentation to avoid similar mistakes.


问:
JSON Decode of Arrays and Dictionaries in Swift Model
For some reason, I can't seem to decode the following JSON from an API, probably because my model is not right for the JSON:

```<code>{"definitions":[{"type":"noun","definition":"the larva of a
butterfly.","example":null,"image_url":null,"emoji":null},
{"type":"adjective","definition":"brand of heavy equipment.","example":null,"image_url":null,"emoji":null}],
"word":"caterpillar","pronunciation":"ˈkadə(r)ˌpilər"}
</code>```

Here is my model:

```<code>struct DefinitionReturned : Codable {
        let Definition : [Definition]
        let word : String
        let pronunciation : String

    }
    struct Definition : Codable {
        let type: String
        let definition: String
        let example: String?
        let image_url: String?
        let emoji : String?
    }
</code>```

The code to decode is:

```<code>let json = try? JSONSerialization.jsonObject(with: data, options: [])

                do {

                    let somedefinitions = try JSONDecoder().decode(DefinitionReturned.self, from: data)
                    print("here are the definitions",somedefinitions)
}
</code>```

The error is:

```<code>ERROR IN DECODING DATA
The data couldn’t be read because it is missing.
keyNotFound(CodingKeys(stringValue: "Definition", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"Definition\", intValue: nil) (\"Definition\").", underlyingError: nil))
</code>```

Of note, there can be one or more definitions.

What am I doing wrong?

答:
```<code>// MARK: - DefinitionReturned
struct DefinitionReturned: Codable {
    let definitions: [Definition]
    let word, pronunciation: String
}

// MARK: - Definition
struct Definition: Codable {
    let type, definition: String
    let example, imageURL, emoji: String?

    enum CodingKeys: String, CodingKey {
        case type, definition, example
        case imageURL = "image_url"
        case emoji
    }
}
</code>```

Then decode

```<code>let definitionReturned = try? JSONDecoder().decode(DefinitionReturned.self, from: jsonData)
</code>```

Body:
For some reason, I can't seem to decode the following JSON from an API, probably because my model is not right for the JSON:

{"definitions":[{"type":"noun","definition":"the larva of a
butterfly.","example":null,"image_url":null,"emoji":null},
{"type":"adjective","definition":"brand of heavy equipment.","example":null,"image_url":null,"emoji":null}],
"word":"caterpillar","pronunciation":"ˈkadə(r)ˌpilər"}

Here is my model:

struct DefinitionReturned : Codable {
        let Definition : [Definition]
        let word : String
        let pronunciation : String

    }
    struct Definition : Codable {
        let type: String
        let definition: String
        let example: String?
        let image_url: String?
        let emoji : String?
    }

The code to decode is:

let json = try? JSONSerialization.jsonObject(with: data, options: [])

                do {

                    let somedefinitions = try JSONDecoder().decode(DefinitionReturned.self, from: data)
                    print("here are the definitions",somedefinitions)
}

The error is:

ERROR IN DECODING DATA
The data couldn’t be read because it is missing.
keyNotFound(CodingKeys(stringValue: "Definition", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"Definition\", intValue: nil) (\"Definition\").", underlyingError: nil))

Of note, there can be one or more definitions.

What am I doing wrong?

Body:
// MARK: - DefinitionReturned
struct DefinitionReturned: Codable {
    let definitions: [Definition]
    let word, pronunciation: String
}

// MARK: - Definition
struct Definition: Codable {
    let type, definition: String
    let example, imageURL, emoji: String?

    enum CodingKeys: String, CodingKey {
        case type, definition, example
        case imageURL = "image_url"
        case emoji
    }
}

Then decode

let definitionReturned = try? JSONDecoder().decode(DefinitionReturned.self, from: jsonData)


问:
When/why to prefix variables with "$" when using jQuery?

Possible Duplicate:

  Why would a javascript variable start with a dollar sign?

I see people using the dollar sign in front of variables when using jQuery. Is there any reason behind this? I'm I missing something basic or is it just a common practice?

答:
For me a common practice is this:

If a variable is private I use an underscore like this:

```<code>(function(){
     var _foo = "bar";
})()</code>```

If it's public I'll use no underscore:

```<code>var foo = "bar"</code>```

And if it's a jQuery selector I'll use the $:

```<code>var $foo = $('bar');
//then you can access it like this
$foo.attr('id')</code>```

It's just coding convention and it allows you to quickly reference what type the variable is later in the code.

Body:
For me a common practice is this:

If a variable is private I use an underscore like this:

(function(){
     var _foo = "bar";
})()

If it's public I'll use no underscore:

var foo = "bar"

And if it's a jQuery selector I'll use the $:

var $foo = $('bar');
//then you can access it like this
$foo.attr('id')

It's just coding convention and it allows you to quickly reference what type the variable is later in the code.


问:
Graph shortest path .. use only labelled edges?
With the new SQL Server version there is the function SHORTEST_PATH.
I use attributes (or Labels) in the edge tables to distinguish the different types of connections.

Unfortunately the SHORTEST_PATH function doesn't seem to allow any attributes in the where condition (if the tables are marked for path)

```<code>SELECT
       l1.CommonName AS CommonName,
       STRING_AGG(l2.CommonName, '->') WITHIN GROUP (GRAPH PATH) AS Verbindung,
       LAST_VALUE(l2.CommonName) WITHIN GROUP (GRAPH PATH) AS LastNode
 from           object as l1,
                connections for path as v,
                object for path as  l2
    where match(SHORTEST_PATH( l1  (-(v)-> l2)+))
    and l1.CommonName = 'jagdtWurst'
    and v.label= 'hierarchie' <<--- This is not possible .... Error
</code>```

Is there a no trick to how to do that anyway?

答:
Looks like you can use a subquery in the from clause.  eg

```<code>SELECT
       l1.CommonName AS CommonName,
       STRING_AGG(l2.CommonName, '->') WITHIN GROUP (GRAPH PATH) AS Verbindung,
       LAST_VALUE(l2.CommonName) WITHIN GROUP (GRAPH PATH) AS LastNode
 from           object as l1,
                (select * from connections where label = 'hierarchie') for path as v,
                object for path as  l2
    where match(SHORTEST_PATH( l1  (-(v)-> l2)+))
    and l1.CommonName = 'jagdtWurst'
</code>```

Body:
With the new SQL Server version there is the function SHORTEST_PATH.
I use attributes (or Labels) in the edge tables to distinguish the different types of connections.

Unfortunately the SHORTEST_PATH function doesn't seem to allow any attributes in the where condition (if the tables are marked for path)

SELECT
       l1.CommonName AS CommonName,
       STRING_AGG(l2.CommonName, '->') WITHIN GROUP (GRAPH PATH) AS Verbindung,
       LAST_VALUE(l2.CommonName) WITHIN GROUP (GRAPH PATH) AS LastNode
 from           object as l1,
                connections for path as v,
                object for path as  l2
    where match(SHORTEST_PATH( l1  (-(v)-> l2)+))
    and l1.CommonName = 'jagdtWurst'
    and v.label= 'hierarchie' <<--- This is not possible .... Error

Is there a no trick to how to do that anyway?

Body:
Looks like you can use a subquery in the from clause.  eg

SELECT
       l1.CommonName AS CommonName,
       STRING_AGG(l2.CommonName, '->') WITHIN GROUP (GRAPH PATH) AS Verbindung,
       LAST_VALUE(l2.CommonName) WITHIN GROUP (GRAPH PATH) AS LastNode
 from           object as l1,
                (select * from connections where label = 'hierarchie') for path as v,
                object for path as  l2
    where match(SHORTEST_PATH( l1  (-(v)-> l2)+))
    and l1.CommonName = 'jagdtWurst'