问:
OpenSSL with no-cms options complains no CMS with make depend
Configuring a pretty bare bones OpenSSL 1.0.2l in MSys 1.0 on Windows with the following.

```<code>./Configure no-zlib no-shared no-dso no-krb5 no-camellia no-capieng no-cast no-cms no-dtls1 no-gost no-gmp no-heartbe
ats no-idea no-jpake no-md2 no-mdc2 no-rc5 no-rdrand no-rfc3779 no-rsax no-sctp no-seed no-sha0 no-static_engine no-whi
rlpool no-rc2 no-rc4 no-ssl2 no-ssl3 mingw
</code>```

I get the following error running make depend after running configure.

```<code>In file included from dh_kdf.c:58:0:
../../include/openssl/cms.h:61:4: error: #error CMS is disabled.
 #  error CMS is disabled.
</code>```

This seems pretty obtuse, I told it no-cms, of course. Any ideas what to do other than just removing no-cms?

```<code>make -v
GNU Make 3.81
Copyright (C) 2006  Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.

This program built for i686-pc-msys

gcc -v
Using built-in specs.
COLLECT_GCC=c:\mingw32\bin\gcc.exe
COLLECT_LTO_WRAPPER=c:/mingw32/bin/../libexec/gcc/i686-w64-mingw32/4.9.2/lto-wrapper.exe
Target: i686-w64-mingw32
Configured with: ../../../src/gcc-4.9.2/configure --host=i686-w64-mingw32 --build=i686-w64-mingw32 --target=i686-w64-mingw32 --prefix=/mingw32 --with-sysroot=/c/mingw492/i686-492-posix-dwarf-rt_v3-rev1/mingw32 --with-gxx-include-dir=/mingw32/i686-w64-mingw32/include/c++ --enable-shared --enable-static --disable-multilib --enable-languages=ada,c,c++,fortran,objc,obj-c++,lto --enable-libstdcxx-time=yes --enable-threads=posix --enable-libgomp --enable-libatomic --enable-lto --enable-graphite --enable-checking=release --enable-fully-dynamic-string --enable-version-specific-runtime-libs --disable-sjlj-exceptions --with-dwarf2 --disable-isl-version-check --disable-cloog-version-check --disable-libstdcxx-pch --disable-libstdcxx-debug --enable-bootstrap --disable-rpath --disable-win32-registry --disable-nls --disable-werror --disable-symvers --with-gnu-as --with-gnu-ld --with-arch=i686 --with-tune=generic --with-libiconv --with-system-zlib --with-gmp=/c/mingw492/prerequisites/i686-w64-mingw32-static --with-mpfr=/c/mingw492/prerequisites/i686-w64-mingw32-static --with-mpc=/c/mingw492/prerequisites/i686-w64-mingw32-static --with-isl=/c/mingw492/prerequisites/i686-w64-mingw32-static --with-cloog=/c/mingw492/prerequisites/i686-w64-mingw32-static --enable-cloog-backend=isl --with-pkgversion='i686-posix-dwarf-rev1, Built by MinGW-W64 project' --with-bugurl=http://sourceforge.net/projects/mingw-w64 CFLAGS='-O2 -pipe -I/c/mingw492/i686-492-posix-dwarf-rt_v3-rev1/mingw32/opt/include -I/c/mingw492/prerequisites/i686-zlib-static/include -I/c/mingw492/prerequisites/i686-w64-mingw32-static/include' CXXFLAGS='-O2 -pipe -I/c/mingw492/i686-492-posix-dwarf-rt_v3-rev1/mingw32/opt/include -I/c/mingw492/prerequisites/i686-zlib-static/include -I/c/mingw492/prerequisites/i686-w64-mingw32-static/include' CPPFLAGS= LDFLAGS='-pipe -L/c/mingw492/i686-492-posix-dwarf-rt_v3-rev1/mingw32/opt/lib -L/c/mingw492/prerequisites/i686-zlib-static/lib -L/c/mingw492/prerequisites/i686-w64-mingw32-static/lib -Wl,--large-address-aware'
Thread model: posix
gcc version 4.9.2 (i686-posix-dwarf-rev1, Built by MinGW-W64 project)
</code>```

答:
It appears OPENSSL_NO_CMS is a valid preprocessor macro. Its used in most places, but not all places. The use of OPENSSL_NO_CMS indicates no-cms is a valid option. (I seem to recall it always has been, but its best to make sure).

Now open on on the OpenSSL issue tracker: Issue 3867, Configuring with no-cms and "undefined reference to CMS_SharedInfo_encode".

In the meantime:

```<code>$ git diff crypto/dh/dh_kdf.c
diff --git a/crypto/dh/dh_kdf.c b/crypto/dh/dh_kdf.c
index a882cb286e..93381f02b8 100644
--- a/crypto/dh/dh_kdf.c
+++ b/crypto/dh/dh_kdf.c
@@ -55,7 +55,11 @@
 #include <openssl/dh.h>
 #include <openssl/evp.h>
 #include <openssl/asn1.h>
-#include <openssl/cms.h>
+#include <openssl/x509.h>
+
+#ifndef OPENSSL_NO_CMS
+# include <openssl/cms.h>
+#endif

 /* Key derivation from X9.42/RFC2631 */
</code>```

However, it looks like there are bigger problems following it in dh_sharedinfo_encode due to use of CMS_SharedInfo_encode (see crypto/dh/dh_kdf.c):

gcc -I.. -I../.. -I../modes -I../asn1 -I../evp -I../../include  -DOPENSSL_THREADS -D_REENTRANT -m64 -DL_ENDIAN -O3 -Wall -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DRC4_ASM -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DGHASH_ASM -DECP_NISTZ256_ASM   -c -o dh_kdf.o dh_kdf.c
dh_kdf.c: In function 'dh_sharedinfo_encode':
dh_kdf.c:122:14: warning: implicit declaration of function 'CMS_SharedInfo_encode' [-Wimplicit-function-declaration]
     derlen = CMS_SharedInfo_encode(pder, &atmp, pukm_oct, outlen);
              ^~~~~~~~~~~~~~~~~~~~~
```

<p>It leads to:</p>

<pre class="lang-none prettyprint-override"><code>../libcrypto.a(dh_kdf.o): In function `DH_KDF_X9_42':
dh_kdf.c:(.text+0x180): undefined reference to `CMS_SharedInfo_encode'
collect2: error: ld returned 1 exit status
../Makefile.shared:164: recipe for target 'link_app.' failed
make[2]: *** [link_app.] Error 1
make[2]: Leaving directory '/home/openssl/apps'
Makefile:156: recipe for target 'openssl' failed
make[1]: *** [openssl] Error 2
make[1]: Leaving directory '/home/openssl/apps'
Makefile:293: recipe for target 'build_apps' failed
make: *** [build_apps] Error 1
</code>```

It looks like the OpenSSL team will need to look at the issue.

Body:
Configuring a pretty bare bones OpenSSL 1.0.2l in MSys 1.0 on Windows with the following.

./Configure no-zlib no-shared no-dso no-krb5 no-camellia no-capieng no-cast no-cms no-dtls1 no-gost no-gmp no-heartbe
ats no-idea no-jpake no-md2 no-mdc2 no-rc5 no-rdrand no-rfc3779 no-rsax no-sctp no-seed no-sha0 no-static_engine no-whi
rlpool no-rc2 no-rc4 no-ssl2 no-ssl3 mingw

I get the following error running make depend after running configure.

In file included from dh_kdf.c:58:0:
../../include/openssl/cms.h:61:4: error: #error CMS is disabled.
 #  error CMS is disabled.

This seems pretty obtuse, I told it no-cms, of course. Any ideas what to do other than just removing no-cms?

make -v
GNU Make 3.81
Copyright (C) 2006  Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.

This program built for i686-pc-msys

gcc -v
Using built-in specs.
COLLECT_GCC=c:\mingw32\bin\gcc.exe
COLLECT_LTO_WRAPPER=c:/mingw32/bin/../libexec/gcc/i686-w64-mingw32/4.9.2/lto-wrapper.exe
Target: i686-w64-mingw32
Configured with: ../../../src/gcc-4.9.2/configure --host=i686-w64-mingw32 --build=i686-w64-mingw32 --target=i686-w64-mingw32 --prefix=/mingw32 --with-sysroot=/c/mingw492/i686-492-posix-dwarf-rt_v3-rev1/mingw32 --with-gxx-include-dir=/mingw32/i686-w64-mingw32/include/c++ --enable-shared --enable-static --disable-multilib --enable-languages=ada,c,c++,fortran,objc,obj-c++,lto --enable-libstdcxx-time=yes --enable-threads=posix --enable-libgomp --enable-libatomic --enable-lto --enable-graphite --enable-checking=release --enable-fully-dynamic-string --enable-version-specific-runtime-libs --disable-sjlj-exceptions --with-dwarf2 --disable-isl-version-check --disable-cloog-version-check --disable-libstdcxx-pch --disable-libstdcxx-debug --enable-bootstrap --disable-rpath --disable-win32-registry --disable-nls --disable-werror --disable-symvers --with-gnu-as --with-gnu-ld --with-arch=i686 --with-tune=generic --with-libiconv --with-system-zlib --with-gmp=/c/mingw492/prerequisites/i686-w64-mingw32-static --with-mpfr=/c/mingw492/prerequisites/i686-w64-mingw32-static --with-mpc=/c/mingw492/prerequisites/i686-w64-mingw32-static --with-isl=/c/mingw492/prerequisites/i686-w64-mingw32-static --with-cloog=/c/mingw492/prerequisites/i686-w64-mingw32-static --enable-cloog-backend=isl --with-pkgversion='i686-posix-dwarf-rev1, Built by MinGW-W64 project' --with-bugurl=http://sourceforge.net/projects/mingw-w64 CFLAGS='-O2 -pipe -I/c/mingw492/i686-492-posix-dwarf-rt_v3-rev1/mingw32/opt/include -I/c/mingw492/prerequisites/i686-zlib-static/include -I/c/mingw492/prerequisites/i686-w64-mingw32-static/include' CXXFLAGS='-O2 -pipe -I/c/mingw492/i686-492-posix-dwarf-rt_v3-rev1/mingw32/opt/include -I/c/mingw492/prerequisites/i686-zlib-static/include -I/c/mingw492/prerequisites/i686-w64-mingw32-static/include' CPPFLAGS= LDFLAGS='-pipe -L/c/mingw492/i686-492-posix-dwarf-rt_v3-rev1/mingw32/opt/lib -L/c/mingw492/prerequisites/i686-zlib-static/lib -L/c/mingw492/prerequisites/i686-w64-mingw32-static/lib -Wl,--large-address-aware'
Thread model: posix
gcc version 4.9.2 (i686-posix-dwarf-rev1, Built by MinGW-W64 project)

Body:
It appears OPENSSL_NO_CMS is a valid preprocessor macro. Its used in most places, but not all places. The use of OPENSSL_NO_CMS indicates no-cms is a valid option. (I seem to recall it always has been, but its best to make sure).

Now open on on the OpenSSL issue tracker: Issue 3867, Configuring with no-cms and "undefined reference to CMS_SharedInfo_encode".

In the meantime:

