问:
Weak-linking vs "--as-needed"
I'm having trouble with using a library that contains weak-symbols and the --as-needed linker flag.

Example

(This uses the Jack library)

```<code>$ cat <<EOF >myjack.c
#include <jack/weakjack.h>
#include <jack/jack.h>
int main() {
  if (jack_client_opent)
     jack_client_open("foobar", JackNoStartServer, 0, 0);
  else return 1;
  return 0;
}
EOF

$ gcc -o myjack myjack.c  -Wl,--no-as-needed -ljack

$ ./myjack && echo "ok" || echo "K.O."
ok

$ ldd myjack | grep jack
    libjack.so.0 => /usr/lib/x86_64-linux-gnu/libjack.so.0 (0x00007f16f615f000)

$ gcc -o myjack myjack.c  -Wl,--as-needed -ljack

$ ./myjack && echo "ok" || echo "K.O."
K.O.

$ ldd myjack | grep jack

$
</code>```

(The example code was edited to not segfault any more, as the segfault is not my actually problem)

The problem

It seems that the problem is:

Jack declares all symbols as weak (if I include <jack/weakjack.h>). this is fine with me; I do want my symbols to stay weak.
esp. my program is weakly linking against jack on OSX (-weak_framework Jackmp), which requires to include <jack/weakjack.h>

When linking with --as-needed, the linker excludes any library, that does not reference at least one non-weak symbol. from the manpage:

--as-needed causes a DT_NEEDED tag to only be emitted for
             a library that at that point in the link satisfies a non-weak
             undefined symbol reference from a regular object file

some OSs (e.g. Ubuntu-16.04LTS) have --as-needed enabled by default.

Now I think that --as-needed is a nice linker feature to get rid of many really unneeded runtime dependencies.

However, I fail to see why a weak dependency is considered as no dependency at all. For me, a weak dependency is to enable optional features. I do want these features to be enabled if possible, and the decision whether this is possible should be a runtime decision. With the current behavior, it becomes a compile-time decision. (If I wanted that, I would simply disable the relevant code via some preprocessor magic).

One solution is obviously to just add --no-as-needed to the linker flags.
I don't want this: I do want to get rid of overlinking, if my distribution (or whoever compiles my binary) thinks this is the thing to do.

So I might turn on as-needed after linking in my known-weak library:

```<code>  gcc -o myjack myjack.c  -Wl,--no-as-needed -ljack -Wl,--as-needed ...
</code>```

but this feels wrong as well, as then all libraries after my forced-needed library are suddenly forced to --as-needed (which might not be what my distribution or whoever compiles my binary thinks that this is the thing to do). It also seems to be adding a lot of cruft to the build chain, just because some library happens to export weak symbols only. I do not want to manually track all libraries that do this.

I also could of course simply not include <jack/weakjack.h>. The reason why it is included is because the application also works on OSX, where I do want to optionally depend on the JACK framework (so I link with -weak_framework Jackmp), and keep my program runnable in th absence of that framework.

I really don't want to clutter my application code because of the subtle differences between linkers on various platforms. This is probably the main issue I'm having with all this: why should I add platform-specific code to my application to cater for different linker specifics - I'd probably be OK with adding feature-specific code, e.g. not including weakjack.h if the compiler has no equivalent for -weak_library or -weak_framework; but currently it seems that the closest I can get is something like #ifdef __APPLE__ which makes me shudder in this context).

So I'd really love some option to force libraries that only have weak symbols to be dylinked nevertheless.

Is there such a thing?

答:
I'm having trouble with using a library that contains weak-symbols and the --as-needed linker flag.

No, you're not.

Find out where your libjack.so is, e.g.

```<code>$ locate libjack
/usr/lib/x86_64-linux-gnu/libjack.so
/usr/lib/x86_64-linux-gnu/libjack.so.0
/usr/lib/x86_64-linux-gnu/libjack.so.0.1.0
...
</code>```

Then use nm to examine the symbol types of the JACK API in libjack.so:

```<code>$ nm -C -D /usr/lib/x86_64-linux-gnu/libjack.so | grep jack_
000000000000e7e0 T jack_acquire_real_time_scheduling
000000000000d530 T jack_activate
000000000002ccf0 T jack_client_close
000000000000e820 T jack_client_create_thread
....
....
000000000000f340 T jack_uuid_empty
000000000000f320 T jack_uuid_parse
000000000000f2e0 T jack_uuid_to_index
000000000000f330 T jack_uuid_unparse
</code>```

You'll find they are all type T ( = ordinary global symbol in text section: man nm). There are
a few weak symbols in the library:

```<code>$ nm -C -D /usr/lib/x86_64-linux-gnu/libjack.so | egrep ' (w|W) '
                 w __cxa_finalize
                 w __gmon_start__
                 w _ITM_deregisterTMCloneTable
                 w _ITM_registerTMCloneTable
                 w _Jv_RegisterClasses
0000000000025410 W std::ctype<char>::do_widen(char) const
0000000000014c10 W void std::vector<unsigned short, std::allocator<unsigned short> >::_M_emplace_back_aux<unsigned short const&>(unsigned short const&)
0000000000014b10 W std::pair<std::_Rb_tree_iterator<unsigned short>, bool> std::_Rb_tree<unsigned short, unsigned short, std::_Identity<unsigned short>, std::less<unsigned short>, std::allocator<unsigned short> >::_M_insert_unique<unsigned short>(unsigned short&&)
0000000000014ad0 W std::_Rb_tree<unsigned short, unsigned short, std::_Identity<unsigned short>, std::less<unsigned short>, std::allocator<unsigned short> >::_M_erase(std::_Rb_tree_node<unsigned short>*)
</code>```

But none of them are in the JACK API. Nothing you can do short of rebuilding your libjack.so is going to change that.
The right way to characterise your problem is:

I'm having trouble linking a library with the --as-needed linker flag to a program in which
I decided to weaken all my references to that library

The defining symbol references of the JACK API in libjack.so are all strong. You have
written a program directing the compiler to emit, in your object code, symbols that are
weak undefined references to the JACK API, and you are finding that, with as-needed linkage,
these weak references fail to compel linkage of libjack.so to provide their missing definitions.

it seems that the problem is:

jack declares all symbols as weak (if I include ).

when linking with --as-needed, the linker excludes any library, that does not reference at least one non-weak symbol.

some OSs (e.g. Ubuntu-16.04LTS) have --as-needed enabled by default.

The last two points are correct. The schism between distros that link shared libraries
as-needed by default and distros that don't goes back to Debian Wheezy, 2013,
which went over to as-needed.
Since then, the Debian-derived distro-clan has followed suit while the RedHat/Fedora
clan has stuck with the status quo ante.

The first point is confused. libjack.so, as we've noted, exports a strongly defined
JACK API that you cannot alter by writing and compiling new code.
If you include <jack/weakjack.h> in one of your source files, then you are
declaring all JACK API symbols weak, in your code, and the compiler will
give you an object file that contains only weak references to the JACK API. <jack/weakjack.h>
just defines macros that have that effect.

It would be surprising if an old and major linux library like libjack
has botched its adaptation to the as-needed schism. I suspect you've overlooked some of
the small print about jack/weakjack.h:

Detailed Description

One challenge faced by developers is that of taking advantage of new features
  introduced in new versions of [ JACK ] while still supporting older versions of
  the system. Normally, if an application uses a new feature in a library/API,
  it is unable to run on earlier versions of the library/API that do not support
  that feature. Such applications would either fail to launch or crash when an
  attempt to use the feature was made. This problem cane be solved using
  weakly-linked symbols.

...

A concrete example will help. Suppose that someone uses a version of a JACK
  client we'll call "Jill". Jill was linked against a version of JACK that contains
  a newer part of the API (say, jack_set_latency_callback()) and would like to use
  it if it is available.

When Jill is run on a system that has a suitably "new" version of JACK, this
  function will be available entirely normally. But if Jill is run on a system
  with an old version of JACK, the function isn't available.

With normal symbol linkage, this would create a startup error whenever someone
  tries to run Jill with the "old" version of JACK. However, functions added to
  JACK after version 0.116.2 are all declared to have "weak" linkage which means
  that their abscence doesn't cause an error during program startup. Instead, Jill
  can test whether or not the symbol jack_set_latency_callback is null or not.
  If its null, it means that the JACK installed on this machine is too old to
  support this function. If its not null, then Jill can use it just like any other
  function in the API. For example:

```<code>if (jack_set_latency_callback) {
    jack_set_latency_callback (jill_client, jill_latency_callback, arg);
}
</code>```

However, there are clients that may want to use this approach to parts of the
  JACK API that predate 0.116.2. For example, they might want to see if even
  really old basic parts of the API like jack_client_open() exist at runtime.

Such clients should include <jack/weakjack.h> before any other JACK header.
  This will make the entire JACK API be subject to weak linkage, so that any and
  all functions can be checked for existence at runtime. It is important to
  understand that very few clients need to do this - if you use this feature you
  should have a clear reason to do so.

[emphasis added]

This makes clear that a program, like yours, that takes the exceptional step of of including jack/weakjack.h for the purpose of weakening its references to the entire JACK API can be expected to run successfully only if it tests the definedness of every JACK API symbol before referencing it and handles the case in which it is not defined. Your program does not conform. This one does:

myjack1.c

```<code>#include <jack/weakjack.h>
#include <jack/jack.h>
#include <stdio.h>

int main() {
    if (jack_client_open) {
        jack_client_open("foobar", JackNoStartServer, 0, 0);
    } else {
        puts("`jack_client_open` is not available");
    }
    return 0;
}
</code>```

and do does this one:

myjack2.c

```<code>#include <jack/weakjack.h>
#include <jack/jack.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>

int main() {
    jack_client_t * (*jack_client_open_fp)
        (const char *, jack_options_t,jack_status_t *,...) = jack_client_open;

    if (!jack_client_open_fp) {
        void * dsoh = dlopen("libjack.so",RTLD_LAZY);
        if (!dsoh) {
            fputs("`libjack` is not available\n",stderr);
            exit(EXIT_FAILURE);
        }
        *(void**)(&jack_client_open_fp) = dlsym(dsoh,"jack_client_open");
        if (!jack_client_open_fp) {
            fputs("`jack_client_open` is not available\n",stderr);
            exit(EXIT_FAILURE);
        }
    }
    jack_client_open_fp("foobar", JackNoStartServer, 0, 0);
    exit(EXIT_SUCCESS);
}
</code>```

