问:
git commit does not commit new files
I am having an issue using bitbucket and codeanywhere. I was trying to install CakePHP onto the PHP based server running on ubuntu.

I have attached my container to the git and pulled all the latest changes from the latest commit. Then I made my own changes and I did:git commit --all and also pushed it with git push.

However my issue is that none of the folders that I created such as "tmp" or "logs" or even files I renamed got committed onto the bitbucket.

I am running this command from the main directory

```<code>cabox@box-codeanywhere:~/workspace$
</code>```

And now even with the files being different if I try to commit again it says the following:

```<code>nothing to commit, working directory clean
</code>```

答:
You can initial a git repo in codeanywhere, and then add a remote for bitbucket git repo, now you can pull/commit/push. Detail steps as below:</p>

```<code>mkdir /path/for/the/bitbucket/repo
cd /path/for/the/bitbucket/repo
git init
git remote add origin <URL for bitbucket repo>
git pull
git commit
git push -u origin branchname
</code>```

Title: git commit does not commit new files

Body:
I am having an issue using bitbucket and codeanywhere. I was trying to install CakePHP onto the PHP based server running on ubuntu.

I have attached my container to the git and pulled all the latest changes from the latest commit. Then I made my own changes and I did:git commit --all and also pushed it with git push.

However my issue is that none of the folders that I created such as "tmp" or "logs" or even files I renamed got committed onto the bitbucket.

I am running this command from the main directory

cabox@box-codeanywhere:~/workspace$

And now even with the files being different if I try to commit again it says the following:

nothing to commit, working directory clean

Body:
You can initial a git repo in codeanywhere, and then add a remote for bitbucket git repo, now you can pull/commit/push. Detail steps as below:

mkdir /path/for/the/bitbucket/repo
cd /path/for/the/bitbucket/repo
git init
git remote add origin <URL for bitbucket repo>
git pull
git commit
git push -u origin branchname


来源: stackexchange

问:
Installing quantlib for javascript
I am trying to install quantlib for javascript on both linux and windows. I get a similar error in both cases.

```<code>[idf@node3 ql]$ sudo npm install quantlib
[sudo] password for idf:

> quantlib@0.2.1 postinstall /home/idf/Documents/js/node_modules/quantlib
> node-pre-gyp install

node-pre-gyp ERR! install error
node-pre-gyp ERR! stack Error: 404 status code downloading tarball https://github.com/quantlibnode/quantlibnode/releases/download/v0.2.1/linux-x64.tar.gz
node-pre-gyp ERR! stack     at Request.<anonymous> (/home/idf/Documents/js/node_modules/node-pre-gyp/lib/install.js:120:27)
node-pre-gyp ERR! stack     at emitOne (events.js:101:20)
node-pre-gyp ERR! stack     at Request.emit (events.js:188:7)
node-pre-gyp ERR! stack     at Request.onRequestResponse (/home/idf/Documents/js/node_modules/request/request.js:1029:10)
node-pre-gyp ERR! stack     at emitOne (events.js:96:13)
node-pre-gyp ERR! stack     at ClientRequest.emit (events.js:188:7)
node-pre-gyp ERR! stack     at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:474:21)
node-pre-gyp ERR! stack     at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
node-pre-gyp ERR! stack     at TLSSocket.socketOnData (_http_client.js:363:20)
node-pre-gyp ERR! stack     at emitOne (events.js:96:13)
node-pre-gyp ERR! System Linux 3.10.0-229.1.2.el7.x86_64
node-pre-gyp ERR! command "/usr/bin/node" "/home/idf/Documents/js/node_modules/.bin/node-pre-gyp" "install"
node-pre-gyp ERR! cwd /home/idf/Documents/js/node_modules/quantlib
node-pre-gyp ERR! node -v v6.9.4
node-pre-gyp ERR! node-pre-gyp -v v0.6.33
node-pre-gyp ERR! not ok
404 status code downloading tarball https://github.com/quantlibnode/quantlibnode/releases/download/v0.2.1/linux-x64.tar.gz
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN enoent ENOENT: no such file or directory, open '/home/idf/Documents/js/package.json'
npm WARN js No description
npm WARN js No repository field.
npm WARN js No README data
npm WARN js No license field.
npm ERR! Linux 3.10.0-229.1.2.el7.x86_64
npm ERR! argv "/usr/bin/node" "/bin/npm" "install" "quantlib"
npm ERR! node v6.9.4
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE

npm ERR! quantlib@0.2.1 postinstall: `node-pre-gyp install`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the quantlib@0.2.1 postinstall script 'node-pre-gyp install'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the quantlib package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-pre-gyp install
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs quantlib
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls quantlib
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/idf/Documents/js/ql/npm-debug.log
[idf@node3 ql]$
</code>```

答:
I'm creator of quantlib.node project, sorry for the late response.

Right now, only windows 32/64 bit pre-build are provided. For Mac and Linux, you'll have to build the addon yourself.

The reason Mac/Linux pre-build is missing is that, the building process is a bit complicated, on Mac/Linux we can't use pre-build quantlib, we need to build it from source and add certain flags: like -std=c++11, which is required by node

And I did try using static linking to boost and quantlib(to remove the library dependency), the generated addon is very big, 200M+ (after tar.gz). This is not convenient for download.

For now, please follow the steps in README.md to build the addon, you probably want to build it using dynamic linking, so the generated addon is much smaller.

I'll see if I can make this part easier, please stay tuned

ContentLicense: CC BY-SA 3.0

Title: Installing quantlib for javascript

Body:
I am trying to install quantlib for javascript on both linux and windows. I get a similar error in both cases.

[idf@node3 ql]$ sudo npm install quantlib
[sudo] password for idf:

> quantlib@0.2.1 postinstall /home/idf/Documents/js/node_modules/quantlib
> node-pre-gyp install

node-pre-gyp ERR! install error
node-pre-gyp ERR! stack Error: 404 status code downloading tarball https://github.com/quantlibnode/quantlibnode/releases/download/v0.2.1/linux-x64.tar.gz
node-pre-gyp ERR! stack     at Request.<anonymous> (/home/idf/Documents/js/node_modules/node-pre-gyp/lib/install.js:120:27)
node-pre-gyp ERR! stack     at emitOne (events.js:101:20)
node-pre-gyp ERR! stack     at Request.emit (events.js:188:7)
node-pre-gyp ERR! stack     at Request.onRequestResponse (/home/idf/Documents/js/node_modules/request/request.js:1029:10)
node-pre-gyp ERR! stack     at emitOne (events.js:96:13)
node-pre-gyp ERR! stack     at ClientRequest.emit (events.js:188:7)
node-pre-gyp ERR! stack     at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:474:21)
node-pre-gyp ERR! stack     at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
node-pre-gyp ERR! stack     at TLSSocket.socketOnData (_http_client.js:363:20)
node-pre-gyp ERR! stack     at emitOne (events.js:96:13)
node-pre-gyp ERR! System Linux 3.10.0-229.1.2.el7.x86_64
node-pre-gyp ERR! command "/usr/bin/node" "/home/idf/Documents/js/node_modules/.bin/node-pre-gyp" "install"
node-pre-gyp ERR! cwd /home/idf/Documents/js/node_modules/quantlib
node-pre-gyp ERR! node -v v6.9.4
node-pre-gyp ERR! node-pre-gyp -v v0.6.33
node-pre-gyp ERR! not ok
404 status code downloading tarball https://github.com/quantlibnode/quantlibnode/releases/download/v0.2.1/linux-x64.tar.gz
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN enoent ENOENT: no such file or directory, open '/home/idf/Documents/js/package.json'
npm WARN js No description
npm WARN js No repository field.
npm WARN js No README data
npm WARN js No license field.
npm ERR! Linux 3.10.0-229.1.2.el7.x86_64
npm ERR! argv "/usr/bin/node" "/bin/npm" "install" "quantlib"
npm ERR! node v6.9.4
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE

npm ERR! quantlib@0.2.1 postinstall: `node-pre-gyp install`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the quantlib@0.2.1 postinstall script 'node-pre-gyp install'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the quantlib package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-pre-gyp install
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs quantlib
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls quantlib
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/idf/Documents/js/ql/npm-debug.log
[idf@node3 ql]$


问:
Word Add-in behavior different in El Capitan vs. Sierra
My Annotate PRO Add-in behaves just fine across Word Online, Windows, and macOS Sierra.

Office Store link if you want to try it.

Users on 10.11.6 have reported that when opening the Annotate taskpane they get the message that, essentially, says they aren't on Word 2016 with WordAPI 1.1.

Same message you get if you browse directly to the taskpane html.

I have validated this behavior on a mac running 10.11.6 and using Microsoft Word 2016 (15.32).

The gold standard for me, when developing and learning the new Microsoft approach, is Word Online. If it works there then it should work...and Microsoft approved my Extension.

So I'm concerned that there is an issue with 10.11.6 that doesn't affect Sierra users. Perhaps something in webkit? My add-in works just fine in Word Online using Safari on 10.11.6.

A related issue/question concerns whether the Add-in appears as a tab in Word.

Annotate appears in Word 2016 Sierra as a tab, like Insert, Review etc.

It does not appear in Word 2016 (with all updates) running on 10.11.6.

Not sure if being part of the "Office Insider Slow" updates plan affects this...but I thought it material and worth mentioning. My Sierra development machine is part of the "Office Insider Slow" updates but the 10.11.6 machine is not.

I will post the manifest XML as a separate question and add the link as a comment.

Any Microsoft or other expert help deeply appreciated. This is a major blocker for me - I can't go to the marketplace with "only works on Sierra with Office Insider Slow" requirements.

答:
I traced my problem to the use of 'const' while in 'use strict'...

I was using a code snippet from Firebase/Google (for authentication across all my apps/websites) that declared a variable using “const”.

In “use strict” this is not allowed in older versions of WebKit. It’s been fixed, which is why Sierra was okay (I guess).