$ git diff crypto/dh/dh_kdf.c
diff --git a/crypto/dh/dh_kdf.c b/crypto/dh/dh_kdf.c
index a882cb286e..93381f02b8 100644
--- a/crypto/dh/dh_kdf.c
+++ b/crypto/dh/dh_kdf.c
@@ -55,7 +55,11 @@
 #include <openssl/dh.h>
 #include <openssl/evp.h>
 #include <openssl/asn1.h>
-#include <openssl/cms.h>
+#include <openssl/x509.h>
+
+#ifndef OPENSSL_NO_CMS
+# include <openssl/cms.h>
+#endif

 /* Key derivation from X9.42/RFC2631 */

However, it looks like there are bigger problems following it in dh_sharedinfo_encode due to use of CMS_SharedInfo_encode (see crypto/dh/dh_kdf.c):

gcc -I.. -I../.. -I../modes -I../asn1 -I../evp -I../../include  -DOPENSSL_THREADS -D_REENTRANT -m64 -DL_ENDIAN -O3 -Wall -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DRC4_ASM -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DGHASH_ASM -DECP_NISTZ256_ASM   -c -o dh_kdf.o dh_kdf.c
dh_kdf.c: In function 'dh_sharedinfo_encode':
dh_kdf.c:122:14: warning: implicit declaration of function 'CMS_SharedInfo_encode' [-Wimplicit-function-declaration]
     derlen = CMS_SharedInfo_encode(pder, &atmp, pukm_oct, outlen);
              ^~~~~~~~~~~~~~~~~~~~~

It leads to:

../libcrypto.a(dh_kdf.o): In function `DH_KDF_X9_42':
dh_kdf.c:(.text+0x180): undefined reference to `CMS_SharedInfo_encode'
collect2: error: ld returned 1 exit status
../Makefile.shared:164: recipe for target 'link_app.' failed
make[2]: *** [link_app.] Error 1
make[2]: Leaving directory '/home/openssl/apps'
Makefile:156: recipe for target 'openssl' failed
make[1]: *** [openssl] Error 2
make[1]: Leaving directory '/home/openssl/apps'
Makefile:293: recipe for target 'build_apps' failed
make: *** [build_apps] Error 1

It looks like the OpenSSL team will need to look at the issue.


来源: stackexchange

问:
How to prevent eslint from blocking git commit?
I'm new to eslint and am using it to enforce coding style. However, when I write a TODO item into my code I get an eslint warning, alright that's fine. But, now when I try to git commit, it comes back with:

```<code>**** ESLint errors found :
line 145, col 9, Warning - Unexpected 'todo' comment. (no-warning-comments)
</code>```

How can I prevent eslint from blocking me from committing? I want it to still warn me about TODOs etc, but I would like to be able to commit my code as well.

答:
You have a pre-commit hook.

```<code>git commit --no-verify
</code>```

allows to avoid it once. Or you can remove it completely from .git/hooks.

ContentLicense: CC BY-SA 4.0

Body:
I'm new to eslint and am using it to enforce coding style. However, when I write a TODO item into my code I get an eslint warning, alright that's fine. But, now when I try to git commit, it comes back with:

**** ESLint errors found :
line 145, col 9, Warning - Unexpected 'todo' comment. (no-warning-comments)

How can I prevent eslint from blocking me from committing? I want it to still warn me about TODOs etc, but I would like to be able to commit my code as well.

Body:
You have a pre-commit hook.

git commit --no-verify

allows to avoid it once. Or you can remove it completely from .git/hooks.


问:
Google App Engine: how to find out, which instance is running which instance-class?
I have created and successfully deployed a NodeJS-app on GoogleAppEngine. I know that they offer several "instance-types" with completely different pricings according to CPU-type, CPU-cores, memory and so on...

One can find the instance classes here in this list: https://cloud.google.com/appengine/pricing

But how do i know, which instance-class is running for my app currently? The dashboard doesnt show me that. "gcloud app instances list" hides this information too. "gcloud app describe" also doesnt provide this information....

How can i find out, which instance is running with which instance class?

Update

The solution provided by @eater is not available for me as the final "config"-column he had mentioned is not visible in "my" dashboard:

Update 2

Since this app was configured with "Flexible Environment" the concrete instance type might be not shown here as there is a specific pricing. Apparently this is the answer on my question.

答:
Go to http://console.cloud.google.com -> select your project in the dropdown on top -> select App Engine on the left hand side menu -> Versions

Select service on the dropdown and then on the list of versions click on the "View" link in the "Config" column. This will show you summary about your version's configuration, including instance type.

For the Flexible environment, there's no instance type as such, instead you can specify resources you want your instance to have, and if you don't specify anything, default values are used. You can see what kind of resources you can specify in this section of documentation
https://cloud.google.com/appengine/docs/flexible/nodejs/configuring-your-app-with-app-yaml#resource-settings
The table also lists default values for resources.

ContentLicense: CC BY-SA 3.0


问:
How do you execute C# code with a button click in asp.net?
I need help executing C# code with a button click. I`m sure there are multiple things wrong with this, however; any help would be much appreciated. Thank you for taking the time to view this post, and have a wonderful day!</p>

```<code>            @{
                CommentController controller = new CommentController();

                UpVotes Upvote = new UpVotes(Misc.GetUser(), c.Postid);

            }

            @{
                if (controller.CheckVote(Upvote))
                {
                    <button type="button" onclick="@{

                        c.Upvotes += 1;

                        controller.PersonUpVote(Upvote);
                        }
                            }">
                        Like
                    </button>
                        }

                        else
                        {

                        <button type="button" onclick="@{

                            controller.PersonDownVote(Upvote);
                            c.Upvotes -= 1;
                        }

                                }">
                            Unlike
                        </button>

                    }
                 }
</code>```

答:
Scratch everything you've done so far as your heading down the wrong path.

On your view you need to attach to the button click via JavaScript then issue an Ajax call back to your controller.

See here http://www.makeitspendit.com/calling-asp-mvc-controllers-from-jquery-ajax/

Body:
I need help executing C# code with a button click. I`m sure there are multiple things wrong with this, however; any help would be much appreciated. Thank you for taking the time to view this post, and have a wonderful day!

            @{
                CommentController controller = new CommentController();

                UpVotes Upvote = new UpVotes(Misc.GetUser(), c.Postid);

            }

            @{
                if (controller.CheckVote(Upvote))
                {
                    <button type="button" onclick="@{

                        c.Upvotes += 1;

                        controller.PersonUpVote(Upvote);
                        }
                            }">
                        Like
                    </button>
                        }

                        else
                        {

                        <button type="button" onclick="@{

                            controller.PersonDownVote(Upvote);
                            c.Upvotes -= 1;
                        }

                                }">
                            Unlike
                        </button>

                    }
                 }


答:
Solution

I navigated to my .git/hooks directory and found a pre-commit bash script. I changed the return value from 1 to 0 in the case where eslint failed and that solved the problem.

A 0 value represents a pass and will allow the commit to continue, a non-zero represents a fail state and will cancel the commit.

Title: How to prevent eslint from blocking git commit?


问:
Extracting element from list of dictionaries in python
I have a list of dictionary objects like this:

```<code>[{'Id': 46, 'Date': '2016-05-09T00:00:00', 'Type': 1, 'PId': None, 'Ct': None},
{'Id': 108, 'Date': '2017-07-01T00:00:00', 'Type': 10, 'PId': None, 'Ct': None}]
</code>```

I can do this to extract Date from the first element of this list:

list_dict[0].get('Date')

How can I get the Date corresponding to Type 10 (without hardcoding that it is the 2nd element in the list)? The solution should return None if Type 10 does not exist.

--EDIT:

Previous version of question was assuming that the list was of json objects, they are actually dictionaries

答:
Just check the type and return the corresponding date like so:</p>

```<code>input = [{'Id': 46, 'Date': '2016-05-09T00:00:00', 'Type': 1, 'PId': None, 'Ct': None}, {'Id': 108, 'Date': '2017-07-01T00:00:00', 'Type': 10, 'PId': None, 'Ct': None}]

def example(input):

    for element in input:
        if element['Type'] == 10:
            return element['Date']

    return None
</code>```

Body:
I have a list of dictionary objects like this:

[{'Id': 46, 'Date': '2016-05-09T00:00:00', 'Type': 1, 'PId': None, 'Ct': None},
{'Id': 108, 'Date': '2017-07-01T00:00:00', 'Type': 10, 'PId': None, 'Ct': None}]

I can do this to extract Date from the first element of this list:

list_dict[0].get('Date')

How can I get the Date corresponding to Type 10 (without hardcoding that it is the 2nd element in the list)? The solution should return None if Type 10 does not exist.

--EDIT:

Previous version of question was assuming that the list was of json objects, they are actually dictionaries

Body:
Just check the type and return the corresponding date like so:

input = [{'Id': 46, 'Date': '2016-05-09T00:00:00', 'Type': 1, 'PId': None, 'Ct': None}, {'Id': 108, 'Date': '2017-07-01T00:00:00', 'Type': 10, 'PId': None, 'Ct': None}]

def example(input):

    for element in input:
        if element['Type'] == 10:
            return element['Date']

    return None


