问:
`git clean` removes ignored files by default?
According to the help, without -x option git clean should let alone the ignored files, but it doesn't.

```<code>[il@reallin test]$ cat .gitignore
*.sar
[il@reallin test]$ mkdir -p conf/sar && touch conf/sar/aaa.sar
[il@reallin test]$ git status
# On branch master
nothing to commit, working directory clean
[il@reallin test]$ git clean -df
Removing conf/
</code>```

conf/sar/aaa.sar is removed. Is it a bug?

答:
Warning: this git clean behavior will slightly change with Git 2.14 (Q3 2017)

"git clean -d" used to clean directories that has ignored files, even though the command should not lose ignored ones without "-x".

"git status --ignored"  did not list ignored and untracked files without "-uall".

See commit 6b1db43 (23 May 2017), and commit bbf504a, commit fb89888, commit df5bcdf, commit 0a81d4a, commit b3487cc (18 May 2017) by Samuel Lijin (sxlijin).

(Merged by Junio C Hamano -- gitster -- in commit f4fd99b, 02 Jun 2017)

clean: teach clean -d to preserve ignored paths

There is an implicit assumption that a directory containing only untracked and ignored paths should itself be considered untracked. This makes sense in use cases where we're asking if a directory should be added to the git database, but not when we're asking if a directory can be safely removed from the working tree; as a result, clean -d would assume that an "untracked" directory containing ignored paths could be deleted, even though doing so would also remove the ignored paths.

To get around this, we teach clean -d to collect ignored paths and skip an untracked directory if it contained an ignored path, instead just removing the untracked contents thereof.

  To achieve this, cmd_clean() has to collect all untracked contents of untracked directories, in addition to all ignored paths, to determine which untracked dirs must be skipped (because they contain ignored paths) and which ones should not be skipped.

But... Since 2017, that change means git status --ignored hangs indefinitely!

As reported by Martin Melka in this thread, and analyzed by SZEDER Gábor:

with a depth of 120 directories it would take over 6*10^23 years to complete

This slowdown was caused by commit df5bcdf, which was part of a
  patch series to fix 'git clean -d' deleting untracked directories even
  if they contained ignored files.

So... a fix is in progress, to be released later in 2020.

Git 2.24 (Q4 2019) illustrates this git clean behavior change introduces a regression.

See commit 502c386 (25 Aug 2019) by SZEDER Gábor (szeder).

(Merged by Junio C Hamano -- gitster -- in commit 026428c, 30 Sep 2019)

t7300-clean: demonstrate deleting nested repo with an ignored file breakage

'git clean -fd' must not delete an untracked directory if it belongs
  to a different Git repository or worktree.

Unfortunately, if a '.gitignore' rule in the outer repository happens to match a file in a nested repository or worktree, then something goes awry and 'git clean -fd' does delete the content of the nested repository's worktree
  except that ignored file, potentially leading to data loss.

Add a test to 't7300-clean.sh' to demonstrate this breakage.

This issue is a regression introduced in 6b1db43 (clean: teach
  clean -d to preserve ignored paths, 2017-05-23, Git v2.13.2).

Git 2.24 further clarifies git clean -d:

See commit 69f272b (01 Oct 2019), and commit 902b90c, commit ca8b539, commit 09487f2, commit e86bbcf, commit 3aca580, commit 29b577b, commit 89a1f4a, commit a3d89d8, commit 404ebce, commit a5e916c, commit bbbb6b0, commit 7541cc5 (17 Sep 2019) by Elijah Newren (newren).

(Merged by Junio C Hamano -- gitster -- in commit aafb754, 11 Oct 2019)

t7300: add testcases showing failure to clean specified pathspecs

Someone brought me a testcase where multiple git-clean invocations were
  required to clean out unwanted files:

```<code>mkdir d{1,2}
touch d{1,2}/ut
touch d1/t && git add d1/t
</code>```

With this setup, the user would need to run

```<code>git clean -ffd */ut
</code>```

twice to delete both ut files.

A little testing showed some interesting variants:

If only one of those two ut files existed (either one), then only one clean command would be necessary.

If both directories had tracked files, then only one git clean would be necessary to clean both files.

If both directories had no tracked files then the clean command above would never clean either of the untracked files despite the pathspec explicitly calling both of them out.

A bisect showed that the failure to clean out the files started with commit cf424f5 ("clean: respect pathspecs with "-d", 2014-03-10, Git v1.9.1).

  However, that pointed to a separate issue: while the "-d" flag was used by the original user who showed me this problem, that flag should have been irrelevant to this problem.

  Testing again without the "-d" flag showed that the same buggy behavior exists without using that flag, and has in fact existed since before cf424f5.

So:

clean: respect pathspecs with "-d"

git-clean uses read_directory to fill in a struct dir with potential hits. However, read_directory does not actually check against our pathspec. It uses a simplified version that may turn up false positives. As a result, we need to
  check that any hits match our pathspec.

We do so reliably for non-directories.

For directories, if "-d" is not given we check that the pathspec matched exactly (i.e., we are even stricter, and require an explicit "git clean foo" to clean "foo/"). But if "-d" is given, rather than relaxing the exact match to allow a recursive match, we do not check the pathspec at all.

This regression was introduced in 113f10f (Make git-clean a builtin, 2007-11-11, Git v1.5.4-rc0).

dir: if our pathspec might match files under a dir, recurse into it

For git clean, if a directory is entirely untracked and the user did not specify -d (corresponding to DIR_SHOW_IGNORED_TOO), then we usually do not want to remove that directory and thus do not recurse into it.

However, if the user manually specified specific (or even globbed) paths somewhere under that directory to remove, then we need to recurse into the directory to make sure we remove the relevant paths under that directory as the user requested.

Note that this does not mean that the recursed-into directory will be added to dir->entries for later removal; as of a few commits earlier in this series, there is another more strict match check that is run after returning from a recursed-into directory before deciding to add it to the list of entries.

  Therefore, this will only result in files underneath the given directory which match one of the pathspecs being added to the entries list.

And:

dir: also check directories for matching pathspecs

Even if a directory doesn't match a pathspec, it is possible, depending on the precise pathspecs, that some file underneath it might.

  So we special case and recurse into the directory for such situations.

  However, we previously always added any untracked directory that we recursed into to the list of untracked paths, regardless of whether the directory itself matched the pathspec.

For the case of git-clean and a set of pathspecs of "dir/file" and "more",
  this caused a problem because we'd end up with dir entries for both of:

```<code>"dir"
"dir/file"
</code>```

Then correct_untracked_entries() would try to helpfully prune duplicates for us by removing "dir/file" since it's under "dir", leaving us with

```<code>"dir"
</code>```

Since the original pathspec only had "dir/file", the only entry left doesn't match and leaves nothing to be removed.

  (Note that if only one pathspec was specified, e.g. only "dir/file", then the common_prefix_len optimizations in fill_directory would cause us to bypass this problem, making it appear in simple tests that we could correctly remove manually specified pathspecs.)

Fix this by actually checking whether the directory we are about to add to the list of dir entries actually matches the pathspec; only do this matching check after we have already returned from recursing into the directory.

That results in:

clean: disambiguate the definition of -d

The -d flag pre-dated git-clean's ability to have paths specified.

  As such, the default for git-clean was to only remove untracked files in
  the current directory, and -d existed to allow it to recurse into
  subdirectories.

The interaction of paths and the -d option appears to not have been carefully considered, as evidenced by numerous bugs and a dearth of tests covering such pairings in the testsuite.

  The definition turns out to be important, so let's look at some of the various ways one could interpret the -d option:

A) Without -d, only look in subdirectories which contain tracked files under them; with -d, also look in subdirectories which are untracked for files to clean.

B) Without specified paths from the user for us to delete, we need to have some kind of default, so...without -d, only look in subdirectories which contain tracked files under them; with -d, also look in subdirectories which are untracked for files to clean.

The important distinction here is that choice B says that the presence or absence of '-d' is irrelevant if paths are specified.

  The logic behind option B is that if a user explicitly asked us to clean a
  specified pathspec, then we should clean anything that matches that
  pathspec.

Some examples may clarify.

Should:

```<code>git clean -f untracked_dir/file
</code>```

remove untracked_dir/file or not?

  It seems crazy not to, but a strict reading of option A says it shouldn't be removed.

  How about:

```<code>git clean -f untracked_dir/file1 tracked_dir/file2
</code>```

or

```<code>git clean -f untracked_dir_1/file1 untracked_dir_2/file2
</code>```

?

  Should it remove either or both of these files?

  Should it require multiple runs to remove both the files listed?  (If this sounds like a crazy question to even ask, see the commit message of "t7300: Add some
  testcases showing failure to clean specified pathspecs" added earlier in
  this patch series.)

  What if -ffd were used instead of -f -- should that allow these to be removed?  Should it take multiple invocations with -ffd?

  What if a glob (such as 'tracked') were used instead of spelling out the directory names?

  What if the filenames involved globs, such as

```<code>git clean -f '*.o'
</code>```

or

```<code>git clean -f '*/*.o'
</code>```

?

The current documentation actually suggests a definition that is
  slightly different than choice A, and the implementation prior to this
  series provided something radically different than either choices A or B.

  (The implementation, though, was clearly just buggy).

There may be other choices as well.

  However, for almost any given choice of definition for -d that I can think of, some of the examples above will appear buggy to the user.

  The only case that doesn't have negative surprises is choice B: treat a user-specified path as a request to clean all untracked files which match that path specification, including recursing into any untracked directories.

Change the documentation and basic implementation to use this definition.

There were two regression tests that indirectly depended on the current
  implementation, but neither was about subdirectory handling.

  These two tests were introduced in commit 5b7570c ("git-clean: add tests for relative path", 2008-03-07, Git v1.5.5-rc0) which was solely created to add coverage for the changes in commit fb328947c8e ("git-clean: correct printing relative path", 2008-03-07).

  Both tests specified a directory that happened to have an untracked subdirectory, but both were only checking that the resulting printout of a file that was removed was shown with a relative path.

  Update these tests appropriately.

Finally, see "Git clean exclude nested sub directory".

Warning: The directory traversal code had redundant recursive calls which made its performance characteristics exponential with respect to the depth of the tree, which was corrected, with Git 2.27 (Q2 2020).

And that affects git clean as well.

See commit c0af173, commit 95c11ec, commit 7f45ab2, commit 1684644, commit 8d92fb2, commit 2df179d, commit 0126d14, commit cd129ee, commit 446f46d, commit 7260c7b, commit ce5c61a (01 Apr 2020) by Elijah Newren (newren).

See commit 0bbd0e8 (01 Apr 2020) by Derrick Stolee (derrickstolee).

(Merged by Junio C Hamano -- gitster -- in commit 6eacc39, 29 Apr 2020)

dir: replace exponential algorithm with a linear one

Signed-off-by: Elijah Newren

dir's read_directory_recursive() naturally operates recursively in order to walk the directory tree.

Treating of directories is sometimes weird because there are so many different permutations about how to handle directories.

Some examples:

'git ls-files -o --directory' only needs to know that a directory itself is untracked; it doesn't need to recurse into it to see what is underneath.

'git status' needs to recurse into an untracked directory, but only to determine whether or not it is empty.

  If there are no files underneath, the directory itself will be omitted from the output.

  If it is not empty, only the directory will be listed.

