问:
Export git history, for a file and a subfolder, into another existing git repo?
Please consider the Bash script testgit.sh, pasted at the end of this post, which will reconstruct the repository examples here.

So, I have oldrepo_git repository, which has some files and folders - and then, a newrepo_git repository, which has just a single commit (for a README). This is what gitk --all sees in these repos:

Basically, I want to export the entire git history for the file a.txt and the entirety of the aa subfolder (so, the aa/aa.txt and aa/ab.txt files - but not the README or b.txt files) from the oldrepo_git repository, and import it in the newrepo_git repository - if possible, with the right timestamps, and branching/merging info.

Since the file called README in oldrepo_git is not part of this operation, and since newrepo_git has nothing else but a README file, I wouldn't expect any conflicts to occur. However, I'm not sure what commands I can use to do this: I'm aware there is git filter-branch, but as far as I know, it will change the history of oldrepo_git "in-place" - it will not "import" this history into newrepo_git.

In other words, if the history of oldrepo_git is:

```<code>$ git log --oneline --graph
*   7e26890 (HEAD -> master) Merge branch 'testbranch'
|\
| * 56ef109 (testbranch) change 5 made
| * 1a78db3 change 4 made
| * d98b4cf change 3 made
| * e5e49af change 2 made
| * 8704c24 change 1 made
|/
* f318d97 added a.txt
* 252bf7f Initial commit
</code>```

... after the process is done, I would like to see this as the history of newrepo_git:

```<code>$ git log --oneline --graph
*   XXXYYGG (HEAD -> master) Merge branch 'testbranch'
|\
| * XXXYYFF (testbranch) change 5 made
| * XXXYYEE change 4 made
| * XXXYYDD change 3 made
| * XXXYYCC change 2 made
| * XXXYYBB change 1 made
|/
* XXXYYAA added a.txt
* 8e99c2d Initial commit by Bob
</code>```

How could I perform this operation?

The Bash script testgit.sh:

```<code>#!/usr/bin/env bash

rm -rf oldrepo_git newrepo_git
mkdir oldrepo_git newrepo_git

cd oldrepo_git
git init
git config user.name tester
git config user.email tester@example.com
echo "# README" >> README
git add README
GIT_COMMITTER_DATE="1558960260" git commit --date "1558960260" -m "Initial commit"
echo "Testing" >> a.txt
git add a.txt
GIT_COMMITTER_DATE="1558960270" git commit --date "1558960270" -m "added a.txt"
git checkout -b testbranch
mkdir aa bb
for ix in 1 2 3 4 5; do
  echo $ix >> a.txt
  echo $ix >> b.txt
  echo $ix >> aa/aa.txt
  echo $ix >> aa/ab.txt
  git add .
  newts="$((1558960270+ix*10))"
  GIT_COMMITTER_DATE="$newts" git commit --date "$newts" -m "change $ix made"
done
git checkout master
ix="$((ix+1))"; newts="$((1558960270+ix*10))"
GIT_COMMITTER_DATE="$newts" GIT_AUTHOR_DATE="$newts" git merge --no-ff --no-edit testbranch

cd ../newrepo_git
git init
git config user.name bob
git config user.email bob@example.com
echo "# Bob's README" >> README
git add README
GIT_COMMITTER_DATE="1558960260" git commit --date "1558960260" -m "Initial commit by Bob"
</code>```

答:
EDIT: you may want to add an extra echo $ix >> bb/bb.txt in the for loop in the testgit.sh script in OP, so that the output in this post matches.