问:
zsim. pin error :$PINPATH environment variable with Pin's path
I want to compile zsim (https://github.com/s5z/zsim)

```<code>~/zsim$ scons -j16
</code>```

then there is an error message

```<code>scons: Reading SConscript files ...
Building opt zsim at build/opt
ERROR: You need to define the $PINPATH environment variable with Pin's path
</code>```

but when i just common pin

```<code>$ pin
E: Missing application name
Pin 3.2
Copyright (c) 2003-2016, Intel Corporation. All rights reserved.
VERSION: 81201 DATE: Feb  2 2017
Usage: pin [OPTION] [-t <tool> [<toolargs>]] -- <command line>
Use -help for a description of options
</code>```

it can find pin, how can fix it,thanks

os:ubuntu 12.04
gcc:4.6.3
g++:4.6.3
pin:3.2

答:
A quick look at the readme specifies the following:
(https://github.com/s5z/zsim/blob/master/README.md)

Download Pin, http://www.pintool.org . Tested with Pin 2.8+ on an
  x86-64 architecture. Compiler flags are set up for Pin 2.9 on x86-64.
  To get flags for other versions, examine the Pin makefile or derive
  from sample pintools. Set the PINPATH environment variable to Pin's
  base directory.

Sounds like you need to do the following

```<code>export PINPATH=<Base directory of your pin install>
</code>```

Body:
I want to compile zsim (https://github.com/s5z/zsim)

~/zsim$ scons -j16

then there is an error message

scons: Reading SConscript files ...
Building opt zsim at build/opt
ERROR: You need to define the $PINPATH environment variable with Pin's path

but when i just common pin

$ pin
E: Missing application name
Pin 3.2
Copyright (c) 2003-2016, Intel Corporation. All rights reserved.
VERSION: 81201 DATE: Feb  2 2017
Usage: pin [OPTION] [-t <tool> [<toolargs>]] -- <command line>
Use -help for a description of options

it can find pin, how can fix it,thanks

os:ubuntu 12.04
gcc:4.6.3
g++:4.6.3
pin:3.2

Body:
A quick look at the readme specifies the following:
(https://github.com/s5z/zsim/blob/master/README.md)

Download Pin, http://www.pintool.org . Tested with Pin 2.8+ on an
  x86-64 architecture. Compiler flags are set up for Pin 2.9 on x86-64.
  To get flags for other versions, examine the Pin makefile or derive
  from sample pintools. Set the PINPATH environment variable to Pin's
  base directory.

Sounds like you need to do the following

export PINPATH=<Base directory of your pin install>


问:
How to check value with all previous row value
I am trying to write a formula in excel to check if the given number is less than any of the previous row value.
For eg.

My excel document is as follows:

```<code>        A            B
1   01/05/2017       10
2   02/05/2017       5
3   03/05/2017       7
4   04/05/2017       11
</code>```

what m hoping to achieve is

```<code>        A            B      C
1   01/05/2017       10     -
2   02/05/2017       5     TRUE (5<10 = true)
3   03/05/2017       7     TRUE (7<5=false & 7<10=true therefor its true)
4   04/05/2017       11    FALSE (11<7=false & 11<5=false and 11<10=false)
</code>```

So if the current value is less than any of the previous value the field should be true or else false.

Note : the sheet is sorted according to timestamp which cannot change

Thanks for you answers.

答:
If you start in C2 then this formula does what you want:

```<code>{=SUM(IF(B2<B$1:B1,1,0))<>0}
</code>```

Please note, this is an array formula, so you need to hit CTRL+SHIFT+ENTER when you enter the formula for it to work.

It gives me this:

If you prefer R1C1 mode, like I do, the formula is:

```<code>{=SUM(IF(RC[-1]<R1C[-1]:R[-1]C[-1],1,0))<>0}
</code>```

Body:
I am trying to write a formula in excel to check if the given number is less than any of the previous row value.
For eg.

My excel document is as follows:

        A            B
1   01/05/2017       10
2   02/05/2017       5
3   03/05/2017       7
4   04/05/2017       11

what m hoping to achieve is

        A            B      C
1   01/05/2017       10     -
2   02/05/2017       5     TRUE (5<10 = true)
3   03/05/2017       7     TRUE (7<5=false & 7<10=true therefor its true)
4   04/05/2017       11    FALSE (11<7=false & 11<5=false and 11<10=false)

So if the current value is less than any of the previous value the field should be true or else false.

Note : the sheet is sorted according to timestamp which cannot change

Thanks for you answers.

Body:
If you start in C2 then this formula does what you want:

{=SUM(IF(B2<B$1:B1,1,0))<>0}

Please note, this is an array formula, so you need to hit CTRL+SHIFT+ENTER when you enter the formula for it to work.

It gives me this:

If you prefer R1C1 mode, like I do, the formula is:

{=SUM(IF(RC[-1]<R1C[-1]:R[-1]C[-1],1,0))<>0}


问:
SQL Using Like, One Variable, Multiple Columns
```<code>--where 'email@aol.com' in(o.SuOrderEmailAddress, o.SuBusEmailAddress, o.SuReturnEmail, O.SuPartsEmail) and es.ictid = 7
</code>```

I want to search one variable (email address) in the multiple columns. This is what I have now, and it works.

I think I need to use Like, because I want to use wildcards. For instance, being able to use *@aol.com would be very helpful. Right now I have to enter an exact email address.

```<code>--Where s.suname like 'rizt%'and es.ictid = 7
</code>```

It was simple enough in this above example, but once I rearrange the syntax to do multiple columns Im lost as to where I can use LIKE so that I can use Wildcards.

Thanks

答:
You could just look at the end of the email address.  Most databases support the right() function:

```<code>where '@aol.com' in (right(o.SuOrderEmailAddress, 8),
                     right(o.SuBusEmailAddress, 8),
                     right(o.SuReturnEmail, 8),
                     right(o.SuPartsEmail, 8)
                    ) and
       es.ictid = 7
</code>```

(Even databases that don't have right() have an equivalent function, in general.)

Some databases support regular expressions, which is another option.  Or, in your case, string concatenation would even work.

EDIT:

If you have a variable, you can do:

```<code>where @var in (right(o.SuOrderEmailAddress, len(@var)),
               right(o.SuBusEmailAddress, len(@var)),
               right(o.SuReturnEmail, len(@var)),
               right(o.SuPartsEmail, len(@var))
              ) and
       es.ictid = 7
</code>```

Body:
--where 'email@aol.com' in(o.SuOrderEmailAddress, o.SuBusEmailAddress, o.SuReturnEmail, O.SuPartsEmail) and es.ictid = 7

I want to search one variable (email address) in the multiple columns. This is what I have now, and it works.

I think I need to use Like, because I want to use wildcards. For instance, being able to use *@aol.com would be very helpful. Right now I have to enter an exact email address.

--Where s.suname like 'rizt%'and es.ictid = 7

It was simple enough in this above example, but once I rearrange the syntax to do multiple columns Im lost as to where I can use LIKE so that I can use Wildcards.

Thanks

Body:
You could just look at the end of the email address.  Most databases support the right() function:

where '@aol.com' in (right(o.SuOrderEmailAddress, 8),
                     right(o.SuBusEmailAddress, 8),
                     right(o.SuReturnEmail, 8),
                     right(o.SuPartsEmail, 8)
                    ) and
       es.ictid = 7

(Even databases that don't have right() have an equivalent function, in general.)

Some databases support regular expressions, which is another option.  Or, in your case, string concatenation would even work.

EDIT:

If you have a variable, you can do:

where @var in (right(o.SuOrderEmailAddress, len(@var)),
               right(o.SuBusEmailAddress, len(@var)),
               right(o.SuReturnEmail, len(@var)),
               right(o.SuPartsEmail, len(@var))
              ) and
       es.ictid = 7


问:
SQL Query: Count Distinct with Condition
This is my simplified table:

```<code> is_clicked | direct_lead_id
------------+----------------
 true       |        4074448
 false      |        4074448
 true       |        4074448
</code>```

I would like to run a query on this to get a distinct count of the direct_lead_id when is_clicked = True. So the result of my query would be 1 in this case. If I added a line to the above table, let say:
true| 407449.
Then I would want to get 2.

答:
```<code>select count(distinct direct_lead_id )
from my_table
where is_clicked = true
</code>```

Body:
This is my simplified table:

 is_clicked | direct_lead_id
------------+----------------
 true       |        4074448
 false      |        4074448
 true       |        4074448

I would like to run a query on this to get a distinct count of the direct_lead_id when is_clicked = True. So the result of my query would be 1 in this case. If I added a line to the above table, let say:
true| 407449.
Then I would want to get 2.


答:
Simple Loop

You can use a simple loop, getting the first dictionary with Type set to 10.

```<code>lst = [
    {'Id': 46, 'Date': '2016-05-09T00:00:00', 'Type': 1, 'PId': None, 'Ct': None},
    {'Id': 108, 'Date': '2017-07-01T00:00:00', 'Type': 10, 'PId': None, 'Ct': None},
]
type_10_date = None
for obj in lst:
    if obj.get('Type') == 10:
        type_10_date = obj.get('Date')

print(type_10_date)
# 2017-07-01T00:00:00
</code>```

Using Filter

You can also use the built-in filter function if you choose, which takes a predicate function that determines what values in an iterable (the list in this case) should be returned. Note: I've included a conversion to a list for Python 3 users who get a filter object back from the built-in filter function.

```<code>type_10_objs = list(filter(lambda d: d.get('Type') == 10, lst))
if type_10_objs:  # This could be an empty list!
    print(type_10_objs[0].get('Date'))
# 2017-07-01T00:00:00
</code>```

Title: Extracting element from list of dictionaries in python

Body:
Simple Loop

You can use a simple loop, getting the first dictionary with Type set to 10.

lst = [
    {'Id': 46, 'Date': '2016-05-09T00:00:00', 'Type': 1, 'PId': None, 'Ct': None},
    {'Id': 108, 'Date': '2017-07-01T00:00:00', 'Type': 10, 'PId': None, 'Ct': None},
]
type_10_date = None
for obj in lst:
    if obj.get('Type') == 10:
        type_10_date = obj.get('Date')

print(type_10_date)
# 2017-07-01T00:00:00

Using Filter

You can also use the built-in filter function if you choose, which takes a predicate function that determines what values in an iterable (the list in this case) should be returned. Note: I've included a conversion to a list for Python 3 users who get a filter object back from the built-in filter function.

type_10_objs = list(filter(lambda d: d.get('Type') == 10, lst))
if type_10_objs:  # This could be an empty list!
    print(type_10_objs[0].get('Date'))
# 2017-07-01T00:00:00


问:
Get all Orders IDs from a product ID in Woocommerce
How can I get an array with Order IDs by Product ID?

I mean receive all orders where specific product is presented.

I know how to do this by MySQL, but is there a way to do this by WP_Query function?

答:
I'd like to note that the above answer will return a duplicate of the order_id if the order has multiple items in it.

E.g.

If there was a product called "apples" with product_id=>1036

Customer puts "apples" 3 times in their cart and purchases it, creating order_id=>555

If I query product_id->1036, I will get array(555,555,555).

There's probably an SQL way of doing this which may be faster, (would appreciate anyone that could add to this), otherwise I used: array_unqiue() to merge the duplicates.

```<code>function retrieve_orders_ids_from_a_product_id( $product_id )
{
    global $wpdb;

    $table_posts = $wpdb->prefix . "posts";
    $table_items = $wpdb->prefix . "woocommerce_order_items";
    $table_itemmeta = $wpdb->prefix . "woocommerce_order_itemmeta";

    // Define HERE the orders status to include in  <==  <==  <==  <==  <==  <==  <==
    $orders_statuses = "'wc-completed', 'wc-processing', 'wc-on-hold'";

    # Requesting All defined statuses Orders IDs for a defined product ID
    $orders_ids = $wpdb->get_col( "
        SELECT $table_items.order_id
        FROM $table_itemmeta, $table_items, $table_posts
        WHERE  $table_items.order_item_id = $table_itemmeta.order_item_id
        AND $table_items.order_id = $table_posts.ID
        AND $table_posts.post_status IN ( $orders_statuses )
        AND $table_itemmeta.meta_key LIKE '_product_id'
        AND $table_itemmeta.meta_value LIKE '$product_id'
        ORDER BY $table_items.order_item_id DESC"
    );
    // return an array of Orders IDs for the given product ID
    $orders_ids = array_unique($orders_ids);
    return $orders_ids;
}
</code>```

Body:
I'd like to note that the above answer will return a duplicate of the order_id if the order has multiple items in it.

E.g.

If there was a product called "apples" with product_id=>1036

Customer puts "apples" 3 times in their cart and purchases it, creating order_id=>555

If I query product_id->1036, I will get array(555,555,555).

There's probably an SQL way of doing this which may be faster, (would appreciate anyone that could add to this), otherwise I used: array_unqiue() to merge the duplicates.

function retrieve_orders_ids_from_a_product_id( $product_id )
{
    global $wpdb;

    $table_posts = $wpdb->prefix . "posts";
    $table_items = $wpdb->prefix . "woocommerce_order_items";
    $table_itemmeta = $wpdb->prefix . "woocommerce_order_itemmeta";

    // Define HERE the orders status to include in  <==  <==  <==  <==  <==  <==  <==
    $orders_statuses = "'wc-completed', 'wc-processing', 'wc-on-hold'";

    # Requesting All defined statuses Orders IDs for a defined product ID
    $orders_ids = $wpdb->get_col( "
        SELECT $table_items.order_id
        FROM $table_itemmeta, $table_items, $table_posts
        WHERE  $table_items.order_item_id = $table_itemmeta.order_item_id
        AND $table_items.order_id = $table_posts.ID
        AND $table_posts.post_status IN ( $orders_statuses )
        AND $table_itemmeta.meta_key LIKE '_product_id'
        AND $table_itemmeta.meta_value LIKE '$product_id'
        ORDER BY $table_items.order_item_id DESC"
    );
    // return an array of Orders IDs for the given product ID
    $orders_ids = array_unique($orders_ids);
    return $orders_ids;
}


问:
Why am I losing my databinding when printing to an XpsDocument?
Update!

Binding works.  The issue is that the XpsDocumentWriter doesn't properly write the first page of the first document of a FixedDocumentSequence.  This seems to be an issue encountered by lots of people doing this sort of thing (i.e., five developers worldwide).  The solution is slightly odd.  I include it as an answer.

Okay, its a bit more subtle than the question suggests.

I've got a series of FixedPages, each has its DataContext set individually.  Each FixedPage also has one or more controls that are bound to the context.

If I add these FixedPages to a single FixedDocument and write this single FixedDocument to an XpsDocument, my binds are de-referenced (so to speak) and the correct values are presented in the XpsDocument.

If I add these FixedPages to individual FixedDocuments (each FP gets added to a new FD), then these FixedDocuments are added to a FixedDocumentSequence, and this sequence is then written to the XpsDocument, my binds are NOT de-referenced and my FixedPages appear blank.

Debugging tells me that I'm not losing my bindings or my binding context, so that's not the cause of this failure.

Here's some sample code to illustrate what's going on:

```<code>// This works
FixedPage fp = CreateFixedPageWithBinding();
fp.DataContext = CreateDataContext();
// Add my databound fixed page to a new fixed document
var fd = new FixedDocument();
var pc = new PageContent();
((IAddChild)pc).AddChild(fp);
fd.Pages.Add(pageContent);
// Create an xps document and write my fixed document to it
var p = Package.Open("c:\\output.xps", FileMode.CreateNew);
var doc = new XpsDocument(p);
var writer = XpsDocument.CreateXpsDocumentWriter(doc);
wri2.Write(fd);
p.Flush();
p.Close();

// This does NOT work
FixedPage fp = CreateFixedPageWithBinding();
fp.DataContext = CreateDataContext();
// Add my databound fixed page to a new fixed document
var fd = new FixedDocument();
var pc = new PageContent();
((IAddChild)pc).AddChild(fp);
fd.Pages.Add(pageContent);
// Create a fixed document sequence and add the fixed document to it
FixedDocumentSequence fds = CreateFixedDocumentSequence();
var dr = new DocumentReference();
dr.BeginInit();
dr.SetDocument(fd);
dr.EndInit();
(fds as IAddChild).AddChild(dr);
// Create an xps document and write the fixed document sequence to it
var p = Package.Open("c:\\output.xps", FileMode.CreateNew);
var doc = new XpsDocument(p);
var writer = XpsDocument.CreateXpsDocumentWriter(doc);
wri2.Write(fds);
p.Flush();
p.Close();
</code>```

You can see that the only difference between the two is that I'm adding the fixed document to a fixed document sequence, which then gets written.

Obviously, whatever magic happens that causes the databinding to be evaluated and the bound values be inserted isn't happening when my fixed documents aren't being Written to the Xps Document.  I need to be able to write more than one fixed document, and the Write method can only be called once, thus requiring I add the FixedDocuments to a FixedDocumentSequence which I then write.  But I also need my damn databinding to work as well!

Any help in this situation would be appreciated.  I know its not exactly the most common part of the framework; I'm just hoping that someone here has some operational experience with this (I'm looking at you, lurking MS employee).

答: One reason that you lose a binding is that you throw an exception somewhere - unfortunately, this exception is silently swallowed and your binding just "stops working". Turn on First-chance exceptions and see if anything gets hit.</p>

ContentLicense: CC BY-SA 2.5

Body:
Update!

Binding works.  The issue is that the XpsDocumentWriter doesn't properly write the first page of the first document of a FixedDocumentSequence.  This seems to be an issue encountered by lots of people doing this sort of thing (i.e., five developers worldwide).  The solution is slightly odd.  I include it as an answer.

Okay, its a bit more subtle than the question suggests.

I've got a series of FixedPages, each has its DataContext set individually.  Each FixedPage also has one or more controls that are bound to the context.

If I add these FixedPages to a single FixedDocument and write this single FixedDocument to an XpsDocument, my binds are de-referenced (so to speak) and the correct values are presented in the XpsDocument.

If I add these FixedPages to individual FixedDocuments (each FP gets added to a new FD), then these FixedDocuments are added to a FixedDocumentSequence, and this sequence is then written to the XpsDocument, my binds are NOT de-referenced and my FixedPages appear blank.

Debugging tells me that I'm not losing my bindings or my binding context, so that's not the cause of this failure.

Here's some sample code to illustrate what's going on:

// This works
FixedPage fp = CreateFixedPageWithBinding();
fp.DataContext = CreateDataContext();
// Add my databound fixed page to a new fixed document
var fd = new FixedDocument();
var pc = new PageContent();
((IAddChild)pc).AddChild(fp);
fd.Pages.Add(pageContent);
// Create an xps document and write my fixed document to it
var p = Package.Open("c:\\output.xps", FileMode.CreateNew);
var doc = new XpsDocument(p);
var writer = XpsDocument.CreateXpsDocumentWriter(doc);
wri2.Write(fd);
p.Flush();
p.Close();

// This does NOT work
FixedPage fp = CreateFixedPageWithBinding();
fp.DataContext = CreateDataContext();
// Add my databound fixed page to a new fixed document
var fd = new FixedDocument();
var pc = new PageContent();
((IAddChild)pc).AddChild(fp);
fd.Pages.Add(pageContent);
// Create a fixed document sequence and add the fixed document to it
FixedDocumentSequence fds = CreateFixedDocumentSequence();
var dr = new DocumentReference();
dr.BeginInit();
dr.SetDocument(fd);
dr.EndInit();
(fds as IAddChild).AddChild(dr);
// Create an xps document and write the fixed document sequence to it
var p = Package.Open("c:\\output.xps", FileMode.CreateNew);
var doc = new XpsDocument(p);
var writer = XpsDocument.CreateXpsDocumentWriter(doc);
wri2.Write(fds);
p.Flush();
p.Close();

You can see that the only difference between the two is that I'm adding the fixed document to a fixed document sequence, which then gets written.

Obviously, whatever magic happens that causes the databinding to be evaluated and the bound values be inserted isn't happening when my fixed documents aren't being Written to the Xps Document.  I need to be able to write more than one fixed document, and the Write method can only be called once, thus requiring I add the FixedDocuments to a FixedDocumentSequence which I then write.  But I also need my damn databinding to work as well!

Any help in this situation would be appreciated.  I know its not exactly the most common part of the framework; I'm just hoping that someone here has some operational experience with this (I'm looking at you, lurking MS employee).

OwnerDisplayName: Paul Betts


问:
How can I get information if a specific cookie (by search of its value) exists or not in JS?
How can I get information if a specific cookie (by search of its value) exists or not in JS?

There is a cookie named 'XYZ' and its value is 'ZYX',
 how can I check if the cookie exists or not by its value?

I dont want to use Jquery

Thanks.

答:
This function returns true if any cookie with value v exists and false otherwise.

```<code>function check(v) {
  return !!document.cookie.split(/;\s*/).filter(function(c) {return v === c.split(/=/)[1]}).length;
}
</code>```

Body:
This function returns true if any cookie with value v exists and false otherwise.

function check(v) {
  return !!document.cookie.split(/;\s*/).filter(function(c) {return v === c.split(/=/)[1]}).length;
}


答:
I think that the real answer is to use Full Text Indexing (if you are using MS SQL - otherwise seeing if there is an equivalent for whatever server you are using).  However, here is an ugly hack that should work:

```<code>WHERE ISNULL(o.SuOrderEmailAddress, '') + '|'
      + ISNULL(o.SuBusEmailAddress, '') + '|'
      + ISNULL(o.SuReturnEmail, '') + '|'
      + ISNULL(O.SuPartsEmail, '') LIKE @pattern
</code>```

This simply concatenates all of the relevant fields into a pipe-delimited list before checking that concatenated string for the @pattern.

Title: SQL Using Like, One Variable, Multiple Columns

Body:
I think that the real answer is to use Full Text Indexing (if you are using MS SQL - otherwise seeing if there is an equivalent for whatever server you are using).  However, here is an ugly hack that should work:

WHERE ISNULL(o.SuOrderEmailAddress, '') + '|'
      + ISNULL(o.SuBusEmailAddress, '') + '|'
      + ISNULL(o.SuReturnEmail, '') + '|'
      + ISNULL(O.SuPartsEmail, '') LIKE @pattern

This simply concatenates all of the relevant fields into a pipe-delimited list before checking that concatenated string for the @pattern.


问:
Does !fork() create a process?
For instance if I call

```<code>if (!fork())
</code>```

does this create a new process like calling

```<code>if (fork())
</code>```

or does it not?

答:
Of course it does. In order to execute

```<code>if (! <expression>)
</code>```

it first has to evaluate <expression>, so that it can then invert the boolean value of the expression and test it with if. When the expression is fork(), it calls the fork function, which creates a new process, and then returns a value in both the child and parent processes.

It's essentially just short for:

```<code>pid_t pid = fork();
if (!pid)
</code>```

Title: Does !fork() create a process?

Body:
For instance if I call

if (!fork())

does this create a new process like calling

if (fork())

or does it not?

Body:
Of course it does. In order to execute

if (! <expression>)

it first has to evaluate <expression>, so that it can then invert the boolean value of the expression and test it with if. When the expression is fork(), it calls the fork function, which creates a new process, and then returns a value in both the child and parent processes.

It's essentially just short for:

pid_t pid = fork();
if (!pid)


问:
ASP.NET MVC3 how to switch the validation to different JS validation framework
How to switch the validation to different JS validation framework in ASP.NET MVC3? The default is Jquery validation.</p>

答:
Here you can find more details for what you want to do?
link text

You can also read this other question here: link text


问:
Get image from local URL (iOS)
I am getting a photo's URL using requestContentEditingInput using the PHLibrary

```<code>asset.requestContentEditingInput(with: PHContentEditingInputRequestOptions()) { (input, _) in
    let url = input?.fullSizeImageURL
}
</code>```

This URL prints: file:///Users/josh/Library/Developer/CoreSimulator/Devices/EE65D986-55E7-414C-A73E-D1C96FF17004/data/Media/DCIM/100APPLE/IMG_0005.JPG.

How do I retrieve this image?  I've tried the following but it does not return anything:

```<code>var fileLocation = "file:///Users/josh/Library/Developer/CoreSimulator/Devices/EE65D986-55E7-414C-A73E-D1C96FF17004/data/Media/DCIM/100APPLE/IMG_0005.JPG"
let url = URL(string: fileLocation)
let asset = PHAsset.fetchAssets(withALAssetURLs: [url!], options: nil)
if let result = asset.firstObject  {
    //asset.firstObject does not exist
}
</code>```

答:
apparently apple will not allow the developer to access any and every photo in the user's photo library even after they have accepted photos usage.  If you are using an image that hasnt been picked from the imagePicker, (i.e. choosing last image in library), you have to store the image in the document directory before you can use the document directory URL.  I guess this prevents people hacking into others photo library</p>

```<code>//Storing the image (in my case, when selecting last photo NOT via imagePicker)

let fileManager = FileManager.default
let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("image01.jpg")
let imageData = UIImageJPEGRepresentation(image!, 1.0)
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)

//Retrieving the image
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask    = FileManager.SearchPathDomainMask.userDomainMask
let paths               = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first {
    let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("image01.jpg")
    if let imageRetrieved = UIImage(contentsOfFile: imageURL.path) {
        //do whatever you want with this image
        print(imageRetrieved)
    }
}
</code>```

Title: Get image from local URL (iOS)

Body:
I am getting a photo's URL using requestContentEditingInput using the PHLibrary

asset.requestContentEditingInput(with: PHContentEditingInputRequestOptions()) { (input, _) in
    let url = input?.fullSizeImageURL
}

This URL prints: file:///Users/josh/Library/Developer/CoreSimulator/Devices/EE65D986-55E7-414C-A73E-D1C96FF17004/data/Media/DCIM/100APPLE/IMG_0005.JPG.

How do I retrieve this image?  I've tried the following but it does not return anything:

var fileLocation = "file:///Users/josh/Library/Developer/CoreSimulator/Devices/EE65D986-55E7-414C-A73E-D1C96FF17004/data/Media/DCIM/100APPLE/IMG_0005.JPG"
let url = URL(string: fileLocation)
let asset = PHAsset.fetchAssets(withALAssetURLs: [url!], options: nil)
if let result = asset.firstObject  {
    //asset.firstObject does not exist
}

Body:
apparently apple will not allow the developer to access any and every photo in the user's photo library even after they have accepted photos usage.  If you are using an image that hasnt been picked from the imagePicker, (i.e. choosing last image in library), you have to store the image in the document directory before you can use the document directory URL.  I guess this prevents people hacking into others photo library

//Storing the image (in my case, when selecting last photo NOT via imagePicker)

let fileManager = FileManager.default
let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("image01.jpg")
let imageData = UIImageJPEGRepresentation(image!, 1.0)
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)

//Retrieving the image
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask    = FileManager.SearchPathDomainMask.userDomainMask
let paths               = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first {
    let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("image01.jpg")
    if let imageRetrieved = UIImage(contentsOfFile: imageURL.path) {
        //do whatever you want with this image
        print(imageRetrieved)
    }
}


问:
Firebase: Should I add GoogleService-Info.plist to .gitignore?
I'm using Firebase for an iOS project that I want to open source.
Should I add GoogleService-Info.plist to .gitignore before I upload I share the project on Github?

I know it contains my API key, client id, etc., which might not be safe to expose?

答:
While it's not the end of the world if you commit GoogleService-Info.plist (similarly, on Android, google-services.json), you're better off leaving it out for one big reason: You're making it clear that others who build your code that they should be setting up their own Firebase project to host its configuration and data (because your project simply won't build with that file missing).  Furthermore, if your project has world-writable resources in it, you can expect that people who get a hold of your app and config so easily will inadvertently start writing data into it, which is probably not what you want.

Open source projects that require a Firebase setup should ideally have it stated in the readme that anyone who wants to work with this app needs to go through the process of setting up Firebase.

The data in these config files is not exactly private - they can be extracted fairly easily from an IPA or Android APK.  It's just probably not in your best interest to share them as part of your app's code.


问:
How to use OrderedMapIterator.previous()
Using Apache Commons Collections I found the OrderedMapIterator interface to navigate back and forth in OrderedMap. Iterating to the next entry works as expected. Going to the previous element doesn't return the previous element but the current element instead.

```<code>OrderedMap<String, String> linkedMap = new LinkedMap<>();
linkedMap.put("key 1", "value 1");
linkedMap.put("key 2", "value 2");
linkedMap.put("key 3", "value 3");

OrderedMapIterator<String, String> iterator = linkedMap.mapIterator();
while (iterator.hasNext()) {
    String key = iterator.next();
    System.out.println(key);

    if (key.endsWith("2") && iterator.hasPrevious()) {
        System.out.println("previous: " + iterator.previous());
        iterator.next(); // back to current element
    }
}
</code>```

I expected the output

```<code>key 1
key 2
previous: key 1
key 3
</code>```

but got

```<code>key 1
key 2
previous: key 2
key 3
</code>```

Do I use OrderedMapIterator wrong or is this a bug?

答:
Its because technically .previous() does  not exactly set current entry to previous, but to next.before. Look how iteration process works:

```<code>nextEntry() {
    ...
    last = next; //its current
    next = next.after;
    ...

previousEntry() {
    ...
    final LinkEntry<K, V> previous = next.before;
    ...
    next = previous;
    last = previous;
</code>```

So your flow will affect the last(current)|next states as follows:

```<code>null|1 -> (next) -> 1|2 -> (next) -> 2|3 <- (previous?) <- 2|2 -> (next) -> 3|null
</code>```

The reason i may think why is behaves so, because its intended to call .next(), .previous() in separate loops.

Imagine a situation where you iterate all way forward, and then need to iterate all way back.

```<code>while (it.hasNext()) {
    String key = it.next();
    list.add(key);
}
while (it.hasPrevious()) {
    String key = it.previous();
    list.remove(key);
}
</code>```

With the behaviour which you want to have, you would ended up with [key 3] in list, which is not correct, but currently it works fine.

Body:
Using Apache Commons Collections I found the OrderedMapIterator interface to navigate back and forth in OrderedMap. Iterating to the next entry works as expected. Going to the previous element doesn't return the previous element but the current element instead.

OrderedMap<String, String> linkedMap = new LinkedMap<>();
linkedMap.put("key 1", "value 1");
linkedMap.put("key 2", "value 2");
linkedMap.put("key 3", "value 3");

OrderedMapIterator<String, String> iterator = linkedMap.mapIterator();
while (iterator.hasNext()) {
    String key = iterator.next();
    System.out.println(key);

    if (key.endsWith("2") && iterator.hasPrevious()) {
        System.out.println("previous: " + iterator.previous());
        iterator.next(); // back to current element
    }
}

I expected the output

key 1
key 2
previous: key 1
key 3

but got

key 1
key 2
previous: key 2
key 3

Do I use OrderedMapIterator wrong or is this a bug?

Body:
Its because technically .previous() does  not exactly set current entry to previous, but to next.before. Look how iteration process works:

nextEntry() {
    ...
    last = next; //its current
    next = next.after;
    ...

previousEntry() {
    ...
    final LinkEntry<K, V> previous = next.before;
    ...
    next = previous;
    last = previous;

So your flow will affect the last(current)|next states as follows:

null|1 -> (next) -> 1|2 -> (next) -> 2|3 <- (previous?) <- 2|2 -> (next) -> 3|null

The reason i may think why is behaves so, because its intended to call .next(), .previous() in separate loops.

Imagine a situation where you iterate all way forward, and then need to iterate all way back.

while (it.hasNext()) {
    String key = it.next();
    list.add(key);
}
while (it.hasPrevious()) {
    String key = it.previous();
    list.remove(key);
}

With the behaviour which you want to have, you would ended up with [key 3] in list, which is not correct, but currently it works fine.


问:
Building an array with select and objects in AngularJS
I'm trying to build an array that allows users to select from a set of options.  I have a generic array of objects, and when I add a new item to my model, I am able to select one of those objects.

The problem I'm having (I believe) is that the ng-options I'm using to populate the list of items get's cleared once a user makes a selection.  I'm not sure how to keep the full list of objects so that the user can change their mind if they want to.

I put together a quick sample of what I'm trying to do - http://jsfiddle.net/b0kwx1nj/

I'd appreciate any help anyone can provide.

Angular:

```<code>var myApp = angular.module('myApp', []);
function ToppingCtrl($scope) {
  $scope.toppings = [{
    name: 'Cheese',
    price: 0.5
  }, {
    name: 'Ham',
    price: 1.5
  }, {
    name: 'Sauce',
    price: 0.25
  }];
  $scope.myToppings = [];

  $scope.addTopping = function() {
    var newTopping = angular.copy($scope.toppings);
    $scope.myToppings.push(newTopping);
  }
}
</code>```

HTML:

```<code><div ng-controller="ToppingCtrl" class="container">
    <table>
        <tr>
            <th>Topping</th>
            <th>Price</th>
        </tr>
        <tr ng-repeat="item in myToppings track by $index">
            <td>
                <select
                    id="top_{{$index}}"
                    name="top_{{$index}}"
                    title="top_{{$index}}"
                    ng-model="myToppings[$index]"
                    ng-options="topping.name for topping in myToppings[$index]"
                >
                    <option value=''>-- select --</option>
                </select>
            </td>
            <td>{{myToppings[$index].price}}</td>
        </tr>
    </table>
    <button ng-click="addTopping()">Add topping</button>
</div>
</code>```

答:
The reason it's getting cleared is addTopping() converts the myToppings[$index] to an array containing 3 elements from toppings which shows up as the dropdown list.

It gets converted to a single element (not an array anymore) as soon as you make a selection in your dropdown - and that's why the value doesn't stick. You should link the ng-options to toppings instead of myToppings[$index] to correct that. And, you can just change the addToppings() to add a new empty object to the myToppings[].

Here's your new code:

HTML:

```<code><select
id="top_{{$index}}"
name="top_{{$index}}"
title="top_{{$index}}"
ng-model="myToppings[$index]"
ng-options="topping.name for topping in toppings"
>
    <option value=''>-- select --</option>
</select>
</code>```

Angular:

```<code>$scope.addTopping = function() {
var newTopping = {};
$scope.myToppings.push(newTopping);
}
</code>```

Hope it helps.

Body:
I'm trying to build an array that allows users to select from a set of options.  I have a generic array of objects, and when I add a new item to my model, I am able to select one of those objects.

The problem I'm having (I believe) is that the ng-options I'm using to populate the list of items get's cleared once a user makes a selection.  I'm not sure how to keep the full list of objects so that the user can change their mind if they want to.

I put together a quick sample of what I'm trying to do - http://jsfiddle.net/b0kwx1nj/

I'd appreciate any help anyone can provide.

Angular:

var myApp = angular.module('myApp', []);
function ToppingCtrl($scope) {
  $scope.toppings = [{
    name: 'Cheese',
    price: 0.5
  }, {
    name: 'Ham',
    price: 1.5
  }, {
    name: 'Sauce',
    price: 0.25
  }];
  $scope.myToppings = [];

  $scope.addTopping = function() {
    var newTopping = angular.copy($scope.toppings);
    $scope.myToppings.push(newTopping);
  }
}

HTML:

            Topping
            Price

                <select
                    id="top_{{$index}}"
                    name="top_{{$index}}"
                    title="top_{{$index}}"
                    ng-model="myToppings[$index]"
                    ng-options="topping.name for topping in myToppings[$index]"
                >
                    <option value=''>-- select --</option>
                </select>

            {{myToppings[$index].price}}

    <button ng-click="addTopping()">Add topping</button>

Body:
The reason it's getting cleared is addTopping() converts the myToppings[$index] to an array containing 3 elements from toppings which shows up as the dropdown list.

It gets converted to a single element (not an array anymore) as soon as you make a selection in your dropdown - and that's why the value doesn't stick. You should link the ng-options to toppings instead of myToppings[$index] to correct that. And, you can just change the addToppings() to add a new empty object to the myToppings[].

Here's your new code:

HTML:

<select
id="top_{{$index}}"
name="top_{{$index}}"
title="top_{{$index}}"
ng-model="myToppings[$index]"
ng-options="topping.name for topping in toppings"
>
    <option value=''>-- select --</option>
</select>

Angular:

$scope.addTopping = function() {
var newTopping = {};
$scope.myToppings.push(newTopping);
}

Hope it helps.


问:
Turning an array into a multidimensional array? Javascript
I am struggling to create a simple function that will taking an array such as

```<code>["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"]
</code>```

and turn it into a multidimensional array that looks like this

```<code>[["chicken","10 lbs"],["hot sauce","4 cups"],["celery","1 stalk"]]
</code>```

essentially index 0 and 1 merge into a new sub array then 2 and 3 merge and so on...

i am trying for loops where i increases +2 but i can't get it quite right, i thought this would be a simple solution but the loops i've made so far are almost crashing my browser...any help would be appreciated. thanks

EDIT:  WOW Thanks for all the rapid responses!  I looked at everything and learned a lot!

答:
Hope this helps...

I added some comments but feel free to ask if you need more explanation.

There are definitely more advanced (and much shorter!) ways of doing this, but this is the most intuitive and easiest to understand, in my opinion.

Right now, if there is an odd amount of elements, the last element will end up being "undefined."  Let me know if you'd like this to work differently.

var array = ["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"];

function combineTwo(inputArray) {
//Starting with the beginning of the array, this function combines index 0 with 1, 2 with 3, and so on for the entire length of the array
  var result = []; //this will the variable that we store our result in
  for (var i = 0; i < inputArray.length; i+=2) {
    //This for loop iterates through every other index of the array... for example: 0, 2, 4, etc.
    result.push([inputArray[i], inputArray[i+1]]); //Adds i and i+1 as a new array to the result array
  }
  return result;
}

console.log(combineTwo(array));```

Body:
I am struggling to create a simple function that will taking an array such as

["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"]

and turn it into a multidimensional array that looks like this

[["chicken","10 lbs"],["hot sauce","4 cups"],["celery","1 stalk"]]

essentially index 0 and 1 merge into a new sub array then 2 and 3 merge and so on...

i am trying for loops where i increases +2 but i can't get it quite right, i thought this would be a simple solution but the loops i've made so far are almost crashing my browser...any help would be appreciated. thanks

EDIT:  WOW Thanks for all the rapid responses!  I looked at everything and learned a lot!


问:
Android Studio - Creating Modules without copying files?
I'm creating projects with dependencies in Android Studio. I know how to link projects by adding modules.

But I realized that 'importing modules' create a copy of the libProject inside the project.

Is there a way to prevent that ? Like an 'external module' ?

Since i'm in charge of both project, I want to be able to push changes to the libProject Repo, without having to copy paste files between folders.

Thanks

答:
If you have, like myself, have multiple modules (I only realised today that copies were included, I thought that the project included links to the source.)

You can have multiple modules/projects along the lines of :-

```<code>include ':app', ':sqlwords', ':dbindex', ':dbcolumn', ':dbtable', ':dbdatabase', ':displayhelp', ':pickdate'
project(':sqlwords').projectDir= new File('d:/Android_Applications/Modules/sqlwords')
project(':dbcolumn').projectDir= new File('d:/Android_Applications/Modules/dbcolumn')
project(':dbtable').projectDir= new File('d:/Android_Applications/Modules/dbtable')
project(':dbindex').projectDir= new File('d:/Android_Applications/Modules/dbindex')
project(':dbdatabase').projectDir= new File('d:/Android_Applications/Modules/dbdatabase')
project(':displayhelp').projectDir= new File('d:/Android_Applications/Modules/displayhelp')
project(':pickdate').projectDir= new File('d:/Android_Applications/PickDateShowCase/pickdate')
</code>```

Body:
If you have, like myself, have multiple modules (I only realised today that copies were included, I thought that the project included links to the source.)

You can have multiple modules/projects along the lines of :-

include ':app', ':sqlwords', ':dbindex', ':dbcolumn', ':dbtable', ':dbdatabase', ':displayhelp', ':pickdate'
project(':sqlwords').projectDir= new File('d:/Android_Applications/Modules/sqlwords')
project(':dbcolumn').projectDir= new File('d:/Android_Applications/Modules/dbcolumn')
project(':dbtable').projectDir= new File('d:/Android_Applications/Modules/dbtable')
project(':dbindex').projectDir= new File('d:/Android_Applications/Modules/dbindex')
project(':dbdatabase').projectDir= new File('d:/Android_Applications/Modules/dbdatabase')
project(':displayhelp').projectDir= new File('d:/Android_Applications/Modules/displayhelp')
project(':pickdate').projectDir= new File('d:/Android_Applications/PickDateShowCase/pickdate')


问:
How to retrieve more than 1000 rows from Parse.com?
I have been using Parse to retrieve a data for a list view. Unfortunately they limit requests to 100 by default to a 1000 max. I have well over that 1000 max in my class. I found a link on the web which shows a way to do it on iOS but how would you do it on Android? Web Link

I am currently adding all the data into a arraylist in a loop until all items are complete (100) then adding them to the list

答:
YAS (Yet Another Solution!) Using async() and await() in javascript.

```<code>async parseFetchAll(collected = []) {
  let query = new Parse.Query(GameScore);
  const limit = 1000;

  query.limit(limit);
  query.skip(collected.length);

  const results = await query.find();

  if(results.length === limit) {
    return await parseFetchAll([ ...collected, ...results ]);
  } else {
    return collected.concat(results);
  }

}
</code>```

Body:
YAS (Yet Another Solution!) Using async() and await() in javascript.

async parseFetchAll(collected = []) {
  let query = new Parse.Query(GameScore);
  const limit = 1000;

  query.limit(limit);
  query.skip(collected.length);

  const results = await query.find();

  if(results.length === limit) {
    return await parseFetchAll([ ...collected, ...results ]);
  } else {
    return collected.concat(results);
  }

}


问:
Putting curl into postman trouble
I was converting a cURL request from the command line command to the postman format and found something odd.

```<code>curl -u testclient:testpass http://localhost.com/ -d 'grant_type=client_credentials'
</code>```

The above cURL command works in the terminal, but not in the Postman import section. I thought it wasn't a big deal, and that I would do it manually, but I can't seem to figure out what to do with the "-u testclient:testpass" portion of it.

```<code>-u testclient:testpass
</code>```

Could someone please explain to me what this formatting means?

答:
As read on the documentation,

```<code>-u, --user <user:password>
</code>```

stands for user and password. So maybe you could select the Authorization tab, and select Basic Auth on the type. Then add the user and password.

Title: Putting curl into postman trouble

Body:
I was converting a cURL request from the command line command to the postman format and found something odd.

curl -u testclient:testpass http://localhost.com/ -d 'grant_type=client_credentials'

The above cURL command works in the terminal, but not in the Postman import section. I thought it wasn't a big deal, and that I would do it manually, but I can't seem to figure out what to do with the "-u testclient:testpass" portion of it.

-u testclient:testpass

Could someone please explain to me what this formatting means?

Body:
As read on the documentation,

-u, --user <user:password>

stands for user and password. So maybe you could select the Authorization tab, and select Basic Auth on the type. Then add the user and password.


问:
Keen IO bulk add operation suddenly stops working
I’m starting to get this error message “One or more events was rejected during the bulk add operation” since July 3rd, every time I run my batch job to upload files from S3 to Keen using the .net SDK.

I'm not sure if this error is coming from Keen IO's server or somewhere else.

Do you have any idea why I’m getting this message?

Thanks in advance.

答:
That error is being thrown by the .net sdk because you hit some kind of API error during async upload. Is it possible for you to inspect which error that is being thrown by the Keen API? If you can get the detailed error response from the API, you can isolate the problem better. Here are the most common errors that you would encounter when posting an event:

Missing or invalid parameters. Error messages will often contain more information to help you figure out what’s wrong. Usually it's invalid JSON in one of your events.

Your request is too big. If your events have hundreds of properties and are unusually large, your batch might be too big to post. You can reduce the batch size to address this.

Some next steps for troubleshooting would be:

See if you can find the error message being thrown by the Keen API. It will have more detail about why the request failed.

Inspect your events to see if there are any obvious reasons why they would fail.


问:
I tried to float three images next to each other a 33% width. Why is there extra space on the right?
I'm pretty new to CSS and I'm not sure how to solve this problem. When I try and left float my three images next to each other with no padding or margin and a 33% width I get extra space on the right. I believe it has something to do with the image not wanting to adjust properly, but since I'm not using them as background images I don't know how I would use the cover attribute.
HTML for images:

```<code><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>
            /* Body styles */
              body {
              background-color: white;
              font-family: ;
              margin: 0px auto;
              width: 100%;
              min-width: 1000px;
              max-width: 1400px;}

             /* Image styles */
              #box img {
              padding: 0px;
              float: left;
              width: 33%; }
        </code>```

        ```
</div>
</div>

</code>```

答:
33% * 3 = 99%. The 1% makes a difference. 33.33% will work better.

But I would use calc(100% / 3) instead.

body {
  background-color: white;
  margin: 0px auto;
  width: 100%;
  min-width: 1000px;
  max-width: 1400px;
}

#box img {
  float: left;
  width: calc(100% / 3);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="box">
  <img src="https://i.stack.imgur.com/2C22p.jpg" alt="Social link box" />
  <img src="https://i.stack.imgur.com/2C22p.jpg" alt="Rewards link box" />
  <img src="https://i.stack.imgur.com/2C22p.jpg" alt="Franchise link box" />
</div></code>```

Body:
I'm pretty new to CSS and I'm not sure how to solve this problem. When I try and left float my three images next to each other with no padding or margin and a 33% width I get extra space on the right. I believe it has something to do with the image not wanting to adjust properly, but since I'm not using them as background images I don't know how I would use the cover attribute.
HTML for images:

            /* Body styles */
              body {
              background-color: white;
              font-family: ;
              margin: 0px auto;
              width: 100%;
              min-width: 1000px;
              max-width: 1400px;}

             /* Image styles */
              #box img {
              padding: 0px;
              float: left;
              width: 33%; }

Body:
33% * 3 = 99%. The 1% makes a difference. 33.33% will work better.

But I would use calc(100% / 3) instead.

body {
  background-color: white;
  margin: 0px auto;
  width: 100%;
  min-width: 1000px;
  max-width: 1400px;
}

#box img {
  float: left;
  width: calc(100% / 3);
}

<div id="box">
  <img src="https://i.stack.imgur.com/2C22p.jpg" alt="Social link box" />
  <img src="https://i.stack.imgur.com/2C22p.jpg" alt="Rewards link box" />
  <img src="https://i.stack.imgur.com/2C22p.jpg" alt="Franchise link box" />
</div>


问:
django html inicial text in form
I have a django form with a forms.Textarea that contains html. If I want the user to see the text he has written whenever he wants to edit the html, how can I fill the <textarea> without django showing all the
s and the <brs?

I am using TinyMCE in the fron, just a javascript library for rich text editing. How can I fill this field with django initial values?

答: Django's |safe filter doesn't work in this case since you can'a place it anywhere (the form renders the html automatically). What solved it is the {% autoescape off %} {% endautoescape %} tags.

Title: django html inicial text in form


问:
javascript test if div has text in it
```<code>1. <div id="div_Msg"> Test the div </div>
2. <div id="div_Msg"> </div>
</code>```

In  the first instance there is the text  in the div. In the second instance there is no text. Using javascript how can it be tested if a div has text in it.

答:
If using jQuery, you can do:

```<code>$.trim($('#div_Msg').text());
</code>```

Note: elements cannot have the same id

Title: javascript test if div has text in it

Body:
1.
 Test the div

2.

In  the first instance there is the text  in the div. In the second instance there is no text. Using javascript how can it be tested if a div has text in it.

Body:
If using jQuery, you can do:

$.trim($('#div_Msg').text());

Note: elements cannot have the same id


问:
Merge objects while preserving unique attributes
I am working on a C# project that takes lists of hundreds of objects of a custom class, and merges them together into a new list.  There may be some cases where a single real-world item is represented several times in the list, but with different attributes.  I am looking for an efficient way to merge these two lists together in such a way that any time a duplicate is found on my search key property, the other properties are merged together (either by overwriting the attributes of one of the objects or by creating a new object with the merged attributes) instead of deleting the second instance.

Here is an example of what I want to do:
Objects of class Dog with elements (ID, Owner, Breed, Colour). The Dog Rover is owned by both Sharon and Paul.  I want my merged list to include the text “Sharon/Paul” as the new attribute for the “Owner” variable.

Original lists:

List A:

1.Rover (23, Sharon, Labrador, Black)

2.Spot (40, Paul, Retriever, Golden)

List B:

Rover (23, Paul, Labrador, Black)

Merged list:

Rover (23, Sharon/ Paul, Labrador, Black)

Spot (40, Paul, Retriever, Golden)

I have been able to join the lists to create:
1.  Rover (23, Sharon, Labrador, Black)
2.  Rover (23, Paul, Labrador, Black)
3.  Spot (40, Paul, Retriever, Golden)
Or run .Unique on the lists to create:
1.  Rover (23, Sharon, Labrador, Black)
2.  Spot (40, Paul, Retriever, Golden)

But neither of those give me all of the information I need in the smallest list possible.

答:
What you need is a full outer join to get all the dogs, and then merge the matching dogs. A full outer join is done in LINQ by doing a left outer join and then a right anti semi join and then using Union to combine them.

I assumed each dog ID will appear at most once in each list and that Breed and Colour would be identical, if not you can merge them like Owner.

```<code>var leftDogs = from da in dogsA
               join db in dogsB on da.ID equals db.ID into dbj
               from db in dbj.DefaultIfEmpty()
               select new Dog {
                   ID = da.ID,
                   Owner = (db == null ? da.Owner : $"{da.Owner}/{db.Owner}"),
                   Breed = da.Breed,
                   Colour = da.Colour
               };

var rightDogs = from db in dogsB
                where !dogsA.Any(da => da.ID == db.ID)
                select db;

var ans = leftDogs.Union(rightDogs);
</code>```

If there is a possibility of duplicate entries in each list for multiple owner dogs, you can reduce the first list then reduce the combination:

```<code>public static IEnumerable<Dog> MergeDupDogs(IEnumerable<Dog> dogsA, IEnumerable<Dog> dogsB) {
    var dogsAReduced = dogsA.Aggregate(new Dictionary<int, Dog>(), (acc, da) => {
        if (!acc.ContainsKey(da.ID))
            acc.Add(da.ID, da);
        else
            acc[da.ID] = new Dog { ID = da.ID, Owner = $"{acc[da.ID].Owner}/{da.Owner}", Breed = da.Breed, Colour = da.Colour };
        return acc;
    });

    return dogsB.Aggregate(dogsAReduced, (acc, db) => {
        if (!acc.ContainsKey(db.ID))
            acc.Add(db.ID, db);
        else
            acc[db.ID] = new Dog { ID = db.ID, Owner = $"{acc[db.ID].Owner}/{db.Owner}", Breed = db.Breed, Colour = db.Colour };
        return acc;
    }).Select(e => e.Value);
}
</code>```

Body:
What you need is a full outer join to get all the dogs, and then merge the matching dogs. A full outer join is done in LINQ by doing a left outer join and then a right anti semi join and then using Union to combine them.

I assumed each dog ID will appear at most once in each list and that Breed and Colour would be identical, if not you can merge them like Owner.

var leftDogs = from da in dogsA
               join db in dogsB on da.ID equals db.ID into dbj
               from db in dbj.DefaultIfEmpty()
               select new Dog {
                   ID = da.ID,
                   Owner = (db == null ? da.Owner : $"{da.Owner}/{db.Owner}"),
                   Breed = da.Breed,
                   Colour = da.Colour
               };

var rightDogs = from db in dogsB
                where !dogsA.Any(da => da.ID == db.ID)
                select db;

var ans = leftDogs.Union(rightDogs);

If there is a possibility of duplicate entries in each list for multiple owner dogs, you can reduce the first list then reduce the combination:

public static IEnumerable<Dog> MergeDupDogs(IEnumerable<Dog> dogsA, IEnumerable<Dog> dogsB) {
    var dogsAReduced = dogsA.Aggregate(new Dictionary<int, Dog>(), (acc, da) => {
        if (!acc.ContainsKey(da.ID))
            acc.Add(da.ID, da);
        else
            acc[da.ID] = new Dog { ID = da.ID, Owner = $"{acc[da.ID].Owner}/{da.Owner}", Breed = da.Breed, Colour = da.Colour };
        return acc;
    });

    return dogsB.Aggregate(dogsAReduced, (acc, db) => {
        if (!acc.ContainsKey(db.ID))
            acc.Add(db.ID, db);
        else
            acc[db.ID] = new Dog { ID = db.ID, Owner = $"{acc[db.ID].Owner}/{db.Owner}", Breed = db.Breed, Colour = db.Colour };
        return acc;
    }).Select(e => e.Value);
}


问:
NLog and Common.Logging nightmare
So I have tried everything I can find to get these two to play together.

I have installed the nuget package Common.Logging.NLog20,

My config looks like:

```<code><configSections>
    <sectionGroup name="common">
        <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
    </sectionGroup>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog20" />
</configSections>
<common>
    <logging>
        <factoryAdapter type="Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog20">
            <arg key="configType" value="INLINE" />
        </factoryAdapter>
    </logging>
</common>
<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
            <assemblyIdentity name="NLog" publicKeyToken="5120e14c03d0593c" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-2.1.0.0" newVersion="2.1.0.0" />
        </dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="Common.Logging" publicKeyToken="af08829b84f0328e" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
        </dependentAssembly>
    </assemblyBinding>
</runtime>
</code>```

I am using the nuget NLog.Configuration package so my nlog config is in a separate file called NLog.config:

```<code><?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  internalLogFile="nlog.ERRORS.txt" internalLogLevel="Error" >

<!--
See http://nlog-project.org/wiki/Configuration_file
for information on customizing logging rules and outputs.
-->
<targets>
    <!-- add your targets here -->
    <target xsi:type="File" name="log" keepFileOpen="true"
            fileName="${basedir}/log_${date:format=yyyyMMdd}.txt"
            layout="${longdate} ${level:uppercase=true:padding=5} - ${logger:shortName=true} - ${message} ${exception:format=tostring}" />
    <target name="log_errors_memory" xsi:type="Memory"
            layout="${longdate} ${level:uppercase=true:padding=5} - ${logger:shortName=true} - ${message} ${exception:format=tostring}" />
    <target name="log_all_memory" xsi:type="Memory"
            layout="${longdate} ${level:uppercase=true:padding=5} - ${logger:shortName=true} - ${message} ${exception:format=tostring}" />
</targets>

<rules>
    <!-- add your logging rules here -->
    <logger name="*" minlevel="Trace" writeTo="log" />
    <logger name="*" minlevel="Trace" writeTo="log_all_memory" />
    <logger name="*" minlevel="Error" writeTo="log_errors_memory" />
</rules>
</nlog>
</code>```

I have tried changing the FactoryAdaptor to NLog, NLog2 and NLog20, I have tried changing the binding redirect, I have tried updating the Common.Logging to version 2.2.0.0.  No matter what I do I get the exception:

```<code>{"Failed obtaining configuration for Common.Logging from configuration section 'common/logging'."}

Inner Exception:
{"An error occurred creating the configuration section handler for common/logging: Type Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog20, Version=2.2.0.0, Culture=neutral, PublicKeyToken=af08829b84f0328e does not implement Common.Logging.ILoggerFactoryAdapter\r\nParameter name: factoryAdapterType\r\nActual value was Common.Logging.NLog.NLogLoggerFactoryAdapter. (D:\\Development\\Code\\DotNet\\vs2013\\exe\\CommandLine\\PSVImporter\\FidessaPSVImport.Test\\bin\\Debug\\FidessaPSVImport.Test.dll.config line 17)"}
</code>```

What am I missing?  This shouldn't be this hard to get working.

答:
Here's an underhanded approach that will save you a lot of hassle. The adapter that ships with Common.Logging.NLogXX,  NLogLoggerFactoryAdapter, does nothing special but setup up NLog for you. This is something that most people can do on their own.

In other words, if you've already setup NLog all you need to do is hookup Common.Logging to NLog. This can be done by writing a simple factory that will create NLog Loggers like this:

```<code>public class MyAdapter : AbstractCachingLoggerFactoryAdapter
{
    protected override ILog CreateLogger(string name)
    {
        return (ILog)typeof(NLogLogger).GetConstructor(
            BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(NLog.Logger) }, null)
            .Invoke(new object[] { NLog.LogManager.GetLogger(name) });
    }
}

public static void ConfigureLogging()
{
    Common.Logging.LogManager.Adapter = new MyAdapter();
}
</code>```

Title: NLog and Common.Logging nightmare

Body:
So I have tried everything I can find to get these two to play together.

I have installed the nuget package Common.Logging.NLog20,

My config looks like:

<configSections>
    <sectionGroup name="common">

    </sectionGroup>

</configSections>
<common>
    <logging>
        <factoryAdapter type="Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog20">
            <arg key="configType" value="INLINE" />
        </factoryAdapter>
    </logging>
</common>
<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
            <assemblyIdentity name="NLog" publicKeyToken="5120e14c03d0593c" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-2.1.0.0" newVersion="2.1.0.0" />
        </dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="Common.Logging" publicKeyToken="af08829b84f0328e" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
        </dependentAssembly>
    </assemblyBinding>
</runtime>

I am using the nuget NLog.Configuration package so my nlog config is in a separate file called NLog.config:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  internalLogFile="nlog.ERRORS.txt" internalLogLevel="Error" >

<targets>

    <target xsi:type="File" name="log" keepFileOpen="true"
            fileName="${basedir}/log_${date:format=yyyyMMdd}.txt"
            layout="${longdate} ${level:uppercase=true:padding=5} - ${logger:shortName=true} - ${message} ${exception:format=tostring}" />
    <target name="log_errors_memory" xsi:type="Memory"
            layout="${longdate} ${level:uppercase=true:padding=5} - ${logger:shortName=true} - ${message} ${exception:format=tostring}" />
    <target name="log_all_memory" xsi:type="Memory"
            layout="${longdate} ${level:uppercase=true:padding=5} - ${logger:shortName=true} - ${message} ${exception:format=tostring}" />
</targets>

<rules>

    <logger name="*" minlevel="Trace" writeTo="log" />
    <logger name="*" minlevel="Trace" writeTo="log_all_memory" />
    <logger name="*" minlevel="Error" writeTo="log_errors_memory" />
</rules>
</nlog>

I have tried changing the FactoryAdaptor to NLog, NLog2 and NLog20, I have tried changing the binding redirect, I have tried updating the Common.Logging to version 2.2.0.0.  No matter what I do I get the exception:

{"Failed obtaining configuration for Common.Logging from configuration section 'common/logging'."}

Inner Exception:
{"An error occurred creating the configuration section handler for common/logging: Type Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog20, Version=2.2.0.0, Culture=neutral, PublicKeyToken=af08829b84f0328e does not implement Common.Logging.ILoggerFactoryAdapter\r\nParameter name: factoryAdapterType\r\nActual value was Common.Logging.NLog.NLogLoggerFactoryAdapter. (D:\\Development\\Code\\DotNet\\vs2013\\exe\\CommandLine\\PSVImporter\\FidessaPSVImport.Test\\bin\\Debug\\FidessaPSVImport.Test.dll.config line 17)"}

What am I missing?  This shouldn't be this hard to get working.

Body:
Here's an underhanded approach that will save you a lot of hassle. The adapter that ships with Common.Logging.NLogXX,  NLogLoggerFactoryAdapter, does nothing special but setup up NLog for you. This is something that most people can do on their own.

In other words, if you've already setup NLog all you need to do is hookup Common.Logging to NLog. This can be done by writing a simple factory that will create NLog Loggers like this:

public class MyAdapter : AbstractCachingLoggerFactoryAdapter
{
    protected override ILog CreateLogger(string name)
    {
        return (ILog)typeof(NLogLogger).GetConstructor(
            BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(NLog.Logger) }, null)
            .Invoke(new object[] { NLog.LogManager.GetLogger(name) });
    }
}