'git status --ignored' needs to recurse into untracked directories and report all the ignored entries and then report the directory as untracked -- UNLESS all the entries under the directory are ignored, in which case we don't print any of the entries under the directory and just report the directory itself as ignored.

  (Note that although this forces us to walk all untracked files underneath the directory as well, we strip them from the output, except for users like 'git clean' who also set DIR_KEEP_TRACKED_CONTENTS.)

For 'git clean', we may need to recurse into a directory that doesn't match any specified pathspecs, if it's possible that there is an entry underneath the directory that can match one of the pathspecs.

  In such a case, we need to be careful to omit the directory itself from the list of paths (see commit 404ebceda01c ("dir: also check directories for matching pathspecs", 2019-09-17, Git v2.24.0-rc0))

Part of the tension noted above is that the treatment of a directory can change based on the files within it, and based on the various settings in dir->flags.

Trying to keep this in mind while reading over the code, it is easy to think in terms of "treat_directory() tells us what to do with a directory, and read_directory_recursive() is the thing that recurses".

Since we need to look into a directory to know how to treat it, though, it is quite easy to decide to (also) recurse into the directory from treat_directory() by adding a read_directory_recursive() call.

Adding such a call is actually fine, IF we make sure that read_directory_recursive() does not also recurse into that same directory.

Unfortunately, commit df5bcdf83aeb ("dir: recurse into untracked dirs for ignored files", 2017-05-18, Git v2.14.0-rc0 -- merge listed in batch #5), added exactly such a case to the code, meaning we'd have two calls to read_directory_recursive() for an untracked directory.

So, if we had a file named

```<code>one/two/three/four/five/somefile.txt
</code>```

and nothing in one/ was tracked, then 'git status --ignored' would call read_directory_recursive() twice on the directory 'one/', and each of those would call read_directory_recursive() twice on the directory 'one/two/', and so on until read_directory_recursive() was called 2^5 times for 'one/two/three/four/five/'.

Avoid calling read_directory_recursive() twice per level by moving a lot of the special logic into treat_directory().

Since dir.c is somewhat complex, extra cruft built up around this over time.

While trying to unravel it, I noticed several instances where the first call to read_directory_recursive() would return e.g.
  path_untracked for some directory and a later one would return e.g.
  path_none, despite the fact that the directory clearly should have been considered untracked.

The code happened to work due to the side-effect from the first invocation of adding untracked entries to dir->entries; this allowed it to get the correct output despite the supposed override in return value by the later call.

I am somewhat concerned that there are still bugs and maybe even testcases with the wrong expectation.

I have tried to carefully document treat_directory() since it becomes more complex after this change (though much of this complexity came from elsewhere that probably deserved better comments to begin with).

However, much of my work felt more like a game of whackamole while attempting to make the code match the existing regression tests than an attempt to create an implementation that matched some clear design.

That seems wrong to me, but the rules of existing behavior had so many special cases that I had a hard time coming up with some overarching rules about what correct behavior is for all cases, forcing me to hope that the regression tests are correct and sufficient.

Such a hope seems likely to be ill-founded, given my experience with dir.c-related testcases in the last few months:

Examples where the documentation was hard to parse or even just wrong:

3aca58045f4f (git-clean.txt: do not claim we will delete files with -n/--dry-run, 2019-09-17, Git v2.24.0-rc0)

09487f2cbad3 (clean: avoid removing untracked files in a nested git
  repository, 2019-09-17, v2.24.0-rc0)

e86bbcf987fa (clean: disambiguate the definition of -d, 2019-09-17)

Examples where testcases were declared wrong and changed:

09487f2cbad3 (clean: avoid removing untracked files in a nested git repository, 2019-09-17, Git v2.24.0-rc0)

e86bbcf987fa (clean: disambiguate the definition of -d, 2019-09-17, Git v2.24.0-rc0)

a2b13367fe55 (Revert "dir.c: make 'git-status --ignored' work within leading directories", 2019-12-10, Git v2.25.0-rc0)

Examples where testcases were clearly inadequate:

502c386ff944 (t7300-clean: demonstrate deleting nested repo with an ignored file breakage, 2019-08-25, Git v2.24.0-rc0)

7541cc530239 (t7300: add testcases showing failure to clean specified pathspecs, 2019-09-17, Git v2.24.0-rc0)

a5e916c7453b (dir: fix off-by-one error in match_pathspec_item, 2019-09-17, Git v2.24.0-rc0)

404ebceda01c (dir: also check directories for matching pathspecs, 2019-09-17, Git v2.24.0-rc0)

09487f2cbad3 (clean: avoid removing untracked files in a nested git repository, 2019-09-17, Git v2.24.0-rc0)

e86bbcf987fa (clean: disambiguate the definition of -d, 2019-09-17, Git v2.24.0-rc0)

452efd11fbf6 (t3011: demonstrate directory traversal failures, 2019-12-10, Git v2.25.0-rc0)

b9670c1f5e6b (dir: fix checks on common prefix directory, 2019-12-19, Git v2.25.0-rc0)

Examples where "correct behavior" was unclear to everyone:

"[RFC PATCH v2 00/12] Fix some git clean issues"

Other commits of note:

902b90cf42bc (clean: fix theoretical path corruption, 2019-09-17, Git v2.24.0-rc0)

However, on the positive side, it does make the code much faster.

For the following simple shell loop in an empty repository:

```<code>git clean -ffd */ut
</code>```0

$dirs/untracked-file
        /usr/bin/time --format="$depth: %e" git status --ignored >/dev/null
      done

I saw the following timings, in seconds (note that the numbers are a little noisy from run-to-run, but the trend is very clear with every run):

```<code>git clean -ffd */ut
</code>```1

For the above run, using strace I can look for the number of untracked directories opened and can verify that it matches the expected 2^($depth+1)-2 (the sum of 2^1 + 2^2 + 2^3 + ... + 2^$depth).

After this fix, with strace I can verify that the number of untracked directories that are opened drops to just $depth, and the timings all drop to 0.00.

In fact, it isn't until a depth of 190 nested directories that it sometimes starts reporting a time of 0.01 seconds and doesn't consistently report 0.01 seconds until there are 240 nested directories. The previous code would have taken

```<code>git clean -ffd */ut
</code>```2

to have completed the 240 nested directories case.

It's not often that you get to speed something up by a factor of 3*10^69.

Body:
According to the help, without -x option git clean should let alone the ignored files, but it doesn't.

[il@reallin test]$ cat .gitignore
*.sar
[il@reallin test]$ mkdir -p conf/sar && touch conf/sar/aaa.sar
[il@reallin test]$ git status
# On branch master
nothing to commit, working directory clean
[il@reallin test]$ git clean -df
Removing conf/

conf/sar/aaa.sar is removed. Is it a bug?

Body:
Warning: this git clean behavior will slightly change with Git 2.14 (Q3 2017)

"git clean -d" used to clean directories that has ignored files, even though the command should not lose ignored ones without "-x".

"git status --ignored"  did not list ignored and untracked files without "-uall".

See commit 6b1db43 (23 May 2017), and commit bbf504a, commit fb89888, commit df5bcdf, commit 0a81d4a, commit b3487cc (18 May 2017) by Samuel Lijin (sxlijin).

(Merged by Junio C Hamano -- gitster -- in commit f4fd99b, 02 Jun 2017)

clean: teach clean -d to preserve ignored paths

There is an implicit assumption that a directory containing only untracked and ignored paths should itself be considered untracked. This makes sense in use cases where we're asking if a directory should be added to the git database, but not when we're asking if a directory can be safely removed from the working tree; as a result, clean -d would assume that an "untracked" directory containing ignored paths could be deleted, even though doing so would also remove the ignored paths.

To get around this, we teach clean -d to collect ignored paths and skip an untracked directory if it contained an ignored path, instead just removing the untracked contents thereof.

  To achieve this, cmd_clean() has to collect all untracked contents of untracked directories, in addition to all ignored paths, to determine which untracked dirs must be skipped (because they contain ignored paths) and which ones should not be skipped.

But... Since 2017, that change means git status --ignored hangs indefinitely!

As reported by Martin Melka in this thread, and analyzed by SZEDER Gábor:

with a depth of 120 directories it would take over 6*10^23 years to complete

This slowdown was caused by commit df5bcdf, which was part of a
  patch series to fix 'git clean -d' deleting untracked directories even
  if they contained ignored files.

So... a fix is in progress, to be released later in 2020.

Git 2.24 (Q4 2019) illustrates this git clean behavior change introduces a regression.

See commit 502c386 (25 Aug 2019) by SZEDER Gábor (szeder).

(Merged by Junio C Hamano -- gitster -- in commit 026428c, 30 Sep 2019)

t7300-clean: demonstrate deleting nested repo with an ignored file breakage

'git clean -fd' must not delete an untracked directory if it belongs
  to a different Git repository or worktree.

Unfortunately, if a '.gitignore' rule in the outer repository happens to match a file in a nested repository or worktree, then something goes awry and 'git clean -fd' does delete the content of the nested repository's worktree
  except that ignored file, potentially leading to data loss.

Add a test to 't7300-clean.sh' to demonstrate this breakage.

This issue is a regression introduced in 6b1db43 (clean: teach
  clean -d to preserve ignored paths, 2017-05-23, Git v2.13.2).

Git 2.24 further clarifies git clean -d:

See commit 69f272b (01 Oct 2019), and commit 902b90c, commit ca8b539, commit 09487f2, commit e86bbcf, commit 3aca580, commit 29b577b, commit 89a1f4a, commit a3d89d8, commit 404ebce, commit a5e916c, commit bbbb6b0, commit 7541cc5 (17 Sep 2019) by Elijah Newren (newren).

(Merged by Junio C Hamano -- gitster -- in commit aafb754, 11 Oct 2019)

t7300: add testcases showing failure to clean specified pathspecs

Someone brought me a testcase where multiple git-clean invocations were
  required to clean out unwanted files:

mkdir d{1,2}
touch d{1,2}/ut
touch d1/t && git add d1/t

With this setup, the user would need to run

git clean -ffd */ut

twice to delete both ut files.

A little testing showed some interesting variants:

If only one of those two ut files existed (either one), then only one clean command would be necessary.

If both directories had tracked files, then only one git clean would be necessary to clean both files.

If both directories had no tracked files then the clean command above would never clean either of the untracked files despite the pathspec explicitly calling both of them out.

A bisect showed that the failure to clean out the files started with commit cf424f5 ("clean: respect pathspecs with "-d", 2014-03-10, Git v1.9.1).

  However, that pointed to a separate issue: while the "-d" flag was used by the original user who showed me this problem, that flag should have been irrelevant to this problem.

  Testing again without the "-d" flag showed that the same buggy behavior exists without using that flag, and has in fact existed since before cf424f5.

So:

clean: respect pathspecs with "-d"

git-clean uses read_directory to fill in a struct dir with potential hits. However, read_directory does not actually check against our pathspec. It uses a simplified version that may turn up false positives. As a result, we need to
  check that any hits match our pathspec.

We do so reliably for non-directories.

For directories, if "-d" is not given we check that the pathspec matched exactly (i.e., we are even stricter, and require an explicit "git clean foo" to clean "foo/"). But if "-d" is given, rather than relaxing the exact match to allow a recursive match, we do not check the pathspec at all.

This regression was introduced in 113f10f (Make git-clean a builtin, 2007-11-11, Git v1.5.4-rc0).

dir: if our pathspec might match files under a dir, recurse into it

For git clean, if a directory is entirely untracked and the user did not specify -d (corresponding to DIR_SHOW_IGNORED_TOO), then we usually do not want to remove that directory and thus do not recurse into it.

However, if the user manually specified specific (or even globbed) paths somewhere under that directory to remove, then we need to recurse into the directory to make sure we remove the relevant paths under that directory as the user requested.

Note that this does not mean that the recursed-into directory will be added to dir->entries for later removal; as of a few commits earlier in this series, there is another more strict match check that is run after returning from a recursed-into directory before deciding to add it to the list of entries.

  Therefore, this will only result in files underneath the given directory which match one of the pathspecs being added to the entries list.

And:

dir: also check directories for matching pathspecs

Even if a directory doesn't match a pathspec, it is possible, depending on the precise pathspecs, that some file underneath it might.

  So we special case and recurse into the directory for such situations.

  However, we previously always added any untracked directory that we recursed into to the list of untracked paths, regardless of whether the directory itself matched the pathspec.

For the case of git-clean and a set of pathspecs of "dir/file" and "more",
  this caused a problem because we'd end up with dir entries for both of:

"dir"
"dir/file"

Then correct_untracked_entries() would try to helpfully prune duplicates for us by removing "dir/file" since it's under "dir", leaving us with

"dir"

Since the original pathspec only had "dir/file", the only entry left doesn't match and leaves nothing to be removed.

  (Note that if only one pathspec was specified, e.g. only "dir/file", then the common_prefix_len optimizations in fill_directory would cause us to bypass this problem, making it appear in simple tests that we could correctly remove manually specified pathspecs.)

Fix this by actually checking whether the directory we are about to add to the list of dir entries actually matches the pathspec; only do this matching check after we have already returned from recursing into the directory.

That results in:

clean: disambiguate the definition of -d

The -d flag pre-dated git-clean's ability to have paths specified.

  As such, the default for git-clean was to only remove untracked files in
  the current directory, and -d existed to allow it to recurse into
  subdirectories.

The interaction of paths and the -d option appears to not have been carefully considered, as evidenced by numerous bugs and a dearth of tests covering such pairings in the testsuite.

  The definition turns out to be important, so let's look at some of the various ways one could interpret the -d option:

A) Without -d, only look in subdirectories which contain tracked files under them; with -d, also look in subdirectories which are untracked for files to clean.

B) Without specified paths from the user for us to delete, we need to have some kind of default, so...without -d, only look in subdirectories which contain tracked files under them; with -d, also look in subdirectories which are untracked for files to clean.