which sketches the usual approach to a discoverable API - apt
for a program meant to install and run on a system that
might not provide libjack at all. So you'd build it without reference to libjack
like:

```<code>gcc -o myjack2 myjack2.c -ldl
</code>```

and on Ubuntu 17.04 - which does provide libjack - it might run like:

```<code>$ ./myjack2
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for 4294967295, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for 4294967295, skipping unlock
</code>```

So the library's T&Cs are in good order with respect to as-needed linkage. That
seems to leave you in a position of being independently dissatisfied that as-needed linkage works
the way it does, rather than in a different way that would allow you to weaken
all your references to the  JACK API and still get libjack to be needed by your weak references to its
API symbols:-

I fail to see why a weak dependency is considered as no dependency at all. For me,
  a weak dependency is to enable optional features. I do want these features to be
  enabled if possible, and the decision whether this is possible should be a
  runtime decision. With the current behavior, it becomes a compile-time decision.

Your view that a weak symbol reference gives rise to a weak linkage dependency on a library
that defines the symbol does not have a footing for the GNU linker. A program
depends on a library if its linkage needs a symbol definition that the libary provides; otherwise
it doesn't depend on that libary: there aren't weak and strong degrees of dependency. (The Darwin Mach-O linker does support a cognate distinction)

There are weak symbols, as opposed to the default and usual kind,
which is strong. {weak|strong} symbol is shorthand for {weakly|strongly} referenced
symbol, since the same symbol may be referenced in multiple linker input files,
sometimes or always weakly and sometimes or always strongly.

A strong symbol must have exactly one defining reference in the linkage.

A weak symbol is such that:

The linker is not obliged to find a definition for it: it may remain undefined in the output file

The linker is not obliged to fault multiple weak definitions of the same symbol
in different input files. If exactly one defining reference within the linkage is
strong, then that strong definition is picked and all weak ones ignored. If all
defining references in the linkage are weak then the linker will pick one at random.