public static void ConfigureLogging()
{
    Common.Logging.LogManager.Adapter = new MyAdapter();
}


问:
Where could $(SrcDir) possibly be defined?
I've recently taken over the build responsibilities at a new company and I'm trying to decipher how their builds work (TFS 2013) and in quite a few files I see that code is copied to $(SrcDir)\ someDestination, but I can't find where SrcDir is defined.

I've searched every file in source control (using file explorer with Search File Contents on) and can't find it defined anywhere and I've even checked the environment variables on the build server, but I can't find anything that defines SrcDir. If it was SourceDir I know that's defined in the Build Agent Properties under Working Directory, but not SrcDir.

答: I found it. It's in the MSBuild Arguments of the build definition:


问:
Why are we mapping properties with different names when logging in Spring Boot?
This is with reference to Spring Boot - Logging documentation. Why are we mapping the property logging.path to logger variable LOG_PATH and  logging.file to logger variable LOG_FILE?

This actually leads to confusion to developers who see one variable name while defining it and another name while consuming it.

答:
Since not all properties from Spring's Environment abstraction are available in the logging system we needed to adapt them. It's pretty common for logging libraries to support references to environment variables so that's the approach that we took.

It's common to see logging configuration like this in a standard logback file:

```<code><file>${USER_HOME}/myApp.log</file>
</code>```