The important distinction here is that choice B says that the presence or absence of '-d' is irrelevant if paths are specified.

  The logic behind option B is that if a user explicitly asked us to clean a
  specified pathspec, then we should clean anything that matches that
  pathspec.

Some examples may clarify.

Should:

git clean -f untracked_dir/file

remove untracked_dir/file or not?

  It seems crazy not to, but a strict reading of option A says it shouldn't be removed.

  How about:

git clean -f untracked_dir/file1 tracked_dir/file2

or

git clean -f untracked_dir_1/file1 untracked_dir_2/file2

?

  Should it remove either or both of these files?

  Should it require multiple runs to remove both the files listed?  (If this sounds like a crazy question to even ask, see the commit message of "t7300: Add some
  testcases showing failure to clean specified pathspecs" added earlier in
  this patch series.)

  What if -ffd were used instead of -f -- should that allow these to be removed?  Should it take multiple invocations with -ffd?

  What if a glob (such as 'tracked') were used instead of spelling out the directory names?

  What if the filenames involved globs, such as

git clean -f '*.o'

or

git clean -f '*/*.o'

?

The current documentation actually suggests a definition that is
  slightly different than choice A, and the implementation prior to this
  series provided something radically different than either choices A or B.

  (The implementation, though, was clearly just buggy).

There may be other choices as well.

  However, for almost any given choice of definition for -d that I can think of, some of the examples above will appear buggy to the user.

  The only case that doesn't have negative surprises is choice B: treat a user-specified path as a request to clean all untracked files which match that path specification, including recursing into any untracked directories.

Change the documentation and basic implementation to use this definition.

There were two regression tests that indirectly depended on the current
  implementation, but neither was about subdirectory handling.

  These two tests were introduced in commit 5b7570c ("git-clean: add tests for relative path", 2008-03-07, Git v1.5.5-rc0) which was solely created to add coverage for the changes in commit fb328947c8e ("git-clean: correct printing relative path", 2008-03-07).

  Both tests specified a directory that happened to have an untracked subdirectory, but both were only checking that the resulting printout of a file that was removed was shown with a relative path.

  Update these tests appropriately.

Finally, see "Git clean exclude nested sub directory".

Warning: The directory traversal code had redundant recursive calls which made its performance characteristics exponential with respect to the depth of the tree, which was corrected, with Git 2.27 (Q2 2020).

And that affects git clean as well.

See commit c0af173, commit 95c11ec, commit 7f45ab2, commit 1684644, commit 8d92fb2, commit 2df179d, commit 0126d14, commit cd129ee, commit 446f46d, commit 7260c7b, commit ce5c61a (01 Apr 2020) by Elijah Newren (newren).

See commit 0bbd0e8 (01 Apr 2020) by Derrick Stolee (derrickstolee).

(Merged by Junio C Hamano -- gitster -- in commit 6eacc39, 29 Apr 2020)

dir: replace exponential algorithm with a linear one

Signed-off-by: Elijah Newren

dir's read_directory_recursive() naturally operates recursively in order to walk the directory tree.

Treating of directories is sometimes weird because there are so many different permutations about how to handle directories.

Some examples:

'git ls-files -o --directory' only needs to know that a directory itself is untracked; it doesn't need to recurse into it to see what is underneath.

'git status' needs to recurse into an untracked directory, but only to determine whether or not it is empty.

  If there are no files underneath, the directory itself will be omitted from the output.

  If it is not empty, only the directory will be listed.

'git status --ignored' needs to recurse into untracked directories and report all the ignored entries and then report the directory as untracked -- UNLESS all the entries under the directory are ignored, in which case we don't print any of the entries under the directory and just report the directory itself as ignored.

  (Note that although this forces us to walk all untracked files underneath the directory as well, we strip them from the output, except for users like 'git clean' who also set DIR_KEEP_TRACKED_CONTENTS.)

For 'git clean', we may need to recurse into a directory that doesn't match any specified pathspecs, if it's possible that there is an entry underneath the directory that can match one of the pathspecs.

  In such a case, we need to be careful to omit the directory itself from the list of paths (see commit 404ebceda01c ("dir: also check directories for matching pathspecs", 2019-09-17, Git v2.24.0-rc0))

Part of the tension noted above is that the treatment of a directory can change based on the files within it, and based on the various settings in dir->flags.

Trying to keep this in mind while reading over the code, it is easy to think in terms of "treat_directory() tells us what to do with a directory, and read_directory_recursive() is the thing that recurses".

Since we need to look into a directory to know how to treat it, though, it is quite easy to decide to (also) recurse into the directory from treat_directory() by adding a read_directory_recursive() call.

Adding such a call is actually fine, IF we make sure that read_directory_recursive() does not also recurse into that same directory.

Unfortunately, commit df5bcdf83aeb ("dir: recurse into untracked dirs for ignored files", 2017-05-18, Git v2.14.0-rc0 -- merge listed in batch #5), added exactly such a case to the code, meaning we'd have two calls to read_directory_recursive() for an untracked directory.

So, if we had a file named

one/two/three/four/five/somefile.txt

and nothing in one/ was tracked, then 'git status --ignored' would call read_directory_recursive() twice on the directory 'one/', and each of those would call read_directory_recursive() twice on the directory 'one/two/', and so on until read_directory_recursive() was called 2^5 times for 'one/two/three/four/five/'.

Avoid calling read_directory_recursive() twice per level by moving a lot of the special logic into treat_directory().

Since dir.c is somewhat complex, extra cruft built up around this over time.

While trying to unravel it, I noticed several instances where the first call to read_directory_recursive() would return e.g.
  path_untracked for some directory and a later one would return e.g.
  path_none, despite the fact that the directory clearly should have been considered untracked.

The code happened to work due to the side-effect from the first invocation of adding untracked entries to dir->entries; this allowed it to get the correct output despite the supposed override in return value by the later call.

I am somewhat concerned that there are still bugs and maybe even testcases with the wrong expectation.

I have tried to carefully document treat_directory() since it becomes more complex after this change (though much of this complexity came from elsewhere that probably deserved better comments to begin with).

However, much of my work felt more like a game of whackamole while attempting to make the code match the existing regression tests than an attempt to create an implementation that matched some clear design.

That seems wrong to me, but the rules of existing behavior had so many special cases that I had a hard time coming up with some overarching rules about what correct behavior is for all cases, forcing me to hope that the regression tests are correct and sufficient.

Such a hope seems likely to be ill-founded, given my experience with dir.c-related testcases in the last few months:

Examples where the documentation was hard to parse or even just wrong:

3aca58045f4f (git-clean.txt: do not claim we will delete files with -n/--dry-run, 2019-09-17, Git v2.24.0-rc0)

09487f2cbad3 (clean: avoid removing untracked files in a nested git
  repository, 2019-09-17, v2.24.0-rc0)

e86bbcf987fa (clean: disambiguate the definition of -d, 2019-09-17)

Examples where testcases were declared wrong and changed:

09487f2cbad3 (clean: avoid removing untracked files in a nested git repository, 2019-09-17, Git v2.24.0-rc0)

e86bbcf987fa (clean: disambiguate the definition of -d, 2019-09-17, Git v2.24.0-rc0)

a2b13367fe55 (Revert "dir.c: make 'git-status --ignored' work within leading directories", 2019-12-10, Git v2.25.0-rc0)

Examples where testcases were clearly inadequate:

502c386ff944 (t7300-clean: demonstrate deleting nested repo with an ignored file breakage, 2019-08-25, Git v2.24.0-rc0)

7541cc530239 (t7300: add testcases showing failure to clean specified pathspecs, 2019-09-17, Git v2.24.0-rc0)

a5e916c7453b (dir: fix off-by-one error in match_pathspec_item, 2019-09-17, Git v2.24.0-rc0)

404ebceda01c (dir: also check directories for matching pathspecs, 2019-09-17, Git v2.24.0-rc0)

09487f2cbad3 (clean: avoid removing untracked files in a nested git repository, 2019-09-17, Git v2.24.0-rc0)

e86bbcf987fa (clean: disambiguate the definition of -d, 2019-09-17, Git v2.24.0-rc0)

452efd11fbf6 (t3011: demonstrate directory traversal failures, 2019-12-10, Git v2.25.0-rc0)

b9670c1f5e6b (dir: fix checks on common prefix directory, 2019-12-19, Git v2.25.0-rc0)

Examples where "correct behavior" was unclear to everyone:

"[RFC PATCH v2 00/12] Fix some git clean issues"

Other commits of note:

902b90cf42bc (clean: fix theoretical path corruption, 2019-09-17, Git v2.24.0-rc0)

However, on the positive side, it does make the code much faster.

For the following simple shell loop in an empty repository:

for depth in $(seq 10 25)
do
  dirs=$(for i in $(seq 1 $depth) ; do printf 'dir/' ; done)
  rm -rf dir
  mkdir -p $dirs

$dirs/untracked-file
        /usr/bin/time --format="$depth: %e" git status --ignored >/dev/null
      done

I saw the following timings, in seconds (note that the numbers are a little noisy from run-to-run, but the trend is very clear with every run):

10: 0.03
11: 0.05
12: 0.08
13: 0.19
14: 0.29
15: 0.50
16: 1.05
17: 2.11
18: 4.11
19: 8.60
20: 17.55
21: 33.87
22: 68.71
23: 140.05
24: 274.45
25: 551.15

For the above run, using strace I can look for the number of untracked directories opened and can verify that it matches the expected 2^($depth+1)-2 (the sum of 2^1 + 2^2 + 2^3 + ... + 2^$depth).

After this fix, with strace I can verify that the number of untracked directories that are opened drops to just $depth, and the timings all drop to 0.00.

In fact, it isn't until a depth of 190 nested directories that it sometimes starts reporting a time of 0.01 seconds and doesn't consistently report 0.01 seconds until there are 240 nested directories. The previous code would have taken

17.55 * 2^220 / (60*60*24*365) = 9.4 * 10^59 YEARS

to have completed the 240 nested directories case.

It's not often that you get to speed something up by a factor of 3*10^69.


来源: stackexchange

问:
I want my background image's opacity become .2 when I hover over an element on top of it
So I have a movie poster image and a play icon on it. How do I make my poster's opacity down WHEN I hover over the play image/icon that is positioned on it?</p>

答:
You can't do it only by css. You need JS events for it.

Check this snippet out

function changeOpacity(){
  document.getElementById('video').style.opacity = 0.5;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#play {
  width: 50px;
  height: 50px;
}

#video {
  width: 300px;
  height: 300px;
}</code>```

```