From the first part of that it follows that an undefined weak reference to
a symbol does not give rise to a linkage dependency at all. A definition is
not needed and the fact that a definition is not needed is the result of a
decision by the programmer (e.g. #include <jack/weak_jack.h>) or perhaps by the
compiler. It is not reasonable to expect that the linker, if directed to link
only shared libraries that are needed, should then link libraries to furnish definitions
of symbols for which you or the compiler have told it that definitions are not needed.

If the linker were to behave like that in your case, that would constitute
a linktime decision to freeze and enable an API which, by including jack/weak_jack.h,
you have indicated you wish to reserve entirely for runtime discovery.

Linking your problem program with -no-as-needed is successful as a way of
smothering the bug in the program. The bug is that by including jack/weak_jack.h
you commit yourself to runtime discovery of the whole API, but don't fulfil that
committment and instead take the availability of the API for granted. Hence the
segfault with as-needed linkage. Linking with -no-as-needed just cancels the
the effect of including jack/weak_jack.h. Including it says your program doesn't
need any of the API definitions: -no-as-needed says, whatever they are, you're getting
them all anyway.

In the light of the fact that all JACK APIs post version 0.116.2 are weakly
defined without resort to jack/weak_jack.h, I think that you simply don't
have any use for this header unless you are indeed planning a program that
will do something worthwhile on a host from which libjack is missing. If you
are planning that, then you have no alternative to runtime discovery of all
the JACK APIs you use, regardless of linkage conventions, because you can't link
libjack anyway.

If not, then just link libjack and, if you merely call jack_client_open,
your program, on any host, will dynamically link all the API definitions, whatever
they are on that host, because your reference to jack_client_open (in the
absence of <jack/weak_jack.h>) will make libjack needed, whether that
matters to the linker that did the linking or not. If you want to be compatible
accross API versions, then you need to implement runtime detection
as documented
of any API that is documented with the attribute JACK_WEAK_EXPORT
 - as opposed to JACK_OPTIONAL_WEAK_EXPORT, or JACK_OPTIONAL_WEAK_DEPRECATED_EXPORT: the latter denote fundamental APIs that
 can only be forcibly weakened via <jack/weak_jack.h>.

Title: Weak-linking vs "--as-needed"

Body:
I'm having trouble with using a library that contains weak-symbols and the --as-needed linker flag.

Example

(This uses the Jack library)

$ cat <<EOF >myjack.c
#include <jack/weakjack.h>
#include <jack/jack.h>
int main() {
  if (jack_client_opent)
     jack_client_open("foobar", JackNoStartServer, 0, 0);
  else return 1;
  return 0;
}
EOF

$ gcc -o myjack myjack.c  -Wl,--no-as-needed -ljack

$ ./myjack && echo "ok" || echo "K.O."
ok

$ ldd myjack | grep jack
    libjack.so.0 => /usr/lib/x86_64-linux-gnu/libjack.so.0 (0x00007f16f615f000)

$ gcc -o myjack myjack.c  -Wl,--as-needed -ljack

$ ./myjack && echo "ok" || echo "K.O."
K.O.

$ ldd myjack | grep jack

$

(The example code was edited to not segfault any more, as the segfault is not my actually problem)

The problem

It seems that the problem is:

Jack declares all symbols as weak (if I include <jack/weakjack.h>). this is fine with me; I do want my symbols to stay weak.
esp. my program is weakly linking against jack on OSX (-weak_framework Jackmp), which requires to include <jack/weakjack.h>

When linking with --as-needed, the linker excludes any library, that does not reference at least one non-weak symbol. from the manpage:

--as-needed causes a DT_NEEDED tag to only be emitted for
             a library that at that point in the link satisfies a non-weak
             undefined symbol reference from a regular object file

some OSs (e.g. Ubuntu-16.04LTS) have --as-needed enabled by default.

Now I think that --as-needed is a nice linker feature to get rid of many really unneeded runtime dependencies.

However, I fail to see why a weak dependency is considered as no dependency at all. For me, a weak dependency is to enable optional features. I do want these features to be enabled if possible, and the decision whether this is possible should be a runtime decision. With the current behavior, it becomes a compile-time decision. (If I wanted that, I would simply disable the relevant code via some preprocessor magic).

One solution is obviously to just add --no-as-needed to the linker flags.
I don't want this: I do want to get rid of overlinking, if my distribution (or whoever compiles my binary) thinks this is the thing to do.

So I might turn on as-needed after linking in my known-weak library:

  gcc -o myjack myjack.c  -Wl,--no-as-needed -ljack -Wl,--as-needed ...

but this feels wrong as well, as then all libraries after my forced-needed library are suddenly forced to --as-needed (which might not be what my distribution or whoever compiles my binary thinks that this is the thing to do). It also seems to be adding a lot of cruft to the build chain, just because some library happens to export weak symbols only. I do not want to manually track all libraries that do this.

I also could of course simply not include <jack/weakjack.h>. The reason why it is included is because the application also works on OSX, where I do want to optionally depend on the JACK framework (so I link with -weak_framework Jackmp), and keep my program runnable in th absence of that framework.

I really don't want to clutter my application code because of the subtle differences between linkers on various platforms. This is probably the main issue I'm having with all this: why should I add platform-specific code to my application to cater for different linker specifics - I'd probably be OK with adding feature-specific code, e.g. not including weakjack.h if the compiler has no equivalent for -weak_library or -weak_framework; but currently it seems that the closest I can get is something like #ifdef __APPLE__ which makes me shudder in this context).

So I'd really love some option to force libraries that only have weak symbols to be dylinked nevertheless.

Is there such a thing?

Body:
I'm having trouble with using a library that contains weak-symbols and the --as-needed linker flag.

No, you're not.

Find out where your libjack.so is, e.g.

$ locate libjack
/usr/lib/x86_64-linux-gnu/libjack.so
/usr/lib/x86_64-linux-gnu/libjack.so.0
/usr/lib/x86_64-linux-gnu/libjack.so.0.1.0
...

Then use nm to examine the symbol types of the JACK API in libjack.so:

$ nm -C -D /usr/lib/x86_64-linux-gnu/libjack.so | grep jack_
000000000000e7e0 T jack_acquire_real_time_scheduling
000000000000d530 T jack_activate
000000000002ccf0 T jack_client_close
000000000000e820 T jack_client_create_thread
....
....
000000000000f340 T jack_uuid_empty
000000000000f320 T jack_uuid_parse
000000000000f2e0 T jack_uuid_to_index
000000000000f330 T jack_uuid_unparse

You'll find they are all type T ( = ordinary global symbol in text section: man nm). There are
a few weak symbols in the library:

$ nm -C -D /usr/lib/x86_64-linux-gnu/libjack.so | egrep ' (w|W) '
                 w __cxa_finalize
                 w __gmon_start__
                 w _ITM_deregisterTMCloneTable
                 w _ITM_registerTMCloneTable
                 w _Jv_RegisterClasses
0000000000025410 W std::ctype<char>::do_widen(char) const
0000000000014c10 W void std::vector<unsigned short, std::allocator<unsigned short> >::_M_emplace_back_aux<unsigned short const&>(unsigned short const&)
0000000000014b10 W std::pair<std::_Rb_tree_iterator<unsigned short>, bool> std::_Rb_tree<unsigned short, unsigned short, std::_Identity<unsigned short>, std::less<unsigned short>, std::allocator<unsigned short> >::_M_insert_unique<unsigned short>(unsigned short&&)
0000000000014ad0 W std::_Rb_tree<unsigned short, unsigned short, std::_Identity<unsigned short>, std::less<unsigned short>, std::allocator<unsigned short> >::_M_erase(std::_Rb_tree_node<unsigned short>*)

But none of them are in the JACK API. Nothing you can do short of rebuilding your libjack.so is going to change that.
The right way to characterise your problem is:

I'm having trouble linking a library with the --as-needed linker flag to a program in which
I decided to weaken all my references to that library

The defining symbol references of the JACK API in libjack.so are all strong. You have
written a program directing the compiler to emit, in your object code, symbols that are
weak undefined references to the JACK API, and you are finding that, with as-needed linkage,
these weak references fail to compel linkage of libjack.so to provide their missing definitions.

it seems that the problem is:

jack declares all symbols as weak (if I include ).

when linking with --as-needed, the linker excludes any library, that does not reference at least one non-weak symbol.

some OSs (e.g. Ubuntu-16.04LTS) have --as-needed enabled by default.

The last two points are correct. The schism between distros that link shared libraries
as-needed by default and distros that don't goes back to Debian Wheezy, 2013,
which went over to as-needed.
Since then, the Debian-derived distro-clan has followed suit while the RedHat/Fedora
clan has stuck with the status quo ante.

The first point is confused. libjack.so, as we've noted, exports a strongly defined
JACK API that you cannot alter by writing and compiling new code.
If you include <jack/weakjack.h> in one of your source files, then you are
declaring all JACK API symbols weak, in your code, and the compiler will
give you an object file that contains only weak references to the JACK API. <jack/weakjack.h>
just defines macros that have that effect.

It would be surprising if an old and major linux library like libjack
has botched its adaptation to the as-needed schism. I suspect you've overlooked some of
the small print about jack/weakjack.h:

Detailed Description

One challenge faced by developers is that of taking advantage of new features
  introduced in new versions of [ JACK ] while still supporting older versions of
  the system. Normally, if an application uses a new feature in a library/API,
  it is unable to run on earlier versions of the library/API that do not support
  that feature. Such applications would either fail to launch or crash when an
  attempt to use the feature was made. This problem cane be solved using
  weakly-linked symbols.

...

A concrete example will help. Suppose that someone uses a version of a JACK
  client we'll call "Jill". Jill was linked against a version of JACK that contains
  a newer part of the API (say, jack_set_latency_callback()) and would like to use
  it if it is available.

When Jill is run on a system that has a suitably "new" version of JACK, this
  function will be available entirely normally. But if Jill is run on a system
  with an old version of JACK, the function isn't available.

With normal symbol linkage, this would create a startup error whenever someone
  tries to run Jill with the "old" version of JACK. However, functions added to
  JACK after version 0.116.2 are all declared to have "weak" linkage which means
  that their abscence doesn't cause an error during program startup. Instead, Jill
  can test whether or not the symbol jack_set_latency_callback is null or not.
  If its null, it means that the JACK installed on this machine is too old to
  support this function. If its not null, then Jill can use it just like any other
  function in the API. For example:

if (jack_set_latency_callback) {
    jack_set_latency_callback (jill_client, jill_latency_callback, arg);
}

However, there are clients that may want to use this approach to parts of the
  JACK API that predate 0.116.2. For example, they might want to see if even
  really old basic parts of the API like jack_client_open() exist at runtime.

Such clients should include <jack/weakjack.h> before any other JACK header.
  This will make the entire JACK API be subject to weak linkage, so that any and
  all functions can be checked for existence at runtime. It is important to
  understand that very few clients need to do this - if you use this feature you
  should have a clear reason to do so.

[emphasis added]

This makes clear that a program, like yours, that takes the exceptional step of of including jack/weakjack.h for the purpose of weakening its references to the entire JACK API can be expected to run successfully only if it tests the definedness of every JACK API symbol before referencing it and handles the case in which it is not defined. Your program does not conform. This one does:

myjack1.c

#include <jack/weakjack.h>
#include <jack/jack.h>
#include <stdio.h>

int main() {
    if (jack_client_open) {
        jack_client_open("foobar", JackNoStartServer, 0, 0);
    } else {
        puts("`jack_client_open` is not available");
    }
    return 0;
}

and do does this one:

myjack2.c

#include <jack/weakjack.h>
#include <jack/jack.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>

int main() {
    jack_client_t * (*jack_client_open_fp)
        (const char *, jack_options_t,jack_status_t *,...) = jack_client_open;

    if (!jack_client_open_fp) {
        void * dsoh = dlopen("libjack.so",RTLD_LAZY);
        if (!dsoh) {
            fputs("`libjack` is not available\n",stderr);
            exit(EXIT_FAILURE);
        }
        *(void**)(&jack_client_open_fp) = dlsym(dsoh,"jack_client_open");
        if (!jack_client_open_fp) {
            fputs("`jack_client_open` is not available\n",stderr);
            exit(EXIT_FAILURE);
        }
    }
    jack_client_open_fp("foobar", JackNoStartServer, 0, 0);
    exit(EXIT_SUCCESS);
}

which sketches the usual approach to a discoverable API - apt
for a program meant to install and run on a system that
might not provide libjack at all. So you'd build it without reference to libjack
like:

gcc -o myjack2 myjack2.c -ldl

and on Ubuntu 17.04 - which does provide libjack - it might run like:

$ ./myjack2
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for 4294967295, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for 4294967295, skipping unlock

So the library's T&Cs are in good order with respect to as-needed linkage. That
seems to leave you in a position of being independently dissatisfied that as-needed linkage works
the way it does, rather than in a different way that would allow you to weaken
all your references to the  JACK API and still get libjack to be needed by your weak references to its
API symbols:-

I fail to see why a weak dependency is considered as no dependency at all. For me,
  a weak dependency is to enable optional features. I do want these features to be
  enabled if possible, and the decision whether this is possible should be a
  runtime decision. With the current behavior, it becomes a compile-time decision.

Your view that a weak symbol reference gives rise to a weak linkage dependency on a library
that defines the symbol does not have a footing for the GNU linker. A program
depends on a library if its linkage needs a symbol definition that the libary provides; otherwise
it doesn't depend on that libary: there aren't weak and strong degrees of dependency. (The Darwin Mach-O linker does support a cognate distinction)

There are weak symbols, as opposed to the default and usual kind,
which is strong. {weak|strong} symbol is shorthand for {weakly|strongly} referenced
symbol, since the same symbol may be referenced in multiple linker input files,
sometimes or always weakly and sometimes or always strongly.

A strong symbol must have exactly one defining reference in the linkage.

A weak symbol is such that:

The linker is not obliged to find a definition for it: it may remain undefined in the output file

The linker is not obliged to fault multiple weak definitions of the same symbol
in different input files. If exactly one defining reference within the linkage is
strong, then that strong definition is picked and all weak ones ignored. If all
defining references in the linkage are weak then the linker will pick one at random.

From the first part of that it follows that an undefined weak reference to
a symbol does not give rise to a linkage dependency at all. A definition is
not needed and the fact that a definition is not needed is the result of a
decision by the programmer (e.g. #include <jack/weak_jack.h>) or perhaps by the
compiler. It is not reasonable to expect that the linker, if directed to link
only shared libraries that are needed, should then link libraries to furnish definitions
of symbols for which you or the compiler have told it that definitions are not needed.

If the linker were to behave like that in your case, that would constitute
a linktime decision to freeze and enable an API which, by including jack/weak_jack.h,
you have indicated you wish to reserve entirely for runtime discovery.

Linking your problem program with -no-as-needed is successful as a way of
smothering the bug in the program. The bug is that by including jack/weak_jack.h
you commit yourself to runtime discovery of the whole API, but don't fulfil that
committment and instead take the availability of the API for granted. Hence the
segfault with as-needed linkage. Linking with -no-as-needed just cancels the
the effect of including jack/weak_jack.h. Including it says your program doesn't
need any of the API definitions: -no-as-needed says, whatever they are, you're getting
them all anyway.

In the light of the fact that all JACK APIs post version 0.116.2 are weakly
defined without resort to jack/weak_jack.h, I think that you simply don't
have any use for this header unless you are indeed planning a program that
will do something worthwhile on a host from which libjack is missing. If you
are planning that, then you have no alternative to runtime discovery of all
the JACK APIs you use, regardless of linkage conventions, because you can't link
libjack anyway.

If not, then just link libjack and, if you merely call jack_client_open,
your program, on any host, will dynamically link all the API definitions, whatever
they are on that host, because your reference to jack_client_open (in the
absence of <jack/weak_jack.h>) will make libjack needed, whether that
matters to the linker that did the linking or not. If you want to be compatible
accross API versions, then you need to implement runtime detection
as documented
of any API that is documented with the attribute JACK_WEAK_EXPORT
 - as opposed to JACK_OPTIONAL_WEAK_EXPORT, or JACK_OPTIONAL_WEAK_DEPRECATED_EXPORT: the latter denote fundamental APIs that
 can only be forcibly weakened via <jack/weak_jack.h>.


来源: stackexchange

问:
Recyclerview within a Scrollview dont coordinate
I have this activity design, which shows a card view inside a scrollView, But under that cardview I need to put a listview or recyclerview. The problem is that I need the scroll of that list to coordinate with the main scroll. Osea that when lower in the content the cardview will disappear and the list of the recyclerview or listview will be crossed.

I need all the content to respond to the main scroll to show up and disappear after titlebar, Which should I change or redesign?

```<code>        <LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        app:cardElevation="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.CoordinatorLayout
            android:id="@+id/post_coordinator"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/post_bg"
                android:layout_width="match_parent"
                android:layout_height="150dp"
                android:scaleType="fitXY"
                android:src="@drawable/default_profile" />

            <android.support.design.widget.FloatingActionButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:fabSize="normal"
                android:src="@drawable/ic_hot_black"
                app:layout_anchorGravity="bottom"
                android:layout_marginLeft="16dp"
                app:layout_anchor="@id/post_bg"
                android:tint="#FFF"
                />

            <com.mikhaellopez.circularimageview.CircularImageView
                android:layout_width="100dp"
                android:layout_height="100dp"
                app:layout_anchor="@id/post_bg"
                app:layout_anchorGravity="center_horizontal|bottom"
                android:src="@drawable/profile"
                app:civ_border_color="#FFF"
                app:civ_border_width="3dp"
                />

            <android.support.design.widget.FloatingActionButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:fabSize="normal"
                android:src="@drawable/ic_hot_black"
                app:layout_anchorGravity="bottom|end"
                android:layout_marginRight="16dp"
                app:layout_anchor="@id/post_bg"
                android:tint="#FFF"
                />

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_marginTop="205dp"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                android:paddingBottom="50dp"
                android:layout_height="wrap_content">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Prepare your Anus Cersei Lanister, You Gonna Die"
                    android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                    android:textColor="#2d2d2d"
                    android:textAlignment="center"
                    />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textAlignment="center"
                    android:text="@string/emilia"
                    android:textColor="@color/secondary_text"
                    android:layout_marginTop="10dp"
                    />

            </LinearLayout>

        </android.support.design.widget.CoordinatorLayout>

    </android.support.v7.widget.CardView>

    <ListView
        android:id="@+id/post_comments"
        android:layout_marginTop="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
    </ListView>

    </LinearLayout>
</ScrollView>
</code>```

答:
I'd recommend putting the CardView inside the RecyclerView as a header, and then you don't need the top ScrollView, the card and the list items would all be scrollable within the RecyclerView.

There are many ways to add a header to a RecyclerView, see here:
Is there an addHeaderView equivalent for RecyclerView?

ContentLicense: CC BY-SA 3.0

Body:
I have this activity design, which shows a card view inside a scrollView, But under that cardview I need to put a listview or recyclerview. The problem is that I need the scroll of that list to coordinate with the main scroll. Osea that when lower in the content the cardview will disappear and the list of the recyclerview or listview will be crossed.

I need all the content to respond to the main scroll to show up and disappear after titlebar, Which should I change or redesign?

        <LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        app:cardElevation="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.CoordinatorLayout
            android:id="@+id/post_coordinator"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/post_bg"
                android:layout_width="match_parent"
                android:layout_height="150dp"
                android:scaleType="fitXY"
                android:src="@drawable/default_profile" />

            <android.support.design.widget.FloatingActionButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:fabSize="normal"
                android:src="@drawable/ic_hot_black"
                app:layout_anchorGravity="bottom"
                android:layout_marginLeft="16dp"
                app:layout_anchor="@id/post_bg"
                android:tint="#FFF"
                />

            <com.mikhaellopez.circularimageview.CircularImageView
                android:layout_width="100dp"
                android:layout_height="100dp"
                app:layout_anchor="@id/post_bg"
                app:layout_anchorGravity="center_horizontal|bottom"
                android:src="@drawable/profile"
                app:civ_border_color="#FFF"
                app:civ_border_width="3dp"
                />

            <android.support.design.widget.FloatingActionButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:fabSize="normal"
                android:src="@drawable/ic_hot_black"
                app:layout_anchorGravity="bottom|end"
                android:layout_marginRight="16dp"
                app:layout_anchor="@id/post_bg"
                android:tint="#FFF"
                />

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_marginTop="205dp"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                android:paddingBottom="50dp"
                android:layout_height="wrap_content">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Prepare your Anus Cersei Lanister, You Gonna Die"
                    android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                    android:textColor="#2d2d2d"
                    android:textAlignment="center"
                    />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textAlignment="center"
                    android:text="@string/emilia"
                    android:textColor="@color/secondary_text"
                    android:layout_marginTop="10dp"
                    />

            </LinearLayout>

        </android.support.design.widget.CoordinatorLayout>

    </android.support.v7.widget.CardView>

    <ListView
        android:id="@+id/post_comments"
        android:layout_marginTop="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
    </ListView>

    </LinearLayout>
</ScrollView>


问:
Fill super view using layoutAnchor
I have weird problem, because I can't fill whole area of super view using layout anchor

this is my code from custom UIView class:

```<code>   private func setupTableView() {
            addSubview(tableView)
            tableView.translatesAutoresizingMaskIntoConstraints = false

            let margins = layoutMarginsGuide

            let trailingAnchor = tableView.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
            let leadingAnchor = tableView.leadingAnchor.constraint(equalTo: margins.leadingAnchor)
            let topAnchor = tableView.topAnchor.constraint(equalTo: margins.topAnchor)
            let bottomAnchor = tableView.bottomAnchor.constraint(equalTo: margins.bottomAnchor)

            NSLayoutConstraint.activate([trailingAnchor, leadingAnchor, topAnchor, bottomAnchor])
}
</code>```

and in result I get weird margins on the left and right site:

答:
You are laying out your tableView relative to the margins of the layoutMarginsGuide.  If you want it to go to the edges of your UIView, then you need to use the anchors of the UIView:

```<code>private func setupTableView() {
    addSubview(tableView)
    tableView.translatesAutoresizingMaskIntoConstraints = false

    let trailingAnchor = tableView.trailingAnchor.constraint(equalTo: trailingAnchor)
    let leadingAnchor = tableView.leadingAnchor.constraint(equalTo: leadingAnchor)
    let topAnchor = tableView.topAnchor.constraint(equalTo: topAnchor)
    let bottomAnchor = tableView.bottomAnchor.constraint(equalTo: bottomAnchor)

    NSLayoutConstraint.activate([trailingAnchor, leadingAnchor, topAnchor, bottomAnchor])
}
</code>```

Title: Fill super view using layoutAnchor

Body:
I have weird problem, because I can't fill whole area of super view using layout anchor

this is my code from custom UIView class:

   private func setupTableView() {
            addSubview(tableView)
            tableView.translatesAutoresizingMaskIntoConstraints = false

            let margins = layoutMarginsGuide

            let trailingAnchor = tableView.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
            let leadingAnchor = tableView.leadingAnchor.constraint(equalTo: margins.leadingAnchor)
            let topAnchor = tableView.topAnchor.constraint(equalTo: margins.topAnchor)
            let bottomAnchor = tableView.bottomAnchor.constraint(equalTo: margins.bottomAnchor)

            NSLayoutConstraint.activate([trailingAnchor, leadingAnchor, topAnchor, bottomAnchor])
}

and in result I get weird margins on the left and right site:

Body:
You are laying out your tableView relative to the margins of the layoutMarginsGuide.  If you want it to go to the edges of your UIView, then you need to use the anchors of the UIView:

private func setupTableView() {
    addSubview(tableView)
    tableView.translatesAutoresizingMaskIntoConstraints = false

    let trailingAnchor = tableView.trailingAnchor.constraint(equalTo: trailingAnchor)
    let leadingAnchor = tableView.leadingAnchor.constraint(equalTo: leadingAnchor)
    let topAnchor = tableView.topAnchor.constraint(equalTo: topAnchor)
    let bottomAnchor = tableView.bottomAnchor.constraint(equalTo: bottomAnchor)

    NSLayoutConstraint.activate([trailingAnchor, leadingAnchor, topAnchor, bottomAnchor])
}


问:
Can't install nuget package because of "Failed to initialize the PowerShell host"
All of a sudden, I am getting this error when upgrading Nuget packages.  None of the fixes that I have come across work.  I am using Visual Studio 2013.

'Newtonsoft.Json 6.0.3' already installed.

Adding 'Newtonsoft.Json 6.0.3' to Tournaments.Notifications.

Successfully added 'Newtonsoft.Json 6.0.3' to Tournaments.Notifications.

Executing script file 'F:\My Webs\BasketballTournaments\MainBranch\packages\Newtonsoft.Json.6.0.3\tools\install.ps1'.

Failed to initialize the PowerShell host. If your PowerShell execution policy setting is set to AllSigned, open the Package Manager Console to initialize the host first.

Package Manager Console

Attempting to perform the InitializeDefaultDrives operation on the 'FileSystem' provider failed.

If I wait for the initialization to finish in the console I was able to add some packages.

答:
I had a similar problem.
I have fixed it by turning "Windows PowerShell 2.0" feature on in "Turn Windows features on or off".
Note that this feature is turned on by default, I manually turned it off few days ago.

I'm working on Windows 10 Pro 64bit and same problem was with Visual Studio 2015 and 2017 (32bit and 64bit app)

ContentLicense: CC BY-SA 4.0


问:
Change value in a 2-value column to its opposite only if a condition in another column is met
I am having problems with some strings I have to change in my data frame. My df is structured like this:

```<code>df <- data.frame(Name = c("a2b", "a1a", "b2a", "a2b", "b1b", "b2a"),
                 Side = c("L", "R", "R", "L", "R", "L"))

    Name    Side
1    a2b       L
2    a1a       R
3    b2a       R
4    a2b       L
5    b1b       R
6    b2a       L
</code>```

What I want to do is replace the value in the "Side" column with its opposite only when the "Name" value has a "2" in it (leaving the rows where the value has "1" unchanged). The "Side" column only has "R" and "L" as possible values. So this is the output that I would like to get:

```<code>    Name    Side
1    a2b       R
2    a1a       R
3    b2a       L
4    a2b       R
5    b1b       R
6    b2a       R
</code>```

I tried many solutions but I am just starting to work with R so I don't really know how "if" statements work yet. Is there a way to do it?

答:
We create an index ('i1') based on the occurence of '2' in 'Name' column, using that index, subset the 'Side' and change the values with chartr

```<code>i1 <- grep("2", df$Name)
df$Side[i1] <- chartr("LR", "RL", df$Side[i1])
df
#   Name Side
#1  a2b    R
#2  a1a    R
#3  b2a    L
#4  a2b    R
#5  b1b    R
#6  b2a    R
</code>```

Or another option is to assign using levels as the 'Side' column is factor

```<code>levels(df$Side[i1]) <- rev(levels(df$Side[i1]))
</code>```

Body:
I am having problems with some strings I have to change in my data frame. My df is structured like this:

df <- data.frame(Name = c("a2b", "a1a", "b2a", "a2b", "b1b", "b2a"),
                 Side = c("L", "R", "R", "L", "R", "L"))

    Name    Side
1    a2b       L
2    a1a       R
3    b2a       R
4    a2b       L
5    b1b       R
6    b2a       L

What I want to do is replace the value in the "Side" column with its opposite only when the "Name" value has a "2" in it (leaving the rows where the value has "1" unchanged). The "Side" column only has "R" and "L" as possible values. So this is the output that I would like to get:

    Name    Side
1    a2b       R
2    a1a       R
3    b2a       L
4    a2b       R
5    b1b       R
6    b2a       R

I tried many solutions but I am just starting to work with R so I don't really know how "if" statements work yet. Is there a way to do it?

Body:
We create an index ('i1') based on the occurence of '2' in 'Name' column, using that index, subset the 'Side' and change the values with chartr

i1 <- grep("2", df$Name)
df$Side[i1] <- chartr("LR", "RL", df$Side[i1])
df
#   Name Side
#1  a2b    R
#2  a1a    R
#3  b2a    L
#4  a2b    R
#5  b1b    R
#6  b2a    R

Or another option is to assign using levels as the 'Side' column is factor

levels(df$Side[i1]) <- rev(levels(df$Side[i1]))


问:
Firebase update in a Google Geocode async method
I am trying to write a method that updates my Firebase database after the geocode function finishes. I am writing the code in Angular2 so my Firebase database is defined in my constructor. I understand that the issue is with asynchronous functions, but I am unsure on how to go about this. Here is my code:

```<code>geocoding(callback){
var geocoder = new google.maps.Geocoder();
  geocoder.geocode({'address': this.loc}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      callback([results[0].geometry.location.lat(), results[0].geometry.location.lng()]);
    } else {
      this.lat = 0;
    }
  });
}
</code>```

and:

```<code>geocode(){
this.geocoding(function(latLng){
  this.db.object('users/' + this.auth.id).update({
    lat: latLng[0],
    lng: latLng[1]
  });
});
}
</code>```

答:
I figured out how to do it. Turns out you need to use promises, here is the working code:

```<code>geocode(address){
    return new Promise(function(resolve,reject){
      var geocoder = new google.maps.Geocoder();
        geocoder.geocode({'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            resolve(results);
          } else {
            this.lat = 0;
          }
        });
      });
  }
</code>```

and:

```<code>  this.geocode(this.loc).then(results => {
      this.db.object('users/' + this.auth.id).update({
        lat: results[0].geometry.location.lat(),
        lng: results[0].geometry.location.lng()
      });
    });
</code>```

Body:
I am trying to write a method that updates my Firebase database after the geocode function finishes. I am writing the code in Angular2 so my Firebase database is defined in my constructor. I understand that the issue is with asynchronous functions, but I am unsure on how to go about this. Here is my code:

geocoding(callback){
var geocoder = new google.maps.Geocoder();
  geocoder.geocode({'address': this.loc}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      callback([results[0].geometry.location.lat(), results[0].geometry.location.lng()]);
    } else {
      this.lat = 0;
    }
  });
}