So it felt pretty natural to add Spring Boot specific variables in the same format.

I also personally quite like the fact that there's a difference between the keys in the application.properties file and the ones you can use in your logging configuration. I think it helps to enforce that you can just add new entries to your application.properties and expect use them in your logging configuration.

Body:
Since not all properties from Spring's Environment abstraction are available in the logging system we needed to adapt them. It's pretty common for logging libraries to support references to environment variables so that's the approach that we took.

It's common to see logging configuration like this in a standard logback file:

<file>${USER_HOME}/myApp.log</file>

So it felt pretty natural to add Spring Boot specific variables in the same format.

I also personally quite like the fact that there's a difference between the keys in the application.properties file and the ones you can use in your logging configuration. I think it helps to enforce that you can just add new entries to your application.properties and expect use them in your logging configuration.


问:
Fail a Jenkins build when a Taurus-run JMeter test records a failure
I've got some tests setup to run via Taurus and kicking them off in a Jenkins stage like so:

```<code>...previous stages...

stage('Load Tests'){
  dir('./tests'){
     bat "bat _testFile.yml"
  }
}

...stages to execute if Load Tests stage succeeds
</code>```

I want to bail out of the whole build if any one of the iterations in any of my tests fails. But this setup, as well as wrapping in a try/catch don't work.