This way you can change the opacity as per your need.

Enjoy :D

Note: You can use onmouseout event to make the image's (or video's) opacity    back to normal just like that.

ContentLicense: CC BY-SA 3.0

Body:
You can't do it only by css. You need JS events for it.

Check this snippet out

function changeOpacity(){
  document.getElementById('video').style.opacity = 0.5;
}

#play {
  width: 50px;
  height: 50px;
}

#video {
  width: 300px;
  height: 300px;
}

<img src="https://i.stack.imgur.com/kZvwc.png" id="play" onmouseover="changeOpacity();" />
<br/>
<img src="https://i.stack.imgur.com/NAM35.jpg" id="video" />

This way you can change the opacity as per your need.

Enjoy :D

Note: You can use onmouseout event to make the image's (or video's) opacity    back to normal just like that.


问:
Select matching array with aggregate
hotdeal:

```<code>{ "property" : "ATL-D406" }
</code>```

translation:

```<code>{ "property" : "ATL-D406", "language" : "gb", "txt": [{"aaa":"hi", "bbb":"bye"}] }
{ "property" : "ATL-D406", "language" : "ru", "txt": [{"aaa":"priviet", "bbb":"baka"}] }
{ "property" : "ATL-D406", "language" : "cn", "txt": [{"aaa":"??", "bbb":"??"}] }
</code>```

Current result:

```<code>{ "property":"ATL-D406", "language":[ "gb", "ru", "cn" ] }
</code>```

What I would like:

```<code>{ "property":"ATL-D406", "language":"gb", "aaa":"hi", "bbb":"bye" }
</code>```

I cannot understand why my $elemMatch is not working, shouldn't it isolate that particular element in the result from "translation"?

Also once I got it to only take the "gb" language, how do I project "aaa" and "bbb" without them being inside an array?  I tried $resolve but then I get no data at all. Can you $resolve an array in an array? ($resolve "txt")?

```<code>db.hotdeal.aggregate([
    { '$match': {} },
    { '$lookup': {
        from: 'translation',
        localField: 'property',
        foreignField: 'property',
        as: 'translations'
    } },

    { '$match':
        { 'translations':
            { '$elemMatch': { 'language': 'gb' } }
        }
    },

    { '$project': {
        _id: 0,
        property: 1,
        language: '$translations.language'
    }}
])
</code>```

答:
You are doing the wrong operation. You want $filter, $map, and also $arrayElemAt by the look of it. The $elemMatch operator is a "query" operation for "selection of data", and is not used to "filter" array content.

db.hotdeal.aggregate([
    { '$match': {} },
    { '$lookup': {
        'from': 'translation',
        'localField': 'property',
        'foreignField': 'property',
        'as': 'translations'
    } },
    { '$project': {
        '_id': 0,
        'property': 1,
        'translation': {
         '$arrrayElemAt': [
           { '$map': {
             'input': {
               '$filter': {
                 'input': '$translations'
                 'as': 't',
                 'cond': { '$eq': [ '$$t.language', 'gb' ] }
               },
             },
             'as': 't',
             'in': {
               'language': '$$t',
               'aaa': { '$arrayElemAt': [ '$$t.txt.aaa', 0 ] },
               'bbb': { '$arrayElemAt': [ '$$t.txt.bbb', 0 ] }
             }
           }},
           0
         ]
       }
    }},
    { '$project': {
      'property': 1,
      'language': '$translation.language',
      'aaa': '$translation.aaa',
      'bbb': '$translation.bbb'
    }}
])
```

<p>I generally find that these sort of <em>"trival"</em> structural changes are best handled in "client code" rather than mangling through the aggregation framework anyway.</p>

<p>So simply do the "join" and then let the "client" process the alteration:</p>

<pre class="lang-js prettyprint-override"><code>db.hotdeal.aggregate([
    { '$match': {} },
    { '$lookup': {
        'from': 'translation',
        'localField': 'property',
        'foreignField': 'property',
        'as': 'translations'
    } }
]).forEach( doc => {
  let translation = doc.translations.find( t => t.language === 'gb' );
  doc.language = translation.language;
  doc.aaa = translation.txt[0].aaa;
  doc.bbb = translation.txt[0].bbb;

  delete doc.translations;
  delete doc._id;
  printjson(doc);
});
</code>```

So that is doing the same thing, yet is far less obtuse.

Title: Select matching array with aggregate

Body:
hotdeal:

{ "property" : "ATL-D406" }

translation:

{ "property" : "ATL-D406", "language" : "gb", "txt": [{"aaa":"hi", "bbb":"bye"}] }
{ "property" : "ATL-D406", "language" : "ru", "txt": [{"aaa":"priviet", "bbb":"baka"}] }
{ "property" : "ATL-D406", "language" : "cn", "txt": [{"aaa":"??", "bbb":"??"}] }

Current result:

{ "property":"ATL-D406", "language":[ "gb", "ru", "cn" ] }

What I would like:

{ "property":"ATL-D406", "language":"gb", "aaa":"hi", "bbb":"bye" }

I cannot understand why my $elemMatch is not working, shouldn't it isolate that particular element in the result from "translation"?

Also once I got it to only take the "gb" language, how do I project "aaa" and "bbb" without them being inside an array?  I tried $resolve but then I get no data at all. Can you $resolve an array in an array? ($resolve "txt")?

db.hotdeal.aggregate([
    { '$match': {} },
    { '$lookup': {
        from: 'translation',
        localField: 'property',
        foreignField: 'property',
        as: 'translations'
    } },

    { '$match':
        { 'translations':
            { '$elemMatch': { 'language': 'gb' } }
        }
    },

    { '$project': {
        _id: 0,
        property: 1,
        language: '$translations.language'
    }}
])

Body:
You are doing the wrong operation. You want $filter, $map, and also $arrayElemAt by the look of it. The $elemMatch operator is a "query" operation for "selection of data", and is not used to "filter" array content.

db.hotdeal.aggregate([
    { '$match': {} },
    { '$lookup': {
        'from': 'translation',
        'localField': 'property',
        'foreignField': 'property',
        'as': 'translations'
    } },
    { '$project': {
        '_id': 0,
        'property': 1,
        'translation': {
         '$arrrayElemAt': [
           { '$map': {
             'input': {
               '$filter': {
                 'input': '$translations'
                 'as': 't',
                 'cond': { '$eq': [ '$$t.language', 'gb' ] }
               },
             },
             'as': 't',
             'in': {
               'language': '$$t',
               'aaa': { '$arrayElemAt': [ '$$t.txt.aaa', 0 ] },
               'bbb': { '$arrayElemAt': [ '$$t.txt.bbb', 0 ] }
             }
           }},
           0
         ]
       }
    }},
    { '$project': {
      'property': 1,
      'language': '$translation.language',
      'aaa': '$translation.aaa',
      'bbb': '$translation.bbb'
    }}
])

I generally find that these sort of "trival" structural changes are best handled in "client code" rather than mangling through the aggregation framework anyway.

So simply do the "join" and then let the "client" process the alteration:

db.hotdeal.aggregate([
    { '$match': {} },
    { '$lookup': {
        'from': 'translation',
        'localField': 'property',
        'foreignField': 'property',
        'as': 'translations'
    } }
]).forEach( doc => {
  let translation = doc.translations.find( t => t.language === 'gb' );
  doc.language = translation.language;
  doc.aaa = translation.txt[0].aaa;
  doc.bbb = translation.txt[0].bbb;

  delete doc.translations;
  delete doc._id;
  printjson(doc);
});

So that is doing the same thing, yet is far less obtuse.


问:
Read from a file which is being actively written to
I have two programs: one (program1) writes to a file continuously, and I want the other program (program2) to read the file continuously. What is happening is that my second program is only reading up to the data point which was written when the second code was executed and stops instead of continuously reading.

Is there any way to achieve the thing?

Basically, I want the output of program1 to be used as the input of program2. Is there any way to read and write in RAM instead of file as disk read costs more time.

Code 2:

```<code>#include <stdio.h>

int main(){

    FILE *fptr;

    fptr = fopen("gbbct1.seq","r");

    char c;
    c = fgetc(fptr);

    while (c != EOF){

        printf("%c", c);
        c = fgetc(fptr);

    }

}
</code>```

I am looking for platform independent approach. If that's not possible, I would like to know for Linux platform.   I don't need to preserve the data once read. I don't want to block program1.

答:
The most basic version of your code needs to reset the file stream status when it encounters EOF and then sleep for a while.  For example, assuming POSIX and using only the simplest (most ubiquitous) functions:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
    const char filename[] = "gbbct1.seq";
    FILE *fptr = fopen(filename, "r");
    if (fptr == 0)
    {
        fprintf(stderr, "failed to open file '%s' for reading\b", filename);
        exit(EXIT_FAILURE);
    }

    while (1)
    {
        int c;
        while ((c = fgetc(fptr)) != EOF)
            fputc(c, stdout);

        clearerr(fptr);
        sleep(1);
    }
    /*NOTREACHED*/
    return EXIT_FAILURE;
}
</code>```

The sleep() function sleeps for an integral number of seconds; if you want sub-second sleeps, you can consider usleep(),
nanosleep(), timer_create() and relatives, etc.

I have a program I call dribbler (because it dribbles data to its output):

```<code>Usage: dribbler [-hlntV][-s nap.time][-r std.dev][-f outfile][-i infile][-m message][-o openstr][-F format]
  -V           Print version information and exit
  -f outfile   Write to named file (dribbler.out)
  -h           Print this help message and exit
  -i infile    Read lines from input file
  -l           Loop back to start of input file on EOF
  -m message   Write message on each line of output
  -n           Number lines read from input file
  -o openstr   Flags passed to fopen() (a+)
  -s nap.time  Sleep for given interval between writes (1.000 second)
  -r std.dev   Randomize the time (Gaussian around nap.time with std.dev)
  -t           Write to standard output instead of file
  -F format    Printf format to use instead of %zu