See [https://bugs.webkit.org/show_bug.cgi?id=161464][1].

But it threw an error on 10.11.6 and (I guess) earlier.

Here is the crucial bit of info: how to turn on debugging for WebKit (when used as an embedded browser):

Run the following command using terminal on your Mac:

```<code>defaults write com.Microsoft.OsfWebHost WebKitDeveloperExtras -bool true
</code>```

After you've run this in Terminal you can right-click on the taskpane and debug...

This isn't an official/supported approach by Apple...but it's working now. Miraculous.

Body:
I traced my problem to the use of 'const' while in 'use strict'...

I was using a code snippet from Firebase/Google (for authentication across all my apps/websites) that declared a variable using “const”.

In “use strict” this is not allowed in older versions of WebKit. It’s been fixed, which is why Sierra was okay (I guess).

See [https://bugs.webkit.org/show_bug.cgi?id=161464][1].

But it threw an error on 10.11.6 and (I guess) earlier.

Here is the crucial bit of info: how to turn on debugging for WebKit (when used as an embedded browser):

Run the following command using terminal on your Mac:

defaults write com.Microsoft.OsfWebHost WebKitDeveloperExtras -bool true

After you've run this in Terminal you can right-click on the taskpane and debug...

This isn't an official/supported approach by Apple...but it's working now. Miraculous.


问:
Change in date format after exporting data.frame from R as .csv
It is a simple question but I couldn't find an answer.

I have this data.frame in R

```<code>df <- data.frame(date = as.Date(c("2001-01-05", "2000-05-13", "2000-07-22", "2000-07-22", "1990-11-03")))
</code>```

I want to export it as .csv file where Month will be abbreviated (%b) and year will be year with century (%Y) as below

```<code>df1 <- df %>% mutate(date = format(as.Date(date, "%Y-%m-%d"), "%b-%Y"))
write.csv(df1, "df1.csv")
> df1
      date
1 Jan-2001
2 May-2000
3 Jul-2000
4 Jul-2000
5 Nov-1990
</code>```

After I opened the df1.csv file, I found a different format for the date as below

I couldn't find the format month(abbreviated)-YEAR. Any suggestion how to fix it?

答:
You have to change the format in all the date cells in Excel.
Go to format cells and then change the format from

```<code>mmm-yy
</code>```

to

```<code>mmm-yyyy
</code>```

This format is not in the the list, change it in the box between "Type" and the format options list

Body:
It is a simple question but I couldn't find an answer.

I have this data.frame in R

df <- data.frame(date = as.Date(c("2001-01-05", "2000-05-13", "2000-07-22", "2000-07-22", "1990-11-03")))

I want to export it as .csv file where Month will be abbreviated (%b) and year will be year with century (%Y) as below

df1 <- df %>% mutate(date = format(as.Date(date, "%Y-%m-%d"), "%b-%Y"))
write.csv(df1, "df1.csv")
> df1
      date
1 Jan-2001
2 May-2000
3 Jul-2000
4 Jul-2000
5 Nov-1990

After I opened the df1.csv file, I found a different format for the date as below

I couldn't find the format month(abbreviated)-YEAR. Any suggestion how to fix it?

Body:
You have to change the format in all the date cells in Excel.
Go to format cells and then change the format from

mmm-yy

to

mmm-yyyy

This format is not in the the list, change it in the box between "Type" and the format options list


问:
Move .ipynb using the IPython Notebook Web Interface
After creating a .ipynb file in the root directory /, how can you move that .pynb file into a deeper directory ie: /subdirectory using the web UI?

答: Duplicate the notebook and delete the original, was my workaround.</p>


问:
Hiding username and password in Visual Studio Azure connection
When making connections in Visual Studio to an Azure SQL Database, you have to write Username and Password for a user that has access to change the SQL database. How do I avoid this, since I'm worried preventing decompilation can only last for so long?

For example:

```<code>    SqlConnection myConnection = new SqlConnection("Server=tcp:MYSERVER;Database=MYDATABASE;user id=MYIDHERE;password=MYPASSWORDHERE;Trusted_Connection=False;Encrypt=True;Connection Timeout=15;");
</code>```

So, long story short, how do I avoid entering user id and password?

It just doesn't feel safe since anyone could be able to add stuff to the database if they decompiled the program.

答:
Azure SQL Database supports two types of authentication: SQL Authentication that uses a username and password and Azure AD Authentication that uses identities managed by Azure Active Directory and is supported for managed and integrated domains. If you don’t want to use SQL Authentication, Azure AD Authentication is an alternative choice.

Besides, Azure SQL Database firewalls prevent all access to your database server until you specify which computers have permission using firewall rules. Client that gets username and password are not able to access your databases if it is not in ranges of acceptable IP addresses that you specify in firewall rules.

Body:
When making connections in Visual Studio to an Azure SQL Database, you have to write Username and Password for a user that has access to change the SQL database. How do I avoid this, since I'm worried preventing decompilation can only last for so long?

For example:

    SqlConnection myConnection = new SqlConnection("Server=tcp:MYSERVER;Database=MYDATABASE;user id=MYIDHERE;password=MYPASSWORDHERE;Trusted_Connection=False;Encrypt=True;Connection Timeout=15;");

So, long story short, how do I avoid entering user id and password?

It just doesn't feel safe since anyone could be able to add stuff to the database if they decompiled the program.


问:
Why is strace missing network syscalls?
When I to run strace on dig (strace dig google.com), there are no sendto or recvfrom syscalls as you would expect for a DNS query. dig is definitely performing network requests: I can see the queries in Wireshark. strace is capturing the socket and close syscalls, though. The full trace is available at https://pastebin.com/aU816wLq, but I pasted the relevant section below:

```<code>futex(0x7f3e959bbe34, FUTEX_WAKE_PRIVATE, 2147483647) = 0
futex(0x7f3e959bbf80, FUTEX_WAKE_PRIVATE, 2147483647) = 0
futex(0x7f3e963f9290, FUTEX_WAKE_PRIVATE, 2147483647) = 0
socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 3
close(3)                                = 0
socket(PF_INET6, SOCK_STREAM, IPPROTO_IP) = 3
getsockname(3, {sa_family=AF_INET6, sin6_port=htons(0), inet_pton(AF_INET6, "::", &sin6_addr), sin6_flowinfo=0, sin6_scope_id=0}, [28]) = 0
close(3)                                = 0
socket(PF_LOCAL, SOCK_STREAM, 0)        = 3
close(3)                                = 0
futex(0x7f3e959bc3ac, FUTEX_WAKE_PRIVATE, 2147483647) = 0
futex(0x7f3e959bbf08, FUTEX_WAKE_PRIVATE, 2147483647) = 0
mmap(NULL, 266240, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f3e965c8000
mmap(NULL, 8392704, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_STACK, -1, 0) = 0x7f3e9028f000
mprotect(0x7f3e9028f000, 4096, PROT_NONE) = 0
clone(child_stack=0x7f3e90a8efb0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7f3e90a8f9d0, tls=0x7f3e90a8f700, child_tidptr=0x7f3e90a8f9d0) = 3083
mmap(NULL, 8392704, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_STACK, -1, 0) = 0x7f3e8fa8e000
mprotect(0x7f3e8fa8e000, 4096, PROT_NONE) = 0
clone(child_stack=0x7f3e9028dfb0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7f3e9028e9d0, tls=0x7f3e9028e700, child_tidptr=0x7f3e9028e9d0) = 3084
brk(0x55fd6e9cd000)                     = 0x55fd6e9cd000
pipe([3, 4])                            = 0
fcntl(3, F_GETFL)                       = 0 (flags O_RDONLY)
fcntl(3, F_SETFL, O_RDONLY|O_NONBLOCK)  = 0
epoll_create(64)                        = 5
epoll_ctl(5, EPOLL_CTL_ADD, 3, {EPOLLIN, {u32=3, u64=3}}) = 0
mmap(NULL, 8392704, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_STACK, -1, 0) = 0x7f3e8f28d000
mprotect(0x7f3e8f28d000, 4096, PROT_NONE) = 0
clone(child_stack=0x7f3e8fa8cfb0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7f3e8fa8d9d0, tls=0x7f3e8fa8d700, child_tidptr=0x7f3e8fa8d9d0) = 3085
open("/usr/share/locale/en_US.UTF-8/libdst.cat", O_RDONLY) = -1 ENOENT (No such file or directory)
open("/usr/share/locale/en_US.UTF-8/LC_MESSAGES/libdst.cat", O_RDONLY) = -1 ENOENT (No such file or directory)
open("/usr/share/locale/en/libdst.cat", O_RDONLY) = -1 ENOENT (No such file or directory)
open("/usr/share/locale/en/LC_MESSAGES/libdst.cat", O_RDONLY) = -1 ENOENT (No such file or directory)
futex(0x7f3e963f9b20, FUTEX_WAKE_PRIVATE, 2147483647) = 0
futex(0x7f3e963f9b24, FUTEX_WAKE_PRIVATE, 2147483647) = 0
brk(0x55fd6e9ee000)                     = 0x55fd6e9ee000
open("/usr/lib/ssl/openssl.cnf", O_RDONLY) = 6
fstat(6, {st_mode=S_IFREG|0644, st_size=10835, ...}) = 0
read(6, "#\n# OpenSSL example configuratio"..., 4096) = 4096
read(6, "Netscape crash on BMPStrings or "..., 4096) = 4096
read(6, " this to avoid interpreting an e"..., 4096) = 2643
read(6, "", 4096)                       = 0
close(6)                                = 0
futex(0x7f3e94c480a8, FUTEX_WAKE_PRIVATE, 2147483647) = 0
open("/usr/lib/x86_64-linux-gnu/openssl-1.0.0/engines/libgost.so", O_RDONLY|O_CLOEXEC) = 6
read(6, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220T\0\0\0\0\0\0"..., 832) = 832
fstat(6, {st_mode=S_IFREG|0644, st_size=93280, ...}) = 0
mmap(NULL, 2188320, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 6, 0) = 0x7f3e8f076000
mprotect(0x7f3e8f08b000, 2093056, PROT_NONE) = 0
mmap(0x7f3e8f28a000, 12288, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 6, 0x14000) = 0x7f3e8f28a000
close(6)                                = 0
mprotect(0x7f3e8f28a000, 4096, PROT_READ) = 0
open("/home/ubuntu-user/.digrc", O_RDONLY)  = -1 ENOENT (No such file or directory)
open("/etc/resolv.conf", O_RDONLY)      = 6
fstat(6, {st_mode=S_IFREG|0644, st_size=208, ...}) = 0
read(6, "# Dynamic resolv.conf(5) file fo"..., 4096) = 208
read(6, "", 4096)                       = 0
close(6)                                = 0
getppid()                               = 3080
rt_sigaction(SIGHUP, {0x7f3e957899e0, ~[RTMIN RT_1], SA_RESTORER, 0x7f3e9553f390}, NULL, 8) = 0
rt_sigsuspend([], 8)                    = ? ERESTARTNOHAND (To be restarted if no handler)
--- SIGTERM {si_signo=SIGTERM, si_code=SI_TKILL, si_pid=3082, si_uid=1000} ---
rt_sigreturn({mask=[HUP INT TERM]})     = -1 EINTR (Interrupted system call)
futex(0x55fd6df085a0, FUTEX_WAIT_PRIVATE, 2, NULL) = 0
futex(0x55fd6df085a0, FUTEX_WAKE_PRIVATE, 1) = 0
futex(0x7f3e90a8f9d0, FUTEX_WAIT, 3083, NULL) = 0
write(4, "\0\0\0\0\377\377\377\377", 8) = 8
epoll_ctl(5, EPOLL_CTL_DEL, 3, 0x7fff8ed49d10) = 0
close(5)                                = 0
close(3)                                = 0
close(4)                                = 0
futex(0x7f3e965cf07c, FUTEX_WAKE_OP_PRIVATE, 1, 1, 0x7f3e965cf078, {FUTEX_OP_SET, 0, FUTEX_OP_CMP_GT, 1}) = 1
futex(0x7f3e965cf028, FUTEX_WAKE_PRIVATE, 1) = 1
munmap(0x7f3e8f076000, 2188320)         = 0
munmap(0x7f3e965c8000, 266240)          = 0
write(1, "\n; <<>> DiG 9.10.3-P4-Ubuntu <<>"..., 484) = 484
exit_group(0)                           = ?
+++ exited with 0 +++
</code>```

I see clone syscalls there. Is dig forking and handling the DNS query in another process?

Versions:

strace -- version 4.11

DiG 9.10.3-P4-Ubuntu

Linux ubuntu 4.4.0-71-generic #92-Ubuntu SMP Fri Mar 24 12:59:01 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

答: The dig process is creating threads. Use strace -f to follow them.

Title: Why is strace missing network syscalls?

Body:
When I to run strace on dig (strace dig google.com), there are no sendto or recvfrom syscalls as you would expect for a DNS query. dig is definitely performing network requests: I can see the queries in Wireshark. strace is capturing the socket and close syscalls, though. The full trace is available at https://pastebin.com/aU816wLq, but I pasted the relevant section below:

futex(0x7f3e959bbe34, FUTEX_WAKE_PRIVATE, 2147483647) = 0
futex(0x7f3e959bbf80, FUTEX_WAKE_PRIVATE, 2147483647) = 0
futex(0x7f3e963f9290, FUTEX_WAKE_PRIVATE, 2147483647) = 0
socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 3
close(3)                                = 0
socket(PF_INET6, SOCK_STREAM, IPPROTO_IP) = 3
getsockname(3, {sa_family=AF_INET6, sin6_port=htons(0), inet_pton(AF_INET6, "::", &sin6_addr), sin6_flowinfo=0, sin6_scope_id=0}, [28]) = 0
close(3)                                = 0
socket(PF_LOCAL, SOCK_STREAM, 0)        = 3
close(3)                                = 0
futex(0x7f3e959bc3ac, FUTEX_WAKE_PRIVATE, 2147483647) = 0
futex(0x7f3e959bbf08, FUTEX_WAKE_PRIVATE, 2147483647) = 0
mmap(NULL, 266240, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f3e965c8000
mmap(NULL, 8392704, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_STACK, -1, 0) = 0x7f3e9028f000
mprotect(0x7f3e9028f000, 4096, PROT_NONE) = 0
clone(child_stack=0x7f3e90a8efb0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7f3e90a8f9d0, tls=0x7f3e90a8f700, child_tidptr=0x7f3e90a8f9d0) = 3083
mmap(NULL, 8392704, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_STACK, -1, 0) = 0x7f3e8fa8e000
mprotect(0x7f3e8fa8e000, 4096, PROT_NONE) = 0
clone(child_stack=0x7f3e9028dfb0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7f3e9028e9d0, tls=0x7f3e9028e700, child_tidptr=0x7f3e9028e9d0) = 3084
brk(0x55fd6e9cd000)                     = 0x55fd6e9cd000
pipe([3, 4])                            = 0
fcntl(3, F_GETFL)                       = 0 (flags O_RDONLY)
fcntl(3, F_SETFL, O_RDONLY|O_NONBLOCK)  = 0
epoll_create(64)                        = 5
epoll_ctl(5, EPOLL_CTL_ADD, 3, {EPOLLIN, {u32=3, u64=3}}) = 0
mmap(NULL, 8392704, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_STACK, -1, 0) = 0x7f3e8f28d000
mprotect(0x7f3e8f28d000, 4096, PROT_NONE) = 0
clone(child_stack=0x7f3e8fa8cfb0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7f3e8fa8d9d0, tls=0x7f3e8fa8d700, child_tidptr=0x7f3e8fa8d9d0) = 3085
open("/usr/share/locale/en_US.UTF-8/libdst.cat", O_RDONLY) = -1 ENOENT (No such file or directory)
open("/usr/share/locale/en_US.UTF-8/LC_MESSAGES/libdst.cat", O_RDONLY) = -1 ENOENT (No such file or directory)
open("/usr/share/locale/en/libdst.cat", O_RDONLY) = -1 ENOENT (No such file or directory)
open("/usr/share/locale/en/LC_MESSAGES/libdst.cat", O_RDONLY) = -1 ENOENT (No such file or directory)
futex(0x7f3e963f9b20, FUTEX_WAKE_PRIVATE, 2147483647) = 0
futex(0x7f3e963f9b24, FUTEX_WAKE_PRIVATE, 2147483647) = 0
brk(0x55fd6e9ee000)                     = 0x55fd6e9ee000
open("/usr/lib/ssl/openssl.cnf", O_RDONLY) = 6
fstat(6, {st_mode=S_IFREG|0644, st_size=10835, ...}) = 0
read(6, "#\n# OpenSSL example configuratio"..., 4096) = 4096
read(6, "Netscape crash on BMPStrings or "..., 4096) = 4096
read(6, " this to avoid interpreting an e"..., 4096) = 2643
read(6, "", 4096)                       = 0
close(6)                                = 0
futex(0x7f3e94c480a8, FUTEX_WAKE_PRIVATE, 2147483647) = 0
open("/usr/lib/x86_64-linux-gnu/openssl-1.0.0/engines/libgost.so", O_RDONLY|O_CLOEXEC) = 6
read(6, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220T\0\0\0\0\0\0"..., 832) = 832
fstat(6, {st_mode=S_IFREG|0644, st_size=93280, ...}) = 0
mmap(NULL, 2188320, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 6, 0) = 0x7f3e8f076000
mprotect(0x7f3e8f08b000, 2093056, PROT_NONE) = 0
mmap(0x7f3e8f28a000, 12288, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 6, 0x14000) = 0x7f3e8f28a000
close(6)                                = 0
mprotect(0x7f3e8f28a000, 4096, PROT_READ) = 0
open("/home/ubuntu-user/.digrc", O_RDONLY)  = -1 ENOENT (No such file or directory)
open("/etc/resolv.conf", O_RDONLY)      = 6
fstat(6, {st_mode=S_IFREG|0644, st_size=208, ...}) = 0
read(6, "# Dynamic resolv.conf(5) file fo"..., 4096) = 208
read(6, "", 4096)                       = 0
close(6)                                = 0
getppid()                               = 3080
rt_sigaction(SIGHUP, {0x7f3e957899e0, ~[RTMIN RT_1], SA_RESTORER, 0x7f3e9553f390}, NULL, 8) = 0
rt_sigsuspend([], 8)                    = ? ERESTARTNOHAND (To be restarted if no handler)
--- SIGTERM {si_signo=SIGTERM, si_code=SI_TKILL, si_pid=3082, si_uid=1000} ---
rt_sigreturn({mask=[HUP INT TERM]})     = -1 EINTR (Interrupted system call)
futex(0x55fd6df085a0, FUTEX_WAIT_PRIVATE, 2, NULL) = 0
futex(0x55fd6df085a0, FUTEX_WAKE_PRIVATE, 1) = 0
futex(0x7f3e90a8f9d0, FUTEX_WAIT, 3083, NULL) = 0
write(4, "\0\0\0\0\377\377\377\377", 8) = 8
epoll_ctl(5, EPOLL_CTL_DEL, 3, 0x7fff8ed49d10) = 0
close(5)                                = 0
close(3)                                = 0
close(4)                                = 0
futex(0x7f3e965cf07c, FUTEX_WAKE_OP_PRIVATE, 1, 1, 0x7f3e965cf078, {FUTEX_OP_SET, 0, FUTEX_OP_CMP_GT, 1}) = 1
futex(0x7f3e965cf028, FUTEX_WAKE_PRIVATE, 1) = 1
munmap(0x7f3e8f076000, 2188320)         = 0
munmap(0x7f3e965c8000, 266240)          = 0
write(1, "\n; <<>> DiG 9.10.3-P4-Ubuntu <<>"..., 484) = 484
exit_group(0)                           = ?
+++ exited with 0 +++

I see clone syscalls there. Is dig forking and handling the DNS query in another process?

Versions:

strace -- version 4.11

DiG 9.10.3-P4-Ubuntu

Linux ubuntu 4.4.0-71-generic #92-Ubuntu SMP Fri Mar 24 12:59:01 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux


问:
Sending Type Parameters like DirectCast
I've made this extension to replace my usage of DirectCast, because i don't find it very readable.

```<code><Extension>
Public Function [As](Of T)(Input As Object) As T
    Return DirectCast(Input, T)
End Function

Dim i = (New Integer).As(Of Integer)
</code>```

My problem is the need for "Of" before writing integer.
DirectCast doesn't need that.

```<code>DirectCast(New Integer, Integer)
</code>```

How can i change my code to have the same appearance as DirectCast's type parameter?

Essentially looking like this:

```<code>Dim i = (New Integer).As(Integer)
</code>```

答:
Just use a normal function instead of an extension method:

```<code>Function ToInt(o As Object) As Integer
  Return DirectCast(o, Integer)
End Function
</code>```

The other option is to use the VB type conversion functions: MSDN link (Note, however, that they return new objects - they are not typecasting functions)

Though really, I'd recommend you stick to the built-in DirectCast function. All you are really doing is replacing a built-in keyword with a custom keyword that no-one else will recognise.

Title: Sending Type Parameters like DirectCast

Body:
I've made this extension to replace my usage of DirectCast, because i don't find it very readable.

<Extension>
Public Function [As](Of T)(Input As Object) As T
    Return DirectCast(Input, T)
End Function

Dim i = (New Integer).As(Of Integer)

My problem is the need for "Of" before writing integer.
DirectCast doesn't need that.

DirectCast(New Integer, Integer)

How can i change my code to have the same appearance as DirectCast's type parameter?

Essentially looking like this:

Dim i = (New Integer).As(Integer)

Body:
Just use a normal function instead of an extension method:

Function ToInt(o As Object) As Integer
  Return DirectCast(o, Integer)
End Function

The other option is to use the VB type conversion functions: MSDN link (Note, however, that they return new objects - they are not typecasting functions)

Though really, I'd recommend you stick to the built-in DirectCast function. All you are really doing is replacing a built-in keyword with a custom keyword that no-one else will recognise.


问:
Can't run Instruments from Xcode
I recently upgraded to Snow Leopard and since then I am having difficulty running Instrument to instrument my app from Xcode.  The Record button would be grayed out, and nothing happens.  There is no message in Xcode's console telling me what's wrong either.  I used to be able to attach it to process or launch the process from Instruments as well, all these are no longer working.

Any idea what's causing this?

答: As pointed out in Apple's discussion forum, restarting your machine works. It works for me.</p>

ContentLicense: CC BY-SA 2.5

Title: Can't run Instruments from Xcode


问:
Converting cordova project using VS 2015 certificate issue
Does any one know how to assign the certificate file to the project while creating the Windows app package.

Basically i have a cordova Ionic project which was already developed and now to make a windows app, i used VS 2015 --new project option from existing code. after few hiccups am able to run the windows app,

however am not able to figure out where to add/assign the certificate which i want to use with this package.
am even trying to find where is the app manifest file however not luck in finding it, i can see config.xml.

Appreciate your help.
Regards,
RK.

答:
Does any one know how to assign the certificate file to the project while creating the Windows app package.

If you haven't got a certificate file, you should create one(.pfx file). You can follow How to create an app package signing certificate to create one.

Once you got the certificate. You can sign your app by modifying the build.json file. You can refer to Sign Windows App for details.


问:
Embedded Class In TypeScript
I am very new to typescript. Here is a problem I need to solve. I already have the following:

```<code>const enum MyEnum {
   ...
};
export class A {
  constructor(
    ...
    public enu?: MyEnu,
    public amount?: number,
  ) {
  }
}
</code>```

Now, I need to move the above two attributes into a class B. After a few tries, I haven't been able to figure out a right way. The following is one of my tries:

```<code>export class A {
    constructor(
      ...
      public b?: B,
    ) {
   }
   export class B {
    constructor(
        public enu?: MyEnu,
        public amount?: number
    ) {
    }
}
</code>```

What will be a right way to define an embedded class in this case?

Updated:
I try the following:

```<code>export interface IB{}
class B implements IB {
  constructor(public enu?: MyEnu, public amount ?: number){}
}
export class A {
  static B = B;
  constructor(public b?: IB) { }
}
</code>```

Without a luck.

答:
The only way I can think of, of pulling this off is something like this:

```<code>export enum MyEnum {
    ...
}

export interface IB {
    ...
}

class B implements IB {
    ...
}

export class A {
    static B = B;
    constructor(public b?: IB) {
        ...
    }
}
</code>```

Or:

```<code>export class A {
    static B = (class B implements IB {
        ...
    });
    constructor(public b?: IB) {
        ...
    }
}
</code>```

You cannot reference A.B in the constructor signature.

Java and typescript are different, you cannot always "mirror" java code into typescript and this is one of those cases.

Also notice that the inner class is like a static inner class in java, you won't be able to access instance members of A from within A.B

Title: Embedded Class In TypeScript

Body:
I am very new to typescript. Here is a problem I need to solve. I already have the following:

const enum MyEnum {
   ...
};
export class A {
  constructor(
    ...
    public enu?: MyEnu,
    public amount?: number,
  ) {
  }
}

Now, I need to move the above two attributes into a class B. After a few tries, I haven't been able to figure out a right way. The following is one of my tries:

export class A {
    constructor(
      ...
      public b?: B,
    ) {
   }
   export class B {
    constructor(
        public enu?: MyEnu,
        public amount?: number
    ) {
    }
}

What will be a right way to define an embedded class in this case?

Updated:
I try the following:

export interface IB{}
class B implements IB {
  constructor(public enu?: MyEnu, public amount ?: number){}
}
export class A {
  static B = B;
  constructor(public b?: IB) { }
}

Without a luck.

Body:
The only way I can think of, of pulling this off is something like this:

export enum MyEnum {
    ...
}

export interface IB {
    ...
}

class B implements IB {
    ...
}

export class A {
    static B = B;
    constructor(public b?: IB) {
        ...
    }
}

Or:

export class A {
    static B = (class B implements IB {
        ...
    });
    constructor(public b?: IB) {
        ...
    }
}

You cannot reference A.B in the constructor signature.

Java and typescript are different, you cannot always "mirror" java code into typescript and this is one of those cases.

Also notice that the inner class is like a static inner class in java, you won't be able to access instance members of A from within A.B


问:
Convert key value pairs with duplicate keys into a Counter
I've got this in Python 2.7

```<code>l = [('a', 1), ('a', 2), ('b', 3), ('b', 4)]
</code>```

How do I get a Counter c where:

```<code>c = Counter({'a': 3, 'b': 7 }]
</code>```

I would prefer to use comprehension if possible or the fastest possible way to do this.

答:
Another way to do this:

```<code>>>> from operator import add
>>> reduce(add, map(lambda x: Counter({x[0]: x[1]}), l))
Counter({'b': 7, 'a': 3})
</code>```

Or sum:

```<code>>>> sum(map(lambda x: Counter({x[0]: x[1]}), l), Counter())
Counter({'b': 7, 'a': 3})
</code>```

Body:
I've got this in Python 2.7

l = [('a', 1), ('a', 2), ('b', 3), ('b', 4)]

How do I get a Counter c where:

c = Counter({'a': 3, 'b': 7 }]

I would prefer to use comprehension if possible or the fastest possible way to do this.

Body:
Another way to do this:

>>> from operator import add
>>> reduce(add, map(lambda x: Counter({x[0]: x[1]}), l))
Counter({'b': 7, 'a': 3})

Or sum:

>>> sum(map(lambda x: Counter({x[0]: x[1]}), l), Counter())
Counter({'b': 7, 'a': 3})


问:
Python: create a pandas data frame from a list
I am using the following code to create a data frame from a list:

```<code>test_list = ['a','b','c','d']
df_test = pd.DataFrame.from_records(test_list, columns=['my_letters'])
df_test
</code>```

The above code works fine. Then I tried the same approach for another list:

```<code>import pandas as pd
q_list = ['112354401', '116115526', '114909312', '122425491', '131957025', '111373473']
df1 = pd.DataFrame.from_records(q_list, columns=['q_data'])
df1
</code>```

But it gave me the following errors this time:

```<code>---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-24-99e7b8e32a52> in <module>()
      1 import pandas as pd
      2 q_list = ['112354401', '116115526', '114909312', '122425491', '131957025', '111373473']
----> 3 df1 = pd.DataFrame.from_records(q_list, columns=['q_data'])
      4 df1

/usr/local/lib/python3.4/dist-packages/pandas/core/frame.py in from_records(cls, data, index, exclude, columns, coerce_float, nrows)
   1021         else:
   1022             arrays, arr_columns = _to_arrays(data, columns,
-> 1023                                              coerce_float=coerce_float)
   1024
   1025             arr_columns = _ensure_index(arr_columns)

/usr/local/lib/python3.4/dist-packages/pandas/core/frame.py in _to_arrays(data, columns, coerce_float, dtype)
   5550         data = lmap(tuple, data)
   5551         return _list_to_arrays(data, columns, coerce_float=coerce_float,
-> 5552                                dtype=dtype)
   5553
   5554

/usr/local/lib/python3.4/dist-packages/pandas/core/frame.py in _list_to_arrays(data, columns, coerce_float, dtype)
   5607         content = list(lib.to_object_array(data).T)
   5608     return _convert_object_array(content, columns, dtype=dtype,
-> 5609                                  coerce_float=coerce_float)
   5610
   5611

/usr/local/lib/python3.4/dist-packages/pandas/core/frame.py in _convert_object_array(content, columns, coerce_float, dtype)
   5666             # caller's responsibility to check for this...
   5667             raise AssertionError('%d columns passed, passed data had %s '
-> 5668                                  'columns' % (len(columns), len(content)))
   5669
   5670     # provide soft conversion of object dtypes

AssertionError: 1 columns passed, passed data had 9 columns
</code>```

Why would the same approach work for one list but not another? Any idea what might be wrong here? Thanks a lot!

答:
DataFrame.from_records treats string as a character list. so it needs as many columns as length of string.

You could simply use the DataFrame constructor.

```<code>In [3]: pd.DataFrame(q_list, columns=['q_data'])
Out[3]:
      q_data
0  112354401
1  116115526
2  114909312
3  122425491
4  131957025
5  111373473
</code>```

Body:
I am using the following code to create a data frame from a list:

test_list = ['a','b','c','d']
df_test = pd.DataFrame.from_records(test_list, columns=['my_letters'])
df_test

The above code works fine. Then I tried the same approach for another list:

import pandas as pd
q_list = ['112354401', '116115526', '114909312', '122425491', '131957025', '111373473']
df1 = pd.DataFrame.from_records(q_list, columns=['q_data'])
df1

But it gave me the following errors this time:

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-24-99e7b8e32a52> in <module>()
      1 import pandas as pd
      2 q_list = ['112354401', '116115526', '114909312', '122425491', '131957025', '111373473']
----> 3 df1 = pd.DataFrame.from_records(q_list, columns=['q_data'])
      4 df1

/usr/local/lib/python3.4/dist-packages/pandas/core/frame.py in from_records(cls, data, index, exclude, columns, coerce_float, nrows)
   1021         else:
   1022             arrays, arr_columns = _to_arrays(data, columns,
-> 1023                                              coerce_float=coerce_float)
   1024
   1025             arr_columns = _ensure_index(arr_columns)

/usr/local/lib/python3.4/dist-packages/pandas/core/frame.py in _to_arrays(data, columns, coerce_float, dtype)
   5550         data = lmap(tuple, data)
   5551         return _list_to_arrays(data, columns, coerce_float=coerce_float,
-> 5552                                dtype=dtype)
   5553
   5554

/usr/local/lib/python3.4/dist-packages/pandas/core/frame.py in _list_to_arrays(data, columns, coerce_float, dtype)
   5607         content = list(lib.to_object_array(data).T)
   5608     return _convert_object_array(content, columns, dtype=dtype,
-> 5609                                  coerce_float=coerce_float)
   5610
   5611

/usr/local/lib/python3.4/dist-packages/pandas/core/frame.py in _convert_object_array(content, columns, coerce_float, dtype)
   5666             # caller's responsibility to check for this...
   5667             raise AssertionError('%d columns passed, passed data had %s '
-> 5668                                  'columns' % (len(columns), len(content)))
   5669
   5670     # provide soft conversion of object dtypes

AssertionError: 1 columns passed, passed data had 9 columns

Why would the same approach work for one list but not another? Any idea what might be wrong here? Thanks a lot!

Body:
DataFrame.from_records treats string as a character list. so it needs as many columns as length of string.

You could simply use the DataFrame constructor.

In [3]: pd.DataFrame(q_list, columns=['q_data'])
Out[3]:
      q_data
0  112354401
1  116115526
2  114909312
3  122425491
4  131957025
5  111373473

ContentLicense: CC BY-SA 4.0


问:
Import maven project from Eclipse to Android Studio
I have a very complex maven project in Eclipse with many modules and submodules and a lot of dependencies to each other and to third party files in pom.xml files.
 It works well in net browsers.
But how can I try it in PC within an Android phone emulator?
 I have found this Android Studio program, but how can I import my very complex maven project from Eclipse without adding extra file(s) to it (like AndroidManifest.xml,etc) and not to destroy the original structure of the project?
Anyway, I could use the File/Open option from menu and I can see the project in AS, but I can't run it.
 What should I do to run?

答:
If you are trying to migrate an Android application from Eclipse IDE to Android Studio, then the hard truth is there is no easy way. I know because I already did this and it was worth the move.

And if you decide to take the hard route you will need to fully understand the directory structure of your Eclipse project compared to the directory structure of Android Studio projects and how the two IDEs build and deploy the project - because they are totally different and Android Studio uses gradle for its build.

Try reading through the Android Studio Guide and the Migrate to Android Studio from Eclipse.


问:
@ManagedProperty null after @PostConstruct in JSF 2.2
My specs:

Dynamic Web Module 3.1

GlassFish Web Extensions 4.0

Java 1.8

JavaScript 1.0

JavaServer Faces 2.2

Server: glassfish-4.1.1

OS: Win 10

IDE: Version: Neon.2 Release (4.6.2)

Please, note that I have researched this topic and found several related posts.

e.g.

@ManagedProperty + @PostConstruct + init() = Nullpointer

@ManagedProperty injected AFTER @PostConstruct

But neither of the proposed solutions worked for me or applied to my situation.
I don't mix CDI and/or JSF and/or Spring. It's JSF 2.2 annotations only.

I inject @ManagedProperty("#{country}") Country country; to my ChangeCountrySystemEventListener but the value of the @ManagedProperty country is null.
I don't really see where the issue is. The Country constructor does get invoked.

Any tips where the issues is?

Here's my full code:

index.xhtml

```<code>    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
        xmlns:h="http://xmlns.jcp.org/jsf/html"
        xmlns:f="http://xmlns.jcp.org/jsf/core">
    <h:head>
        <title>Title</title>
    </h:head>
    <h:body>

        <h3><h:outputText value="#{country.name}" /> </h3>
        <h:form>

            <h:commandButton
                id="changeCountryNameBtn"
                value="Change"
                action="result"
                actionListener="#{appBean.changeCountryName}"
             />

        </h:form>
    </h:body>
    </html>
</code>```

AppBean.java

```<code>    package com.test.beans;

    import javax.faces.application.Application;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.SessionScoped;
    import javax.faces.context.FacesContext;
    import javax.faces.event.ActionEvent;

    @ManagedBean
    @SessionScoped
    public class AppBean {

        public void changeCountryName(ActionEvent ev) {

            FacesContext context = FacesContext.getCurrentInstance();
            Application app = context.getApplication();
            app.publishEvent(context, ChangeCountrySystemEvent.class, ev.getSource());
            System.out.println(">>>> AppBean.publishEvent(ChangeCountrySystemEvent) fired... " + ev.getSource());

        }

    }
</code>```

ChangeCountrySystemEvent.java

```<code>    package com.test.beans;
    import javax.faces.event.SystemEvent;

    public class ChangeCountrySystemEvent extends SystemEvent {

        private static final long serialVersionUID = -1587717461942271611L;

        public ChangeCountrySystemEvent(Object source) {
            super(source);
            System.out.println(">>>> ChangeCountrySystemEvent.class :: constructor invoked!");
        }

    }
</code>```

ChangeCountrySystemEventListener.java

```<code>    package com.test.beans;

    import javax.faces.bean.ManagedProperty;
    import javax.faces.context.FacesContext;
    import javax.faces.event.SystemEvent;
    import javax.faces.event.SystemEventListener;

    public class ChangeCountrySystemEventListener implements SystemEventListener {

        @ManagedProperty("#{country}")
        Country country;

        // getters and setters
        public Country getCountry() {
            return country;
        }

        public void setCountry(Country country) {
            this.country = country;
        }

        public ChangeCountrySystemEventListener(FacesContext fc) {
            super();
            System.out.println(">>>> ChangeCountrySystemEventListener.class :: Listener constructor invoked!!!");
        }

        @Override
        public void processEvent(SystemEvent se) {

            if (country != null) {
                country.setName("Sweden");
                System.out.println(">>>> ChangeCountrySystemEventListener.class :: SYSTEM EVENT PROCESSED... <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ");
            } else if (country == null) {
                System.out.println(">>>> ChangeCountrySystemEventListener.class :: processEvent() > country managed property is EMPTY !!!!");
            }
        }

        @Override
        public boolean isListenerForSource(Object source) {
            return true; // needs to be set to true, otherwise "processEvent" won't be called...
        }

    }
</code>```

Country.java

```<code>    package com.test.beans;

    import javax.annotation.PostConstruct;
    import javax.faces.application.Application;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.SessionScoped;
    import javax.faces.context.FacesContext;

    @ManagedBean(name = "country", eager = true)
    @SessionScoped
    public class Country {

        private String name = "Norway";

        public Country() {
            System.out.println(">>>> Country constructor called...");
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @PostConstruct
        public void init() {
            FacesContext fc = FacesContext.getCurrentInstance();
            Application app = fc.getApplication();
            app.subscribeToEvent(ChangeCountrySystemEvent.class, new ChangeCountrySystemEventListener(fc));
            System.out.println(">>>> Country.class :: app.subscribeToEvent() called... ");
        }
    }
</code>```

Console output:

```<code>2017-04-02T21:49:51.392-0300|Info: JSF_TestProject was successfully deployed in 579 milliseconds.
2017-04-02T21:49:52.251-0300|Info: >>>> Country constructor called...
2017-04-02T21:49:52.277-0300|Info: >>>> ChangeCountrySystemEventListener.class :: Listener constructor invoked!!!
2017-04-02T21:49:52.277-0300|Info: >>>> Country.class :: app.subscribeToEvent() called...
2017-04-02T21:50:16.572-0300|Info: >>>> ChangeCountrySystemEvent.class :: constructor invoked!
2017-04-02T21:50:16.572-0300|Info: >>>> ChangeCountrySystemEventListener.class :: processEvent() > country managed property is EMPTY !!!!
2017-04-02T21:50:16.572-0300|Info: >>>> AppBean.publishEvent(ChangeCountrySystemEvent) fired... javax.faces.component.html.HtmlCommandButton@424c250c
</code>```

答:
The ManagedProperty can be used on a field of a class annotated with ManagedBean to inject a value into this property.

If this annotation is present on a class that does not have the ManagedBean annotation, the implementation must take no action on this annotation.

Please see http://docs.oracle.com/javaee/6/api/javax/faces/bean/ManagedProperty.html

Since the class ChangeCountrySystemEventListener is not annotated with ManagedBean, no action is taken on the ManagedProperty field country and its null.

Body:
My specs:

Dynamic Web Module 3.1

GlassFish Web Extensions 4.0

Java 1.8

JavaScript 1.0

JavaServer Faces 2.2

Server: glassfish-4.1.1

OS: Win 10

IDE: Version: Neon.2 Release (4.6.2)

Please, note that I have researched this topic and found several related posts.

e.g.

@ManagedProperty + @PostConstruct + init() = Nullpointer

@ManagedProperty injected AFTER @PostConstruct

But neither of the proposed solutions worked for me or applied to my situation.
I don't mix CDI and/or JSF and/or Spring. It's JSF 2.2 annotations only.

I inject @ManagedProperty("#{country}") Country country; to my ChangeCountrySystemEventListener but the value of the @ManagedProperty country is null.
I don't really see where the issue is. The Country constructor does get invoked.

Any tips where the issues is?

Here's my full code:

index.xhtml

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>
        <title>Title</title>
    </h:head>
    <h:body>

<h:outputText value="#{country.name}" />

        <h:form>

            <h:commandButton
                id="changeCountryNameBtn"
                value="Change"
                action="result"
                actionListener="#{appBean.changeCountryName}"
             />

        </h:form>
    </h:body>

AppBean.java

    package com.test.beans;

    import javax.faces.application.Application;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.SessionScoped;
    import javax.faces.context.FacesContext;
    import javax.faces.event.ActionEvent;

    @ManagedBean
    @SessionScoped
    public class AppBean {

        public void changeCountryName(ActionEvent ev) {

            FacesContext context = FacesContext.getCurrentInstance();
            Application app = context.getApplication();
            app.publishEvent(context, ChangeCountrySystemEvent.class, ev.getSource());
            System.out.println(">>>> AppBean.publishEvent(ChangeCountrySystemEvent) fired... " + ev.getSource());

        }

    }

ChangeCountrySystemEvent.java

    package com.test.beans;
    import javax.faces.event.SystemEvent;

    public class ChangeCountrySystemEvent extends SystemEvent {

        private static final long serialVersionUID = -1587717461942271611L;

        public ChangeCountrySystemEvent(Object source) {
            super(source);
            System.out.println(">>>> ChangeCountrySystemEvent.class :: constructor invoked!");
        }

    }

ChangeCountrySystemEventListener.java

    package com.test.beans;

    import javax.faces.bean.ManagedProperty;
    import javax.faces.context.FacesContext;
    import javax.faces.event.SystemEvent;
    import javax.faces.event.SystemEventListener;

    public class ChangeCountrySystemEventListener implements SystemEventListener {

        @ManagedProperty("#{country}")
        Country country;

        // getters and setters
        public Country getCountry() {
            return country;
        }

        public void setCountry(Country country) {
            this.country = country;
        }

        public ChangeCountrySystemEventListener(FacesContext fc) {
            super();
            System.out.println(">>>> ChangeCountrySystemEventListener.class :: Listener constructor invoked!!!");
        }

        @Override
        public void processEvent(SystemEvent se) {

            if (country != null) {
                country.setName("Sweden");
                System.out.println(">>>> ChangeCountrySystemEventListener.class :: SYSTEM EVENT PROCESSED... <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ");
            } else if (country == null) {
                System.out.println(">>>> ChangeCountrySystemEventListener.class :: processEvent() > country managed property is EMPTY !!!!");
            }
        }

        @Override
        public boolean isListenerForSource(Object source) {
            return true; // needs to be set to true, otherwise "processEvent" won't be called...
        }

    }

Country.java

    package com.test.beans;

    import javax.annotation.PostConstruct;
    import javax.faces.application.Application;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.SessionScoped;
    import javax.faces.context.FacesContext;

    @ManagedBean(name = "country", eager = true)
    @SessionScoped
    public class Country {

        private String name = "Norway";

        public Country() {
            System.out.println(">>>> Country constructor called...");
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @PostConstruct
        public void init() {
            FacesContext fc = FacesContext.getCurrentInstance();
            Application app = fc.getApplication();
            app.subscribeToEvent(ChangeCountrySystemEvent.class, new ChangeCountrySystemEventListener(fc));
            System.out.println(">>>> Country.class :: app.subscribeToEvent() called... ");
        }
    }

Console output:

2017-04-02T21:49:51.392-0300|Info: JSF_TestProject was successfully deployed in 579 milliseconds.
2017-04-02T21:49:52.251-0300|Info: >>>> Country constructor called...
2017-04-02T21:49:52.277-0300|Info: >>>> ChangeCountrySystemEventListener.class :: Listener constructor invoked!!!
2017-04-02T21:49:52.277-0300|Info: >>>> Country.class :: app.subscribeToEvent() called...
2017-04-02T21:50:16.572-0300|Info: >>>> ChangeCountrySystemEvent.class :: constructor invoked!
2017-04-02T21:50:16.572-0300|Info: >>>> ChangeCountrySystemEventListener.class :: processEvent() > country managed property is EMPTY !!!!
2017-04-02T21:50:16.572-0300|Info: >>>> AppBean.publishEvent(ChangeCountrySystemEvent) fired... javax.faces.component.html.HtmlCommandButton@424c250c


问:
shellsort algorithm isn't working
I wanted to implement shellsort myself instead of copy pasting the ones online, I would appreciate if anyone could help me find the mistake and improve my silly lil code I will put down my code down below

```<code>#include <iostream>
#include <cmath>

using namespace std;

void swap(int p, int j, int *arr);
void shellSort(int arr[], int gap, int size);

int main() {
    int array[] = {12, 2, 4, 23, 5, 1, 6, 8, 16, 64, 32, 7, 43, 243, 76};
    int size = 15;
    for (int i = 15; i >= 1; i /= 2) {
        shellSort(array,i,size);
        cout << i << endl;
    }

    print(array, 15);
    // shellSortwhile(array, 15);
    print(array, 15);
}

void shellSort(int arr[], int gap, int size) {
    for (int i = 0; i < size; i += gap) {
        if (arr[i] > arr[i + gap]) {
            swap(i, i + gap, arr);
            for(int j = i; j >= 0; j -= gap) {
                if (arr[j] < arr[j - gap]) {
                    swap(j-gap, j, arr);
                }
            }
        }
    }
}
</code>```

My output is:

```<code>Now the array will be printed
2
4
5
6
7
7
8
1076814756
12
15
16
23
32
43
64
</code>```

答: You are reading/writing out of bounds. i+gap is 15 in your first iteration. You have only 15 elements in your array, so you are reading one past the last element. This is the most common mistake in C, don't feel bad about it!

Title: shellsort algorithm isn't working

Body:
I wanted to implement shellsort myself instead of copy pasting the ones online, I would appreciate if anyone could help me find the mistake and improve my silly lil code I will put down my code down below

#include <iostream>
#include <cmath>

using namespace std;

void swap(int p, int j, int *arr);
void shellSort(int arr[], int gap, int size);

int main() {
    int array[] = {12, 2, 4, 23, 5, 1, 6, 8, 16, 64, 32, 7, 43, 243, 76};
    int size = 15;
    for (int i = 15; i >= 1; i /= 2) {
        shellSort(array,i,size);
        cout << i << endl;
    }

    print(array, 15);
    // shellSortwhile(array, 15);
    print(array, 15);
}

void shellSort(int arr[], int gap, int size) {
    for (int i = 0; i < size; i += gap) {
        if (arr[i] > arr[i + gap]) {
            swap(i, i + gap, arr);
            for(int j = i; j >= 0; j -= gap) {
                if (arr[j] < arr[j - gap]) {
                    swap(j-gap, j, arr);
                }
            }
        }
    }
}

My output is:

Now the array will be printed
2
4
5
6
7
7
8
1076814756
12
15
16
23
32
43
64


问:
Max stress node
I am trying to generate scripts to automatically create views of a model at the max stress location.
I know I could read every node and check the stress of each with python but this will take a while due to the size of the model. As this feature appears in CAE is there an easy way to script this?
Once I know the node I am interested in I can then utilize the location of this to generate the views I want.</p>

答:
Calculation of unique nodal stresses

At first you have to think about what stress values you wan't to have. (max unique nodal stress of the whole tensor, Mises, MaxPrincipal,...)
If you wan't for example unique nodal Mises stresses you can calculate Mises stresses for each extrapolated stress tensor and than calculate the unique nodal stresses or the other way around. You will also find that option in the Abaqus CAE Gui.

In this answer I will show how to calculate the max stress value for a whole unique nodal stress tensor.

At first get the stress values.
If you have Abaqus Python 6.13 or newer installed use the FieldBulkData method to get your data. It is much faster as the value method shown in the answer of agentp. For example:

```<code>Field=odb.steps[Steps[0]].frames[1].fieldOutputs['S']
Field = Field.getSubset(position = ELEMENT_NODAL)
Values=Field.bulkDataBlocks[0].data
NodeLabels=Field.bulkDataBlocks[0].nodeLabels
</code>```

Now we have the extrapolated stress values. The calculation of unique values is copied from:
average of all rows corresponing to all unique rows

```<code>NodeLabels_unique, unq_idx = np.unique(NodeLabels, return_inverse=True)
Values_Averaged=np.zeros((NodeLabels_unique.size,Values.shape[1]))
unq_counts = np.bincount(unq_idx)
for i in xrange(0,Values.shape[1]):
    unq_sum = np.bincount(unq_idx, weights=Values[:,i])
    Values_Averaged[:,i] = unq_sum / unq_counts

 #Index of max stress value
 max_ind=np.unravel_index(np.argmax(Values_Averaged),Values_Averaged.shape)

 #Print the results
 print("The max stress is at NodeLabel "+str(NodeLabels_unique[max_ind[0]])+ " its value is "+ str(Values_Averaged[max_ind]) +" MPa.")
</code>```

On my Notebook the whole averaging process takes about 9s for 17,000,000 Element_Nodal values.

Title: Max stress node

Body:
Calculation of unique nodal stresses

At first you have to think about what stress values you wan't to have. (max unique nodal stress of the whole tensor, Mises, MaxPrincipal,...)
If you wan't for example unique nodal Mises stresses you can calculate Mises stresses for each extrapolated stress tensor and than calculate the unique nodal stresses or the other way around. You will also find that option in the Abaqus CAE Gui.

In this answer I will show how to calculate the max stress value for a whole unique nodal stress tensor.

At first get the stress values.
If you have Abaqus Python 6.13 or newer installed use the FieldBulkData method to get your data. It is much faster as the value method shown in the answer of agentp. For example:

Field=odb.steps[Steps[0]].frames[1].fieldOutputs['S']
Field = Field.getSubset(position = ELEMENT_NODAL)
Values=Field.bulkDataBlocks[0].data
NodeLabels=Field.bulkDataBlocks[0].nodeLabels

Now we have the extrapolated stress values. The calculation of unique values is copied from:
average of all rows corresponing to all unique rows

NodeLabels_unique, unq_idx = np.unique(NodeLabels, return_inverse=True)
Values_Averaged=np.zeros((NodeLabels_unique.size,Values.shape[1]))
unq_counts = np.bincount(unq_idx)
for i in xrange(0,Values.shape[1]):
    unq_sum = np.bincount(unq_idx, weights=Values[:,i])
    Values_Averaged[:,i] = unq_sum / unq_counts

 #Index of max stress value
 max_ind=np.unravel_index(np.argmax(Values_Averaged),Values_Averaged.shape)

 #Print the results
 print("The max stress is at NodeLabel "+str(NodeLabels_unique[max_ind[0]])+ " its value is "+ str(Values_Averaged[max_ind]) +" MPa.")

On my Notebook the whole averaging process takes about 9s for 17,000,000 Element_Nodal values.


问:
Azure notifications hub push notification failing or delivering invalid or incomplete data
I am using the following php code to send a push notification to Android application using Azure Notification Hub.

```<code>$hub = new NotificationHub("Endpoint=sb://ServiceName.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SharedAccessKey", "ServiceNameNotification");

        $message = '{"data":{"message":"This is a sample notification","title":"Sample Notification","action":"Test","action_id":"60"}}';
        $notification = new AzureNotification("gcm", $message);
        $hub->sendNotification($notification, null);
</code>```

But unfortunately most of the times the notification is not getting delivered, although I am getting a 201 as the response. Whenever it does get delivered, the results are unpredictable, sometimes the contents of old notifications end up getting shown.

The following code is used to show the notifications in Android app (Xamarin.Android) :

```<code>using System;
using Android.App;
using Android.Content;
using Gcm.Client;
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json.Linq;
using ServiceName.Helpers;

[assembly: Permission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")]
//GET_ACCOUNTS is needed only for Android versions 4.0.3 and below
[assembly: UsesPermission(Name = "android.permission.GET_ACCOUNTS")]
[assembly: UsesPermission(Name = "android.permission.INTERNET")]
[assembly: UsesPermission(Name = "android.permission.WAKE_LOCK")]
namespace ServiceName.Droid
{
    [BroadcastReceiver(Permission = Gcm.Client.Constants.PERMISSION_GCM_INTENTS)]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE },
        Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK },
        Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY },
        Categories = new string[] { "@PACKAGE_NAME@" })]
    public class ServiceNameBroadcastReceiver : GcmBroadcastReceiverBase<PushHandlerService>
    {
        public static string[] senderIDs = new string[] { Constants.SenderID };

        public const string TAG = "MyBroadcastReceiver-GCM";
    }
    // The ServiceAttribute must be applied to the class.
    [Service]
    public class PushHandlerService : GcmServiceBase
    {

        public static string RegistrationID { get; private set; }

        public PushHandlerService() : base(ServiceNameBroadcastReceiver.senderIDs) { }
        protected override void OnMessage(Context context, Intent intent)
        {
            string message = string.Empty;
            string title = string.Empty;
            string action = string.Empty;
            string action_id = string.Empty;
            if (intent.Extras.ContainsKey("title"))
            {
                title = intent.Extras.Get("title").ToString();
            }
            if (intent.Extras.ContainsKey("message"))
            {
                message = intent.Extras.Get("message").ToString();
            }
            if (intent.Extras.ContainsKey("action"))
            {
                action = intent.Extras.Get("action").ToString();
            }
            if (intent.Extras.ContainsKey("action_id"))
            {
                action_id = intent.Extras.Get("action_id").ToString();
            }

            // Extract the push notification message from the intent.
            if (!string.IsNullOrWhiteSpace(message) || !string.IsNullOrWhiteSpace(title))
            {
                // Create a notification manager to send the notification.
                var notificationManager =
                    GetSystemService(Context.NotificationService) as NotificationManager;

                // Create a new intent to show the notification in the UI.
                PendingIntent contentIntent =
                    PendingIntent.GetActivity(context, 0,
                                              new Intent(this, typeof(MainActivity)), 0);

                // Create the notification using the builder.
                var builder = new Notification.Builder(context);
                builder.SetAutoCancel(false);
                if (!string.IsNullOrWhiteSpace(title))
                {
                    builder.SetContentTitle(title);
                }
                else
                {
                    builder.SetContentTitle("Notification from ServiceName");
                }
                if (!string.IsNullOrWhiteSpace(message))
                {
                    builder.SetContentText(message);
                }
                else
                {
                    builder.SetContentText("Hello ServiceName User");
                }
                builder.SetSmallIcon(Resource.Drawable.ic_stat_icon);
                builder.SetContentIntent(contentIntent);
                var notification = builder.Build();

                // Display the notification in the Notifications Area.
                notificationManager.Notify(1, notification);

            }
        }
        protected override void OnError(Context context, string errorId)
        {
            System.Diagnostics.Debug.WriteLine(
                string.Format("Error occurred in the notification: {0}.", errorId));
        }
        protected override async void OnRegistered(Context context, string registrationId)
        {
            System.Diagnostics.Debug.WriteLine("The device has been registered with GCM.", "Success!");

            // Get the MobileServiceClient from the current activity instance.
            MobileServiceClient client = MainActivity.CurrentActivity.CurrentClient;
            var push = client.GetPush();

            // Define a message body for GCM.
            const string templateBodyGCM = "{\"data\":{\"message\":\"$(messageParam)\", \"title\": \"$(titleParam)\", \"action\":\"$(actionParam)\",\"action_id\":\"$(action_idParam)\"}}";

            // Define the template registration as JSON.
            JObject templates = new JObject();
            templates["genericMessage"] = new JObject
            {
                {"body", templateBodyGCM }
            };

            try
            {
                // Make sure we run the registration on the same thread as the activity,
                // to avoid threading errors.
                MainActivity.CurrentActivity.RunOnUiThread(
                    // Register the template with Notification Hubs.
                    async () => {

                        try
                        {
                        await push.RegisterAsync(registrationId, templates);

                        System.Diagnostics.Debug.WriteLine(
                    string.Format("Push Installation Id " + push.InstallationId.ToString()));

                var res = await MiscServices.RegisterDevice(Settings.UserID, Settings.AccessToken, push.InstallationId.ToString(), "gcm");
                if ((bool)res.data)
                {
                    System.Diagnostics.Debug.WriteLine("Registered InstallationId in Server");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("Cannot register with Server" + " " + res.status.StatusCode);
                }

            }
                        catch (Exception e)
                        {
                        }

                });

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(
                    string.Format("Error with Azure push registration: {0}", ex.Message));
            }
        }

        protected override void OnUnRegistered(Context context, string registrationId)
        {
            System.Diagnostics.Debug.WriteLine("Unregistered with Azure push registration");
            }
    }

}
</code>```

Even test notifications fail to get delivered at times, but mostly test notifications work fine. We can't really figure out where the issue is occurring, any help is much appreciated.

答:
As you successfully sent messages to Azure NH, and got 201 responses. When you send a notification via Notification Hubs, initially it just gets queued up for NH to do processing to figure out all its targets and then eventually NH sends it to the PNS.

This means that when you are using REST API or any of the client SDK, the successful return of your send call only means that the message has been successfully queued up with Notification Hub.

It doesn’t give an insight into what happened when NH eventually got to send the message to PNS. If your notification is not arriving at the client device, there is a possibility that when NH tried to deliver the message to PNS, there was an error e.g. the payload size exceeded the maximum allowed by the PNS or the credentials configured in NH are invalid etc.

To get an insight into the PNS errors, we have introduced a property called EnableTestSend feature. This property is automatically enabled when you send test messages from the portal or Visual Studio client and therefore allows you to see detailed debugging information.

Or you can try to call via RESTful APIs for troubleshooting:
https://mynamespace.servicebus.windows.net/mynotificationhub/messages?api-version=2013-10&test

Please refer to Azure Notification Hubs - Diagnosis guidelines for more info.

Body:
I am using the following php code to send a push notification to Android application using Azure Notification Hub.

$hub = new NotificationHub("Endpoint=sb://ServiceName.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SharedAccessKey", "ServiceNameNotification");

        $message = '{"data":{"message":"This is a sample notification","title":"Sample Notification","action":"Test","action_id":"60"}}';
        $notification = new AzureNotification("gcm", $message);
        $hub->sendNotification($notification, null);

But unfortunately most of the times the notification is not getting delivered, although I am getting a 201 as the response. Whenever it does get delivered, the results are unpredictable, sometimes the contents of old notifications end up getting shown.

The following code is used to show the notifications in Android app (Xamarin.Android) :

using System;
using Android.App;
using Android.Content;
using Gcm.Client;
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json.Linq;
using ServiceName.Helpers;

[assembly: Permission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")]
//GET_ACCOUNTS is needed only for Android versions 4.0.3 and below
[assembly: UsesPermission(Name = "android.permission.GET_ACCOUNTS")]
[assembly: UsesPermission(Name = "android.permission.INTERNET")]
[assembly: UsesPermission(Name = "android.permission.WAKE_LOCK")]
namespace ServiceName.Droid
{
    [BroadcastReceiver(Permission = Gcm.Client.Constants.PERMISSION_GCM_INTENTS)]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE },
        Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK },
        Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY },
        Categories = new string[] { "@PACKAGE_NAME@" })]
    public class ServiceNameBroadcastReceiver : GcmBroadcastReceiverBase<PushHandlerService>
    {
        public static string[] senderIDs = new string[] { Constants.SenderID };

        public const string TAG = "MyBroadcastReceiver-GCM";
    }
    // The ServiceAttribute must be applied to the class.
    [Service]
    public class PushHandlerService : GcmServiceBase
    {

        public static string RegistrationID { get; private set; }

        public PushHandlerService() : base(ServiceNameBroadcastReceiver.senderIDs) { }
        protected override void OnMessage(Context context, Intent intent)
        {
            string message = string.Empty;
            string title = string.Empty;
            string action = string.Empty;
            string action_id = string.Empty;
            if (intent.Extras.ContainsKey("title"))
            {
                title = intent.Extras.Get("title").ToString();
            }
            if (intent.Extras.ContainsKey("message"))
            {
                message = intent.Extras.Get("message").ToString();
            }
            if (intent.Extras.ContainsKey("action"))
            {
                action = intent.Extras.Get("action").ToString();
            }
            if (intent.Extras.ContainsKey("action_id"))
            {
                action_id = intent.Extras.Get("action_id").ToString();
            }

            // Extract the push notification message from the intent.
            if (!string.IsNullOrWhiteSpace(message) || !string.IsNullOrWhiteSpace(title))
            {
                // Create a notification manager to send the notification.
                var notificationManager =
                    GetSystemService(Context.NotificationService) as NotificationManager;

                // Create a new intent to show the notification in the UI.
                PendingIntent contentIntent =
                    PendingIntent.GetActivity(context, 0,
                                              new Intent(this, typeof(MainActivity)), 0);

                // Create the notification using the builder.
                var builder = new Notification.Builder(context);
                builder.SetAutoCancel(false);
                if (!string.IsNullOrWhiteSpace(title))
                {
                    builder.SetContentTitle(title);
                }
                else
                {
                    builder.SetContentTitle("Notification from ServiceName");
                }
                if (!string.IsNullOrWhiteSpace(message))
                {
                    builder.SetContentText(message);
                }
                else
                {
                    builder.SetContentText("Hello ServiceName User");
                }
                builder.SetSmallIcon(Resource.Drawable.ic_stat_icon);
                builder.SetContentIntent(contentIntent);
                var notification = builder.Build();

                // Display the notification in the Notifications Area.
                notificationManager.Notify(1, notification);

            }
        }
        protected override void OnError(Context context, string errorId)
        {
            System.Diagnostics.Debug.WriteLine(
                string.Format("Error occurred in the notification: {0}.", errorId));
        }
        protected override async void OnRegistered(Context context, string registrationId)
        {
            System.Diagnostics.Debug.WriteLine("The device has been registered with GCM.", "Success!");

            // Get the MobileServiceClient from the current activity instance.
            MobileServiceClient client = MainActivity.CurrentActivity.CurrentClient;
            var push = client.GetPush();

            // Define a message body for GCM.
            const string templateBodyGCM = "{\"data\":{\"message\":\"$(messageParam)\", \"title\": \"$(titleParam)\", \"action\":\"$(actionParam)\",\"action_id\":\"$(action_idParam)\"}}";

            // Define the template registration as JSON.
            JObject templates = new JObject();
            templates["genericMessage"] = new JObject
            {
                {"body", templateBodyGCM }
            };

            try
            {
                // Make sure we run the registration on the same thread as the activity,
                // to avoid threading errors.
                MainActivity.CurrentActivity.RunOnUiThread(
                    // Register the template with Notification Hubs.
                    async () => {

                        try
                        {
                        await push.RegisterAsync(registrationId, templates);

                        System.Diagnostics.Debug.WriteLine(
                    string.Format("Push Installation Id " + push.InstallationId.ToString()));

                var res = await MiscServices.RegisterDevice(Settings.UserID, Settings.AccessToken, push.InstallationId.ToString(), "gcm");
                if ((bool)res.data)
                {
                    System.Diagnostics.Debug.WriteLine("Registered InstallationId in Server");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("Cannot register with Server" + " " + res.status.StatusCode);
                }

            }
                        catch (Exception e)
                        {
                        }

                });

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(
                    string.Format("Error with Azure push registration: {0}", ex.Message));
            }
        }

        protected override void OnUnRegistered(Context context, string registrationId)
        {
            System.Diagnostics.Debug.WriteLine("Unregistered with Azure push registration");
            }
    }

}

Even test notifications fail to get delivered at times, but mostly test notifications work fine. We can't really figure out where the issue is occurring, any help is much appreciated.


问:
Inserting timestamp array in MySQL DateTime
I'm trying to insert an array of dates in database but the program does not behave. I'm doing something wrong.

This insert NULL:

```<code>// initialize the array with first date
$dates = array(strtotime("+17 days", strtotime($period_startdate)));
// now loop 26 times to get the next 26 dates
for ($i = 1; $i <= 26; $i++) {
    // add 14 days to previous date in the array
    $dates[] = strtotime("+14 days", $dates[$i-1]);
}
// echo the results
foreach ($dates as $date) {
    // prepare and bind for paydates
    $insertpaydates= $db->prepare("INSERT INTO paydates (payroll_secret_id,paydate) VALUES (?,?)");
    $insertpaydates->bind_param("ss",$secret_id,$dates[$date]);
}
</code>```

This insert only one row and wrong date (1970-01-01)

```<code>// initialize the array with first date
$dates = array(strtotime("+17 days", strtotime($period_startdate)));
// now loop 26 times to get the next 26 dates
for ($i = 1; $i <= 26; $i++) {
    // add 14 days to previous date in the array
    $dates[] = strtotime("+14 days", $dates[$i-1]);
}
// echo the results
foreach ($dates as $date) {
    $Item_Date[$date] = date("Y-m-d", strtotime($Item_Date[$date]));
    // prepare and bind for paydates
    $insertpaydates= $db->prepare("INSERT INTO paydates (payroll_secret_id,paydate) VALUES (?,?)");
    $insertpaydates->bind_param("ss",$secret_id,$Item_Date[$date] );
}
</code>```

答:
Wrong use of Foreach

The problem on the first code snippet is inside the foreach loop. When you loop through an array, the second parameter will be the actual entry of the array, not just the key. So instead of using $dates[$date] you should simply use $date inside your loop.

Execute Query Inside Loop

You also have to execute the query for each time you bind new parameters to the statement, or else you will just override the old parameters and do a single execution after the loop. So you should add the execute to the foreach-loop so that it writes on each iteration.

Prepare Statements Outside Loops

A third thing you should do to improve the performance of your code is to move the SQL Prepare statement to outside the loop. Instead of preparing the statement 26 times you can only do it once, and then execute it with different values 26 times. This will make a big difference in the execution time.

Timestamps != DateTime

In the comments below to this post it seems like you are using a bad combination of data and data types in the MySQL database. You're trying to write an integer timestamp to a DateTime field. You should convert it into a valid date format before writing it.

So final code would be:

```<code>// Convert our $_POST value to a timestamp.
$period_startdate = strtotime($period_startdate);

// We init the first date value.
$dates = array(
    date('Y-m-d H:i:s', strtotime("+17 days", $period_startdate)),
);

for ($i = 1; $i <= 26; $i++) {
    // Add 14 days to previous date in the array.
    // Notice we have to convert the previous date in the array to a timestamp using strtotime().
    $dates[] = date('Y-m-d H:i:s', strtotime("+14 days", strtotime($dates[$i-1])));
}

// We prepare our statement before the loop to avoid preparing it
// multiple times. This saves performance.
$insertpaydates = $db->prepare("INSERT INTO paydates (payroll_secret_id,paydate) VALUES (?,?)");

foreach ($dates as $date) {
    // Here we change from $dates[$date] to simply $date
    $insertpaydates->bind_param("ss", $secret_id, $date);
    // Here we execute the query for each date.
    $insertpaydates->execute();
}
</code>```

Body:
I'm trying to insert an array of dates in database but the program does not behave. I'm doing something wrong.

This insert NULL:

// initialize the array with first date
$dates = array(strtotime("+17 days", strtotime($period_startdate)));
// now loop 26 times to get the next 26 dates
for ($i = 1; $i <= 26; $i++) {
    // add 14 days to previous date in the array
    $dates[] = strtotime("+14 days", $dates[$i-1]);
}
// echo the results
foreach ($dates as $date) {
    // prepare and bind for paydates
    $insertpaydates= $db->prepare("INSERT INTO paydates (payroll_secret_id,paydate) VALUES (?,?)");
    $insertpaydates->bind_param("ss",$secret_id,$dates[$date]);
}

This insert only one row and wrong date (1970-01-01)

// initialize the array with first date
$dates = array(strtotime("+17 days", strtotime($period_startdate)));
// now loop 26 times to get the next 26 dates
for ($i = 1; $i <= 26; $i++) {
    // add 14 days to previous date in the array
    $dates[] = strtotime("+14 days", $dates[$i-1]);
}
// echo the results
foreach ($dates as $date) {
    $Item_Date[$date] = date("Y-m-d", strtotime($Item_Date[$date]));
    // prepare and bind for paydates
    $insertpaydates= $db->prepare("INSERT INTO paydates (payroll_secret_id,paydate) VALUES (?,?)");
    $insertpaydates->bind_param("ss",$secret_id,$Item_Date[$date] );
}

Body:
Wrong use of Foreach

The problem on the first code snippet is inside the foreach loop. When you loop through an array, the second parameter will be the actual entry of the array, not just the key. So instead of using $dates[$date] you should simply use $date inside your loop.

Execute Query Inside Loop

You also have to execute the query for each time you bind new parameters to the statement, or else you will just override the old parameters and do a single execution after the loop. So you should add the execute to the foreach-loop so that it writes on each iteration.

Prepare Statements Outside Loops

A third thing you should do to improve the performance of your code is to move the SQL Prepare statement to outside the loop. Instead of preparing the statement 26 times you can only do it once, and then execute it with different values 26 times. This will make a big difference in the execution time.

Timestamps != DateTime

In the comments below to this post it seems like you are using a bad combination of data and data types in the MySQL database. You're trying to write an integer timestamp to a DateTime field. You should convert it into a valid date format before writing it.

So final code would be:

// Convert our $_POST value to a timestamp.
$period_startdate = strtotime($period_startdate);

// We init the first date value.
$dates = array(
    date('Y-m-d H:i:s', strtotime("+17 days", $period_startdate)),
);

for ($i = 1; $i <= 26; $i++) {
    // Add 14 days to previous date in the array.
    // Notice we have to convert the previous date in the array to a timestamp using strtotime().
    $dates[] = date('Y-m-d H:i:s', strtotime("+14 days", strtotime($dates[$i-1])));
}

// We prepare our statement before the loop to avoid preparing it
// multiple times. This saves performance.
$insertpaydates = $db->prepare("INSERT INTO paydates (payroll_secret_id,paydate) VALUES (?,?)");

foreach ($dates as $date) {
    // Here we change from $dates[$date] to simply $date
    $insertpaydates->bind_param("ss", $secret_id, $date);
    // Here we execute the query for each date.
    $insertpaydates->execute();
}


问:
Using two database reference in Cloud Functions for Firebase
I am creating 2 projects:

1: For Managers. Where all data are manipulated by managers. These are contents, pictures etc.

2: For users. Where all information are indexed for users to search contents easily. User information are stored such as names etc.

I want to configure the first project's cloud functions to index the information managed and store it to the second project.

Is this possible? Or should I just put them all in one project. I want to scale them individually in the long run. Thanks for any help.

答:
You can refer to any project you want using the Firebase Admin SDK.  You can add it to your functions index.js and initialize it to point to the project you want to use:

```<code>const admin = require('firebase-admin');
admin.initializeApp(...);
</code>```

The object you pass to initializeApp() should describe the project you're trying to connect to.  See the docs for that.

Body:
You can refer to any project you want using the Firebase Admin SDK.  You can add it to your functions index.js and initialize it to point to the project you want to use:

const admin = require('firebase-admin');
admin.initializeApp(...);

The object you pass to initializeApp() should describe the project you're trying to connect to.  See the docs for that.


问:
How to compile dynamic content in Angular UI tabs?
In this plunk I have an Angular UI tab that displays HTML content. Each content has a div containing an ng-click directive, that doesn't work. Most likely the directive needs to be compiled? how to achieve that?

HTML

```<code>  <uib-tabset>
    <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}">
      <div ng-bind-html="tab.content"></div>
    </uib-tab>
  </uib-tabset>
</code>```

Javascript

```<code>var app = angular.module('ui.bootstrap.demo', ['ui.bootstrap', 'ngSanitize']);

app.controller('ctl', function ($scope) {

     $scope.tabs = [
       { title:'title 1', content:'<div ng-click="click(1)" id="id1">111</div>' },
       { title:'title 2', content:'<div ng-click="click(2)" id="id2">222</div>' }
     ];

     $scope.click = function(i){
       alert(i);
     };

});
</code>```

答:
This is the answer, compile using this directive:

```<code>app.directive('dynamic', function($compile) {
    return {
        restrict: 'A',
        replace: true,
        link: function (scope, element, attrs) {
            scope.$watch(attrs.dynamic, function(html) {
                element[0].innerHTML = html;
                $compile(element.contents())(scope);
            });
        }
    };
});
</code>```

see here

Body:
In this plunk I have an Angular UI tab that displays HTML content. Each content has a div containing an ng-click directive, that doesn't work. Most likely the directive needs to be compiled? how to achieve that?

HTML

  <uib-tabset>
    <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}">

    </uib-tab>
  </uib-tabset>

Javascript

var app = angular.module('ui.bootstrap.demo', ['ui.bootstrap', 'ngSanitize']);

app.controller('ctl', function ($scope) {

     $scope.tabs = [
       { title:'title 1', content:'
111
' },
       { title:'title 2', content:'
222
' }
     ];

     $scope.click = function(i){
       alert(i);
     };

});

Body:
This is the answer, compile using this directive:

app.directive('dynamic', function($compile) {
    return {
        restrict: 'A',
        replace: true,
        link: function (scope, element, attrs) {
            scope.$watch(attrs.dynamic, function(html) {
                element[0].innerHTML = html;
                $compile(element.contents())(scope);
            });
        }
    };
});

see here