答: My fault. The fail criteria were not properly implemented. Now that they are, the above 'successfully' fails the jenkins build when the criteria are not met.</p>

Body:
I've got some tests setup to run via Taurus and kicking them off in a Jenkins stage like so:

...previous stages...

stage('Load Tests'){
  dir('./tests'){
     bat "bat _testFile.yml"
  }
}

...stages to execute if Load Tests stage succeeds

I want to bail out of the whole build if any one of the iterations in any of my tests fails. But this setup, as well as wrapping in a try/catch don't work.


问:
UIView get width/height without UIViewController
I have this:

```<code>class SheetView: UIView {

  override init(frame: CGRect) {
    super.init(frame: frame)

    RCTLogInfo("SHEET VIEW INIT'ED")
    let width = String(format:"%.3f", Double(self.frame.size.width));
    let height = String(format:"%.3f", Double(self.frame.size.height));
    RCTLogInfo("Width: " + width + ", Height: " + height);

  }

  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

}
</code>```

However width and height are always 0. Reading here Access UIView width at runtime it seems I need a viewDidLayoutSubviews but a UIView doesn't seem to have this. I have to use UIViewController to use viewDidLayoutSubviews, however I cannot change from UIView, because the place this component gets used, expects a UIView:

```<code>class SheetViewManager : RCTViewManager {

  override func view() -> UIView! {
    return SheetView();
  }

}
</code>```