</code>```

I used:

```<code>$ dribbler -s 3 -r 1.3 -f gbbct1.seq &
[1] 81129
$
</code>```

to write to the control file that program2 is coded to read.  I then ran program2 on it, and it produced the outputs as it proceeded.

It's hard to show the time sequence on SO.  I have another program (the story of my life) called tstamp which reads lines of input and prints them with a timestamp prefixed to the line:

```<code>Usage: tstamp [-hV][-f num][-F format]
  -f num  Number of fractional digits (0, 3, 6, 9)
  -h      Print this help message and exit
  -F fmt  Time format (strftime(3)) to use
  -V      Print version information and exit
</code>```

I tried modifying program2.c to set line buffered mode on my Mac (macOS Sierra 10.12.5, GCC 7.1.0), by adding the line below before the while loop in program2.c, but it was effectively ignored, somewhat to my surprise and chagrin:

```<code>setvbuf(fptr, 0, _IOLBF, 0);
</code>```

So, I rewrote the while loop as:

```<code>    while ((c = fgetc(fptr)) != EOF)
    {
        fputc(c, stdout);
        if (c == '\n')
            fflush(stdout);
    }
</code>```

Then I was able to run dribbler in the background, and program2 | tstamp -f 3 to get output like:

```<code>$ program2 | tstamp -f 3
2017-06-03 23:52:44.836: 0: message written to file
2017-06-03 23:52:44.836: 1: message written to file
2017-06-03 23:52:44.836: 2: message written to file
2017-06-03 23:52:44.836: 3: message written to file
[…more similar lines with the same time stamp…]
2017-06-03 23:52:44.836: 22: message written to file
2017-06-03 23:52:44.836: 23: message written to file
2017-06-03 23:52:44.836: 24: message written to file
2017-06-03 23:52:44.836: 25: message written to file
2017-06-03 23:52:50.859: 26: message written to file
2017-06-03 23:52:54.866: 27: message written to file
2017-06-03 23:52:58.880: 28: message written to file
2017-06-03 23:53:02.888: 29: message written to file
2017-06-03 23:53:05.902: 30: message written to file
2017-06-03 23:53:07.907: 31: message written to file
2017-06-03 23:53:09.913: 32: message written to file
2017-06-03 23:53:12.925: 33: message written to file
2017-06-03 23:53:14.935: 34: message written to file
2017-06-03 23:53:15.938: 35: message written to file
2017-06-03 23:53:19.954: 36: message written to file
2017-06-03 23:53:21.964: 37: message written to file
2017-06-03 23:53:23.972: 38: message written to file
^C
$ kill %1
[1]+  Terminated: 15          dribbler -s 3 -r 1.3 -f gbbct1.seq
$
</code>```

You can see that I'd had dribbler running for a while when I started program2 (it got modified and recompiled — part of my chagrin), so there was quite a lot of date to read immediately (hence the multiple lines with the timestamp 2017-06-03 23:52:44.836:), but then it was waiting on dribbler to write more, and as you can see, it sometimes waited nearly 6 seconds between lines, and other times about 1 second, and various intervals in between.  The gaps are made more uniform by program2 sleeping for a second at a time.  (Yes, I wrote these tools to help answer questions on SO — but dribbler and tstamp both pre-date this question by months.)

Body:
I have two programs: one (program1) writes to a file continuously, and I want the other program (program2) to read the file continuously. What is happening is that my second program is only reading up to the data point which was written when the second code was executed and stops instead of continuously reading.

Is there any way to achieve the thing?

Basically, I want the output of program1 to be used as the input of program2. Is there any way to read and write in RAM instead of file as disk read costs more time.

Code 2:

#include <stdio.h>

int main(){

    FILE *fptr;

    fptr = fopen("gbbct1.seq","r");

    char c;
    c = fgetc(fptr);

    while (c != EOF){

        printf("%c", c);
        c = fgetc(fptr);

    }

}

I am looking for platform independent approach. If that's not possible, I would like to know for Linux platform.   I don't need to preserve the data once read. I don't want to block program1.

Body:
The most basic version of your code needs to reset the file stream status when it encounters EOF and then sleep for a while.  For example, assuming POSIX and using only the simplest (most ubiquitous) functions:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
    const char filename[] = "gbbct1.seq";
    FILE *fptr = fopen(filename, "r");
    if (fptr == 0)
    {
        fprintf(stderr, "failed to open file '%s' for reading\b", filename);
        exit(EXIT_FAILURE);
    }

    while (1)
    {
        int c;
        while ((c = fgetc(fptr)) != EOF)
            fputc(c, stdout);

        clearerr(fptr);
        sleep(1);
    }
    /*NOTREACHED*/
    return EXIT_FAILURE;
}

The sleep() function sleeps for an integral number of seconds; if you want sub-second sleeps, you can consider usleep(),
nanosleep(), timer_create() and relatives, etc.

I have a program I call dribbler (because it dribbles data to its output):

Usage: dribbler [-hlntV][-s nap.time][-r std.dev][-f outfile][-i infile][-m message][-o openstr][-F format]
  -V           Print version information and exit
  -f outfile   Write to named file (dribbler.out)
  -h           Print this help message and exit
  -i infile    Read lines from input file
  -l           Loop back to start of input file on EOF
  -m message   Write message on each line of output
  -n           Number lines read from input file
  -o openstr   Flags passed to fopen() (a+)
  -s nap.time  Sleep for given interval between writes (1.000 second)
  -r std.dev   Randomize the time (Gaussian around nap.time with std.dev)
  -t           Write to standard output instead of file
  -F format    Printf format to use instead of %zu

I used:

$ dribbler -s 3 -r 1.3 -f gbbct1.seq &
[1] 81129
$

to write to the control file that program2 is coded to read.  I then ran program2 on it, and it produced the outputs as it proceeded.

It's hard to show the time sequence on SO.  I have another program (the story of my life) called tstamp which reads lines of input and prints them with a timestamp prefixed to the line:

Usage: tstamp [-hV][-f num][-F format]
  -f num  Number of fractional digits (0, 3, 6, 9)
  -h      Print this help message and exit
  -F fmt  Time format (strftime(3)) to use
  -V      Print version information and exit

I tried modifying program2.c to set line buffered mode on my Mac (macOS Sierra 10.12.5, GCC 7.1.0), by adding the line below before the while loop in program2.c, but it was effectively ignored, somewhat to my surprise and chagrin:

setvbuf(fptr, 0, _IOLBF, 0);

So, I rewrote the while loop as:

    while ((c = fgetc(fptr)) != EOF)
    {
        fputc(c, stdout);
        if (c == '\n')
            fflush(stdout);
    }

Then I was able to run dribbler in the background, and program2 | tstamp -f 3 to get output like:

$ program2 | tstamp -f 3
2017-06-03 23:52:44.836: 0: message written to file
2017-06-03 23:52:44.836: 1: message written to file
2017-06-03 23:52:44.836: 2: message written to file
2017-06-03 23:52:44.836: 3: message written to file
[…more similar lines with the same time stamp…]
2017-06-03 23:52:44.836: 22: message written to file
2017-06-03 23:52:44.836: 23: message written to file
2017-06-03 23:52:44.836: 24: message written to file
2017-06-03 23:52:44.836: 25: message written to file
2017-06-03 23:52:50.859: 26: message written to file
2017-06-03 23:52:54.866: 27: message written to file
2017-06-03 23:52:58.880: 28: message written to file
2017-06-03 23:53:02.888: 29: message written to file
2017-06-03 23:53:05.902: 30: message written to file
2017-06-03 23:53:07.907: 31: message written to file
2017-06-03 23:53:09.913: 32: message written to file
2017-06-03 23:53:12.925: 33: message written to file
2017-06-03 23:53:14.935: 34: message written to file
2017-06-03 23:53:15.938: 35: message written to file
2017-06-03 23:53:19.954: 36: message written to file
2017-06-03 23:53:21.964: 37: message written to file
2017-06-03 23:53:23.972: 38: message written to file
^C
$ kill %1
[1]+  Terminated: 15          dribbler -s 3 -r 1.3 -f gbbct1.seq
$

You can see that I'd had dribbler running for a while when I started program2 (it got modified and recompiled — part of my chagrin), so there was quite a lot of date to read immediately (hence the multiple lines with the timestamp 2017-06-03 23:52:44.836:), but then it was waiting on dribbler to write more, and as you can see, it sometimes waited nearly 6 seconds between lines, and other times about 1 second, and various intervals in between.  The gaps are made more uniform by program2 sleeping for a second at a time.  (Yes, I wrote these tools to help answer questions on SO — but dribbler and tstamp both pre-date this question by months.)


问:
Java: how to modify instance variable of a child class
The story goes like this:

I have an abstract class called Algorithms and a lot of classes that extend it. Some of them have parameters to tune. Some have none, and some have up to 5.

I would like to have a method in Algorithms that can tune an arbitrary parameter. e.g.:

```<code>public static void tune (String paramName, double minValue, double MaxValue)
{ ... }
</code>```

So that I can call it like this on 'class SoftRankBoots extends Algorithm':

```<code>Algorithm srb = new SoftRankBoost();
srb.tune("delta", 0, 1);
</code>```

Note that SoftRankBoost has an instance variable 'double delta';

How can I achieve this?

Thank you.

答:
Instead of implementing the method tune in the Abstract class leave it an abstract method, that implementing classes must implement.

So

```<code>public abstract void tune (String paramName, double minValue, double MaxValue);
</code>```

With out seeing the whole picture of what you are trying to do it is hard to give you better advice. But what you are suggesting just seems like a bad idea in general.

ContentLicense: CC BY-SA 2.5

Body:
The story goes like this:

I have an abstract class called Algorithms and a lot of classes that extend it. Some of them have parameters to tune. Some have none, and some have up to 5.

I would like to have a method in Algorithms that can tune an arbitrary parameter. e.g.:

public static void tune (String paramName, double minValue, double MaxValue)
{ ... }

So that I can call it like this on 'class SoftRankBoots extends Algorithm':

Algorithm srb = new SoftRankBoost();
srb.tune("delta", 0, 1);

Note that SoftRankBoost has an instance variable 'double delta';

How can I achieve this?

Thank you.

Body:
Instead of implementing the method tune in the Abstract class leave it an abstract method, that implementing classes must implement.

So

public abstract void tune (String paramName, double minValue, double MaxValue);

With out seeing the whole picture of what you are trying to do it is hard to give you better advice. But what you are suggesting just seems like a bad idea in general.


问:
Why clang report same types as incompatible?
I want to use the pointer returned by malloc() as the name of a multi-dimensional array, thus I cast the pointer. When compiling, I got an error:

```<code>clang++ -o cast cast.cpp
cast.cpp:29:12: error: assigning to 'int8_t (*)[width]' from incompatible type
      'int8_t (*)[width]'
  int8line = (int8_t (*)[width])(array);
           ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