Ok, I guess this is how it should be done - at least in relation to the OP (where we don't have remote repos yet); first, copy the oldrepo:

```<code>cp -a oldrepo_git oldrepo_filt_git
</code>```

Then apparently we have to delete all the stuff we don't want in the copied oldrepo, by using git filter-branch in combination with git rm - part of this command I found here: Detach many subdirectories into a new, separate Git repository

```<code>cd oldrepo_filt_git
git filter-branch --index-filter "git rm --cached --ignore-unmatch -r $(bash -O extglob -c 'ls -xd !(a*)')" --prune-empty -- --all
</code>```

Note, since here we want to tell to git rm what to delete, we want to specify what we do not want to keep, as the inverse of what we want to keep; and here I want to keep a.txt file and aa folder - so a glob match would be a*. Then you need the bash extglob function to get that; so if a whole list is:

```<code>$ ls
a.txt  aa  b.txt  bb  README
</code>```

... then the extglob stanza which will give us only the file/folder names to delete gives:

```<code>$ bash -O extglob -c 'ls -xd !(a*)'
b.txt  bb  README
</code>```

So, after git filter-branch command is ran:

```<code>$ git filter-branch --index-filter "git rm --cached --ignore-unmatch -r $(bash -O extglob -c 'ls -xd !(a*)')" --prune-empty -- --all
Rewrite 252bf7ff5f385dad880240d5d80e68f24ae09b59 (1/8) (0 seconds passed, remaining 0 predicted)    rm 'README'
Rewrite f318d9712cd7aacdb5dd45febbcdbbce6b741e08 (2/8) (1 seconds passed, remaining 3 predicted)    rm 'README'
Rewrite 00b62e7da8784d45850d7483cbea88fdc4aa844c (2/8) (1 seconds passed, remaining 3 predicted)    rm 'README'
rm 'b.txt'
rm 'bb/bb.txt'
Rewrite c618eff47d38412c54a8381a5bacc921bddefe2d (2/8) (1 seconds passed, remaining 3 predicted)    rm 'README'
rm 'b.txt'
rm 'bb/bb.txt'
Rewrite 2cada8d822d83f37bdc4a37bcfb03047c1cc1ded (5/8) (3 seconds passed, remaining 1 predicted)    rm 'README'
rm 'b.txt'
rm 'bb/bb.txt'
Rewrite 7b296b70018f4105f190d06ed4d9c58e3f80532f (5/8) (3 seconds passed, remaining 1 predicted)    rm 'README'
rm 'b.txt'
rm 'bb/bb.txt'
Rewrite 18a1ad1d35cd8573c39485d0a29b630325f9727d (7/8) (5 seconds passed, remaining 0 predicted)    rm 'README'
rm 'b.txt'
rm 'bb/bb.txt'
Rewrite 2ffbbf03d51363f1ced3aaaf000d5921c9d8b919 (7/8) (5 seconds passed, remaining 0 predicted)    rm 'README'
rm 'b.txt'
rm 'bb/bb.txt'

Ref 'refs/heads/master' was rewritten
Ref 'refs/heads/testbranch' was rewritten
</code>```

... we have:

```<code>$ git log --oneline --graph --stat
*   31cd8b5 (HEAD -> master) Merge branch 'testbranch'
|\
| * 42b153d (testbranch) change 5 made
| |  a.txt     | 1 +
| |  aa/aa.txt | 1 +
| |  aa/ab.txt | 1 +
| |  3 files changed, 3 insertions(+)
| * ff1be9d change 4 made
| |  a.txt     | 1 +
| |  aa/aa.txt | 1 +
| |  aa/ab.txt | 1 +
| |  3 files changed, 3 insertions(+)
| * 90f050c change 3 made
| |  a.txt     | 1 +
| |  aa/aa.txt | 1 +
| |  aa/ab.txt | 1 +
| |  3 files changed, 3 insertions(+)
| * d2d2136 change 2 made
| |  a.txt     | 1 +
| |  aa/aa.txt | 1 +
| |  aa/ab.txt | 1 +
| |  3 files changed, 3 insertions(+)
| * ab237ac change 1 made
|/
|    a.txt     | 1 +
|    aa/aa.txt | 1 +
|    aa/ab.txt | 1 +
|    3 files changed, 3 insertions(+)
* ea0a32d added a.txt
   a.txt | 1 +
   1 file changed, 1 insertion(+)
</code>```

... which confirms that this is the filtered state of the repository that I wanted - and I guess, this I'd want to merge into my newrepo_git now.

Ok, so it turns out, I don't quite want to "merge" into newrepo_git, I want to "join" - most of the info for here I found in Join two Git repositories and keep the original commit dates. - axiac@web

So, first, we change directory to newrepo:

```<code>cd ../newrepo_git
</code>```

Note that at this point, most of the resources online will recommend:

```<code>git remote add oldrepo ../oldrepo_filt_git/
git pull oldrepo master --allow-unrelated-histories
</code>```

... but this will result with a history with two roots - which is not what I want:

```<code>$ git log --oneline --graph --stat
*   845c81e (HEAD -> master) Merge branch 'master' of ../oldrepo_filt_git
|\
| *   31cd8b5 (oldrepo/master) Merge branch 'testbranch'
| |\
| | * 42b153d (oldrepo/testbranch) change 5 made
| | |  a.txt     | 1 +
| | |  aa/aa.txt | 1 +
| | |  aa/ab.txt | 1 +
| | |  3 files changed, 3 insertions(+)
| | * ff1be9d change 4 made
| | |  a.txt     | 1 +
| | |  aa/aa.txt | 1 +
| | |  aa/ab.txt | 1 +
| | |  3 files changed, 3 insertions(+)
| | * 90f050c change 3 made
| | |  a.txt     | 1 +
| | |  aa/aa.txt | 1 +
| | |  aa/ab.txt | 1 +
| | |  3 files changed, 3 insertions(+)
| | * d2d2136 change 2 made
| | |  a.txt     | 1 +
| | |  aa/aa.txt | 1 +
| | |  aa/ab.txt | 1 +
| | |  3 files changed, 3 insertions(+)
| | * ab237ac change 1 made
| |/
| |    a.txt     | 1 +
| |    aa/aa.txt | 1 +
| |    aa/ab.txt | 1 +
| |    3 files changed, 3 insertions(+)
| * ea0a32d added a.txt
|    a.txt | 1 +
|    1 file changed, 1 insertion(+)
* 8e99c2d Initial commit by Bob
   README | 1 +
   1 file changed, 1 insertion(+)
</code>```

What I want, instead, is that commit ea0a32d added a.txt follows/stems from 8e99c2d Initial commit by Bob -> that would be the "joining" of repositories mentioned earlier.

Note also, you could do git format-patch --root HEAD -o ../ from oldrepo_git, and then import the patches in newrepo_git with for ix in ../*.patch; do echo $ix; git am -k < $ix; done - but this will not preserve merge history (all history will be flattened)!

So, in order to do a proper "joining", instead, I do first a fetch:

```<code>$ git remote add old-repo ../oldrepo_filt_git

$ git fetch old-repo
warning: no common commits
remote: Enumerating objects: 29, done.
remote: Counting objects: 100% (29/29), done.
remote: Compressing objects: 100% (17/17), done.
remote: Total 29 (delta 2), reused 0 (delta 0)
Unpacking objects: 100% (29/29), done.
From ../oldrepo_filt_git
 * [new branch]      master     -> old-repo/master
 * [new branch]      testbranch -> old-repo/testbranch
</code>```

... then adding and renaming of branches, (and saving of timestamps in /tmp/hashlist) as recommended in the post - and then cherry-pick the first commit in old-repo:

```<code>cd oldrepo_filt_git
git filter-branch --index-filter "git rm --cached --ignore-unmatch -r $(bash -O extglob -c 'ls -xd !(a*)')" --prune-empty -- --all
</code>```0

At this point, the repo state is:

```<code>cd oldrepo_filt_git
git filter-branch --index-filter "git rm --cached --ignore-unmatch -r $(bash -O extglob -c 'ls -xd !(a*)')" --prune-empty -- --all
</code>```1

Now, here we can do a rebase - note that in the cited post, they get an error here, but for this particular example, it seems to proceed without an error:

```<code>cd oldrepo_filt_git
git filter-branch --index-filter "git rm --cached --ignore-unmatch -r $(bash -O extglob -c 'ls -xd !(a*)')" --prune-empty -- --all
</code>```2

At this point, the newrepo history is almost there - the only problem is that the commit timestamps are different:

```<code>$ git log --graph --pretty=fuller
*   commit 61fbe54721a9432e91e48917ed036f55da4105a4 (HEAD -> oldrepo-head)
|\  Merge: 427cf77 f8e8f8a
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:32:10 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Tue May 28 12:57:00 2019 +0200
| |
| |     Merge branch 'testbranch'
| |
| * commit f8e8f8aedaa7bc999bdfdd49542c9ee04edb770c
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:32:00 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Tue May 28 12:56:58 2019 +0200
| |
| |     change 5 made
| |
| * commit b084029040d6596e0795e7567b2684dc59c02241
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:31:50 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Tue May 28 12:56:56 2019 +0200
| |
| |     change 4 made
| |
| * commit b62dabca3a46efbe76edb10591935db136f74aaa
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:31:40 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Tue May 28 12:56:54 2019 +0200
| |
| |     change 3 made
| |
| * commit 252f3e9697b87b4f59cd0a74681ef25401340fcf
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:31:30 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Tue May 28 12:56:51 2019 +0200
| |
| |     change 2 made
| |
| * commit c382c8a713489ca0e5dc106bed29fdce379952b0
|/  Author:     tester <tester@example.com>
|   AuthorDate: Mon May 27 14:31:20 2019 +0200
|   Commit:     bob <bob@example.com>
|   CommitDate: Tue May 28 12:56:49 2019 +0200
|
|       change 1 made
|
* commit 427cf77417a2406db5dd6a0e9bd4fb60542f2ee1 (new-master)
| Author:     tester <tester@example.com>
| AuthorDate: Mon May 27 14:31:10 2019 +0200
| Commit:     bob <bob@example.com>
| CommitDate: Tue May 28 12:55:43 2019 +0200
|
|     added a.txt
|
* commit 8e99c2d71048b4999d012b33d34386351d6d0fef
  Author:     bob <bob@example.com>
  AuthorDate: Mon May 27 14:31:00 2019 +0200
  Commit:     bob <bob@example.com>
  CommitDate: Mon May 27 14:31:00 2019 +0200

      Initial commit by Bob
</code>```

They have the same problem in the cited post, too, and the suggestion is to use filter-branch to rewrite the commit timestamps, to be the same as the author timestamps:

```<code>$ git filter-branch --env-filter 'export GIT_COMMITTER_DATE=$(fgrep -m 1 $(git log -1 --pretty=%T $GIT_COMMIT) /tmp/hashlist | cut -d" " -f2)' new-master..oldrepo-head
Rewrite 61fbe54721a9432e91e48917ed036f55da4105a4 (3/6) (1 seconds passed, remaining 1 predicted)
Ref 'refs/heads/oldrepo-head' was rewritten
</code>```

... however, this did not work for me, because by now, the commit hashes have changed from what was there in /tmp/hashlist.

So, I used an easier approach - simply have filter-branch read the author date timestamp at each commit, and copy/reapply it as committer date (note I use -f here to compensate for the effects of the previous filter-branch, otherwise I get "Cannot create a new backup. ... Force overwriting the backup with -f"):

```<code>$ git filter-branch -f --env-filter 'export GIT_COMMITTER_DATE=$(git log -1 --pretty=%at $GIT_COMMIT)' new-master..oldrepo-head
Rewrite f2b2385d85c74dbf0cbf8fabc02ec30cb50d8f2a (3/6) (1 seconds passed, remaining 1 predicted)
Ref 'refs/heads/oldrepo-head' was rewritten
</code>```

At this point, we can see that the state of the repo is almost as I need it - except the first oldrepo commit does not have the commit timestamp changed; so I try again:

```<code>sd@DESKTOP-RO11QOC MSYS /c/Users/sd/AppData/Local/Temp/newrepo_git
$ git filter-branch -f --env-filter 'export GIT_COMMITTER_DATE=$(git log -1 --pretty=%at $GIT_COMMIT)' 427cf77417a
You must specify a ref to rewrite.

sd@DESKTOP-RO11QOC MSYS /c/Users/sd/AppData/Local/Temp/newrepo_git
$ git filter-branch -f --env-filter 'export GIT_COMMITTER_DATE=$(git log -1 --pretty=%at $GIT_COMMIT)' new-master
Rewrite 427cf77417a2406db5dd6a0e9bd4fb60542f2ee1 (2/2) (0 seconds passed, remaining 0 predicted)
Ref 'refs/heads/new-master' was rewritten
</code>```

... but it still shows the same difference between timestamps in log:

```<code>$ git log --graph --stat --pretty=fuller
*   commit cdaa4b82f3833770a9051a2490487548603e3af8 (HEAD -> oldrepo-head)
|\  Merge: 427cf77 9bfc6cd
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:32:10 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Mon May 27 14:32:10 2019 +0200
| |
| |     Merge branch 'testbranch'
| |
...
* commit 427cf77417a2406db5dd6a0e9bd4fb60542f2ee1 (refs/original/refs/heads/new-master)
| Author:     tester <tester@example.com>
| AuthorDate: Mon May 27 14:31:10 2019 +0200
| Commit:     bob <bob@example.com>
| CommitDate: Tue May 28 12:55:43 2019 +0200
|
|     added a.txt
|
|  a.txt | 1 +
|  1 file changed, 1 insertion(+)
...
</code>```

Anyways, now we should "cleanup" as recommended in the post:

```<code>$ git branch -m oldrepo-head master
$ git branch -D oldrepo-root
Deleted branch oldrepo-root (was ea0a32d).
$ git branch -D new-master
Deleted branch new-master (was 4ac225e).
$ rm .git/refs/original/refs/heads/new-master
$ git remote remove old-repo
</code>```

And finally, I managed to overwrite the commit timestamp for commit 427cf774, by adding a temporary branch there (since filter-branch needs a ref, it seemingly cannot use a commit hash directly), and using it to specify tmp^..tmp as the filter-branch range:

```<code>$ git branch tmp 427cf774
$ git filter-branch -f --env-filter 'export GIT_COMMITTER_DATE=$(git log -1 --pretty=%at $GIT_COMMIT)' tmp^..tmp
Rewrite 427cf77417a2406db5dd6a0e9bd4fb60542f2ee1 (1/1) (0 seconds passed, remaining 0 predicted)
Ref 'refs/heads/tmp' was rewritten
$ git log --graph --stat --pretty=fuller tmp
* commit 4ac225e308e280e3a96be0168c6e9dece44d4979 (tmp)
| Author:     tester <tester@example.com>
| AuthorDate: Mon May 27 14:31:10 2019 +0200
| Commit:     bob <bob@example.com>
| CommitDate: Mon May 27 14:31:10 2019 +0200
|
|     added a.txt
|
|  a.txt | 1 +
|  1 file changed, 1 insertion(+)
|
...
$ git branch -D tmp
Deleted branch tmp (was 4ac225e).
</code>```

... and finally, I can see that newrepo contains oldrepo commits as I envisioned them:

```<code>$ ls
a.txt  aa  b.txt  bb  README
</code>```0

Easy, eh? :)

But I'm not really sure if this is the right process - so if anyone more knowledgeable can confirm it - or if there is an easier way, - that would be great ...

Body:
Please consider the Bash script testgit.sh, pasted at the end of this post, which will reconstruct the repository examples here.

So, I have oldrepo_git repository, which has some files and folders - and then, a newrepo_git repository, which has just a single commit (for a README). This is what gitk --all sees in these repos:

Basically, I want to export the entire git history for the file a.txt and the entirety of the aa subfolder (so, the aa/aa.txt and aa/ab.txt files - but not the README or b.txt files) from the oldrepo_git repository, and import it in the newrepo_git repository - if possible, with the right timestamps, and branching/merging info.

Since the file called README in oldrepo_git is not part of this operation, and since newrepo_git has nothing else but a README file, I wouldn't expect any conflicts to occur. However, I'm not sure what commands I can use to do this: I'm aware there is git filter-branch, but as far as I know, it will change the history of oldrepo_git "in-place" - it will not "import" this history into newrepo_git.

In other words, if the history of oldrepo_git is:

$ git log --oneline --graph
*   7e26890 (HEAD -> master) Merge branch 'testbranch'
|\
| * 56ef109 (testbranch) change 5 made
| * 1a78db3 change 4 made
| * d98b4cf change 3 made
| * e5e49af change 2 made
| * 8704c24 change 1 made
|/
* f318d97 added a.txt
* 252bf7f Initial commit

... after the process is done, I would like to see this as the history of newrepo_git:

$ git log --oneline --graph
*   XXXYYGG (HEAD -> master) Merge branch 'testbranch'
|\
| * XXXYYFF (testbranch) change 5 made
| * XXXYYEE change 4 made
| * XXXYYDD change 3 made
| * XXXYYCC change 2 made
| * XXXYYBB change 1 made
|/
* XXXYYAA added a.txt
* 8e99c2d Initial commit by Bob

How could I perform this operation?

The Bash script testgit.sh:

#!/usr/bin/env bash

rm -rf oldrepo_git newrepo_git
mkdir oldrepo_git newrepo_git

cd oldrepo_git
git init
git config user.name tester
git config user.email tester@example.com
echo "# README" >> README
git add README
GIT_COMMITTER_DATE="1558960260" git commit --date "1558960260" -m "Initial commit"
echo "Testing" >> a.txt
git add a.txt
GIT_COMMITTER_DATE="1558960270" git commit --date "1558960270" -m "added a.txt"
git checkout -b testbranch
mkdir aa bb
for ix in 1 2 3 4 5; do
  echo $ix >> a.txt
  echo $ix >> b.txt
  echo $ix >> aa/aa.txt
  echo $ix >> aa/ab.txt
  git add .
  newts="$((1558960270+ix*10))"
  GIT_COMMITTER_DATE="$newts" git commit --date "$newts" -m "change $ix made"
done
git checkout master
ix="$((ix+1))"; newts="$((1558960270+ix*10))"
GIT_COMMITTER_DATE="$newts" GIT_AUTHOR_DATE="$newts" git merge --no-ff --no-edit testbranch

cd ../newrepo_git
git init
git config user.name bob
git config user.email bob@example.com
echo "# Bob's README" >> README
git add README
GIT_COMMITTER_DATE="1558960260" git commit --date "1558960260" -m "Initial commit by Bob"

Body:
EDIT: you may want to add an extra echo $ix >> bb/bb.txt in the for loop in the testgit.sh script in OP, so that the output in this post matches.

Ok, I guess this is how it should be done - at least in relation to the OP (where we don't have remote repos yet); first, copy the oldrepo:

cp -a oldrepo_git oldrepo_filt_git

Then apparently we have to delete all the stuff we don't want in the copied oldrepo, by using git filter-branch in combination with git rm - part of this command I found here: Detach many subdirectories into a new, separate Git repository

cd oldrepo_filt_git
git filter-branch --index-filter "git rm --cached --ignore-unmatch -r $(bash -O extglob -c 'ls -xd !(a*)')" --prune-empty -- --all

Note, since here we want to tell to git rm what to delete, we want to specify what we do not want to keep, as the inverse of what we want to keep; and here I want to keep a.txt file and aa folder - so a glob match would be a*. Then you need the bash extglob function to get that; so if a whole list is:

$ ls
a.txt  aa  b.txt  bb  README

... then the extglob stanza which will give us only the file/folder names to delete gives:

$ bash -O extglob -c 'ls -xd !(a*)'
b.txt  bb  README

So, after git filter-branch command is ran:

$ git filter-branch --index-filter "git rm --cached --ignore-unmatch -r $(bash -O extglob -c 'ls -xd !(a*)')" --prune-empty -- --all
Rewrite 252bf7ff5f385dad880240d5d80e68f24ae09b59 (1/8) (0 seconds passed, remaining 0 predicted)    rm 'README'
Rewrite f318d9712cd7aacdb5dd45febbcdbbce6b741e08 (2/8) (1 seconds passed, remaining 3 predicted)    rm 'README'
Rewrite 00b62e7da8784d45850d7483cbea88fdc4aa844c (2/8) (1 seconds passed, remaining 3 predicted)    rm 'README'
rm 'b.txt'
rm 'bb/bb.txt'
Rewrite c618eff47d38412c54a8381a5bacc921bddefe2d (2/8) (1 seconds passed, remaining 3 predicted)    rm 'README'
rm 'b.txt'
rm 'bb/bb.txt'
Rewrite 2cada8d822d83f37bdc4a37bcfb03047c1cc1ded (5/8) (3 seconds passed, remaining 1 predicted)    rm 'README'
rm 'b.txt'
rm 'bb/bb.txt'
Rewrite 7b296b70018f4105f190d06ed4d9c58e3f80532f (5/8) (3 seconds passed, remaining 1 predicted)    rm 'README'
rm 'b.txt'
rm 'bb/bb.txt'
Rewrite 18a1ad1d35cd8573c39485d0a29b630325f9727d (7/8) (5 seconds passed, remaining 0 predicted)    rm 'README'
rm 'b.txt'
rm 'bb/bb.txt'
Rewrite 2ffbbf03d51363f1ced3aaaf000d5921c9d8b919 (7/8) (5 seconds passed, remaining 0 predicted)    rm 'README'
rm 'b.txt'
rm 'bb/bb.txt'

Ref 'refs/heads/master' was rewritten
Ref 'refs/heads/testbranch' was rewritten

... we have:

$ git log --oneline --graph --stat
*   31cd8b5 (HEAD -> master) Merge branch 'testbranch'
|\
| * 42b153d (testbranch) change 5 made
| |  a.txt     | 1 +
| |  aa/aa.txt | 1 +
| |  aa/ab.txt | 1 +
| |  3 files changed, 3 insertions(+)
| * ff1be9d change 4 made
| |  a.txt     | 1 +
| |  aa/aa.txt | 1 +
| |  aa/ab.txt | 1 +
| |  3 files changed, 3 insertions(+)
| * 90f050c change 3 made
| |  a.txt     | 1 +
| |  aa/aa.txt | 1 +
| |  aa/ab.txt | 1 +
| |  3 files changed, 3 insertions(+)
| * d2d2136 change 2 made
| |  a.txt     | 1 +
| |  aa/aa.txt | 1 +
| |  aa/ab.txt | 1 +
| |  3 files changed, 3 insertions(+)
| * ab237ac change 1 made
|/
|    a.txt     | 1 +
|    aa/aa.txt | 1 +
|    aa/ab.txt | 1 +
|    3 files changed, 3 insertions(+)
* ea0a32d added a.txt
   a.txt | 1 +
   1 file changed, 1 insertion(+)

... which confirms that this is the filtered state of the repository that I wanted - and I guess, this I'd want to merge into my newrepo_git now.

Ok, so it turns out, I don't quite want to "merge" into newrepo_git, I want to "join" - most of the info for here I found in Join two Git repositories and keep the original commit dates. - axiac@web

So, first, we change directory to newrepo:

cd ../newrepo_git

Note that at this point, most of the resources online will recommend:

git remote add oldrepo ../oldrepo_filt_git/
git pull oldrepo master --allow-unrelated-histories

... but this will result with a history with two roots - which is not what I want:

$ git log --oneline --graph --stat
*   845c81e (HEAD -> master) Merge branch 'master' of ../oldrepo_filt_git
|\
| *   31cd8b5 (oldrepo/master) Merge branch 'testbranch'
| |\
| | * 42b153d (oldrepo/testbranch) change 5 made
| | |  a.txt     | 1 +
| | |  aa/aa.txt | 1 +
| | |  aa/ab.txt | 1 +
| | |  3 files changed, 3 insertions(+)
| | * ff1be9d change 4 made
| | |  a.txt     | 1 +
| | |  aa/aa.txt | 1 +
| | |  aa/ab.txt | 1 +
| | |  3 files changed, 3 insertions(+)
| | * 90f050c change 3 made
| | |  a.txt     | 1 +
| | |  aa/aa.txt | 1 +
| | |  aa/ab.txt | 1 +
| | |  3 files changed, 3 insertions(+)
| | * d2d2136 change 2 made
| | |  a.txt     | 1 +
| | |  aa/aa.txt | 1 +
| | |  aa/ab.txt | 1 +
| | |  3 files changed, 3 insertions(+)
| | * ab237ac change 1 made
| |/
| |    a.txt     | 1 +
| |    aa/aa.txt | 1 +
| |    aa/ab.txt | 1 +
| |    3 files changed, 3 insertions(+)
| * ea0a32d added a.txt
|    a.txt | 1 +
|    1 file changed, 1 insertion(+)
* 8e99c2d Initial commit by Bob
   README | 1 +
   1 file changed, 1 insertion(+)

What I want, instead, is that commit ea0a32d added a.txt follows/stems from 8e99c2d Initial commit by Bob -> that would be the "joining" of repositories mentioned earlier.

Note also, you could do git format-patch --root HEAD -o ../ from oldrepo_git, and then import the patches in newrepo_git with for ix in ../*.patch; do echo $ix; git am -k < $ix; done - but this will not preserve merge history (all history will be flattened)!

So, in order to do a proper "joining", instead, I do first a fetch:

$ git remote add old-repo ../oldrepo_filt_git

$ git fetch old-repo
warning: no common commits
remote: Enumerating objects: 29, done.
remote: Counting objects: 100% (29/29), done.
remote: Compressing objects: 100% (17/17), done.
remote: Total 29 (delta 2), reused 0 (delta 0)
Unpacking objects: 100% (29/29), done.
From ../oldrepo_filt_git
 * [new branch]      master     -> old-repo/master
 * [new branch]      testbranch -> old-repo/testbranch

... then adding and renaming of branches, (and saving of timestamps in /tmp/hashlist) as recommended in the post - and then cherry-pick the first commit in old-repo:

$ git branch oldrepo-head old-repo/master
Branch 'oldrepo-head' set up to track remote branch 'master' from 'old-repo'.

$ git branch oldrepo-root $(git log oldrepo-head --reverse --pretty=%H | head -n 1)

$ git log --pretty='%T %ct' ..oldrepo-head > /tmp/hashlist

$ git branch -m master new-master

$ git cherry-pick --strategy-option=theirs oldrepo-root
[new-master 427cf77] added a.txt
 Author: tester <tester@example.com>
 Date: Mon May 27 14:31:10 2019 +0200
 1 file changed, 1 insertion(+)
 create mode 100644 a.txt

At this point, the repo state is:

$ git log --oneline --graph
* 427cf77 (HEAD -> new-master) added a.txt
* 8e99c2d Initial commit by Bob

Now, here we can do a rebase - note that in the cited post, they get an error here, but for this particular example, it seems to proceed without an error:

$ git rebase --preserve-merges --onto new-master --root oldrepo-head
Successfully rebased and updated refs/heads/oldrepo-head.

At this point, the newrepo history is almost there - the only problem is that the commit timestamps are different:

$ git log --graph --pretty=fuller
*   commit 61fbe54721a9432e91e48917ed036f55da4105a4 (HEAD -> oldrepo-head)
|\  Merge: 427cf77 f8e8f8a
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:32:10 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Tue May 28 12:57:00 2019 +0200
| |
| |     Merge branch 'testbranch'
| |
| * commit f8e8f8aedaa7bc999bdfdd49542c9ee04edb770c
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:32:00 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Tue May 28 12:56:58 2019 +0200
| |
| |     change 5 made
| |
| * commit b084029040d6596e0795e7567b2684dc59c02241
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:31:50 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Tue May 28 12:56:56 2019 +0200
| |
| |     change 4 made
| |
| * commit b62dabca3a46efbe76edb10591935db136f74aaa
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:31:40 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Tue May 28 12:56:54 2019 +0200
| |
| |     change 3 made
| |
| * commit 252f3e9697b87b4f59cd0a74681ef25401340fcf
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:31:30 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Tue May 28 12:56:51 2019 +0200
| |
| |     change 2 made
| |
| * commit c382c8a713489ca0e5dc106bed29fdce379952b0
|/  Author:     tester <tester@example.com>
|   AuthorDate: Mon May 27 14:31:20 2019 +0200
|   Commit:     bob <bob@example.com>
|   CommitDate: Tue May 28 12:56:49 2019 +0200
|
|       change 1 made
|
* commit 427cf77417a2406db5dd6a0e9bd4fb60542f2ee1 (new-master)
| Author:     tester <tester@example.com>
| AuthorDate: Mon May 27 14:31:10 2019 +0200
| Commit:     bob <bob@example.com>
| CommitDate: Tue May 28 12:55:43 2019 +0200
|
|     added a.txt
|
* commit 8e99c2d71048b4999d012b33d34386351d6d0fef
  Author:     bob <bob@example.com>
  AuthorDate: Mon May 27 14:31:00 2019 +0200
  Commit:     bob <bob@example.com>
  CommitDate: Mon May 27 14:31:00 2019 +0200

      Initial commit by Bob

They have the same problem in the cited post, too, and the suggestion is to use filter-branch to rewrite the commit timestamps, to be the same as the author timestamps:

$ git filter-branch --env-filter 'export GIT_COMMITTER_DATE=$(fgrep -m 1 $(git log -1 --pretty=%T $GIT_COMMIT) /tmp/hashlist | cut -d" " -f2)' new-master..oldrepo-head
Rewrite 61fbe54721a9432e91e48917ed036f55da4105a4 (3/6) (1 seconds passed, remaining 1 predicted)
Ref 'refs/heads/oldrepo-head' was rewritten

... however, this did not work for me, because by now, the commit hashes have changed from what was there in /tmp/hashlist.

So, I used an easier approach - simply have filter-branch read the author date timestamp at each commit, and copy/reapply it as committer date (note I use -f here to compensate for the effects of the previous filter-branch, otherwise I get "Cannot create a new backup. ... Force overwriting the backup with -f"):

$ git filter-branch -f --env-filter 'export GIT_COMMITTER_DATE=$(git log -1 --pretty=%at $GIT_COMMIT)' new-master..oldrepo-head
Rewrite f2b2385d85c74dbf0cbf8fabc02ec30cb50d8f2a (3/6) (1 seconds passed, remaining 1 predicted)
Ref 'refs/heads/oldrepo-head' was rewritten

At this point, we can see that the state of the repo is almost as I need it - except the first oldrepo commit does not have the commit timestamp changed; so I try again:

sd@DESKTOP-RO11QOC MSYS /c/Users/sd/AppData/Local/Temp/newrepo_git
$ git filter-branch -f --env-filter 'export GIT_COMMITTER_DATE=$(git log -1 --pretty=%at $GIT_COMMIT)' 427cf77417a
You must specify a ref to rewrite.

sd@DESKTOP-RO11QOC MSYS /c/Users/sd/AppData/Local/Temp/newrepo_git
$ git filter-branch -f --env-filter 'export GIT_COMMITTER_DATE=$(git log -1 --pretty=%at $GIT_COMMIT)' new-master
Rewrite 427cf77417a2406db5dd6a0e9bd4fb60542f2ee1 (2/2) (0 seconds passed, remaining 0 predicted)
Ref 'refs/heads/new-master' was rewritten

... but it still shows the same difference between timestamps in log:

$ git log --graph --stat --pretty=fuller
*   commit cdaa4b82f3833770a9051a2490487548603e3af8 (HEAD -> oldrepo-head)
|\  Merge: 427cf77 9bfc6cd
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:32:10 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Mon May 27 14:32:10 2019 +0200
| |
| |     Merge branch 'testbranch'
| |
...
* commit 427cf77417a2406db5dd6a0e9bd4fb60542f2ee1 (refs/original/refs/heads/new-master)
| Author:     tester <tester@example.com>
| AuthorDate: Mon May 27 14:31:10 2019 +0200
| Commit:     bob <bob@example.com>
| CommitDate: Tue May 28 12:55:43 2019 +0200
|
|     added a.txt
|
|  a.txt | 1 +
|  1 file changed, 1 insertion(+)
...

Anyways, now we should "cleanup" as recommended in the post:

$ git branch -m oldrepo-head master
$ git branch -D oldrepo-root
Deleted branch oldrepo-root (was ea0a32d).
$ git branch -D new-master
Deleted branch new-master (was 4ac225e).
$ rm .git/refs/original/refs/heads/new-master
$ git remote remove old-repo

And finally, I managed to overwrite the commit timestamp for commit 427cf774, by adding a temporary branch there (since filter-branch needs a ref, it seemingly cannot use a commit hash directly), and using it to specify tmp^..tmp as the filter-branch range:

$ git branch tmp 427cf774
$ git filter-branch -f --env-filter 'export GIT_COMMITTER_DATE=$(git log -1 --pretty=%at $GIT_COMMIT)' tmp^..tmp
Rewrite 427cf77417a2406db5dd6a0e9bd4fb60542f2ee1 (1/1) (0 seconds passed, remaining 0 predicted)
Ref 'refs/heads/tmp' was rewritten
$ git log --graph --stat --pretty=fuller tmp
* commit 4ac225e308e280e3a96be0168c6e9dece44d4979 (tmp)
| Author:     tester <tester@example.com>
| AuthorDate: Mon May 27 14:31:10 2019 +0200
| Commit:     bob <bob@example.com>
| CommitDate: Mon May 27 14:31:10 2019 +0200
|
|     added a.txt
|
|  a.txt | 1 +
|  1 file changed, 1 insertion(+)
|
...
$ git branch -D tmp
Deleted branch tmp (was 4ac225e).

... and finally, I can see that newrepo contains oldrepo commits as I envisioned them:

$ git log --graph --stat --pretty=fuller
*   commit cdaa4b82f3833770a9051a2490487548603e3af8
|\  Merge: 427cf77 9bfc6cd
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:32:10 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Mon May 27 14:32:10 2019 +0200
| |
| |     Merge branch 'testbranch'
| |
| * commit 9bfc6cde58be9102102f839e5cc0fe8f25f0f78c
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:32:00 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Mon May 27 14:32:00 2019 +0200
| |
| |     change 5 made
| |
| |  a.txt     | 1 +
| |  aa/aa.txt | 1 +
| |  aa/ab.txt | 1 +
| |  3 files changed, 3 insertions(+)
| |
| * commit 485ae0f50054610b6a41098fb695e59d194cc856
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:31:50 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Mon May 27 14:31:50 2019 +0200
| |
| |     change 4 made
| |
| |  a.txt     | 1 +
| |  aa/aa.txt | 1 +
| |  aa/ab.txt | 1 +
| |  3 files changed, 3 insertions(+)
| |
| * commit b6804b6e8e313b5c4766568a287f0785503e3a11
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:31:40 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Mon May 27 14:31:40 2019 +0200
| |
| |     change 3 made
| |
| |  a.txt     | 1 +
| |  aa/aa.txt | 1 +
| |  aa/ab.txt | 1 +
| |  3 files changed, 3 insertions(+)
| |
| * commit 8b463423d2a99929a6a248e38ba1368a56d3769d
| | Author:     tester <tester@example.com>
| | AuthorDate: Mon May 27 14:31:30 2019 +0200
| | Commit:     bob <bob@example.com>
| | CommitDate: Mon May 27 14:31:30 2019 +0200
| |
| |     change 2 made
| |
| |  a.txt     | 1 +
| |  aa/aa.txt | 1 +
| |  aa/ab.txt | 1 +
| |  3 files changed, 3 insertions(+)
| |
| * commit 3bc0bed30ebea1498a15711825b2ea8347cc374d
|/  Author:     tester <tester@example.com>
|   AuthorDate: Mon May 27 14:31:20 2019 +0200
|   Commit:     bob <bob@example.com>
|   CommitDate: Mon May 27 14:31:20 2019 +0200
|
|       change 1 made
|
|    a.txt     | 1 +
|    aa/aa.txt | 1 +
|    aa/ab.txt | 1 +
|    3 files changed, 3 insertions(+)
|
* commit 427cf77417a2406db5dd6a0e9bd4fb60542f2ee1
| Author:     tester <tester@example.com>
| AuthorDate: Mon May 27 14:31:10 2019 +0200
| Commit:     bob <bob@example.com>
| CommitDate: Tue May 28 12:55:43 2019 +0200
|
|     added a.txt
|
|  a.txt | 1 +
|  1 file changed, 1 insertion(+)
|
* commit 8e99c2d71048b4999d012b33d34386351d6d0fef
  Author:     bob <bob@example.com>
  AuthorDate: Mon May 27 14:31:00 2019 +0200
  Commit:     bob <bob@example.com>
  CommitDate: Mon May 27 14:31:00 2019 +0200

      Initial commit by Bob

   README | 1 +
   1 file changed, 1 insertion(+)

Easy, eh? :)

But I'm not really sure if this is the right process - so if anyone more knowledgeable can confirm it - or if there is an easier way, - that would be great ...


来源: stackexchange

问:
Want to grep in .tar.gz file in Solaris
i have a file in .tar.gz format in solaris. i want to grep some line from that. i am using zipgrep command but unable to find the line. Below is my sample file and command that i am using.

Sample file:

BD201701.tar.gz

BD201702.tar.gz

BD201703.tar.gz

i am using below command to search a line that contains bangladesh.

```<code>zipgrep 'bangladesh' BD2017*
</code>```

But it;s showing below error.

```<code>[BD201701.tar.gz]
End-of-central-directory signature not found.  Either this file is not
a zipfile, or it constitutes one disk of a multi-part archive.  In the
latter case the central directory and zipfile comment will be found on
the last disk(s) of this archive.
zipinfo:  cannot find zipfile directory in one of BD201701.tar.gz or
      BD201701.tar.gz.zip, and cannot find BD201701.tar.gz.ZIP, period.
/usr/bin/zipgrep: test: argument expected
</code>```

答:
zgrep does not work on solaris servers. In case the requirement is to find a pattern in a/all file(s) inside a directory given that the files are zipped, the following command can be used.

```<code>gzgrep 'pattern' filename
</code>```

or

```<code>gzgrep 'bangladesh' BD2017*
</code>```

ContentLicense: CC BY-SA 3.0

Title: Want to grep in .tar.gz file in Solaris

Body:
i have a file in .tar.gz format in solaris. i want to grep some line from that. i am using zipgrep command but unable to find the line. Below is my sample file and command that i am using.

Sample file:

BD201701.tar.gz

BD201702.tar.gz

BD201703.tar.gz

i am using below command to search a line that contains bangladesh.

zipgrep 'bangladesh' BD2017*

But it;s showing below error.

[BD201701.tar.gz]
End-of-central-directory signature not found.  Either this file is not
a zipfile, or it constitutes one disk of a multi-part archive.  In the
latter case the central directory and zipfile comment will be found on
the last disk(s) of this archive.
zipinfo:  cannot find zipfile directory in one of BD201701.tar.gz or
      BD201701.tar.gz.zip, and cannot find BD201701.tar.gz.ZIP, period.
/usr/bin/zipgrep: test: argument expected

Body:
zgrep does not work on solaris servers. In case the requirement is to find a pattern in a/all file(s) inside a directory given that the files are zipped, the following command can be used.

gzgrep 'pattern' filename

or

gzgrep 'bangladesh' BD2017*

ContentLicense: CC BY-SA 4.0


问:
Express cors not allowing credentials
I have a frontend setup with react and a back-end made with express and mongodb, I have a component which needs to make a fetch request including the credentials with should be already set. All of the routes work on postman but I'm not able to recreate the functionality with the fetch function.
Express server:

```<code>...
    server.use(helmet());
    server.use(compression());
    server.use(cors({
      credentials: true,
    }));

    if (process.env.NODE_ENV !== "production") {
      server.use(logger("dev"));
    }
    server.use(express.json());
    server.use(express.urlencoded({ extended: false }));

    server.use(cookieParser());

    server.use(
      session({
        secret: process.env.COOKIE_SECRET,
        resave: true,
        saveUninitialized: false,
        store: new MongoStore({ mongooseConnection: mongoose.connection })
      })
    );

    server.use(auth.initialize);
    server.use(auth.session);
    server.use(auth.setUser);

    //API ROUTES
    server.use("/user", require("./api/routes/user"));
    server.use("/pitch", require("./api/routes/pitch"));
    server.use("/match", require("./api/routes/matchmaking"));
...
</code>```

User routes:

```<code>router.post("/login", passport.authenticate("local"), (req, res, next) => {
  return res.status(200).json({
    message: "User logged in correctly",
    redirect: "/"
  });
});

router.get("/checklogin", (req, res, next) => {
  if (req.user) return next();
  else
    return res.status(401).json({
      error: "User not authenticated"
    });
},
 (req, res, next) => {
  return res.status(200).json({
    message: "User logged in correctly",
    redirect: "/"
  });
});
</code>```

Frontend:

```<code>  useEffect(() => {
    async function fetchData() {
      const response = await fetch("http://localhost:8000/user/checklogin", {
        credentials: 'include'
      });
      const data = await response.json();

      console.log(data);

    }

    fetchData();
  }, []);
</code>```

Using this code I get this error

```<code>Access to fetch at 'http://localhost:8000/user/checklogin' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
</code>```

As I said prior everything works on postman but not with the fetch function.

答:
You can do something like this
in express

```<code>app.use(cors({credentials: true, origin: 'http://localhost:3000'}));
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", 'http://localhost:3000');
    res.header("Access-Control-Allow-Credentials", true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
    next();
});
</code>```

in router

```<code>router.all('*', cors());
</code>```

while sending response do

```<code> res.header("Access-Control-Allow-Origin", 'http://localhost:3000');
 res.json(someJson)
</code>```

Title: Express cors not allowing credentials

Body:
I have a frontend setup with react and a back-end made with express and mongodb, I have a component which needs to make a fetch request including the credentials with should be already set. All of the routes work on postman but I'm not able to recreate the functionality with the fetch function.
Express server:

...
    server.use(helmet());
    server.use(compression());
    server.use(cors({
      credentials: true,
    }));

    if (process.env.NODE_ENV !== "production") {
      server.use(logger("dev"));
    }
    server.use(express.json());
    server.use(express.urlencoded({ extended: false }));

    server.use(cookieParser());

    server.use(
      session({
        secret: process.env.COOKIE_SECRET,
        resave: true,
        saveUninitialized: false,
        store: new MongoStore({ mongooseConnection: mongoose.connection })
      })
    );

    server.use(auth.initialize);
    server.use(auth.session);
    server.use(auth.setUser);

    //API ROUTES
    server.use("/user", require("./api/routes/user"));
    server.use("/pitch", require("./api/routes/pitch"));
    server.use("/match", require("./api/routes/matchmaking"));
...

User routes:

router.post("/login", passport.authenticate("local"), (req, res, next) => {
  return res.status(200).json({
    message: "User logged in correctly",
    redirect: "/"
  });
});

router.get("/checklogin", (req, res, next) => {
  if (req.user) return next();
  else
    return res.status(401).json({
      error: "User not authenticated"
    });
},
 (req, res, next) => {
  return res.status(200).json({
    message: "User logged in correctly",
    redirect: "/"
  });
});

Frontend:

  useEffect(() => {
    async function fetchData() {
      const response = await fetch("http://localhost:8000/user/checklogin", {
        credentials: 'include'
      });
      const data = await response.json();

      console.log(data);

    }

    fetchData();
  }, []);

Using this code I get this error

Access to fetch at 'http://localhost:8000/user/checklogin' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

As I said prior everything works on postman but not with the fetch function.

Body:
You can do something like this
in express

app.use(cors({credentials: true, origin: 'http://localhost:3000'}));
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", 'http://localhost:3000');
    res.header("Access-Control-Allow-Credentials", true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
    next();
});

in router

router.all('*', cors());

while sending response do

 res.header("Access-Control-Allow-Origin", 'http://localhost:3000');
 res.json(someJson)


问:
I have two function I want to merge them into one function and add only one record instead of two record
I have two function I want to merge them into one function and add only one record instead of two record

How can I solve this

services
in services two function

addNews(_INewsModu: INewsModule){
  var body = JSON.stringify(_INewsModu);
  var headerOptions = new Headers({'Content-Type': 'application/json'});

  var requsetOptions = new RequestOptions({method : RequestMethod.Post,headers :headerOptions});

  postFile(caption: string, fileToUpload: File){

  const endpoint = 'http://localhost:56181/api/UploadImage';
  const formData: FormData = new FormData();
  formData.append('Image',fileToUpload,fileToUpload.name);
  formData.append('ImageCaption',caption);
  return this.http.post(endpoint,formData);
}```
</div>
</div>
</p>

<p>component<br>
call 2 function in component </p>

<p>how can merge them into one function and add only one record instead of two record</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>OnSubmit2(Caption,Image){
  this._NewsService.postFile(Caption.value,this.fileToUpload).subscribe(
    data =>{
      console.log('done');
      Caption.value=null;
      Image.value = null;
      this.toastr.success("New IMAGE Added Successfuly", "IMAGE");

    }
  )
}
OnSubmit(form :NgForm){
  if (form.value.IDNews == null ){
    this._NewsService.addNews(form.value).subscribe(data =>{
      this.resetForm(form);
      this.toastr.success("New Record Added Successfuly", "News");
  })</code>```

How can I solve this

template

```<code><form class="emp-form" #employeeForm="ngForm" (ngSubmit)="newSubmit(employeeForm,Caption,Image)">

<input type="hidden" name="IDNews" #IDNews="ngModel" [(ngModel)]="_NewsService._INewsModule.IDNews">
<div class="form-row">
    <input class="form-control" name="IDCategoery" #IDCategoery="ngModel" [(ngModel)]={{selected}}
    placeholder="ID Categoery" required>

<div class="validation-error" *ngIf="IDCategoery.invalid && IDCategoery.touched">This Field is Required.</div>
</div> -->
<div style="float:left;padding:10px;margin:0 auto;" *ngIf="myCat_News">
<select [(ngModel)]="selected" name="myCat_News" >
<option *ngFor="let book of myCat_News" [(ngValue)]="book.NameCategory && book.IDCategoery">{{book.NameCategory}}</option>

  </select>

<input  class="form-control" name="IDCategoery" #IDCategoery="ngModel" [(ngModel)]=selected>

</div>
<div class="form-group col-md-6">

<input class="form-control" name="NameNews" #NameNews="ngModel" [(ngModel)]="_NewsService._INewsModule.NameNews" placeholder="NameNews"
    required>

<div class="validation-error" *ngIf="NameNews.invalid && NameNews.touched">This Field is Required.</div>
</div>
</div>

<div class="form-group">

<textarea  class="form-control" name="TopicNews" #TopicNews="ngModel" [(ngModel)]="_NewsService._INewsModule.TopicNews" placeholder="TopicNews">        </textarea>

</div>
<div class="form-row">

<div class="form-group col-md-6">

<input class="form-control" name="DateNews" #DateNews="ngModel" [(ngModel)]="_NewsService._INewsModule.DateNews" placeholder="Emp Code">
</div>

<div class="row">
<div class="input-field col s12">
<input type="text" #Caption ngModel name="Caption" id="Caption" required>
<label for="Caption">Caption</label>
</div>
</div>
<img [src]="imageUrl"  style="width:250px;height:200px">
<input type="file" #Image accept="image/*" (change)="handleFileInput($event.target.files)">

<!-- <div style="float:left;padding:10px;margin:0 auto;" *ngIf="myCat_News">
<select [(ngModel)]="selected"name="myCat_News">
<option *ngFor="let book of myCat_News" [(ngValue)]="book.IDCategoery">{{book.IDCategoery}}</option>
</select>
<p>{{ selected }}</p>
</div> -->
</div>
<div class="form-row">
<div class="form-group col-md-8">

<button [disabled]="!employeeForm.valid" type="submit" class="btn btn-lg btn-block btn-info">

<i class="fa fa-floppy-o"></i> Submit</button>
</div>
<div class="form-group col-md-4">
<button type="button" class="btn btn-lg btn-block btn-secondary" (click)="resetForm(employeeForm)">
<i class="fa fa-repeat"></i> Reset</button>
</div>
</div>
</form>
</code>```

答:
you can use forkJoin

```<code>import { forkJoin } from 'rxjs';
</code>```

...

```<code>newSubmit(form :NgForm, Caption,Image) {
    const add$ = form.value.IDNews == null ? this._NewsService.addNews(form.value) : empty();

    forkJoin(
      this._NewsService.postFile(Caption.value,this.fileToUpload),
      add$
    )
    .subscribe(data => {
      console.log(data); // data will be result of both observables
     });
}
</code>```

Body:
I have two function I want to merge them into one function and add only one record instead of two record

How can I solve this

services
in services two function

addNews(_INewsModu: INewsModule){
  var body = JSON.stringify(_INewsModu);
  var headerOptions = new Headers({'Content-Type': 'application/json'});

  var requsetOptions = new RequestOptions({method : RequestMethod.Post,headers :headerOptions});

  postFile(caption: string, fileToUpload: File){

  const endpoint = 'http://localhost:56181/api/UploadImage';
  const formData: FormData = new FormData();
  formData.append('Image',fileToUpload,fileToUpload.name);
  formData.append('ImageCaption',caption);
  return this.http.post(endpoint,formData);
}

component

call 2 function in component

how can merge them into one function and add only one record instead of two record

OnSubmit2(Caption,Image){
  this._NewsService.postFile(Caption.value,this.fileToUpload).subscribe(
    data =>{
      console.log('done');
      Caption.value=null;
      Image.value = null;
      this.toastr.success("New IMAGE Added Successfuly", "IMAGE");

    }
  )
}
OnSubmit(form :NgForm){
  if (form.value.IDNews == null ){
    this._NewsService.addNews(form.value).subscribe(data =>{
      this.resetForm(form);
      this.toastr.success("New Record Added Successfuly", "News");
  })

How can I solve this

template

<form class="emp-form" #employeeForm="ngForm" (ngSubmit)="newSubmit(employeeForm,Caption,Image)">

<input type="hidden" name="IDNews" #IDNews="ngModel" [(ngModel)]="_NewsService._INewsModule.IDNews">

    <input class="form-control" name="IDCategoery" #IDCategoery="ngModel" [(ngModel)]={{selected}}
    placeholder="ID Categoery" required>

This Field is Required.

 -->

<select [(ngModel)]="selected" name="myCat_News" >
<option *ngFor="let book of myCat_News" [(ngValue)]="book.NameCategory && book.IDCategoery">{{book.NameCategory}}</option>

  </select>

<input  class="form-control" name="IDCategoery" #IDCategoery="ngModel" [(ngModel)]=selected>

<input class="form-control" name="NameNews" #NameNews="ngModel" [(ngModel)]="_NewsService._INewsModule.NameNews" placeholder="NameNews"
    required>

This Field is Required.

<textarea  class="form-control" name="TopicNews" #TopicNews="ngModel" [(ngModel)]="_NewsService._INewsModule.TopicNews" placeholder="TopicNews">        </textarea>

<input class="form-control" name="DateNews" #DateNews="ngModel" [(ngModel)]="_NewsService._INewsModule.DateNews" placeholder="Emp Code">

<input type="text" #Caption ngModel name="Caption" id="Caption" required>
Caption

<input type="file" #Image accept="image/*" (change)="handleFileInput($event.target.files)">

<button [disabled]="!employeeForm.valid" type="submit" class="btn btn-lg btn-block btn-info">

 Submit</button>

<button type="button" class="btn btn-lg btn-block btn-secondary" (click)="resetForm(employeeForm)">
 Reset</button>

</form>

Body:
you can use forkJoin

import { forkJoin } from 'rxjs';

...

newSubmit(form :NgForm, Caption,Image) {
    const add$ = form.value.IDNews == null ? this._NewsService.addNews(form.value) : empty();

    forkJoin(
      this._NewsService.postFile(Caption.value,this.fileToUpload),
      add$
    )
    .subscribe(data => {
      console.log(data); // data will be result of both observables
     });
}


问:
SAS join on a flag to indicate percentile
I am looking to join two tables together

Table 1 - The baseball dataset

```<code>DATA baseball;
    SET sashelp.baseball
        (KEEP = crhits);
RUN;
</code>```

Table 2 - A table containing the percentiles of CRhits

```<code>PROC STDIZE
    DATA = baseball
    OUT=_NULL_
    PCTLMTD=ORD_STAT
    PCTLDEF=5
    OUTSTAT=STDLONGPCTLS
        (WHERE = (SUBSTR(_TYPE_,1,1) = "P"))
    pctlpts = 1 TO 99 BY 1;
RUN;
</code>```

I would like to join these tables together to create a table that contains the values for crhits and then a column identifying which percentile that value belongs to like below

```<code>crhits    percentile    percentile_value
54        p3            54
66        p5            66
825       p63           825
1134      p76           1133
</code>```

The last column indicates the percentile value given by stdlongpctls

I currently use the following code to calculate the percentiles and a loop to count the number of "Events" per percentile, per factor

I have tried a cross-join but I am having trouble visualising how to join these two tables without an explicit key

```<code>PROC SQL;
    CREATE TABLE cross_join_table   AS
    SELECT
          a.crhits
        , b._TYPE_
        , CASE WHEN
            a.crhits < b.type       THEN b._TYPE_   END AS percentile
    FROM
        baseball                    a
    CROSS JOIN
        stdlongpctls                b;
QUIT;
</code>```

If there is another easier / more efficient way to find the number of observations and number of dependent variables (e.g. I am modelling on a default flag event in my actual dataset, so the sum of 1's per percentile group, I would appreciate it)

答:
Use PROC RANK instead to group it into the percentiles.

```<code>proc rank data=sashelp.baseball out=baseball_ranks group=100;
var crhits;
rank rank_crhits;
run;
</code>```

You can then summarize it using PROC MEANS.

Body:
I am looking to join two tables together

Table 1 - The baseball dataset

DATA baseball;
    SET sashelp.baseball
        (KEEP = crhits);
RUN;

Table 2 - A table containing the percentiles of CRhits

PROC STDIZE
    DATA = baseball
    OUT=_NULL_
    PCTLMTD=ORD_STAT
    PCTLDEF=5
    OUTSTAT=STDLONGPCTLS
        (WHERE = (SUBSTR(_TYPE_,1,1) = "P"))
    pctlpts = 1 TO 99 BY 1;
RUN;

I would like to join these tables together to create a table that contains the values for crhits and then a column identifying which percentile that value belongs to like below

crhits    percentile    percentile_value
54        p3            54
66        p5            66
825       p63           825
1134      p76           1133

The last column indicates the percentile value given by stdlongpctls

I currently use the following code to calculate the percentiles and a loop to count the number of "Events" per percentile, per factor

I have tried a cross-join but I am having trouble visualising how to join these two tables without an explicit key

PROC SQL;
    CREATE TABLE cross_join_table   AS
    SELECT
          a.crhits
        , b._TYPE_
        , CASE WHEN
            a.crhits < b.type       THEN b._TYPE_   END AS percentile
    FROM
        baseball                    a
    CROSS JOIN
        stdlongpctls                b;
QUIT;

If there is another easier / more efficient way to find the number of observations and number of dependent variables (e.g. I am modelling on a default flag event in my actual dataset, so the sum of 1's per percentile group, I would appreciate it)

Body:
Use PROC RANK instead to group it into the percentiles.

proc rank data=sashelp.baseball out=baseball_ranks group=100;
var crhits;
rank rank_crhits;
run;

You can then summarize it using PROC MEANS.


问:
AVPlayer unable to play m3u8 file if there is any space in the file path
I am doing the HLS experiment in my iOS App.
Please find my below sample .m3u8 file. The first one "480/1.005 Program Management1351620000001 200055 mp4 v4.m3u8" not playing. I am assuming because of the white space it's not playing.

Is there any way to fix the things by setting up/changing any configuration in the AVPlayer?

```<code>#EXTM3U
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio-0",NAME="Default",AUTOSELECT=YES,DEFAULT=YES,URI="audio/1.005_Program_Management1351620000001-200071_m4a_v4.m3u8"
#EXT-X-I-FRAME-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=6903000,CODECS="avc1.42001e",URI="480/1.005 Program Management1351620000001 200055 mp4 iframe.m3u8"
#EXT-X-I-FRAME-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=9204000,CODECS="avc1.42001e",URI="720/1.005_Program_Management1351620000001-200045_mp4_iframe.m3u8"
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=451000,RESOLUTION=400x224,CODECS="avc1.42001e,mp4a.40.5",AUDIO="audio-0"
480/1.005 Program Management1351620000001 200055 mp4 v4.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=492000,RESOLUTION=480x270,CODECS="avc1.42001e,mp4a.40.5",AUDIO="audio-0"
720/1.005_Program_Management1351620000001-200045_mp4_v4.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=291000,CODECS="mp4a.40.5",AUDIO="audio-0"
audio/1.005_Program_Management1351620000001-200071_m4a_v4.m3u8
</code>```

答: I'm not sure but when I do about video live streaming. If you want to play on iOS, your video must follow standard from Apple (H264). Otherwise, you must you your player instead of using AVPlayer. In Android may be it can be played very well.</p>

Body:
I am doing the HLS experiment in my iOS App.
Please find my below sample .m3u8 file. The first one "480/1.005 Program Management1351620000001 200055 mp4 v4.m3u8" not playing. I am assuming because of the white space it's not playing.

Is there any way to fix the things by setting up/changing any configuration in the AVPlayer?

#EXTM3U
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio-0",NAME="Default",AUTOSELECT=YES,DEFAULT=YES,URI="audio/1.005_Program_Management1351620000001-200071_m4a_v4.m3u8"
#EXT-X-I-FRAME-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=6903000,CODECS="avc1.42001e",URI="480/1.005 Program Management1351620000001 200055 mp4 iframe.m3u8"
#EXT-X-I-FRAME-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=9204000,CODECS="avc1.42001e",URI="720/1.005_Program_Management1351620000001-200045_mp4_iframe.m3u8"
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=451000,RESOLUTION=400x224,CODECS="avc1.42001e,mp4a.40.5",AUDIO="audio-0"
480/1.005 Program Management1351620000001 200055 mp4 v4.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=492000,RESOLUTION=480x270,CODECS="avc1.42001e,mp4a.40.5",AUDIO="audio-0"
720/1.005_Program_Management1351620000001-200045_mp4_v4.m3u8
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=291000,CODECS="mp4a.40.5",AUDIO="audio-0"
audio/1.005_Program_Management1351620000001-200071_m4a_v4.m3u8


问:
Wicked PDF - showing fontawesome icons as sqaure box
I am using wicked-pdf gem (v1.2.2) to generate a PDF report which contains a font awesome icon.

I have kept the fontawesome file in this path:

vendor/assets/fonts/fontawesome.css.erb

and corresponding fonts in this path:

vendor/assets/fonts/fontawesome/fa-brands-400.eot

A sample snippet from fontawesome.css.erb: (this is how fonts are referred)

```<code>/*!
 * Font Awesome Free 5.5.0 by @fontawesome - https://fontawesome.com
 * License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
 */

@font-face {
  font-family: 'Font Awesome 5 Brands';
  font-style: normal;
  font-weight: normal;
  src: url('<%= asset_path 'fontawesome/fa-brands-400.eot' %>');
  src: url('<%= asset_path 'fontawesome/fa-brands-400.eot' %>?#iefix') format("embedded-opentype"), url('<%= asset_path 'fontawesome/fa-brands-400.woff2' %>') format("woff2"), url('<%= asset_path 'fontawesome/fa-brands-400.woff' %>') format("woff"), url('<%= asset_path 'fontawesome/fa-brands-400.ttf' %>') format("truetype"), url('<%= asset_path 'fontawesome/fa-brands-400.svg#fontawesome' %>') format("svg"); }
</code>```

I am using asset pipeline.

I have included the fontawesome to the report layout (report.html.erb) as below:

```<code><%= stylesheet_link_tag wicked_pdf_asset_base64('fontawesome.css') %>
</code>```

When I load the PDF in debug mode, I get square boxes only and I do not see anything in PDF.

I referred this question: Font Awesome not working, icons showing as squares

and added the CDN link to fontawesome in place of local file.
It worked only in debug mode.

When I tried in PDF mode, it took a long period of loading time and finally it didn't show the font. Hence, this is not a solution for me.

Looking forward to your inputs. Thanks

Changes:
I updated the fontawesome.css.erb with absolute reference to font file:

```<code>@font-face {
  font-family: 'Font Awesome 5 Free';
  font-style: normal;
  font-weight: 400;
  src: url('<%= ActionController::Base.helpers.wicked_pdf_asset_path('fontawesome/fa-brands-400.woff') %>');
}
</code>```

In debug mode, I am getting the following error in Chrome browser.

Not allowed to load local resource: file:///home/Projects/my_app/vendor/assets/fonts/fontawesome/fa-brands-400.woff

答:
Wickedpdf opens html as a local file, so all urls should be either relative to some temporary folder, full local file paths (these are generated by wicked pdf helpers) or absolute urls with hosts.

Your fontawesome.css contains urls to font files that does not contain host by default. You can either create a separate version of that for pdf generation, or include in html template head itself:

```<code><style>
@font-face {
  font-family: 'Font Awesome 5 Brands';
  font-style: normal; font-weight: normal;
  src: url('<%= wicked_pdf_asset_path 'fontawesome/fa-brands-400.woff' %>');
}
</style>
</code>```

(no need for iefix and can use less formats, because we are sure that wkhtmltopdf is not IE, also there was a bug with fallback urls for fonts not working)

Body:
I am using wicked-pdf gem (v1.2.2) to generate a PDF report which contains a font awesome icon.

I have kept the fontawesome file in this path:

vendor/assets/fonts/fontawesome.css.erb

and corresponding fonts in this path:

vendor/assets/fonts/fontawesome/fa-brands-400.eot

A sample snippet from fontawesome.css.erb: (this is how fonts are referred)

/*!
 * Font Awesome Free 5.5.0 by @fontawesome - https://fontawesome.com
 * License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
 */

@font-face {
  font-family: 'Font Awesome 5 Brands';
  font-style: normal;
  font-weight: normal;
  src: url('<%= asset_path 'fontawesome/fa-brands-400.eot' %>');
  src: url('<%= asset_path 'fontawesome/fa-brands-400.eot' %>?#iefix') format("embedded-opentype"), url('<%= asset_path 'fontawesome/fa-brands-400.woff2' %>') format("woff2"), url('<%= asset_path 'fontawesome/fa-brands-400.woff' %>') format("woff"), url('<%= asset_path 'fontawesome/fa-brands-400.ttf' %>') format("truetype"), url('<%= asset_path 'fontawesome/fa-brands-400.svg#fontawesome' %>') format("svg"); }

I am using asset pipeline.

I have included the fontawesome to the report layout (report.html.erb) as below:

<%= stylesheet_link_tag wicked_pdf_asset_base64('fontawesome.css') %>

When I load the PDF in debug mode, I get square boxes only and I do not see anything in PDF.

I referred this question: Font Awesome not working, icons showing as squares

and added the CDN link to fontawesome in place of local file.
It worked only in debug mode.

When I tried in PDF mode, it took a long period of loading time and finally it didn't show the font. Hence, this is not a solution for me.

Looking forward to your inputs. Thanks

Changes:
I updated the fontawesome.css.erb with absolute reference to font file:

@font-face {
  font-family: 'Font Awesome 5 Free';
  font-style: normal;
  font-weight: 400;
  src: url('<%= ActionController::Base.helpers.wicked_pdf_asset_path('fontawesome/fa-brands-400.woff') %>');
}

In debug mode, I am getting the following error in Chrome browser.

Not allowed to load local resource: file:///home/Projects/my_app/vendor/assets/fonts/fontawesome/fa-brands-400.woff

Body:
Wickedpdf opens html as a local file, so all urls should be either relative to some temporary folder, full local file paths (these are generated by wicked pdf helpers) or absolute urls with hosts.

Your fontawesome.css contains urls to font files that does not contain host by default. You can either create a separate version of that for pdf generation, or include in html template head itself:

<style>
@font-face {
  font-family: 'Font Awesome 5 Brands';
  font-style: normal; font-weight: normal;
  src: url('<%= wicked_pdf_asset_path 'fontawesome/fa-brands-400.woff' %>');
}
</style>

(no need for iefix and can use less formats, because we are sure that wkhtmltopdf is not IE, also there was a bug with fallback urls for fonts not working)


问:
Alter dictionary values within Process pool in python
I'm trying to alter a dictionary in python inside a process pool environment, but the dictionary isn't changed when the pool finishes.

Here's a minimal example of the problem (the output batch_input is all zeros, although inside per_batch_build it changes the relevant values)

from multiprocessing import Pool, freeze_support
import numpy as np
import itertools

def test_process():
    batch_size = 2
    batch_input = {'part_evecs': np.zeros((2, 10, 10)),
                   'model_evecs': np.zeros((2, 10, 10)),
                   }

    batch_model_dist = np.zeros((2, 10, 10))

    pool = Pool(4)
    batch_output = pool.map(per_batch_build, itertools.izip(itertools.repeat(batch_input),
                                                            itertools.repeat(batch_model_dist),
                                                            list(range(batch_size))))
    pool.close()
    pool.join()

    return batch_input, batch_model_dist

# @profile
# def per_batch_build(batch_input, batch_model_dist, batch_part_dist, dataset, i_batch):
def per_batch_build(tuple_input):
    batch_input, batch_model_dist, i_batch = tuple_input

    batch_model_dist[i_batch] = np.ones((10,10))

    batch_input['part_evecs'][i_batch] = np.ones((10,10))
    batch_input['model_evecs'][i_batch] = np.ones((10,10))
```

<p>But unfortunately <code>batch_input, batch_model_dist, batch_part_dist</code> are all zeros, although when printing <code>batch_input</code> inside <code>per_batch_build</code> is not zero.
<br><br>
Using the solutions provided from previous discussions, the result stays the same (the output arrays are all zeros)<br></p>

```from multiprocessing import Pool, freeze_support, Manager, Array
import numpy as np
import itertools
import ctypes

def test_process():
    manager = Manager()

    shared_array_base = Array(ctypes.c_double, [0] * (2*10*10))
    shared_array = np.ctypeslib.as_array(shared_array_base.get_obj())
    shared_array = shared_array.reshape((2,10,10))

    batch_size = 2
    batch_input = manager.dict({'part_evecs': shared_array,
                               # 'model_evecs': np.zeros((2, 10, 10)),
                               })

    batch_model_dist = np.zeros((2, 10, 10))

    pool = Pool(4)
    batch_output = pool.map(per_batch_build, itertools.izip(itertools.repeat(batch_input),
                                                            itertools.repeat(batch_model_dist),
                                                            list(range(batch_size))))
    pool.close()
    pool.join()

    return batch_input, batch_model_dist

# @profile
# def per_batch_build(batch_input, batch_model_dist, batch_part_dist, dataset, i_batch):
def per_batch_build(tuple_input):
    batch_input, batch_model_dist, i_batch = tuple_input

    batch_model_dist[i_batch] = np.ones((10,10))

    batch_input['part_evecs'][i_batch] = np.ones((10,10))
    # batch_input['model_evecs'][i_batch] = np.ones((10,10))
```

答:
You are changing a copy of the object created inside per_batch_build. You are naming them identically in both functions so it may be confusing.

Add
print(id(batch_model_dist))
inside both functions and see for yourself.

[Edit]
I should probably also link related response, for example:

Is shared readonly data copied to different processes for multiprocessing?

Body:
I'm trying to alter a dictionary in python inside a process pool environment, but the dictionary isn't changed when the pool finishes.

Here's a minimal example of the problem (the output batch_input is all zeros, although inside per_batch_build it changes the relevant values)

from multiprocessing import Pool, freeze_support
import numpy as np
import itertools

def test_process():
    batch_size = 2
    batch_input = {'part_evecs': np.zeros((2, 10, 10)),
                   'model_evecs': np.zeros((2, 10, 10)),
                   }

    batch_model_dist = np.zeros((2, 10, 10))

    pool = Pool(4)
    batch_output = pool.map(per_batch_build, itertools.izip(itertools.repeat(batch_input),
                                                            itertools.repeat(batch_model_dist),
                                                            list(range(batch_size))))
    pool.close()
    pool.join()

    return batch_input, batch_model_dist

# @profile
# def per_batch_build(batch_input, batch_model_dist, batch_part_dist, dataset, i_batch):
def per_batch_build(tuple_input):
    batch_input, batch_model_dist, i_batch = tuple_input

    batch_model_dist[i_batch] = np.ones((10,10))

    batch_input['part_evecs'][i_batch] = np.ones((10,10))
    batch_input['model_evecs'][i_batch] = np.ones((10,10))

But unfortunately batch_input, batch_model_dist, batch_part_dist are all zeros, although when printing batch_input inside per_batch_build is not zero.

Using the solutions provided from previous discussions, the result stays the same (the output arrays are all zeros)

from multiprocessing import Pool, freeze_support, Manager, Array
import numpy as np
import itertools
import ctypes

def test_process():
    manager = Manager()

    shared_array_base = Array(ctypes.c_double, [0] * (2*10*10))
    shared_array = np.ctypeslib.as_array(shared_array_base.get_obj())
    shared_array = shared_array.reshape((2,10,10))

    batch_size = 2
    batch_input = manager.dict({'part_evecs': shared_array,
                               # 'model_evecs': np.zeros((2, 10, 10)),
                               })

    batch_model_dist = np.zeros((2, 10, 10))

    pool = Pool(4)
    batch_output = pool.map(per_batch_build, itertools.izip(itertools.repeat(batch_input),
                                                            itertools.repeat(batch_model_dist),
                                                            list(range(batch_size))))
    pool.close()
    pool.join()

    return batch_input, batch_model_dist

# @profile
# def per_batch_build(batch_input, batch_model_dist, batch_part_dist, dataset, i_batch):
def per_batch_build(tuple_input):
    batch_input, batch_model_dist, i_batch = tuple_input

    batch_model_dist[i_batch] = np.ones((10,10))

    batch_input['part_evecs'][i_batch] = np.ones((10,10))
    # batch_input['model_evecs'][i_batch] = np.ones((10,10))


问:
AttributeError: 'NoneType' object has no attribute 'find_all' Beautifulsoup wrong class
I'm trying to scrape a house's price of this link : https://www.bienici.com/recherche/achat/france?page=2

And I need to know what's wrong with my program ?

My program :

```<code> from bs4 import BeautifulSoup
 import requests
 import csv

 with open("out.csv", "w", newline="") as f:
     writer = csv.writer(f)
     writer.writerow("Prix")

     for i in range(1, 20):
         url = "https://www.bienici.com/recherche/achat/france?page=%s" % i
         soup = BeautifulSoup(requests.get(url).text, "html.parser")
         data = soup.find(class_="resultsListContainer")

         for data in data.find_all(class_="sideListItemContainerInTableForListInResult"):
             prix = data.find("span", {"class": "thePrice"})
             prix = prix.text if prix else ""

             writer.writerow(prix)
</code>```

I get this error :

```<code>   Traceback (most recent call last):
     File "1.py", line 16, in <module>
        for data in data.find_all(class_="sideListItemContainerInTableForListInResult"):
   AttributeError: 'NoneType' object has no attribute 'find_all'
</code>```

I think my error is in the class_="sideListItemContainerInTableForListInResult" , but when I inspect the html code I think it's the right one !!

答:
The problem here is that data is NoneType, i.e. data = soup.find(class_="resultsListContainer") is returning None, which means the for loop will fail.

I don't know enough about the exact problem you're trying to solve to know if this is a problem with your code or if the website sometimes doesn't have anything in the "resultListContainer" class. If it is the case that sometime this is missing, you can do a check before reaching the for loop to make sure the data variable is not None.

Body:
I'm trying to scrape a house's price of this link : https://www.bienici.com/recherche/achat/france?page=2

And I need to know what's wrong with my program ?

My program :

 from bs4 import BeautifulSoup
 import requests
 import csv

 with open("out.csv", "w", newline="") as f:
     writer = csv.writer(f)
     writer.writerow("Prix")

     for i in range(1, 20):
         url = "https://www.bienici.com/recherche/achat/france?page=%s" % i
         soup = BeautifulSoup(requests.get(url).text, "html.parser")
         data = soup.find(class_="resultsListContainer")

         for data in data.find_all(class_="sideListItemContainerInTableForListInResult"):
             prix = data.find("span", {"class": "thePrice"})
             prix = prix.text if prix else ""

             writer.writerow(prix)

I get this error :

   Traceback (most recent call last):
     File "1.py", line 16, in <module>
        for data in data.find_all(class_="sideListItemContainerInTableForListInResult"):
   AttributeError: 'NoneType' object has no attribute 'find_all'

I think my error is in the class_="sideListItemContainerInTableForListInResult" , but when I inspect the html code I think it's the right one !!


问:
display only fixed no of items in Recycler view and remaining items in new page(using Show all)
i have 100 items which is parsed from a JSON file.
i want to display 20 items in a recycler(horizontal scroll) and on reaching the 20th item i want to add a footer that shows a "Show ALL"(imagebutton) which when clicked goes to a new page where you can view all the 100 items in a grid view//
,my doubt is how can i just display only 20 items out of the 100 items in the first page.</p>

答:
In your adapter inside getItemCount() method just return your wanted number of items:

```<code> @Override
public int getItemCount() {
    return 20; //20 items will be displayed
}
</code>```

Body:
In your adapter inside getItemCount() method just return your wanted number of items:

 @Override
public int getItemCount() {
    return 20; //20 items will be displayed
}


问:
How to rename multiple files in vscode (visual studio code)?
I wonder, if there is way to rename multiple files in visual studio code? I have tried to use find and replace, no luck.</p>

答:
VS Code only supports single file name. On Windows, to do batch rename, you can use one of the following

```<code>[CMD]

// Change the extensions of all .doc files to .txt
ren *.doc *.txt

// Replace the first three characters of all files starting with 'abc' by 'xyz'
ren abc* xyz*

[PowerShell]
Get-ChildItem *.txt | Rename-Item -NewName { $_.Name.Replace('.txt','.log') }
</code>```

A comprehensive tutorial can be found here

Body:
VS Code only supports single file name. On Windows, to do batch rename, you can use one of the following

[CMD]

// Change the extensions of all .doc files to .txt
ren *.doc *.txt

// Replace the first three characters of all files starting with 'abc' by 'xyz'
ren abc* xyz*

[PowerShell]
Get-ChildItem *.txt | Rename-Item -NewName { $_.Name.Replace('.txt','.log') }

A comprehensive tutorial can be found here


问:
Making columns out of spans
I recive {patients} and place it into a div:

```<code><div className="patients">
   {patients}
</div>
</code>```

It contains Name and Surname, each row in two spans:

(Dev Tools)

(Current state)

How can style those spans into columns (table-like)?

(Expexted result)

---EDIT---

Content of {patients} changes. It's a result of searching, so different names come, sometimes more, sometimes less. I can't apply a style to them separatly.
See the code.

答: You can use display with table/table-row/table-cell or use display block with a fix with or make each row a flexbox with a fixed width or some other solution. There are many ways to achieve that.</p>

Title: Making columns out of spans

Body:
I recive {patients} and place it into a div:

   {patients}

It contains Name and Surname, each row in two spans:

(Dev Tools)

(Current state)

How can style those spans into columns (table-like)?

(Expexted result)

---EDIT---

Content of {patients} changes. It's a result of searching, so different names come, sometimes more, sometimes less. I can't apply a style to them separatly.
See the code.


问:
How can I print the next line to the current line provided they start with certain words?
I want to print the next line on the current line provided the current line starts with "This" and the next line starts with "That" of a file and write it back to the same file. How can I achieve this?

Note: I have some other lines in my file that I want to maintain as they are.

```<code>prev = ''
with open("myfile.txt", 'r') as f:
    for line in f:
        if line.startswith('This') and prev.startswith('That'):
        # Attach 'That' line with 'This' line
        prev = line
#Once done, write back to myfile.txt
</code>```

INPUT:

```<code>Foo
This is my current line
That is my next line
Bar
</code>```

OUTPUT:

```<code>Foo
This is my current line That is my next line
Bar
</code>```

答:
We want to attach lines that don't start with This directly to the output. Lines that do start with This need to be deferred until you get a That or not. In the former case, you strip out the newline between them, in the latter you attach both as-is.

```<code>with open('myfile.txt', 'r') as f:
    lines = f.readlines()

for index, line in enumerate(lines):
    if line.startswith('That') and index and lines[index - 1].startswith('This'):
        lines[index - 1] = lines[index - 1].replace('\n', ' ')

with open('myfile.txt', 'w') as f:
    f.writelines(lines)
</code>```

All you need to do is remove the newline characters: writelines won't insert any new ones for you.

While I've chosen to read the entire file into memory, you don't need to do this. A fairly standard approach would be to open a temporary file, write to it on the fly line-by-line, and then move it to replace the input file. The details of how to do that can already be found on SO.

Body:
I want to print the next line on the current line provided the current line starts with "This" and the next line starts with "That" of a file and write it back to the same file. How can I achieve this?

Note: I have some other lines in my file that I want to maintain as they are.

prev = ''
with open("myfile.txt", 'r') as f:
    for line in f:
        if line.startswith('This') and prev.startswith('That'):
        # Attach 'That' line with 'This' line
        prev = line
#Once done, write back to myfile.txt

INPUT:

Foo
This is my current line
That is my next line
Bar

OUTPUT:

Foo
This is my current line That is my next line
Bar

Body:
We want to attach lines that don't start with This directly to the output. Lines that do start with This need to be deferred until you get a That or not. In the former case, you strip out the newline between them, in the latter you attach both as-is.

with open('myfile.txt', 'r') as f:
    lines = f.readlines()

for index, line in enumerate(lines):
    if line.startswith('That') and index and lines[index - 1].startswith('This'):
        lines[index - 1] = lines[index - 1].replace('\n', ' ')

with open('myfile.txt', 'w') as f:
    f.writelines(lines)

All you need to do is remove the newline characters: writelines won't insert any new ones for you.

While I've chosen to read the entire file into memory, you don't need to do this. A fairly standard approach would be to open a temporary file, write to it on the fly line-by-line, and then move it to replace the input file. The details of how to do that can already be found on SO.


问:
How to detect tab change from the active tab page
While searching in the Ionic docs to find how to detect tab change, I found that there is the ionTabsDidChange event that is directly linked to the ion-tabs component.

My purpose is slightly different in the way that I need to listen to the tab change from the page/component related to the tab itself, and use some of its data.

For example, if I have a component named TabXPage, I wonder if there is a way to create a method that helps to listen to the tab change, something like this:

@Component({
  selector: 'app-tabx',
  templateUrl: './tabx.page.html',
  styleUrls: ['./tabx.page.scss'],
})
export class TabXPage implements OnInit {

    //...

    onTabChange() {
        // Execute tab change actions using some data that EXISTS IN TabXPage
    }

}
```

I looked upon Angular lifecycle hooks, but I did not find any applicable event since the page is preserved in the same state while navigating through the Ionic tabs.

答:
I found a solution using Ionic lifecycle hooks, I am not sure if it's the best regarding the subject but it's working for my case.

I used simply the ionViewDidLeave page event:

@Component({
  selector: 'app-tabx',
  templateUrl: './tabx.page.html',
  styleUrls: ['./tabx.page.scss'],
})
export class TabXPage implements OnInit {
    //...

    ionViewDidLeave() {
        console.log("TabX is exited")
    }
}
```

Body:
While searching in the Ionic docs to find how to detect tab change, I found that there is the ionTabsDidChange event that is directly linked to the ion-tabs component.

My purpose is slightly different in the way that I need to listen to the tab change from the page/component related to the tab itself, and use some of its data.

For example, if I have a component named TabXPage, I wonder if there is a way to create a method that helps to listen to the tab change, something like this:

@Component({
  selector: 'app-tabx',
  templateUrl: './tabx.page.html',
  styleUrls: ['./tabx.page.scss'],
})
export class TabXPage implements OnInit {

    //...

    onTabChange() {
        // Execute tab change actions using some data that EXISTS IN TabXPage
    }

}

I looked upon Angular lifecycle hooks, but I did not find any applicable event since the page is preserved in the same state while navigating through the Ionic tabs.


问:
Strange visual studio 2008 behavior when pressing keys
Every once in a while I'll do something that causes strang behavior when pressing certain keys.

1)The single quote key (') will not type a character unless I press it twice, in which case it will print two backwards single quote characters (``).

2)The ` (backwards single quote?) key types a # character.

3)The angle bracket keys (< and >) type a single quote (') and a period (.).

4)Shift + any A-Z character types the character and brings the code completion window up.

I'm sure there's other symptomps, and they only want I've found to stop it is to restart Visual studio.  This behavior does not appear in any other apps.  Anybody experience this?

答:
If you have multiple languages on your machine, then you probably triggered this behavior by pressing ctrl+shift, which causes windows to switch the system language for the active window.

You can either press it again, or better yet, disable the language bar and all other secondary languages.

OwnerDisplayName: Jeremy

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: John Sheehan

OwnerDisplayName: sqook


问:
How to generate a random value and its result from a list?
What I want is, generate a random value displayed in a h tag, and also, display the good value relative to the random one, in an other tag.

```<code>var first = ['1+2', '10+20', '100+200'];
var second = ['3', '30', '300'];

var first_value = first[Math.floor(Math.random()*first.length)];
var second_value = second[Math.floor(Math.random()*second.length)];

document.getElementById('first_value').innerHTML = first_value;
document.getElementById('second_value').innerHTML = second_value;
</code>```

At the moment, everything is generated randomly, there is no relation between the 2 values generated.

If "10+20" is randomly selected, I want to display "30" in the second html tag.

答:
Just store the the random index for both arrays.

```<code>var index = Math.floor(Math.random() * first.length); // assuming same length

document.getElementById('first_value').innerHTML = first[index];
document.getElementById('second_value').innerHTML = second[index];
</code>```

Another approach is to store values of the same group in an array, and keep the logical group together, instead of using two different arrays.

```<code>var data = [
        ['1+2', 3],
        ['10+20', 30],
        ['100+200', '300']
    ];
    index = Math.floor(Math.random() * data.length);

document.getElementById('first_value').innerHTML = data[index][0];
document.getElementById('second_value').innerHTML = data[index][1];
</code>```

Body:
What I want is, generate a random value displayed in a h tag, and also, display the good value relative to the random one, in an other tag.

var first = ['1+2', '10+20', '100+200'];
var second = ['3', '30', '300'];

var first_value = first[Math.floor(Math.random()*first.length)];
var second_value = second[Math.floor(Math.random()*second.length)];

document.getElementById('first_value').innerHTML = first_value;
document.getElementById('second_value').innerHTML = second_value;

At the moment, everything is generated randomly, there is no relation between the 2 values generated.

If "10+20" is randomly selected, I want to display "30" in the second html tag.

Body:
Just store the the random index for both arrays.

var index = Math.floor(Math.random() * first.length); // assuming same length

document.getElementById('first_value').innerHTML = first[index];
document.getElementById('second_value').innerHTML = second[index];

Another approach is to store values of the same group in an array, and keep the logical group together, instead of using two different arrays.

var data = [
        ['1+2', 3],
        ['10+20', 30],
        ['100+200', '300']
    ];
    index = Math.floor(Math.random() * data.length);

document.getElementById('first_value').innerHTML = data[index][0];
document.getElementById('second_value').innerHTML = data[index][1];


问:
Why image optimizer resulting identical version with no enhancement?
I installed composer require spatie/image-optimizer, but when I run the example below the I had two problems:
1- The class could not be found by calling it by using (use). So I solved it by using include.

2- After solving the first problem, the code works fine but the resultant image is the same image with no optimization.

```<code>include 'Spatie/Imageoptimizer/src/OptimizerChainFactory.php';

require __DIR__.'/autoload.php';

$pathToImage =  "D:/xampp/htdocs/images/vendor/uploads/2.png";

//use Spatie\ImageOptimizer\OptimizerChainFactory;

// Get the image and store the original size
$image = $pathToImage;
$originalSize = filesize($image);

// Optimize updates the existing image
$optimizerChain = OptimizerChainFactory::create();
$optimizerChain->optimize($image);

// Clear stat cache to get the optimized size
clearstatcache();

// Check the optimized size
$optimizedSize = filesize($image);
$percentChange = (1 - $optimizedSize / $originalSize) * 100;
echo sprintf("The image is now %.2f%% smaller\n", $percentChange);
exit(0);
</code>```

Could you please suggest me any solutions!

答: I found the cause of the problem, which is the jpg and Optipng tools are not installed in the windows. Is there any way to install the tools in windows and link them to the plugin.</p>

Body:
I installed composer require spatie/image-optimizer, but when I run the example below the I had two problems:
1- The class could not be found by calling it by using (use). So I solved it by using include.

2- After solving the first problem, the code works fine but the resultant image is the same image with no optimization.

include 'Spatie/Imageoptimizer/src/OptimizerChainFactory.php';

require __DIR__.'/autoload.php';

$pathToImage =  "D:/xampp/htdocs/images/vendor/uploads/2.png";

//use Spatie\ImageOptimizer\OptimizerChainFactory;

// Get the image and store the original size
$image = $pathToImage;
$originalSize = filesize($image);

// Optimize updates the existing image
$optimizerChain = OptimizerChainFactory::create();
$optimizerChain->optimize($image);

// Clear stat cache to get the optimized size
clearstatcache();

// Check the optimized size
$optimizedSize = filesize($image);
$percentChange = (1 - $optimizedSize / $originalSize) * 100;
echo sprintf("The image is now %.2f%% smaller\n", $percentChange);
exit(0);

Could you please suggest me any solutions!


问:
I'm getting unexpected top header in react-navigation
I'm using react-navigation's createBottomTabNavigator for tab component in react-native.
The problem is that I'm getting unnecessary top header.

This image is what I'm getting now.

I want to remove the top header.
Please help me.

This is my navigator code.

```<code>import HomeContainer from 'src/mainView/homeContainer'
import CameraPage from 'src/mainView/pages/cameraPage'
import CarOwnerVoicePage from 'src/mainView/pages/carOwnerVoicePage'
import ProfileContainer from 'src/profile'

const TabNavigator = createBottomTabNavigator(
  {
    home: {screen: HomeContainer},
    carOwnerVoice: {screen: CarOwnerVoicePage},
    camera: {screen: CameraPage},
    profile: {screen: ProfileContainer}
  },
  {
    headerMode: 'none' ,
    tabBarOptions: {
      labelStyle: {
        fontSize: 15,
        marginBottom: 10,
        padding: 0,
      },
    },
  }
);

export default createAppContainer(TabNavigator);
</code>```

答:
If you want to hide on specific screen than do like this:</p>

```<code>// create a component
export default class Login extends Component<{}> {
  static navigationOptions = { header: null };
}
</code>```

Body:
I'm using react-navigation's createBottomTabNavigator for tab component in react-native.
The problem is that I'm getting unnecessary top header.

This image is what I'm getting now.

I want to remove the top header.
Please help me.

This is my navigator code.

import HomeContainer from 'src/mainView/homeContainer'
import CameraPage from 'src/mainView/pages/cameraPage'
import CarOwnerVoicePage from 'src/mainView/pages/carOwnerVoicePage'
import ProfileContainer from 'src/profile'

const TabNavigator = createBottomTabNavigator(
  {
    home: {screen: HomeContainer},
    carOwnerVoice: {screen: CarOwnerVoicePage},
    camera: {screen: CameraPage},
    profile: {screen: ProfileContainer}
  },
  {
    headerMode: 'none' ,
    tabBarOptions: {
      labelStyle: {
        fontSize: 15,
        marginBottom: 10,
        padding: 0,
      },
    },
  }
);

export default createAppContainer(TabNavigator);

Body:
If you want to hide on specific screen than do like this:

// create a component
export default class Login extends Component<{}> {
  static navigationOptions = { header: null };
}


问:
Use of unresolved identifier 'SDKApplicationDelegate'
This is the code for both Google-signin and Facebook-signin. Google-signin works perfectly fine but Facebook "SDKApplicationDelegate" won't seem to work. I have imported all my pod (import FacebookCore, Facebook Login, FacebookShare).

Why is SDKApplication not working?

```<code>import UIKit
import GoogleSignIn
import FacebookCore

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        GIDSignIn.sharedInstance().clientID = "1043921468178-epj1ms4mnc4tbf2j3vb0kudggfmtnc8b.apps.googleusercontent.com"
        GIDSignIn.sharedInstance().delegate = self
        return SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        let googleDidHandle = GIDSignIn.sharedInstance().handle(url as URL?,
                                                                sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
                                                                annotation: options[UIApplication.OpenURLOptionsKey.annotation])
        let facebookDidHandle = SDKApplicationDelegate.shared.application(app, open: url, options: options)

         return googleDidHandle || facebookDidHandle
    }
</code>```

答: I was facing same problem, the solution I found was to import FBSDKCoreKit and rename it to ApplicationDelegate, but what I've done is to downgrade version of FacebookCore and FacebookLogin to the previous one (I was using 0.5.0) Facebook SDK seems to have a lot of bugs on this new version, I advise you to do the same.

Body:
This is the code for both Google-signin and Facebook-signin. Google-signin works perfectly fine but Facebook "SDKApplicationDelegate" won't seem to work. I have imported all my pod (import FacebookCore, Facebook Login, FacebookShare).

Why is SDKApplication not working?

import UIKit
import GoogleSignIn
import FacebookCore

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        GIDSignIn.sharedInstance().clientID = "1043921468178-epj1ms4mnc4tbf2j3vb0kudggfmtnc8b.apps.googleusercontent.com"
        GIDSignIn.sharedInstance().delegate = self
        return SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        let googleDidHandle = GIDSignIn.sharedInstance().handle(url as URL?,
                                                                sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
                                                                annotation: options[UIApplication.OpenURLOptionsKey.annotation])
        let facebookDidHandle = SDKApplicationDelegate.shared.application(app, open: url, options: options)

         return googleDidHandle || facebookDidHandle
    }


问:
PHP sort by arbitrary order
I need a function in php to sort a list of words according to an arbitrary ordering.

Any words in the list not in my predefined order should be sorted alphabetically at the end of the list.

Below is my first attempt, it is neither elegant or efficient. Can you suggest a better way to acheive this?

Thanks

```<code>public static function sortWords(&$inputArray){
    $order=array("Banana","Orange", "Apple", "Kiwi");
    sort($inputArray);
    for($i=0;$i<count($inputArray));$i++){
        $ac = $inputArray[$i];
        $position = array_search($ac,$order);
        if($position !== false && $i != $position){
            $temp=$inputArray[$position];
            $inputArray[$position]=$inputArray[$i];
            $inputArray[$i]=$temp;
        }
    }
}
</code>```

答:
PHP provides the usort() and uksort() functions to allow you to write your own sorting routines. Of these two, you'll be wanting usort().

Both these functions expect you to write a stand-alone function, which takes as input two elements of the input array, and returns the order that they should be sorted into. The usort() function then runs its own sorting algorithm, calling your function as to establish the sorting order often as required until it has sorted the entire array.

So you'd write something like this....

```<code>function mycompare($a, $b) {
    if ($a == $b) {return 0;}
    $order=array("Banana","Orange", "Apple", "Kiwi");
    $position = array_search($a,$order);
    $position2 = array_search($b, $order);

    //if both are in the $order, then sort according to their order in $order...
    if ($position2!==false && $position!==false) {return ($position < $position2) ? -1 : 1;}
    //if only one is in $order, then sort to put the one in $order first...
    if($position!==false) {return -1;}
    if($position2!==false) {return 1;}

    //if neither in $order, then a simple alphabetic sort...
    return ($a < $b) ? -1 : 1;
}
</code>```

...then just call usort($inputarray,'mycompare'); to sort them.

Title: PHP sort by arbitrary order

Body:
I need a function in php to sort a list of words according to an arbitrary ordering.

Any words in the list not in my predefined order should be sorted alphabetically at the end of the list.

Below is my first attempt, it is neither elegant or efficient. Can you suggest a better way to acheive this?

Thanks

public static function sortWords(&$inputArray){
    $order=array("Banana","Orange", "Apple", "Kiwi");
    sort($inputArray);
    for($i=0;$i<count($inputArray));$i++){
        $ac = $inputArray[$i];
        $position = array_search($ac,$order);
        if($position !== false && $i != $position){
            $temp=$inputArray[$position];
            $inputArray[$position]=$inputArray[$i];
            $inputArray[$i]=$temp;
        }
    }
}

Body:
PHP provides the usort() and uksort() functions to allow you to write your own sorting routines. Of these two, you'll be wanting usort().

Both these functions expect you to write a stand-alone function, which takes as input two elements of the input array, and returns the order that they should be sorted into. The usort() function then runs its own sorting algorithm, calling your function as to establish the sorting order often as required until it has sorted the entire array.

So you'd write something like this....

function mycompare($a, $b) {
    if ($a == $b) {return 0;}
    $order=array("Banana","Orange", "Apple", "Kiwi");
    $position = array_search($a,$order);
    $position2 = array_search($b, $order);

    //if both are in the $order, then sort according to their order in $order...
    if ($position2!==false && $position!==false) {return ($position < $position2) ? -1 : 1;}
    //if only one is in $order, then sort to put the one in $order first...
    if($position!==false) {return -1;}
    if($position2!==false) {return 1;}

    //if neither in $order, then a simple alphabetic sort...
    return ($a < $b) ? -1 : 1;
}

...then just call usort($inputarray,'mycompare'); to sort them.