Is there anyway to get height/width in just the UIView?

答:
Yes you sure can. Try this . (Swift 3.0)

```<code>override func layoutSubviews() {
   super.layoutSubviews()
  print(self.frame)
}
</code>```

Make sure you know that if your custom view's superview doesn't give your custom view a frame either by frame setting or by autolayout via storyboard or programmatically, your frame will remain at 0 width and 0 height

Body:
I have this:

class SheetView: UIView {

  override init(frame: CGRect) {
    super.init(frame: frame)

    RCTLogInfo("SHEET VIEW INIT'ED")
    let width = String(format:"%.3f", Double(self.frame.size.width));
    let height = String(format:"%.3f", Double(self.frame.size.height));
    RCTLogInfo("Width: " + width + ", Height: " + height);

  }

  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

}

However width and height are always 0. Reading here Access UIView width at runtime it seems I need a viewDidLayoutSubviews but a UIView doesn't seem to have this. I have to use UIViewController to use viewDidLayoutSubviews, however I cannot change from UIView, because the place this component gets used, expects a UIView:

class SheetViewManager : RCTViewManager {

  override func view() -> UIView! {
    return SheetView();
  }

}

Is there anyway to get height/width in just the UIView?

Body:
Yes you sure can. Try this . (Swift 3.0)