</code>```

But compiling with icpc on the same platform (OS X) and g++/icpc on Linux, no error is thrown.

UPDATE: The width is variable, thus can not be const.

Tested compilers are:

Mac OS X

```<code>icpc (ICC) 17.0.4 20170411

clang --version
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.6.0
Thread model: posix
</code>```

Linux 2.6.32:

```<code>icpc (ICC) 14.0.0 20130728
g++ (GCC) 4.4.6 20110731
</code>```

The result should be:

```<code>icpc -std=c++11 -o cast cast.cpp && ./cast 5
0   1   2   3   4
5   6   7   8   9

0   1   2   3   4
5   6   7   8   9
</code>```

minimum compilable code (updated):

```<code>#include <iostream>
#include <cstdint>

using namespace std;

int main(int argc, char* argv[])
{
  if (argc != 2)
  {
    cerr << "needs one argument\n";
    exit(EXIT_FAILURE);
  }
  long width = atol(argv[1]);

  int8_t *array = static_cast<int8_t(*)>(malloc(sizeof(int8_t)*2*width));
  for (int i = 0; i < 2*width; i++)
    array[i] = i;

  for (int j = 0; j < 2; j++)
  {
    for (int i = 0; i < width; i++)
    {
      cout << static_cast<int>(array[i+j*width]);
      if (i < (width-1))
        cout << '\t';
    }
    cout << '\n';
  }

  cout << '\n';

  int8_t (*int8line)[width];
  int8line = (int8_t (*)[width])(array);
  for (int j = 0; j < 2; j++)
  {
    for (int i = 0; i < width; i++)
    {
      cout << static_cast<int>(int8line[j][i]);
      if (i < (width-1))
        cout << '\t';
    }
    cout << '\n';
  }

  free(array);
  exit(EXIT_SUCCESS);
}
</code>```

答:
Having a non-constexpr width is called varaible length array and is not standard C++.

The type of int8line is therefore in a weird state, int8_t (*)[width] is not an actual type, resulting in the compiler producing the confusing error message.

As Zbynek Vyskovsky - kvr000 pointed out, using const long width = 5 will work, this is because it makes width a constant expression, something known at compile time. This makes the array not a variable length array.

You should probably use std::vector instead.

Body:
I want to use the pointer returned by malloc() as the name of a multi-dimensional array, thus I cast the pointer. When compiling, I got an error:

clang++ -o cast cast.cpp
cast.cpp:29:12: error: assigning to 'int8_t (*)[width]' from incompatible type
      'int8_t (*)[width]'
  int8line = (int8_t (*)[width])(array);
           ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.

But compiling with icpc on the same platform (OS X) and g++/icpc on Linux, no error is thrown.

UPDATE: The width is variable, thus can not be const.

Tested compilers are:

Mac OS X

icpc (ICC) 17.0.4 20170411

clang --version
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.6.0
Thread model: posix

Linux 2.6.32:

icpc (ICC) 14.0.0 20130728
g++ (GCC) 4.4.6 20110731

The result should be:

icpc -std=c++11 -o cast cast.cpp && ./cast 5
0   1   2   3   4
5   6   7   8   9

0   1   2   3   4
5   6   7   8   9

minimum compilable code (updated):

#include <iostream>
#include <cstdint>

using namespace std;

int main(int argc, char* argv[])
{
  if (argc != 2)
  {
    cerr << "needs one argument\n";
    exit(EXIT_FAILURE);
  }
  long width = atol(argv[1]);

  int8_t *array = static_cast<int8_t(*)>(malloc(sizeof(int8_t)*2*width));
  for (int i = 0; i < 2*width; i++)
    array[i] = i;

  for (int j = 0; j < 2; j++)
  {
    for (int i = 0; i < width; i++)
    {
      cout << static_cast<int>(array[i+j*width]);
      if (i < (width-1))
        cout << '\t';
    }
    cout << '\n';
  }

  cout << '\n';

  int8_t (*int8line)[width];
  int8line = (int8_t (*)[width])(array);
  for (int j = 0; j < 2; j++)
  {
    for (int i = 0; i < width; i++)
    {
      cout << static_cast<int>(int8line[j][i]);
      if (i < (width-1))
        cout << '\t';
    }
    cout << '\n';
  }

  free(array);
  exit(EXIT_SUCCESS);
}


问:
Display name over clicked/hovered node? (D3.js version 4)
Currently I have names of my nodes display. I think I would like to only  have the name of a node display if the user clicks on the node or hovers over it (will decide after testing what I like).

To display text I have this currently:

```<code>var nodes_text = svg.selectAll(".nodetext")
        .data(nodes)
        .enter()
        .append("text")
        .attr("class", "nodetext slds-text-heading--label")
        .attr("text-anchor", "middle")
        .attr("dx", -20)
        .attr("dy", 20)
        .text(function(d) {
            return  d.name;
        });