and:

geocode(){
this.geocoding(function(latLng){
  this.db.object('users/' + this.auth.id).update({
    lat: latLng[0],
    lng: latLng[1]
  });
});
}

Body:
I figured out how to do it. Turns out you need to use promises, here is the working code:

geocode(address){
    return new Promise(function(resolve,reject){
      var geocoder = new google.maps.Geocoder();
        geocoder.geocode({'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            resolve(results);
          } else {
            this.lat = 0;
          }
        });
      });
  }

and:

  this.geocode(this.loc).then(results => {
      this.db.object('users/' + this.auth.id).update({
        lat: results[0].geometry.location.lat(),
        lng: results[0].geometry.location.lng()
      });
    });


问:
Docker compose for Nginx/PHP-FPM/Composer
I am trying to setup Docker for my application relying on an LEMP stack. To this end, I plan to use Docker compose in order to spawn one container for Nginx, one for PHP-FPM and one for MySQL.

This is all working well for the basic illustration use-cases found in the online tutorials, but when I try to apply it to my use-case, I struggle with a design issue.

To give a bit of context, my web application relies on Composer for PHP dependencies and Gulp+Bower for CSS/JS dependencies (and LESS compilation, assets minimization, etc.).

The problem is that I need to build the application (i.e. install all dependencies and run some gulp tasks) and provide the result of this build to both Nginx and PHP-FPM containers.