override func layoutSubviews() {
   super.layoutSubviews()
  print(self.frame)
}

Make sure you know that if your custom view's superview doesn't give your custom view a frame either by frame setting or by autolayout via storyboard or programmatically, your frame will remain at 0 width and 0 height


问:
Splice() function not working as expected
I'm trying to remove a particular element from an array in JavaScript using splice() function but I'm not able to delete the target element.

```<code>    var a = [];
    a.push("cs");
    a.push("ac");
    var curr2 = a.indexOf("ac");
    if(curr2 != -1){
        a = a.splice(curr2,1);
    }
    console.log(a);
</code>```

Expected result : ["cs"] Actual Result : ["ac"]

Can someone explain this behaviour. Thanks!

答:
You code is pulling 1 element from the array starting at index 1:

var a = [];
a.push("cs");
a.push("ac");
var curr2 = a.indexOf("ac");
console.log("curr2 = " + curr2);
// curr2 = 1;
if (curr2 != -1) {
    var b = a.slice();
    b.splice(curr2, 1);
    console.log(b);
    // ["ac"]
    var c = a.slice();
    c.splice(1, 1);
    console.log(c);
    // ["ac"]
}
   ```

Body:
I'm trying to remove a particular element from an array in JavaScript using splice() function but I'm not able to delete the target element.

    var a = [];
    a.push("cs");
    a.push("ac");
    var curr2 = a.indexOf("ac");
    if(curr2 != -1){
        a = a.splice(curr2,1);
    }
    console.log(a);

Expected result : ["cs"] Actual Result : ["ac"]

Can someone explain this behaviour. Thanks!


问:
Why is this ternary operator syntax invalid?
I am trying to write a simple ternary operator which would look like this in ruby:

0 > 1 ? alice+=1 : bob+=1

I have it written in python like this:

alice += 1 if 0 > 1 else bob += 1

This ternary operator throws an invalid syntax at bob+=1. Why is this happening, and how can I make the second operator execute along the same lines as the first?

答:
Ternary syntax is an expression; you've tried to use it as a one-line if-then-else.  You can pick the increment value, that comes from the RHS of the equation, such as:

```<code>alice += 1 if bob > 1 else 0
</code>```

... but you can't change the assignment's target like this.  If you really need to do that, you can assign a custom tuple to the LHS alice, bob, but that seems overkill.  Just use the natural if statement

```<code>if 0 > 1:
    alice += 1
else:
    bob += 1
</code>```

The final execution code will be that same, and the source stays more readable.

Body:
Ternary syntax is an expression; you've tried to use it as a one-line if-then-else.  You can pick the increment value, that comes from the RHS of the equation, such as:

alice += 1 if bob > 1 else 0

... but you can't change the assignment's target like this.  If you really need to do that, you can assign a custom tuple to the LHS alice, bob, but that seems overkill.  Just use the natural if statement

if 0 > 1:
    alice += 1
else:
    bob += 1

The final execution code will be that same, and the source stays more readable.


问:
Angular 2 different views based on Desktop or Mobile
I'm working on web site, that has slight different functionality based on version desktop/mobile.

I tried to apply it via @View, but it looks like this decorator is now deprecated.
Please, advise me best practice, how to implement this feature in Angular 2.

答:
```<code>@Component({
  selector: 'my-component',
  templateUrl: "./" + (window.screen.width > 900 ?
                     "my-component.desktop.html" :
                     "my-component.mobile.html"),
  styleUrls: ['./my-component.css']
})
</code>```