</code>```

My initial thought was to delete the last statement in the above code and move it to a "onclick" event...

```<code>svg.select("circle").on("click", function(d) {
svg.select(".nodetext").text(function(d) {
            return  d.name;
        });

});
</code>```

However this only works if I click my central node for some reason. Was wondering if there is a more obvious way. My node data is stored in an array called "nodes."

EDIT: Here is JFiddle of some test data that shows basic problem. Clicking purple node works but others do not
https://jsfiddle.net/mg8b46aj/1/

答:
Since you have two different selections for the texts and the circles (not a group with those elements, which is the traditional approach), a possible solution is filtering the texts based on the clicked circle:

```<code>svg.selectAll("circle").on("click", function(d) {
    svg.selectAll(".nodetext").filter(function (e){
        return e.name === d.name})
    .text(function(d) {
        return  d.name;
    });
</code>```

Here is the update fiddle: https://jsfiddle.net/2L9rzqbs/

Body:
Currently I have names of my nodes display. I think I would like to only  have the name of a node display if the user clicks on the node or hovers over it (will decide after testing what I like).

To display text I have this currently:

var nodes_text = svg.selectAll(".nodetext")
        .data(nodes)
        .enter()
        .append("text")
        .attr("class", "nodetext slds-text-heading--label")
        .attr("text-anchor", "middle")
        .attr("dx", -20)
        .attr("dy", 20)
        .text(function(d) {
            return  d.name;
        });

My initial thought was to delete the last statement in the above code and move it to a "onclick" event...

svg.select("circle").on("click", function(d) {
svg.select(".nodetext").text(function(d) {
            return  d.name;
        });

});

However this only works if I click my central node for some reason. Was wondering if there is a more obvious way. My node data is stored in an array called "nodes."

EDIT: Here is JFiddle of some test data that shows basic problem. Clicking purple node works but others do not
https://jsfiddle.net/mg8b46aj/1/

Body:
Since you have two different selections for the texts and the circles (not a group with those elements, which is the traditional approach), a possible solution is filtering the texts based on the clicked circle:

svg.selectAll("circle").on("click", function(d) {
    svg.selectAll(".nodetext").filter(function (e){
        return e.name === d.name})
    .text(function(d) {
        return  d.name;
    });

Here is the update fiddle: https://jsfiddle.net/2L9rzqbs/


问:
Eclipse online access extremely slow--cannot complete updates or install new software
I'm trying to set up an Ubuntu 10.10 image in VMWare to do some Android development (my machine actually runs Windows 7 64bit). I've downloaded Eclipse 3.6.1 and when I tried to install the Android Tools by going to Help -> Install New Software, Eclipse would just get stuck trying to download the software. Even after 20 minutes no progress had been made.

I tried to check if Eclipse had internet access by checking for updates, and this too is having problems. If I do Help -> Check for Updates, Eclipse will start to search and then take a very long time to do any progress. It took like 20 minutes to go from 12% complete to 25%, and then 30 minutes to go from 25% to 50%.

I installed the Java JDK just a few minutes before at full speed, so I know it's not something to do with my VMWare setup. Any idea as to what could be happening?

答:
You're right, Eclipse updating can be horribly slow, regardless of connection speed.

From what I can tell, this is because it checks a whole bunch of slow servers looking for updates every time you try and install something. You can disable this behaviour in the "Install New Software" dialog by unchecking the "Contact all update sites" option. I find that things go an awful lot faster then.


问:
How to target div#specificDiv in jquery?
I want to ask that how can i target a specific division in Jquery code. In the code below we are targeting "everything", Even if we change this to "div", it will target all the divisions in the file.But my question is that how can we target a specific division, As i want to target at the div with class "particles particles2"

$(document).ready(function() {

  $(document).on('click', function() {
    $('body').jGravity({
      target: 'eveything',
      ignoreClass: 'ignoreMe',
      weight: 25,
      depth: 5,
      drag: true
    });
    // Misc code for demo purposes
    $(this).removeClass('#fountains');

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="template-page"> </div>
<div class="particles particles2 ignoreMe jGravity" id="fountains"></div></code>```

答:
Simple example:

$(document).ready(function() {
    $(document).on('click',".particles", function() {
        /*$('body').jGravity({
            target: 'eveything',
            ignoreClass: 'ignoreMe',
            weight: 25,
            depth: 5,
            drag: true
        });
        // Misc code for demo purposes
        $(this).removeClass('#fountains');*/
        console.log("Test Click!");
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.particles{
  cursor: pointer;
}</code>```

Click me!
```

Body:
Simple example:

$(document).ready(function() {
    $(document).on('click',".particles", function() {
        /*$('body').jGravity({
            target: 'eveything',
            ignoreClass: 'ignoreMe',
            weight: 25,
            depth: 5,
            drag: true
        });
        // Misc code for demo purposes
        $(this).removeClass('#fountains');*/
        console.log("Test Click!");
    });
});

.particles{
  cursor: pointer;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="particles particles2 ignoreMe jGravity" id="fountains">Click me!</div>


问:
Overriding same method twice from same class
I was understanding how iterator() method works with ArrayList class  . In ArrayList class I found iterator() method overridden twice from same class AbstractList .

```<code>public Iterator<E> iterator() {
    return new Itr();         // Itr is an inner private class of
                               //   ArrayList which
                              // implements Iterator interface .
}

public Iterator<E> iterator() {
        return listIterator();
    }
</code>```

But how is this possible ? There should be an error here of already defined . I am confused .

答:
The first iterator() method you see belongs to the ArrayList class, but the second does not.

It belongs to the SubList class, which is an inner class of ArrayList:

```<code>private class SubList extends AbstractList<E> implements RandomAccess {
    ...
    public Iterator<E> iterator() {
        return listIterator();
    }
    ...
}
</code>```

Therefore it is not overridden twice by the same class. Each class overrides it once.

Body:
I was understanding how iterator() method works with ArrayList class  . In ArrayList class I found iterator() method overridden twice from same class AbstractList .

public Iterator<E> iterator() {
    return new Itr();         // Itr is an inner private class of
                               //   ArrayList which
                              // implements Iterator interface .
}

public Iterator<E> iterator() {
        return listIterator();
    }

But how is this possible ? There should be an error here of already defined . I am confused .

Body:
The first iterator() method you see belongs to the ArrayList class, but the second does not.

It belongs to the SubList class, which is an inner class of ArrayList:

private class SubList extends AbstractList<E> implements RandomAccess {
    ...
    public Iterator<E> iterator() {
        return listIterator();
    }
    ...
}

Therefore it is not overridden twice by the same class. Each class overrides it once.


问:
How to remove decoration of an  tag
I have an a tag and a li inside it. The a tag colors the list items innterText. How can I nullify its effects on the color of its content and also remove the underline?

Code:

```<code><!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <ul>
            <a href="google.com"><li>asd</li></a>
        </ul>
    </body>
</html>
</code>```

答:
It is invalid to have  inside
 tag in the way you did, and it's also won't pass the W3C validation. However, If I understand your question, you may try this:

```<code><ul>
    <li>
        <a href="#">
            <ul>
                <li>asd</li>
            </ul>
        </a>
    </li>
</ul>
</code>```

In order to remove the underline, you can do:

```<code>ul li a {
    text-decoration: none;
    color: #b61c1c; /* For Example */
}
</code>```

Fiddle

Title: How to remove decoration of an <a> tag

Body:
I have an a tag and a li inside it. The a tag colors the list items innterText. How can I nullify its effects on the color of its content and also remove the underline?

Code:

<!DOCTYPE html>

asd

Body:
It is invalid to have <a> inside <ul> tag in the way you did, and it's also won't pass the W3C validation. However, If I understand your question, you may try this:

<ul>
    <li>
        <a href="#">
            <ul>
                <li>asd</li>
            </ul>
        </a>
    </li>
</ul>

In order to remove the underline, you can do:

ul li a {
    text-decoration: none;
    color: #b61c1c; /* For Example */
}

Fiddle


问:
Unable to change UILabel in a method after calling different method in different class
I am trying to update a UILabel with data retrieved from a different class, so in ViewDidLoad, I am calling a method in that different class, then in that class, calling a method in the ViewController to update the UILabel. Here is a simplified version of the code I'm trying to run:

```<code>import UIKit

  class ViewController: UIViewController {

    @IBOutlet var label: UILabel!
    override func viewDidLoad() {
    super.viewDidLoad()
    test().runTest()
}

func print() {
    label.text = "test123"
}

}
</code>```

and the other class:

```<code>import UIKit

class test: UIView {

    func runTest() {
        ViewController().print()
    }
}
</code>```

I keep getting an error message printed in the console saying: "fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)"

And an error on the "label.text = "test123" saying: "Thread 1: EXC_Bad_Instruction(code=EXC_(386_INVOP, subcode = 0x0)"

Thanks in advance for your help.

答:
```<code>Your label IBOutlet is nil because you are creating a new viewcontroller instance and your viewcontroller is not attached any story board. you can pass self to     func runTest() and on self you can call print. Hope it will help!

You can use this

import UIKit

  class ViewController: UIViewController {

    @IBOutlet var label: UILabel!
    override func viewDidLoad() {
    super.viewDidLoad()
    test().runTest(self)
}

func print() {
    label.text = "test123"
}

}

import UIKit

class test: UIView {

    func runTest(controller:ViewController) {
        controller.print()
    }
}
</code>```

Body:
I am trying to update a UILabel with data retrieved from a different class, so in ViewDidLoad, I am calling a method in that different class, then in that class, calling a method in the ViewController to update the UILabel. Here is a simplified version of the code I'm trying to run:

import UIKit

  class ViewController: UIViewController {

    @IBOutlet var label: UILabel!
    override func viewDidLoad() {
    super.viewDidLoad()
    test().runTest()
}

func print() {
    label.text = "test123"
}

}

and the other class:

import UIKit

class test: UIView {

    func runTest() {
        ViewController().print()
    }
}

I keep getting an error message printed in the console saying: "fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)"

And an error on the "label.text = "test123" saying: "Thread 1: EXC_Bad_Instruction(code=EXC_(386_INVOP, subcode = 0x0)"

Thanks in advance for your help.


问:
Tool to see HTML5 Web SQL database?
Does anyone know of a tool (like PHPMyAdmin or similar) that will allow me to view the HTML5 Web SQL databases within my browser?</p>

答:
Developers tools (aka F12 tools) provided by Google Chrome browser is your best bet. In fact it helps you see not just web SQL databases but you can also see localStorage, sessionStorage, IndexedDB, cookies etc.

Here is the navigation path:

```<code>Google Chrome -> Press F12 -> Application tab -> Storage Node in left navigation bar -> Web SQL node -> <Database Name> node
</code>```

More details on this is available here.

Title: Tool to see HTML5 Web SQL database?

Body:
Developers tools (aka F12 tools) provided by Google Chrome browser is your best bet. In fact it helps you see not just web SQL databases but you can also see localStorage, sessionStorage, IndexedDB, cookies etc.

Here is the navigation path:

Google Chrome -> Press F12 -> Application tab -> Storage Node in left navigation bar -> Web SQL node -> <Database Name> node

More details on this is available here.


问:
Is RIA Services right for our Silverlight app at this point?
I'm looking at Silverlight architectures and RIA Services looks interesting, but I am a bit concerned about its prelease status and how the feature set will change.

We need our client app to be as responsive as possible over a slow network link, so a high priority is a solid sync system for pushing model state changes from the client back to the server. Will RIA Services help us in this regard or will I have to roll my own logic to do this ? Are there any other frameworks that can assist with this? Is the feature set involved in these requirements liable to change much in the next couple of months?

If it makes any difference, our frontend is 100% Silverlight, so we dont need to worry about exposing SOAP APIs from the server or anything like that. It appears to me that RIA so far is a bit more mature for Silverlight use. Is this correct?

答:
I would look into some of the ORM's / IoC Frameworks which help create a separation of interests.  A couple examples are Castle Windsor IoC, they have a sample Silverlight 4 application that utilizes the Castle Windsor Framework.  Another common ORM for Silverlight is
BL Toolkit.  These have been around for a while in the Java arena but are newer in the .NET area.  They basically help to move the complexities of the relational data model out of the UI code and delegate it to the Framework.</p>


Title: calculate distances between different trips in loops

Body:
I have a data frame called p.1 with 16 column of information for each of the points recorded by the Argos system, this are the important columns, date, lon (longitud), lat (latitud), trip is the number of the trip and the distance to the coast.

date               |   lon        |    lat        | trip |  distancetocoast
2014-06-11 19:02:00 -58,3508585     -51,88438373    1       2236,067977
2014-06-12 01:02:00 -58,35589725    -51,88349529    1       1000
2014-06-12 13:02:00 -58,27224941    -51,91903677    1       7211,102551
2014-06-12 19:02:00 -58,27974654    -51,90535003    1       5830,951895
2014-06-13 01:02:00 -58,32331901    -51,89410464    1       3605,551275
2014-06-13 07:02:00 -58,35833139    -51,88809227    1       1414,213562
2014-06-13 13:02:00 -58,35617673    -51,88156281    1       1000
2014-06-13 19:02:00 -58,34055711    -51,89002367    1       2236,067977
2014-06-14 01:02:00 -58,34982536    -51,8715761     2       1000
2014-06-14 13:02:00 -58,3073814     -51,92722937    2       7071,067812
2014-06-14 19:02:00 -58,34581314    -51,86761133    3       1000
2014-06-15 01:02:00 -58,34050624    -51,88382088    3       1414,213562
2014-06-15 13:02:00 -58,2974691     -51,91795326    3       6324,55532
2014-06-15 19:02:00 -58,19881901    -51,95172233    3       13000
2014-06-16 01:02:00 -58,1348416     -51,98673766    3       18788,29423
2014-06-16 07:02:00 -57,99399544    -52,06988191    3       28861,73938
2014-06-16 13:02:00 -58,00469754    -52,02795069    3       26627,05391
2014-06-16 19:02:00 -57,92758675    -52,02184666    3       29000
2014-06-17 01:02:00 -57,91658235    -51,99748699    3       28284,27125
2014-06-17 07:02:00 -57,77015528    -51,99031797    3       30805,8436
2014-06-17 13:02:00 -57,99601712    -51,91519551    3       17804,49381
2014-06-17 19:02:00 -58,06820013    -51,92972737    3       14866,06875
2014-06-18 01:02:00 -58,19845185    -51,89522513    3       7615,773106
2014-06-18 07:02:00 -58,35241361    -51,88015998    3       1000
2014-06-18 13:02:00 -58,35603546    -51,88336878    3       1000
2014-06-18 19:02:00 -58,33350332    -51,87308427    3       1000
2014-06-19 01:02:00 -58,33839581    -51,87846631    3       1414,213562
2014-06-19 07:02:00 -58,42661519    -51,80902388    4       0
2014-06-19 13:02:00 -58,30461883    -51,93745837    4       7810,249676
2014-06-19 19:02:00 -58,18362875    -51,96475914    4       14317,82106

In the beggining I just sumed the distance from coast of every trip with the next function:

tripID<-c(1:length(unique(p.1$trip)))
tripdistance<-aggregate(p.1$dist,by=list(unique.values=p.1$trip),FUN=sum)

This is clearly wrong, how can I calculate the distance traveled in each trip and start from 0 in the next trip?

I´ve been trying with other functions as: spDistsN1 and trackDistance but I can´t make it work.

Body:
You may find the dplyr to provide the tools you need to do this.

First, if you plan on posting more questions on SO, it will be helpful to use dput to provide copies of your data set in a way that is easy for others to reproduce.  For this example, it was easy enough to read your data set in via readr.

library(readr)
library(dplyr)
library(trip)

p.1 <-
  readr::read_delim(delim = "|",
                    locale = locale(decimal_mark = ",", grouping_mark = "."),
                    trim_ws = TRUE,
                    file =
"date               | lon          | lat          | trip | distancetocoast
2014-06-11 19:02:00 | -58,3508585  | -51,88438373 | 1    | 2236,067977
2014-06-12 01:02:00 | -58,35589725 | -51,88349529 | 1    | 1000
2014-06-12 13:02:00 | -58,27224941 | -51,91903677 | 1    | 7211,102551
2014-06-12 19:02:00 | -58,27974654 | -51,90535003 | 1    | 5830,951895
2014-06-13 01:02:00 | -58,32331901 | -51,89410464 | 1    | 3605,551275
2014-06-13 07:02:00 | -58,35833139 | -51,88809227 | 1    | 1414,213562
2014-06-13 13:02:00 | -58,35617673 | -51,88156281 | 1    | 1000
2014-06-13 19:02:00 | -58,34055711 | -51,89002367 | 1    | 2236,067977
2014-06-14 01:02:00 | -58,34982536 | -51,8715761  | 2    | 1000
2014-06-14 13:02:00 | -58,3073814  | -51,92722937 | 2    | 7071,067812
2014-06-14 19:02:00 | -58,34581314 | -51,86761133 | 3    | 1000
2014-06-15 01:02:00 | -58,34050624 | -51,88382088 | 3    | 1414,213562
2014-06-15 13:02:00 | -58,2974691  | -51,91795326 | 3    | 6324,55532
2014-06-15 19:02:00 | -58,19881901 | -51,95172233 | 3    | 13000
2014-06-16 01:02:00 | -58,1348416  | -51,98673766 | 3    | 18788,29423
2014-06-16 07:02:00 | -57,99399544 | -52,06988191 | 3    | 28861,73938
2014-06-16 13:02:00 | -58,00469754 | -52,02795069 | 3    | 26627,05391
2014-06-16 19:02:00 | -57,92758675 | -52,02184666 | 3    | 29000
2014-06-17 01:02:00 | -57,91658235 | -51,99748699 | 3    | 28284,27125
2014-06-17 07:02:00 | -57,77015528 | -51,99031797 | 3    | 30805,8436
2014-06-17 13:02:00 | -57,99601712 | -51,91519551 | 3    | 17804,49381
2014-06-17 19:02:00 | -58,06820013 | -51,92972737 | 3    | 14866,06875
2014-06-18 01:02:00 | -58,19845185 | -51,89522513 | 3    | 7615,773106
2014-06-18 07:02:00 | -58,35241361 | -51,88015998 | 3    | 1000
2014-06-18 13:02:00 | -58,35603546 | -51,88336878 | 3    | 1000
2014-06-18 19:02:00 | -58,33350332 | -51,87308427 | 3    | 1000
2014-06-19 01:02:00 | -58,33839581 | -51,87846631 | 3    | 1414,213562
2014-06-19 07:02:00 | -58,42661519 | -51,80902388 | 4    | 0
2014-06-19 13:02:00 | -58,30461883 | -51,93745837 | 4    | 7810,249676
2014-06-19 19:02:00 | -58,18362875 | -51,96475914 | 4    | 14317,82106")

dplyr provides a group_by function that will do exactly what it sounds like, create groups defined by the values within one or more columns.  The mutate command creates columns of a data set.

A vector distance_traveled has been created to start at 0 for the first entry of each trip and then use spDist for the distance traveled.

The cumulative distance and the total distance for each trip is also reported.  If you are unfamiliar with the %>% operator, read help("%>%", package = "magrittr").

p.1 %>%
group_by(trip) %>%
arrange(date) %>%
mutate(distance_traveled       = c(0, spDists(x = cbind(lon, lat), longlat = TRUE, segments = TRUE)),
       cumlative_trip_distance = cumsum(distance_traveled),
       total_trip_distance     = sum(distance_traveled)) %>%
ungroup() %>%
print.data.frame

p.1
#                   date       lon       lat trip distancetocoast distance_traveled cumlative_trip_distance total_trip_distance
# 1  2014-06-11 19:02:00 -58.35086 -51.88438    1        2236.068         0.0000000               0.0000000           16.875313
# 2  2014-06-12 01:02:00 -58.35590 -51.88350    1        1000.000         0.3607526               0.3607526           16.875313
# 3  2014-06-12 13:02:00 -58.27225 -51.91904    1        7211.103         6.9846980               7.3454506           16.875313
# 4  2014-06-12 19:02:00 -58.27975 -51.90535    1        5830.952         1.6078870               8.9533376           16.875313
# 5  2014-06-13 01:02:00 -58.32332 -51.89410    1        3605.551         3.2496828              12.2030205           16.875313
# 6  2014-06-13 07:02:00 -58.35833 -51.88809    1        1414.214         2.5015138              14.7045343           16.875313
# 7  2014-06-13 13:02:00 -58.35618 -51.88156    1        1000.000         0.7415006              15.4460348           16.875313
# 8  2014-06-13 19:02:00 -58.34056 -51.89002    1        2236.068         1.4292778              16.8753126           16.875313
# 9  2014-06-14 01:02:00 -58.34983 -51.87158    2        1000.000         0.0000000               0.0000000            6.846905
# 10 2014-06-14 13:02:00 -58.30738 -51.92723    2        7071.068         6.8469049               6.8469049            6.846905
# 11 2014-06-14 19:02:00 -58.34581 -51.86761    3        1000.000         0.0000000               0.0000000          103.020176
# 12 2014-06-15 01:02:00 -58.34051 -51.88382    3        1414.214         1.8402281               1.8402281          103.020176
# 13 2014-06-15 13:02:00 -58.29747 -51.91795    3        6324.555         4.8164202               6.6566483          103.020176
# 14 2014-06-15 19:02:00 -58.19882 -51.95172    3       13000.000         7.7558235              14.4124718          103.020176
# 15 2014-06-16 01:02:00 -58.13484 -51.98674    3       18788.294         5.8746536              20.2871254          103.020176
# 16 2014-06-16 07:02:00 -57.99400 -52.06988    3       28861.739        13.3804466              33.6675720          103.020176
# 17 2014-06-16 13:02:00 -58.00470 -52.02795    3       26627.054         4.7230685              38.3906405          103.020176
# 18 2014-06-16 19:02:00 -57.92759 -52.02185    3       29000.000         5.3362603              43.7269008          103.020176
# 19 2014-06-17 01:02:00 -57.91658 -51.99749    3       28284.271         2.8138115              46.5407123          103.020176
# 20 2014-06-17 07:02:00 -57.77016 -51.99032    3       30805.844        10.0892378              56.6299501          103.020176
# 21 2014-06-17 13:02:00 -57.99602 -51.91520    3       17804.494        17.6348017              74.2647518          103.020176
# 22 2014-06-17 19:02:00 -58.06820 -51.92973    3       14866.069         5.2225348              79.4872866          103.020176
# 23 2014-06-18 01:02:00 -58.19845 -51.89523    3        7615.773         9.7503783              89.2376649          103.020176
# 24 2014-06-18 07:02:00 -58.35241 -51.88016    3        1000.000        10.7319100              99.9695749          103.020176
# 25 2014-06-18 13:02:00 -58.35604 -51.88337    3        1000.000         0.4355097             100.4050846          103.020176
# 26 2014-06-18 19:02:00 -58.33350 -51.87308    3        1000.000         1.9279737             102.3330583          103.020176
# 27 2014-06-19 01:02:00 -58.33840 -51.87847    3        1414.214         0.6871181             103.0201763          103.020176
# 28 2014-06-19 07:02:00 -58.42662 -51.80902    4           0.000         0.0000000               0.0000000           25.433053
# 29 2014-06-19 13:02:00 -58.30462 -51.93746    4        7810.250        16.5773793              16.5773793           25.433053
# 30 2014-06-19 19:02:00 -58.18363 -51.96476    4       14317.821         8.8556734              25.4330527           25.433053


问:
pip freeze doesn't show anything in Windows installation?
I have Python27 installed in Windows 7

I am trying to build a reddit bot using this tutorial

I found instructions on how to install pip for windows from here

The page says that after installing pip, I can use pip freeze to check if the installation went correctly

It says pip freeze should display some information as shown below

Microsoft Windows [Version 6.2.9200] (c) 2012 Microsoft Corporation.
  All rights reserved.

C:\Users\Username>cd c:\Python27\Scripts

c:\Python27\Scripts>pip freeze

  antiorm==1.1.1

  enum34==1.0

  requests==2.3.0 virtualenv==1.11.6

However pip freeze doesn't show me anything at all

Did pip install correctly, or is there any problem? Is there any other way i can test proper installation?

答:
If you want to test it thoroughly, you can use your actual pip installation to install something. For example, numpy would be a good sized example that can rule many problems out.

> pip install numpy

Now, run pip freeze again to check if pip is working as expected. It should then have something to show.

If you want to test it even further, you can open a terminal and

```<code>> python
> import numpy
</code>```

That should be the complete test of your pip installation.

Additionally, whenever I install a new tool in my stack, I like to validate its path with where <executable name> (on Windows) and which <executable name> (on Linux). There are some compilers like Java that are always conflicting with other installations (like crazy, to the point that a complex setup may sometimes have to inject an absolute path to enforce the use of the correct version).

Also, asking the executable for its version can rule many other problems out. In your case, you can use pip --version to check which version you got and compare it to the stable or latest, according to what you want to use.

Body:
If you want to test it thoroughly, you can use your actual pip installation to install something. For example, numpy would be a good sized example that can rule many problems out.

> pip install numpy

Now, run pip freeze again to check if pip is working as expected. It should then have something to show.

If you want to test it even further, you can open a terminal and

> python
> import numpy

That should be the complete test of your pip installation.

Additionally, whenever I install a new tool in my stack, I like to validate its path with where <executable name> (on Windows) and which <executable name> (on Linux). There are some compilers like Java that are always conflicting with other installations (like crazy, to the point that a complex setup may sometimes have to inject an absolute path to enforce the use of the correct version).

Also, asking the executable for its version can rule many other problems out. In your case, you can use pip --version to check which version you got and compare it to the stable or latest, according to what you want to use.


答:
Overriding the same method twice from same class is not allowed. In your case, these are two different classes, namely:

```<code>public class ArrayList<E> extends AbstractList<E>
private class SubList extends AbstractList<E> implements RandomAccess
</code>```

and the latter is an inner class of the former, that's why both can have same method with same signature.

Title: Overriding same method twice from same class

Body:
Overriding the same method twice from same class is not allowed. In your case, these are two different classes, namely:

public class ArrayList<E> extends AbstractList<E>
private class SubList extends AbstractList<E> implements RandomAccess

and the latter is an inner class of the former, that's why both can have same method with same signature.


问:
How to compute the "15% of the time" randomness?
I'm looking for a decent, elegant method of calculating this simple logic.

Right now I can't think of one, it's spinning my head.

I am required to do some action only 15% of the time.

I'm used to "50% of the time" where I just mod the milliseconds of the current time and see if it's odd or even, but I don't think that's elegant.

How would I elegantly calculate "15% of the time"?  Random number generator maybe?

Pseudo-code or any language are welcome.

Hope this is not subjective, since I'm looking for the "smartest" short-hand method of doing that.

Thanks.

答:
This quote is from a great article about how to use a random number generator:

Note: Do NOT use

```<code>  y = rand()  %  M;
</code>```

as this focuses on the lower bits of
  rand(). For linear congruential random
  number generators, which rand() often
  is, the lower bytes are much less
  random than the higher bytes. In fact
  the lowest bit cycles between 0 and 1.
  Thus rand() may cycle between even and
  odd (try it out). Note rand() does not
  have to be a linear congruential
  random number generator. It's
  perfectly permissible for it to be
  something better which does not have
  this problem.

and it contains formulas and pseudo-code for

r = [0,1) = {r: 0 <= r < 1} real

x = [0,M) = {x: 0 <= x < M} real

y = [0,M) = {y: 0 <= y < M} integer

z =  [1,M] = {z: 1 <= z <= M} integer

Body:
This quote is from a great article about how to use a random number generator:

Note: Do NOT use

  y = rand()  %  M;

as this focuses on the lower bits of
  rand(). For linear congruential random
  number generators, which rand() often
  is, the lower bytes are much less
  random than the higher bytes. In fact
  the lowest bit cycles between 0 and 1.
  Thus rand() may cycle between even and
  odd (try it out). Note rand() does not
  have to be a linear congruential
  random number generator. It's
  perfectly permissible for it to be
  something better which does not have
  this problem.

and it contains formulas and pseudo-code for

r = [0,1) = {r: 0 <= r < 1} real

x = [0,M) = {x: 0 <= x < M} real

y = [0,M) = {y: 0 <= y < M} integer

z =  [1,M] = {z: 1 <= z <= M} integer

ContentLicense: CC BY-SA 4.0