Here is what I have come to so far:

docker-compose.yml:

```<code>version: "3"

networks:
  database:
  server:

volumes:
  mysql-data:
  source:

services:
  php:
    build: .
    volumes:
      - source:/app:ro
    restart: always
    networks:
      - database
      - server
    depends_on:
      - mysql

  mysql:
    image: mysql:5.7
    volumes:
      - mysql-data:/var/lib/mysql
    restart: always
    networks:
      - database
    environment:
      MYSQL_ROOT_PASSWORD: rootpassword
      MYSQL_USER: test
      MYSQL_PASSWORD: test
      MYSQL_DATABASE: test

  nginx:
    image: nginx
    volumes:
      - source:/app:ro
    restart: always
    networks:
      - server
    depends_on:
      - php
</code>```

Dockerfile:

```<code>FROM php:7.1-fpm
WORKDIR /app

# Install dependencies
RUN curl -sL https://deb.nodesource.com/setup_8.x | bash -
RUN apt-get update && apt-get install -y \
    git \
    nodejs \
    zip
RUN curl -sL https://getcomposer.org/installer | php -- --install-dir /usr/bin --filename composer

# Get application dependencies
COPY composer.json ./
RUN composer install -o

COPY package.json gulpfile.js bower.json ./
RUN npm install
RUN npm run gulp
RUN npm run rev

# Copy application
COPY . ./
</code>```

However, as a Docker beginner, I am not sure it is right to rely on a volume for the build result of the application, or to have the build steps part of one of the containers running the application.

Thanks in advance for any help or advice!

Nicolas

答:
Look this for PHP7-FPM - NGINX - MySQL - ELK : https://github.com/maxpou/docker-symfony
And this for container management : https://portainer.io

My custom docker file with Node / Gulp

/php7-fpm/Dockerfile

```<code>FROM php:7.0-fpm

RUN apt-get update && apt-get install -y \
    git \
    unzip \
    wget \
    ntp \
    gnupg

RUN curl -sL https://deb.nodesource.com/setup_6.x | bash -
RUN apt-get install -y nodejs
RUN npm config set registry "http://registry.npmjs.org/"
RUN npm install -g gulp bower

# Install Composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN composer --version

# Set timezone
RUN rm /etc/localtime
RUN ln -s /usr/share/zoneinfo/Europe/Paris /etc/localtime
RUN "date"

# Type docker-php-ext-install to see available extensions
RUN docker-php-ext-install pdo_mysql

RUN apt-get update && apt-get install -y \
        libfreetype6-dev \
        libjpeg62-turbo-dev \
        libmcrypt-dev \
        libpng-dev \
    && docker-php-ext-install -j$(nproc) iconv mcrypt \
    && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \
    && docker-php-ext-install -j$(nproc) gd

# install xdebug
#RUN pecl install xdebug
#RUN docker-php-ext-enable xdebug
#RUN echo "error_reporting = E_ALL" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
#RUN echo "display_startup_errors = On" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
#RUN echo "display_errors = On" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
#RUN echo "xdebug.remote_enable=1" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
#RUN echo "xdebug.remote_connect_back=1" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
#RUN echo "xdebug.idekey=\"PHPSTORM\"" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
#RUN echo "xdebug.remote_port=9001" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini

RUN apt-get update \
    && apt-get -y install \
            libmagickwand-dev \
        --no-install-recommends \
    && pecl install imagick \
    && docker-php-ext-enable imagick \
    && rm -r /var/lib/apt/lists/*

RUN echo "file_uploads = On\n" \
         "memory_limit = 500M\n" \
         "upload_max_filesize = 500M\n" \
         "post_max_size = 500M\n" \
         "max_execution_time = 600\n" \
         > /usr/local/etc/php/conf.d/uploads.ini

RUN echo "realpath_cache_ttl = 7200\n" \
          "realpath_cache_size = 4M\n" \
         > /usr/local/etc/php/conf.d/opti-symfony.ini

RUN echo "date.timezone=Europe/Paris" \
         > /usr/local/etc/php/conf.d/time-zone.ini

RUN docker-php-ext-install opcache

WORKDIR /var/www/symfony
</code>```

If you have an error gives us ;)

Happy Docker

Body:
I am trying to setup Docker for my application relying on an LEMP stack. To this end, I plan to use Docker compose in order to spawn one container for Nginx, one for PHP-FPM and one for MySQL.

This is all working well for the basic illustration use-cases found in the online tutorials, but when I try to apply it to my use-case, I struggle with a design issue.

To give a bit of context, my web application relies on Composer for PHP dependencies and Gulp+Bower for CSS/JS dependencies (and LESS compilation, assets minimization, etc.).

The problem is that I need to build the application (i.e. install all dependencies and run some gulp tasks) and provide the result of this build to both Nginx and PHP-FPM containers.

Here is what I have come to so far:

docker-compose.yml:

version: "3"

networks:
  database:
  server:

volumes:
  mysql-data:
  source:

services:
  php:
    build: .
    volumes:
      - source:/app:ro
    restart: always
    networks:
      - database
      - server
    depends_on:
      - mysql

  mysql:
    image: mysql:5.7
    volumes:
      - mysql-data:/var/lib/mysql
    restart: always
    networks:
      - database
    environment:
      MYSQL_ROOT_PASSWORD: rootpassword
      MYSQL_USER: test
      MYSQL_PASSWORD: test
      MYSQL_DATABASE: test

  nginx:
    image: nginx
    volumes:
      - source:/app:ro
    restart: always
    networks:
      - server
    depends_on:
      - php

Dockerfile:

FROM php:7.1-fpm
WORKDIR /app

# Install dependencies
RUN curl -sL https://deb.nodesource.com/setup_8.x | bash -
RUN apt-get update && apt-get install -y \
    git \
    nodejs \
    zip
RUN curl -sL https://getcomposer.org/installer | php -- --install-dir /usr/bin --filename composer

# Get application dependencies
COPY composer.json ./
RUN composer install -o

COPY package.json gulpfile.js bower.json ./
RUN npm install
RUN npm run gulp
RUN npm run rev

# Copy application
COPY . ./

However, as a Docker beginner, I am not sure it is right to rely on a volume for the build result of the application, or to have the build steps part of one of the containers running the application.

Thanks in advance for any help or advice!

Nicolas

Body:
Look this for PHP7-FPM - NGINX - MySQL - ELK : https://github.com/maxpou/docker-symfony
And this for container management : https://portainer.io

My custom docker file with Node / Gulp

/php7-fpm/Dockerfile

FROM php:7.0-fpm

RUN apt-get update && apt-get install -y \
    git \
    unzip \
    wget \
    ntp \
    gnupg

RUN curl -sL https://deb.nodesource.com/setup_6.x | bash -
RUN apt-get install -y nodejs
RUN npm config set registry "http://registry.npmjs.org/"
RUN npm install -g gulp bower

# Install Composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN composer --version

# Set timezone
RUN rm /etc/localtime
RUN ln -s /usr/share/zoneinfo/Europe/Paris /etc/localtime
RUN "date"

# Type docker-php-ext-install to see available extensions
RUN docker-php-ext-install pdo_mysql

RUN apt-get update && apt-get install -y \
        libfreetype6-dev \
        libjpeg62-turbo-dev \
        libmcrypt-dev \
        libpng-dev \
    && docker-php-ext-install -j$(nproc) iconv mcrypt \
    && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \
    && docker-php-ext-install -j$(nproc) gd

# install xdebug
#RUN pecl install xdebug
#RUN docker-php-ext-enable xdebug
#RUN echo "error_reporting = E_ALL" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
#RUN echo "display_startup_errors = On" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
#RUN echo "display_errors = On" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
#RUN echo "xdebug.remote_enable=1" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
#RUN echo "xdebug.remote_connect_back=1" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
#RUN echo "xdebug.idekey=\"PHPSTORM\"" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
#RUN echo "xdebug.remote_port=9001" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini

RUN apt-get update \
    && apt-get -y install \
            libmagickwand-dev \
        --no-install-recommends \
    && pecl install imagick \
    && docker-php-ext-enable imagick \
    && rm -r /var/lib/apt/lists/*

RUN echo "file_uploads = On\n" \
         "memory_limit = 500M\n" \
         "upload_max_filesize = 500M\n" \
         "post_max_size = 500M\n" \
         "max_execution_time = 600\n" \
         > /usr/local/etc/php/conf.d/uploads.ini

RUN echo "realpath_cache_ttl = 7200\n" \
          "realpath_cache_size = 4M\n" \
         > /usr/local/etc/php/conf.d/opti-symfony.ini

RUN echo "date.timezone=Europe/Paris" \
         > /usr/local/etc/php/conf.d/time-zone.ini

RUN docker-php-ext-install opcache

WORKDIR /var/www/symfony

If you have an error gives us ;)

Happy Docker


问:
Is it a good idea to use the _id value of a mongodb object in the DOM?
I'm learning mongoDB (and mongoose) at the moment (on an express server). I hava a database with an array of multiple objects. (Something like this):

```<code>{texts: [{s: "a"}, {s: "b"}, {s: "c"}]}
</code>```

The objects have _id attributes. (59613f576db598107269eea7, 59613f576db598107269eea8, 59613f576db598107269eea9, 59613f576db598107269eeaa)

My plan is doing something like this (visible for the visitor):

```<code><input id="59613f576db598107269eea7" value="a" />
<input id="59613f576db598107269eea8" value="b" />
<input id="59613f576db598107269eea9" value="c" />
</code>```

What can the visitor of my page do if he knows those keys? Do they tell anything about the number of the objects in my database? Do they tell anything about the time when they were stored? ...

答:
The object id is a 12-byte internal id in a collection and exposes the following information:

4 bytes representing the seconds since epoch

3 byte machine identifier

2 byte process id

3 byte counter

This can be read on the MongoDB Manual.

This is a security risk as you are leaking this information to potential attackers in the internet.

It is better to design a primary key that gives actual meaning to the key fields as a commenter said.

In MongoDB it is possible, though not recommended, to define your own object id.

Body:
I'm learning mongoDB (and mongoose) at the moment (on an express server). I hava a database with an array of multiple objects. (Something like this):

{texts: [{s: "a"}, {s: "b"}, {s: "c"}]}

The objects have _id attributes. (59613f576db598107269eea7, 59613f576db598107269eea8, 59613f576db598107269eea9, 59613f576db598107269eeaa)

My plan is doing something like this (visible for the visitor):

<input id="59613f576db598107269eea7" value="a" />
<input id="59613f576db598107269eea8" value="b" />
<input id="59613f576db598107269eea9" value="c" />

What can the visitor of my page do if he knows those keys? Do they tell anything about the number of the objects in my database? Do they tell anything about the time when they were stored? ...


问:
How to cut corner of an image

I make this view with a swift file

```<code>import UIKit

@IBDesignable class DesignView: UIView {

@IBInspectable var CornerRadius: CGFloat = 0 {
    didSet {
        self.layer.cornerRadius = CornerRadius
    }
  }

}
</code>```

But when i set a image background the image overflow of the view like this :

I tried to apply the same swift file to my image view like this

```<code>import UIKit

@IBDesignable class DesignImageView: UIImageView {

@IBInspectable var CornerRadius: CGFloat = 0 {
    didSet {
        self.layer.cornerRadius = CornerRadius
    }
  }

}
</code>```

But nothing append so how can i cut the corner without edit my image ?

答:
Add this code out of your Class Scope

```<code>extension UIView // Almost any Kind of View inherits UIView Ex: UIImageView
{
    func setCorner(withRadius radius : CGFloat)
    {
        self.layer.cornerRadius = radius
        self.clipsToBounds = true //your view won't cross the bound
    }
}
</code>```

And use like . .

DesignImageView.setCorner(withRadius: 5)

Title: How to cut corner of an image

Body:
I make this view with a swift file

import UIKit

@IBDesignable class DesignView: UIView {

@IBInspectable var CornerRadius: CGFloat = 0 {
    didSet {
        self.layer.cornerRadius = CornerRadius
    }
  }

}

But when i set a image background the image overflow of the view like this :

I tried to apply the same swift file to my image view like this

import UIKit

@IBDesignable class DesignImageView: UIImageView {

@IBInspectable var CornerRadius: CGFloat = 0 {
    didSet {
        self.layer.cornerRadius = CornerRadius
    }
  }

}

But nothing append so how can i cut the corner without edit my image ?

Body:
Add this code out of your Class Scope

extension UIView // Almost any Kind of View inherits UIView Ex: UIImageView
{
    func setCorner(withRadius radius : CGFloat)
    {
        self.layer.cornerRadius = radius
        self.clipsToBounds = true //your view won't cross the bound
    }
}

And use like . .

DesignImageView.setCorner(withRadius: 5)


问:
Are there any operator in Haskell that fold list of actions with (>>)?
I want some operator <?> that could transform this

```<code>test arg1 >>
test arg2 >>
test arg3 >>
test arg4
</code>```

to this

```<code>test <?> [ arg1
         , arg2
         , arg3
         , arg4
         ]
</code>```

答:
You can simply use mapM_ :: Monad m => (a -> m b) -> [a] -> m () for that:

```<code>mapM_ test [arg1,arg2,arg3,arg4]
</code>```

Or if you really want to write it infix:

```<code>test `mapM_` [ arg1
             , arg2
             , arg3
             , arg4
             ]
</code>```

Body:
I want some operator <?> that could transform this

test arg1 >>
test arg2 >>
test arg3 >>
test arg4

to this

test <?> [ arg1
         , arg2
         , arg3
         , arg4
         ]

Body:
You can simply use mapM_ :: Monad m => (a -> m b) -> [a] -> m () for that:

mapM_ test [arg1,arg2,arg3,arg4]

Or if you really want to write it infix:

test `mapM_` [ arg1
             , arg2
             , arg3
             , arg4
             ]


问:
What are the primary differences between Haskell and F#?
I've searched on the Internet for comparisons between F# and Haskell but haven't found anything really definitive. What are the primary differences and why would I want to choose one over the other?</p>

答:
Haskell is a "pure" functional language, where as F# has aspects of both imperative/OO and functional languages. Haskell also has lazy evaluation, which is fairly rare amongst functional languages.

What do these things mean? A pure functional language, means there are no side effects (or changes in shared state, when a function is called) which means that you are guaranteed that if you call f(x), nothing else happens besides returning a value from the function, such as console output, database output, changes to global or static variables.. and although Haskell can have non pure functions (through monads), it must be 'explicitly' implied through declaration.

Pure functional languages and 'No side effect' programming has gained popularity recently as it lends itself well to multi core concurrency, as it is much harder to get wrong with no shared state, rather than myriad locks & semaphores.

Lazy evaluation is where a function is NOT evaluated until it is absolutely necessary required. meaning that many operation can be avoided when not necessary. Think of this in a basic C# if clause such as this:

```<code>if(IsSomethingTrue() && AnotherThingTrue())
{
    do something;
}
</code>```

If IsSomethingTrue() is false then AnotherThingTrue() method is never evaluated.

While Haskell is an amazing language, the major benefit of F# (for the time being), is that it sits on top of the CLR. This lends it self to polyglot programming. One day, you may write your web UI in ASP.net MVC, your business logic in C#, your core algorithms in F# and your unit tests in Ironruby....  All amongst the the .Net framework.

Listen to the Software Engineering radio with Simon Peyton Jones for more info on Haskell: Episode 108: Simon Peyton Jones on Functional Programming and Haskell

OwnerDisplayName: kronoz

LastEditorDisplayName: jolson

Body:
Haskell is a "pure" functional language, where as F# has aspects of both imperative/OO and functional languages. Haskell also has lazy evaluation, which is fairly rare amongst functional languages.

What do these things mean? A pure functional language, means there are no side effects (or changes in shared state, when a function is called) which means that you are guaranteed that if you call f(x), nothing else happens besides returning a value from the function, such as console output, database output, changes to global or static variables.. and although Haskell can have non pure functions (through monads), it must be 'explicitly' implied through declaration.

Pure functional languages and 'No side effect' programming has gained popularity recently as it lends itself well to multi core concurrency, as it is much harder to get wrong with no shared state, rather than myriad locks & semaphores.

Lazy evaluation is where a function is NOT evaluated until it is absolutely necessary required. meaning that many operation can be avoided when not necessary. Think of this in a basic C# if clause such as this:

if(IsSomethingTrue() && AnotherThingTrue())
{
    do something;
}

If IsSomethingTrue() is false then AnotherThingTrue() method is never evaluated.

While Haskell is an amazing language, the major benefit of F# (for the time being), is that it sits on top of the CLR. This lends it self to polyglot programming. One day, you may write your web UI in ASP.net MVC, your business logic in C#, your core algorithms in F# and your unit tests in Ironruby....  All amongst the the .Net framework.

Listen to the Software Engineering radio with Simon Peyton Jones for more info on Haskell: Episode 108: Simon Peyton Jones on Functional Programming and Haskell

OwnerDisplayName: Christi


问:
Why does Visual Studio give you Page_Load for WebForms as a default?
When creating a new WebForm, Visual Studios creates a Page_Load handler in the code behind as a default, which is cool.  So for years, I have always put code for doing things like set properties of controls in Page_Load.  Recently, I used Reflector to look at some assemblies written by Microsoft and saw that they have put the same type of logic in a method called OnLoad (which supposedly raises the load event).  So I started to wonder, where is the best place really to set the properties of controls, in OnLoad or Page_Load?  Or in a different method altogether?  And if not Page_Load, why does Studio add that to the code behind?

My final thought:  Although I know that putting logic in OnLoad works fine, I will probably stick with Page_Load for now because that's conventional.  I asked the question really to find out if I had been missing out on something new after I started seeing OnLoad come up in other people's code.  Thank you all for your thoughtful answers!

答:
Indeed, if you go back to the bad old days of ASP.Net 1.1 development, you actually see the wiring up taking place, created for you in each and every page:

```<code>    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
        InitializeComponent();
        base.OnInit(e);
    }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion
</code>```

And every now and then, I'd do something that caused VS to remove that little line in the InitializeComponent, and couldn't work out why my page stopped doing anything.

OwnerDisplayName: Barneytron

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Barneytron

Body:
Indeed, if you go back to the bad old days of ASP.Net 1.1 development, you actually see the wiring up taking place, created for you in each and every page:

    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
        InitializeComponent();
        base.OnInit(e);
    }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion

And every now and then, I'd do something that caused VS to remove that little line in the InitializeComponent, and couldn't work out why my page stopped doing anything.

OwnerDisplayName: Zhaph


问:
Python Pandas multiply based on columns and add suffix
I have two DataFrame objects which I would like to multiply based on the column names and output the new column with a suffix...

```<code>df1 = pd.DataFrame(np.random.randint(0,10, size=(5,5)), columns=list('ABCDE'))

    A   B   C   D   E
0   6   2   1   7   2
1   0   0   2   1   8
2   7   2   6   6   9
3   2   5   5   1   3
4   9   1   6   7   4

df2 = pd.DataFrame(np.random.randint(1, 10, size=(5,3)), columns=list('ABC'))

    A   B   C
0   2   1   2
1   7   5   1
2   2   1   4
3   7   8   5
4   9   2   2
</code>```

I would like the output to be listed as with columns A_x, B_x and C_x being the product of the aligning columns in df1 and df2

```<code>    A   B   C   A_x  B_x    C_x    D    E
0   6   2   1   12     2    2      7    2
1   0   0   2   0      0    2      1    8
2   7   2   6   14     2    24     6    9
3   2   5   5   14     40   25     1    3
4   9   1   6   81     2    12     7    4
</code>```

答:
You can use intersection for get same columns names and then multiple by mul, add add_suffix and last concat df1:

```<code>cols = df1.columns.intersection(df2.columns)
df = df1[cols].mul(df2[cols], axis=1).add_suffix('_x')
df = pd.concat([df1, df], axis=1)
print (df)
   A  B  C  D   E  A_x  B_x  C_x
0  6  2  1  7   2   12    2    2
1  0  0  2  1   8    0    0    2
2  7  2  6  6   9   14    2   24
3  2  5  5  1   3   14   40   25
4  9  1  6  7  42   81    2   12
</code>```

If need change order of columns:

```<code>cols = df1.columns.intersection(df2.columns)
df = df1[cols].mul(df2[cols], axis=1).add_suffix('_x')
cols1 = cols.tolist() + \
        df.columns.tolist() +  \
        df1.columns.difference(df2.columns).tolist()
df = pd.concat([df1, df], axis=1)

print (df[cols1])
   A  B  C  A_x  B_x  C_x  D   E
0  6  2  1   12    2    2  7   2
1  0  0  2    0    0    2  1   8
2  7  2  6   14    2   24  6   9
3  2  5  5   14   40   25  1   3
4  9  1  6   81    2   12  7  42
</code>```

Body:
I have two DataFrame objects which I would like to multiply based on the column names and output the new column with a suffix...

df1 = pd.DataFrame(np.random.randint(0,10, size=(5,5)), columns=list('ABCDE'))

    A   B   C   D   E
0   6   2   1   7   2
1   0   0   2   1   8
2   7   2   6   6   9
3   2   5   5   1   3
4   9   1   6   7   4

df2 = pd.DataFrame(np.random.randint(1, 10, size=(5,3)), columns=list('ABC'))

    A   B   C
0   2   1   2
1   7   5   1
2   2   1   4
3   7   8   5
4   9   2   2

I would like the output to be listed as with columns A_x, B_x and C_x being the product of the aligning columns in df1 and df2

    A   B   C   A_x  B_x    C_x    D    E
0   6   2   1   12     2    2      7    2
1   0   0   2   0      0    2      1    8
2   7   2   6   14     2    24     6    9
3   2   5   5   14     40   25     1    3
4   9   1   6   81     2    12     7    4

Body:
You can use intersection for get same columns names and then multiple by mul, add add_suffix and last concat df1:

cols = df1.columns.intersection(df2.columns)
df = df1[cols].mul(df2[cols], axis=1).add_suffix('_x')
df = pd.concat([df1, df], axis=1)
print (df)
   A  B  C  D   E  A_x  B_x  C_x
0  6  2  1  7   2   12    2    2
1  0  0  2  1   8    0    0    2
2  7  2  6  6   9   14    2   24
3  2  5  5  1   3   14   40   25
4  9  1  6  7  42   81    2   12

If need change order of columns:

cols = df1.columns.intersection(df2.columns)
df = df1[cols].mul(df2[cols], axis=1).add_suffix('_x')
cols1 = cols.tolist() + \
        df.columns.tolist() +  \
        df1.columns.difference(df2.columns).tolist()
df = pd.concat([df1, df], axis=1)

print (df[cols1])
   A  B  C  A_x  B_x  C_x  D   E
0  6  2  1   12    2    2  7   2
1  0  0  2    0    0    2  1   8
2  7  2  6   14    2   24  6   9
3  2  5  5   14   40   25  1   3
4  9  1  6   81    2   12  7  42


问:
Pulling a dynamic key value from a JSON array search result query
I use Wikipedia API to search for Wiki articles. When I click the submit button I get an Array in JSON as a result :

```<code>0 {ns: 0, title: "Help", size: 3677, wordcount: 433, snippet: "<span class=\"searchmatch\">Help</span> is any form …mmand-line shells that invokes documentations and", …}

1 {ns: 0, title: "Online help", size: 7326, wordcount: 380, snippet: "(HTML), which includes HTML <span class=\"searchmat…earchmatch\">help</span> is also provided via live", …}

2 {ns: 0, title: "Help desk", size: 9491, wordcount: 1296, snippet: "A <span class=\"searchmatch\">help</span> desk is a …ated to a company's or institution's products and", …}

...
</code>```

I need to pull the value of the title and use it inside the HTML in a results list and at the same time put it inside the url so the user can click on a result and go to the corresponding page. (url:http://../[title])

The array is located in data.query.search

Since the results are dynamic I would probably need some kind of a for loop that will iterate through this array no matter how many results there are. I have tried with this for loop but it doesn't work.

```<code>console.log(data.query.search); //shows array in console
          data.query.search =""; //the location of JSON array
 for (i = 0; i < data.query.search["results"].length; i++) {
  data.query.search["results"][i]["title"];
  console.log("results");
}
</code>```

I suspect that I am not targeting the array elements,keys and values properly. I am grateful for any suggestion. Cheers.

答:
Your code has some weird things. First, you are "clearing" data.query.search in the second line. Second, in the loop, you don't assign the title of each result to any variable and just print "results". Third, you said the array is in data.query.search, but you try to access a property results. You can try the following:

var data = { query: { search: [
  {ns: 0, title: "Help", size: 3677, wordcount: 433},
  {ns: 0, title: "Online help", size: 7326, wordcount: 380},
  {ns: 0, title: "Help desk", size: 9491, wordcount: 1296}
]}};

for (var i = 0; i < data.query.search.length; i++) {
  var result = data.query.search[i];
  var title = result.title;

  console.log(title);
}```

Body:
I use Wikipedia API to search for Wiki articles. When I click the submit button I get an Array in JSON as a result :

0 {ns: 0, title: "Help", size: 3677, wordcount: 433, snippet: "Help is any form …mmand-line shells that invokes documentations and", …}

1 {ns: 0, title: "Online help", size: 7326, wordcount: 380, snippet: "(HTML), which includes HTML help is also provided via live", …}

2 {ns: 0, title: "Help desk", size: 9491, wordcount: 1296, snippet: "A help desk is a …ated to a company's or institution's products and", …}

...

I need to pull the value of the title and use it inside the HTML in a results list and at the same time put it inside the url so the user can click on a result and go to the corresponding page. (url:http://../[title])

The array is located in data.query.search

Since the results are dynamic I would probably need some kind of a for loop that will iterate through this array no matter how many results there are. I have tried with this for loop but it doesn't work.

console.log(data.query.search); //shows array in console
          data.query.search =""; //the location of JSON array
 for (i = 0; i < data.query.search["results"].length; i++) {
  data.query.search["results"][i]["title"];
  console.log("results");
}

I suspect that I am not targeting the array elements,keys and values properly. I am grateful for any suggestion. Cheers.


问:
Cannot understand the Output of this Code
```<code>void abc(int n) {
    if (n <= 10) {
        abc(++n);
        printf("%d\n", n);
    }
}

void main() {
    int m = 5;
    abc(m);
}
</code>```

The output shows:

```<code>11
10
9
8
7
6
</code>```

I cannot understand the output. Please explain. I am a novice code lover.

答:
```<code>void abc(int n)
{
   if (n<=10)
   {
      abc(++n);
      printf("%d\n",n);
   }
}

void main()
{
   int m=5;
   abc(m);
}
</code>```

When main is called, a variable m is initialized to 5.

abc is then called and the 5 is passed to it.

When abc first executes, n = 5. If n is less than or greater than 10, abc is called again but this time with 1+n. Therefore, since 5 is less than 10, abc is called and 6 is passed to it.

Body:
void abc(int n) {
    if (n <= 10) {
        abc(++n);
        printf("%d\n", n);
    }
}

void main() {
    int m = 5;
    abc(m);
}

The output shows:

11
10
9
8
7
6

I cannot understand the output. Please explain. I am a novice code lover.

Body:
void abc(int n)
{
   if (n<=10)
   {
      abc(++n);
      printf("%d\n",n);
   }
}

void main()
{
   int m=5;
   abc(m);
}

When main is called, a variable m is initialized to 5.

abc is then called and the 5 is passed to it.

When abc first executes, n = 5. If n is less than or greater than 10, abc is called again but this time with 1+n. Therefore, since 5 is less than 10, abc is called and 6 is passed to it.


答:
To make the function clear exclude the recursive code of it itself the following way

```<code>void abc(int n)
{
if (n<=10){
    ++n;
    printf("%d\n",n);
    }
}
</code>```

So if the function is called with argument equal to 5 then the function outputs 6. If the function is called with argument equal to 10 then the function outputs 11 due to the expression statement

```<code>++n;
</code>```

Now just add the recursive call the following way

```<code>void abc(int n)
{
if (n<=10)
    ++n;
    {abc( n);
    printf("%d\n",n);
    }
}
</code>```

and you will get the described result.

Take into account that according to the C Standard the function main shall be declared like

```<code>int main( void )
</code>```

Title: Cannot understand the Output of this Code

Body:
To make the function clear exclude the recursive code of it itself the following way

void abc(int n)
{
if (n<=10){
    ++n;
    printf("%d\n",n);
    }
}

So if the function is called with argument equal to 5 then the function outputs 6. If the function is called with argument equal to 10 then the function outputs 11 due to the expression statement

++n;

Now just add the recursive call the following way

void abc(int n)
{
if (n<=10)
    ++n;
    {abc( n);
    printf("%d\n",n);
    }
}

and you will get the described result.

Take into account that according to the C Standard the function main shall be declared like

int main( void )


问:
How to use .split() while setting an argument to skip a specific tag
I am trying to split all text group from a readme file, this is to get all the individual words, however words written inside the markdown syntax for embeding a URL.. []() are showing unwanted results.

So, if I use .split() on this sentence

The site uses the [stackoverlow api](https://api.stackexchange.com/docs)  to fetch all existing tags and create a

.split() will treat [stackoverflow api](.. as two words and yield this result

```<code>>>> r = "The site uses the [stackoverlow api](https://api.stackexchange.com/docs)  to fetch"
>>> print(r.split())
['The', 'site', 'uses', 'the', '[stackoverlow', 'api](https://api.stackexchange.com/docs)', 'to', 'fetch']
>>>
</code>```

Since this is unintended, is there way to ignore anything inside []() or treat it as a single word?

答:
if i understand correctly ,a simple solution would be to replace all instances of "[", "]" and then split:

```<code>st = "The site uses the [stackoverlow api](https://api.stackexchange.com/docs) to fetch all existing tags and create a"

st.replace("["," ").replace("]", " ").split()
</code>```

this will give you :

```<code>['The', 'site', 'uses', 'the', 'stackoverlow', 'api', '(https://api.stackexchange.com/docs)', 'to', 'fetch', 'all', 'existing', 'tags', 'and', 'create', 'a']
</code>```

of course you can also replace "(", ")" or any other manipulation to split the url as well.

Body:
I am trying to split all text group from a readme file, this is to get all the individual words, however words written inside the markdown syntax for embeding a URL.. []() are showing unwanted results.

So, if I use .split() on this sentence

The site uses the [stackoverlow api](https://api.stackexchange.com/docs)  to fetch all existing tags and create a

.split() will treat [stackoverflow api](.. as two words and yield this result

>>> r = "The site uses the [stackoverlow api](https://api.stackexchange.com/docs)  to fetch"
>>> print(r.split())
['The', 'site', 'uses', 'the', '[stackoverlow', 'api](https://api.stackexchange.com/docs)', 'to', 'fetch']
>>>

Since this is unintended, is there way to ignore anything inside []() or treat it as a single word?

Body:
if i understand correctly ,a simple solution would be to replace all instances of "[", "]" and then split:

st = "The site uses the [stackoverlow api](https://api.stackexchange.com/docs) to fetch all existing tags and create a"

st.replace("["," ").replace("]", " ").split()

this will give you :

['The', 'site', 'uses', 'the', 'stackoverlow', 'api', '(https://api.stackexchange.com/docs)', 'to', 'fetch', 'all', 'existing', 'tags', 'and', 'create', 'a']

of course you can also replace "(", ")" or any other manipulation to split the url as well.


问:
How to split a String with null until the end in Java?
I have to stringify a simple Double array in order to put it in my database (in this case this is the best way I found)

I'm using StringUtils.join() to stringify but I have a problem with the splitting because there is a lot of null values at the end of my array (which is expected).

Here is some code example :

```<code>final String NEEDLE = "_";
Double[] dblArray = new Double[]{2.0, 2.0, 2.0, 0.0, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null};
String joined = StringUtils.join(dblArray, NEEDLE);
String[] split = joined.split(NEEDLE); //I will then cast the string to double

Log.d("MyApp", "joined=" + joined);
Log.d("MyApp", "1 - split=" + Arrays.toString(split));
Log.d("MyApp", "2 - StringUtils.split=" + Arrays.toString(StringUtils.split(joined, NEEDLE)));
Log.d("MyApp", "3 - split+xxx=" + Arrays.toString((joined+"xxx").split(NEEDLE)));
Log.d("MyApp", "4 - StringUtils.split+xxx=" + Arrays.toString(StringUtils.split(joined+"xxx", NEEDLE)));
</code>```

And here ARE the results :

D: joined=2.0_2.0_2.0_0.0_______________________________________________________

  D: 1 - split=[2.0, 2.0, 2.0, 0.0]

  D: 2 - StringUtils.split=[2.0, 2.0, 2.0, 0.0]

  D: 3 - split+xxx=[2.0, 2.0, 2.0, 0.0, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , xxx]

  D: 4 - StringUtils.split+xxx=[2.0, 2.0, 2.0, 0.0, xxx]

The expected behaviour is the #3, but as you can see, for my split result to contain the null values, I have to add something at the end of the string, which is highly unexpected.

Is there a clean way to split it with null values until the end but without adding dummy value in the end ?

答:
You're calling split(NEEDLE):

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

You should call split(NEEDLE, -1):

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

Body:
I have to stringify a simple Double array in order to put it in my database (in this case this is the best way I found)

I'm using StringUtils.join() to stringify but I have a problem with the splitting because there is a lot of null values at the end of my array (which is expected).

Here is some code example :

final String NEEDLE = "_";
Double[] dblArray = new Double[]{2.0, 2.0, 2.0, 0.0, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null};
String joined = StringUtils.join(dblArray, NEEDLE);
String[] split = joined.split(NEEDLE); //I will then cast the string to double

Log.d("MyApp", "joined=" + joined);
Log.d("MyApp", "1 - split=" + Arrays.toString(split));
Log.d("MyApp", "2 - StringUtils.split=" + Arrays.toString(StringUtils.split(joined, NEEDLE)));
Log.d("MyApp", "3 - split+xxx=" + Arrays.toString((joined+"xxx").split(NEEDLE)));
Log.d("MyApp", "4 - StringUtils.split+xxx=" + Arrays.toString(StringUtils.split(joined+"xxx", NEEDLE)));

And here ARE the results :

D: joined=2.0_2.0_2.0_0.0_______________________________________________________

  D: 1 - split=[2.0, 2.0, 2.0, 0.0]

  D: 2 - StringUtils.split=[2.0, 2.0, 2.0, 0.0]

  D: 3 - split+xxx=[2.0, 2.0, 2.0, 0.0, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , xxx]

  D: 4 - StringUtils.split+xxx=[2.0, 2.0, 2.0, 0.0, xxx]

The expected behaviour is the #3, but as you can see, for my split result to contain the null values, I have to add something at the end of the string, which is highly unexpected.

Is there a clean way to split it with null values until the end but without adding dummy value in the end ?


问:
Delphi how to do SearchReplace in a component property in all the files of a project?
I need to do a SearchReplace in all my forms (all the dfm) for changing all the occurences of ':' to ';' in all the TQuery.Strings (of type TStrings).

How can I accomplish this? I'd like to do it at desing time: I would like that my dfm contain ";", not do a runtime substitution.

答:
Assuming you're storing all your .dfm files in text format, just use any of the simple grep tools available.

If you're not sure if you're storing your .dfm files in text, right click on a form and see if the checkbox below set.

As I recall, there are other good reasons to store .dfm's as text. And, there's a command line tool to convert all .dfm's in a directory tree to text. See this thread: link text


问:
Directive callback executed after ng-if removes directive from scope

I have an angular directive on my page, within ng-if.

I have a service which exposes a function that receives a callback as a parameter. Let's call this function functionX.

When the ng-if expression evaluates to true, my directive invokes functionX, and sends it a callback to execute at some point in the future.

Now, the problem is: If my ng-if expressions now changes to false, the service still executes the callback I sent it...

Any ideas how to deal with this issue?

答:
I've figured out what was causing the callback to execute after the directive's scope was destroyed by ng-if evaluating to false:

The service was registering the directive scope to a PubSub publish event, and not de-registering it once the directive scope was destroyed. Which means that there was a reference to the destroyed scope hanging on out there...

So in summary: Always make sure to clean up after yourself when registering for PubSub events!


问:
Storing an unknown function from another class to execute later on itself
I have a class that parameters there can change, i'm creating a class that sorts groups of the first class, by the given parameter it needed to be sorted by.

```<code>class class1
{
   private int p1;
   private int p2;
 //and etc depending on the need of it
}
</code>```

for each parameter there is a get function.

i tried to do the following:

```<code>class class2<T>
{
   private Func<T> getValue;
   public class2(Func<T> getValue)
   {
       this.getValue = getValue;
   }

 public void Add(class1 cs)
 {
     //here is where i want to execute getValue on cs itself to compare them to one another.
 }
}
</code>```

I have tried doing the following in the main class:

```<code>  class Program
    {
        static void Main(string[] args)
        {
            class1 c1 = new class1(1, 2);
            class2<int> c2 = new class2<int>(c1.getp1)
        }
    }
</code>```

but it only stores the the function for c1, and i cant execute it as i need it.

Is there a way to do it?
Thanks ahead for the help and sorry for the dumb explanation.

答:
Instead of Func<T>, use Func<class1,T> (msdn docs).

```<code>class class2<T>
{
   private Func<class1, T> getValue;
   public class2(Func<class1, T> getValue)
   {
       this.getValue = getValue;
   }

   public void Add(class1 cs)
   {
       // Something like this
       var val = this.getValue(class1);
       // do something with val
   }
}

class Program
{
    static void Main(string[] args)
    {
        class1 c1 = new class1(1, 2);
        // create the Func as a lambda and pass to the constructor.
        class2<int> c2 = new class2<int>(c => c.getp1)
    }
}
</code>```

I haven't ran/compiled this.

Body:
I have a class that parameters there can change, i'm creating a class that sorts groups of the first class, by the given parameter it needed to be sorted by.

class class1
{
   private int p1;
   private int p2;
 //and etc depending on the need of it
}

for each parameter there is a get function.

i tried to do the following:

class class2<T>
{
   private Func<T> getValue;
   public class2(Func<T> getValue)
   {
       this.getValue = getValue;
   }

 public void Add(class1 cs)
 {
     //here is where i want to execute getValue on cs itself to compare them to one another.
 }
}

I have tried doing the following in the main class:

  class Program
    {
        static void Main(string[] args)
        {
            class1 c1 = new class1(1, 2);
            class2<int> c2 = new class2<int>(c1.getp1)
        }
    }

but it only stores the the function for c1, and i cant execute it as i need it.

Is there a way to do it?
Thanks ahead for the help and sorry for the dumb explanation.

Body:
Instead of Func<T>, use Func<class1,T> (msdn docs).

class class2<T>
{
   private Func<class1, T> getValue;
   public class2(Func<class1, T> getValue)
   {
       this.getValue = getValue;
   }

   public void Add(class1 cs)
   {
       // Something like this
       var val = this.getValue(class1);
       // do something with val
   }
}

class Program
{
    static void Main(string[] args)
    {
        class1 c1 = new class1(1, 2);
        // create the Func as a lambda and pass to the constructor.
        class2<int> c2 = new class2<int>(c => c.getp1)
    }
}

I haven't ran/compiled this.