问:
How does the linker handle identical template instantiations across translation units?
Suppose I have two translation-units:

foo.cpp

```<code>void foo() {
  auto v = std::vector<int>();
}
</code>```

bar.cpp

```<code>void bar() {
  auto v = std::vector<int>();
}
</code>```

When I compile these translation-units, each will instantiate std::vector<int>.

My question is: how does this work at the linking stage?

Do both instantiations have different mangled names?

Does the linker remove them as duplicates?

答:
C++ requires that an inline function definition
be present in a translation unit that references the function. Template member
functions are implicitly inline, but also by default are instantiated with external
linkage. Hence the duplication of definitions that will be visible to the linker when
the same template is instantiated with the same template arguments in different
translation units. How the linker copes with this duplication is your question.

Your C++ compiler is subject to the C++ Standard, but your linker is not subject
to any codified standard as to how it shall link C++: it is a law unto itself,
rooted in computing history and indifferent to the source language of the object
code it links. Your compiler has to work with what a target linker
can and will do so that you can successfully link your programs and see them do
what you expect. So I'll show you how the GCC C++ compiler interworks with
the GNU linker to handle identical template instantiations in different translation units.

This demonstration exploits the fact that while the C++ Standard requires -
by the One Definition Rule
- that the instantiations in different translation units of the same template with
the same template arguments shall have the same definition, the compiler -
of course - cannot enforce any requirement like that on relationships between different
translation units. It has to trust us.

So we'll instantiate the same template with the same parameters in different
translation units, but we'll cheat by injecting a macro-controlled difference into
the implementations in different translation units that will subsequently show
us which definition the linker picks.

If you suspect this cheat invalidates the demonstration, remember: the compiler
cannot know whether the ODR is ever honoured across different translation units,
so it cannot behave differently on that account, and there's no such thing
as "cheating" the linker. Anyhow, the demo will demonstrate that it is valid.

First we have our cheat template header:

thing.hpp

```<code>#ifndef THING_HPP
#define THING_HPP
#ifndef ID
#error ID undefined
#endif

template<typename T>
struct thing
{
    T id() const {
        return T{ID};
    }
};

#endif
</code>```

The value of the macro ID is the tracer value we can inject.

Next a source file:

foo.cpp

```<code>#define ID 0xf00
#include "thing.hpp"

unsigned foo()
{
    thing<unsigned> t;
    return t.id();
}
</code>```

It defines function foo, in which thing<unsigned> is
instantiated to define t, and t.id() is returned. By being a function with
external linkage that instantiates thing<unsigned>, foo serves the purposes
of:-

obliging the compiler to do that instantiating at all

exposing the instantiation in linkage so we can then probe what the
linker does with it.

Another source file:

boo.cpp

```<code>#define ID 0xb00
#include "thing.hpp"

unsigned boo()
{
    thing<unsigned> t;
    return t.id();
}
</code>```

which is just like foo.cpp except that it defines boo in place of foo and
sets ID = 0xb00.

And lastly a program source:

main.cpp

```<code>#include <iostream>

extern unsigned foo();
extern unsigned boo();

int main()
{
    std::cout << std::hex
    << '\n' << foo()
    << '\n' << boo()
    << std::endl;
    return 0;
}
</code>```

This program will print, as hex, the return value of foo() - which our cheat should make
= f00 - then the return value of boo() - which our cheat should make = b00.

Now we'll compile foo.cpp, and we'll do it with -save-temps because we want
a look at the assembly:

```<code>g++ -c -save-temps foo.cpp
</code>```

This writes the assembly in foo.s and the portion of interest there is
the definition of thing<unsigned int>::id() const (mangled = _ZNK5thingIjE2idEv):

```<code>    .section    .text._ZNK5thingIjE2idEv,"axG",@progbits,_ZNK5thingIjE2idEv,comdat
    .align 2
    .weak   _ZNK5thingIjE2idEv
    .type   _ZNK5thingIjE2idEv, @function
_ZNK5thingIjE2idEv:
.LFB2:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    movq    %rdi, -8(%rbp)
    movl    $3840, %eax
    popq    %rbp
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc
</code>```

Three of the directives at the top are significant:

```<code>.section    .text._ZNK5thingIjE2idEv,"axG",@progbits,_ZNK5thingIjE2idEv,comdat
</code>```

This one puts the function definition in a linkage section of its own called
.text._ZNK5thingIjE2idEv that will be output, if it's needed, merged into the
.text (i.e. code) section of program in which the object file is linked. A
linkage section like that, i.e. .text.<function_name> is called a function-section.
It's a code section that contains only the definition of function <function_name>.

The directive:

```<code>.weak   _ZNK5thingIjE2idEv
</code>```

is crucial. It classifies thing<unsigned int>::id() const as a weak symbol.
The GNU linker recognises strong symbols and weak symbols. For a strong symbol, the
linker will accept only one definition in the linkage. If there are more, it will give a multiple
-definition error. But for a weak symbol, it will tolerate any number of definitions,
and pick one. If a weakly defined symbol also has (just one) strong definition in the linkage then the
strong definition will be picked. If a symbol has multiple weak definitions and no strong definition,
then the linker can pick any one of the weak definitions, arbitrarily.

The directive:

```<code>.type   _ZNK5thingIjE2idEv, @function
</code>```

classifies thing<unsigned int>::id() as referring to a function - not data.

Then in the body of the definition, the code is assembled at the address
labelled by the weak global symbol _ZNK5thingIjE2idEv, the same one locally
labelled .LFB2. The code returns 3840 ( = 0xf00).

Next we'll compile boo.cpp the same way:

```<code>g++ -c -save-temps boo.cpp
</code>```

and look again at how thing<unsigned int>::id() is defined in boo.s

```<code>#define ID 0xf00
#include "thing.hpp"

unsigned foo()
{
    thing<unsigned> t;
    return t.id();
}
</code>```0

It's identical, except for our cheat: this definition returns 2816 ( = 0xb00).

While we're here, let's note something that might or might not go without saying:
Once we're in assembly (or object code), classes have evaporated. Here,
we're down to: -

data

code

symbols, which can label data or label code.

So nothing here specifically represents the instantiation of thing<T> for
T = unsigned. All that's left of thing<unsigned> in this instance is
the definition of _ZNK5thingIjE2idEv a.k.a thing<unsigned int>::id() const.

So now we know what the compiler does about instantiating thing<unsigned>
in a given translation unit. If it is obliged to instantiate a thing<unsigned>
member function, then it assembles the definition of the instantiated member
function at a weakly global symbol that identifies the member function, and it
puts this definition into its own function-section.

Now let's see what the linker does.

First we'll compile the main source file.

```<code>#define ID 0xf00
#include "thing.hpp"

unsigned foo()
{
    thing<unsigned> t;
    return t.id();
}
</code>```1

Then link all the object files, requesting a diagnostic trace on _ZNK5thingIjE2idEv,
and a linkage map file:

```<code>#define ID 0xf00
#include "thing.hpp"

unsigned foo()
{
    thing<unsigned> t;
    return t.id();
}
</code>```2

So the linker tells us that the program gets the definition of _ZNK5thingIjE2idEv from
foo.o and calls it in boo.o.

Running the program shows it's telling the truth:

```<code>./prog

f00
f00
</code>```

Both foo() and boo() are returning the value of thing<unsigned>().id()
as instantiated in foo.cpp.

What has become of the other definition of thing<unsigned int>::id() const
in boo.o? The map file shows us:

prog.map

```<code>...
Discarded input sections
 ...
 ...
 .text._ZNK5thingIjE2idEv
                0x0000000000000000        0xf boo.o
 ...
 ...
</code>```

The linker chucked away the function-section in boo.o that
contained the other definition.

Let's now link prog again, but this time with foo.o and boo.o in the
reverse order:

```<code>$ g++ -o prog main.o boo.o foo.o -Wl,--trace-symbol='_ZNK5thingIjE2idEv',-M=prog.map
boo.o: definition of _ZNK5thingIjE2idEv
foo.o: reference to _ZNK5thingIjE2idEv
</code>```

This time, the program gets the definition of _ZNK5thingIjE2idEv from boo.o and
calls it in foo.o. The program confirms that:

```<code>$ ./prog

b00
b00
</code>```

And the map file shows:

```<code>...
Discarded input sections
 ...
 ...
 .text._ZNK5thingIjE2idEv
                0x0000000000000000        0xf foo.o
 ...
 ...
</code>```

that the linker chucked away the function-section .text._ZNK5thingIjE2idEv
from foo.o.

That completes the picture.

The compiler emits, in each translation unit, a weak definition of
each instantiated template member in its own function section. The linker
then just picks the first of those weak definitions that it encounters
in the linkage sequence when it needs to resolve a reference to the weak
symbol. Because each of the weak symbols addresses a definition, any
one one of them - in particular, the first one - can be used to resolve all references
to the symbol in the linkage, and the rest of the weak definitions are
expendable. The surplus weak definitions must be ignored, because
the linker can only link one definition of a given symbol. And the surplus
weak definitions can be discarded by the linker, with no collateral
damage to the program, because the compiler placed each one in a linkage section all by itself.

By picking the first weak definition it sees, the linker is effectively
picking at random, because the order in which object files are linked is arbitrary.
But this is fine, as long as we obey the ODR accross multiple translation units,
because it we do, then all of the weak definitions are indeed identical. The usual practice of #include-ing a class template everywhere from a header file (and not macro-injecting any local edits when we do so) is a fairly robust way of obeying the rule.

Body:
Suppose I have two translation-units:

foo.cpp

void foo() {
  auto v = std::vector<int>();
}

bar.cpp

void bar() {
  auto v = std::vector<int>();
}

When I compile these translation-units, each will instantiate std::vector<int>.

My question is: how does this work at the linking stage?

Do both instantiations have different mangled names?

Does the linker remove them as duplicates?

Body:
C++ requires that an inline function definition
be present in a translation unit that references the function. Template member
functions are implicitly inline, but also by default are instantiated with external
linkage. Hence the duplication of definitions that will be visible to the linker when
the same template is instantiated with the same template arguments in different
translation units. How the linker copes with this duplication is your question.

Your C++ compiler is subject to the C++ Standard, but your linker is not subject
to any codified standard as to how it shall link C++: it is a law unto itself,
rooted in computing history and indifferent to the source language of the object
code it links. Your compiler has to work with what a target linker
can and will do so that you can successfully link your programs and see them do
what you expect. So I'll show you how the GCC C++ compiler interworks with
the GNU linker to handle identical template instantiations in different translation units.

This demonstration exploits the fact that while the C++ Standard requires -
by the One Definition Rule
- that the instantiations in different translation units of the same template with
the same template arguments shall have the same definition, the compiler -
of course - cannot enforce any requirement like that on relationships between different
translation units. It has to trust us.

So we'll instantiate the same template with the same parameters in different
translation units, but we'll cheat by injecting a macro-controlled difference into
the implementations in different translation units that will subsequently show
us which definition the linker picks.

If you suspect this cheat invalidates the demonstration, remember: the compiler
cannot know whether the ODR is ever honoured across different translation units,
so it cannot behave differently on that account, and there's no such thing
as "cheating" the linker. Anyhow, the demo will demonstrate that it is valid.

First we have our cheat template header:

thing.hpp

#ifndef THING_HPP
#define THING_HPP
#ifndef ID
#error ID undefined
#endif

template<typename T>
struct thing
{
    T id() const {
        return T{ID};
    }
};

#endif

The value of the macro ID is the tracer value we can inject.

Next a source file:

foo.cpp

#define ID 0xf00
#include "thing.hpp"

unsigned foo()
{
    thing<unsigned> t;
    return t.id();
}

It defines function foo, in which thing<unsigned> is
instantiated to define t, and t.id() is returned. By being a function with
external linkage that instantiates thing<unsigned>, foo serves the purposes
of:-

obliging the compiler to do that instantiating at all

exposing the instantiation in linkage so we can then probe what the
linker does with it.

Another source file:

boo.cpp

#define ID 0xb00
#include "thing.hpp"

unsigned boo()
{
    thing<unsigned> t;
    return t.id();
}

which is just like foo.cpp except that it defines boo in place of foo and
sets ID = 0xb00.

And lastly a program source:

main.cpp

#include <iostream>

extern unsigned foo();
extern unsigned boo();

int main()
{
    std::cout << std::hex
    << '\n' << foo()
    << '\n' << boo()
    << std::endl;
    return 0;
}

This program will print, as hex, the return value of foo() - which our cheat should make
= f00 - then the return value of boo() - which our cheat should make = b00.

Now we'll compile foo.cpp, and we'll do it with -save-temps because we want
a look at the assembly:

g++ -c -save-temps foo.cpp

This writes the assembly in foo.s and the portion of interest there is
the definition of thing<unsigned int>::id() const (mangled = _ZNK5thingIjE2idEv):

    .section    .text._ZNK5thingIjE2idEv,"axG",@progbits,_ZNK5thingIjE2idEv,comdat
    .align 2
    .weak   _ZNK5thingIjE2idEv
    .type   _ZNK5thingIjE2idEv, @function
_ZNK5thingIjE2idEv:
.LFB2:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    movq    %rdi, -8(%rbp)
    movl    $3840, %eax
    popq    %rbp
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc

Three of the directives at the top are significant:

.section    .text._ZNK5thingIjE2idEv,"axG",@progbits,_ZNK5thingIjE2idEv,comdat

This one puts the function definition in a linkage section of its own called
.text._ZNK5thingIjE2idEv that will be output, if it's needed, merged into the
.text (i.e. code) section of program in which the object file is linked. A
linkage section like that, i.e. .text.<function_name> is called a function-section.
It's a code section that contains only the definition of function <function_name>.

The directive:

.weak   _ZNK5thingIjE2idEv

is crucial. It classifies thing<unsigned int>::id() const as a weak symbol.
The GNU linker recognises strong symbols and weak symbols. For a strong symbol, the
linker will accept only one definition in the linkage. If there are more, it will give a multiple
-definition error. But for a weak symbol, it will tolerate any number of definitions,
and pick one. If a weakly defined symbol also has (just one) strong definition in the linkage then the
strong definition will be picked. If a symbol has multiple weak definitions and no strong definition,
then the linker can pick any one of the weak definitions, arbitrarily.

The directive:

.type   _ZNK5thingIjE2idEv, @function

classifies thing<unsigned int>::id() as referring to a function - not data.

Then in the body of the definition, the code is assembled at the address
labelled by the weak global symbol _ZNK5thingIjE2idEv, the same one locally
labelled .LFB2. The code returns 3840 ( = 0xf00).

Next we'll compile boo.cpp the same way:

g++ -c -save-temps boo.cpp

and look again at how thing<unsigned int>::id() is defined in boo.s

    .section    .text._ZNK5thingIjE2idEv,"axG",@progbits,_ZNK5thingIjE2idEv,comdat
    .align 2
    .weak   _ZNK5thingIjE2idEv
    .type   _ZNK5thingIjE2idEv, @function
_ZNK5thingIjE2idEv:
.LFB2:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    movq    %rdi, -8(%rbp)
    movl    $2816, %eax
    popq    %rbp
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc

It's identical, except for our cheat: this definition returns 2816 ( = 0xb00).

While we're here, let's note something that might or might not go without saying:
Once we're in assembly (or object code), classes have evaporated. Here,
we're down to: -

data

code

symbols, which can label data or label code.

So nothing here specifically represents the instantiation of thing<T> for
T = unsigned. All that's left of thing<unsigned> in this instance is
the definition of _ZNK5thingIjE2idEv a.k.a thing<unsigned int>::id() const.

So now we know what the compiler does about instantiating thing<unsigned>
in a given translation unit. If it is obliged to instantiate a thing<unsigned>
member function, then it assembles the definition of the instantiated member
function at a weakly global symbol that identifies the member function, and it
puts this definition into its own function-section.

Now let's see what the linker does.

First we'll compile the main source file.

g++ -c main.cpp

Then link all the object files, requesting a diagnostic trace on _ZNK5thingIjE2idEv,
and a linkage map file:

g++ -o prog main.o foo.o boo.o -Wl,--trace-symbol='_ZNK5thingIjE2idEv',-M=prog.map
foo.o: definition of _ZNK5thingIjE2idEv
boo.o: reference to _ZNK5thingIjE2idEv

So the linker tells us that the program gets the definition of _ZNK5thingIjE2idEv from
foo.o and calls it in boo.o.

Running the program shows it's telling the truth:

./prog

f00
f00

Both foo() and boo() are returning the value of thing<unsigned>().id()
as instantiated in foo.cpp.

What has become of the other definition of thing<unsigned int>::id() const
in boo.o? The map file shows us:

prog.map

...
Discarded input sections
 ...
 ...
 .text._ZNK5thingIjE2idEv
                0x0000000000000000        0xf boo.o
 ...
 ...

The linker chucked away the function-section in boo.o that
contained the other definition.

Let's now link prog again, but this time with foo.o and boo.o in the
reverse order:

$ g++ -o prog main.o boo.o foo.o -Wl,--trace-symbol='_ZNK5thingIjE2idEv',-M=prog.map
boo.o: definition of _ZNK5thingIjE2idEv
foo.o: reference to _ZNK5thingIjE2idEv

This time, the program gets the definition of _ZNK5thingIjE2idEv from boo.o and
calls it in foo.o. The program confirms that:

$ ./prog

b00
b00

And the map file shows:

...
Discarded input sections
 ...
 ...
 .text._ZNK5thingIjE2idEv
                0x0000000000000000        0xf foo.o
 ...
 ...

that the linker chucked away the function-section .text._ZNK5thingIjE2idEv
from foo.o.

That completes the picture.

The compiler emits, in each translation unit, a weak definition of
each instantiated template member in its own function section. The linker
then just picks the first of those weak definitions that it encounters
in the linkage sequence when it needs to resolve a reference to the weak
symbol. Because each of the weak symbols addresses a definition, any
one one of them - in particular, the first one - can be used to resolve all references
to the symbol in the linkage, and the rest of the weak definitions are
expendable. The surplus weak definitions must be ignored, because
the linker can only link one definition of a given symbol. And the surplus
weak definitions can be discarded by the linker, with no collateral
damage to the program, because the compiler placed each one in a linkage section all by itself.

By picking the first weak definition it sees, the linker is effectively
picking at random, because the order in which object files are linked is arbitrary.
But this is fine, as long as we obey the ODR accross multiple translation units,
because it we do, then all of the weak definitions are indeed identical. The usual practice of #include-ing a class template everywhere from a header file (and not macro-injecting any local edits when we do so) is a fairly robust way of obeying the rule.

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Would "Constrained Types" be useful in VB/C#?

Intro

This question prompted by Marc Gravell's suggestion that I post new language feature suggestions to this site to gather general opinion on them.

The idea is to gather if they might be helpful or maybe there is already another way to achieve what I am after.

Suggestion (Constrained Types)

A normal variable declaration in VB.Net is written thus:

```<code>Dim SomeVariable as SomeType
</code>```

I suggest allowing the following form(s)

```<code>Dim SomeVariable1 as {SomeType, ISomeInterface}
Dim SomeVariable2 as {SomeType, ISomeInterface, ISomeOtherInterface}
</code>```

This syntax is borrowed from Vb.Net's style of constraining Generics

Why allow this?...What is it good for?

Well the specific case I originally thought of was to define a particular subset of controls.
I wished to create an interface for a series of Control factories which would provide controls based on some business rules.

The consumer of these controls would require, through the interface, that all controls created, should also implement some series of interfaces (only one in my case) which gave all these controls additional facilities not found generally in normal controls.

It is worth noting that the following currently does not work.

```<code>Public Interface ISpecialControl
End Interface

Public Interface IControlProvider
    Function CreateControl(Of T As {Control, ISpecialControl})() As T
End Interface

Public Class SpecialTextBoxProvider
    Implements IControlProvider
    Public Function CreateControl(Of T As {Control, ISpecialControl})() As T Implements IControlProvider.CreateControl
        Return New SpecialTextBox
    End Function
End Class

Public Class SpecialTextBox
    Inherits TextBox
    Implements ISpecialControl
    Public Sub New()

    End Sub
End Class
</code>```

I think this translates to C# as:

```<code>public interface ISpecialControl
{
}

public interface IControlProvider
{
    T CreateControl<T>()
        where T : Control, ISpecialControl;
}

public class SpecialTextBoxProvider : IControlProvider
{
    public T CreateControl<T>()
        where T : Control, ISpecialControl
    {
        return new SpecialTextBox();
    }
}

public class SpecialTextBox : TextBox, ISpecialControl
{
}
</code>```

The attempt to return "New SpecialTextbox" fails due to an inability to cast SpecialTextbox to T.

```<code>"Value of type 'MyApp.SpecialTextBox' cannot be converted to 'T'"
</code>```

I realize that my factories could be allowed to return simple controls and I could check at runtime if they implemented ISpecialControl, but this would yield runtime problems which I would rather check at compile time since it is a logical possibility even if not currently a practical one

Update: The idea is that these factories could sit in external (perhaps even third party) assemblies and could take a dependency on any control libraries they wanted, creating and returning derivatives of these controls which also implemented ISpecialControl.

These assemblies could be located through self-configuring-reflection (Reflection on first pass followed by configuration, which is then used on further runs) and used without any knowledge by the calling assembly on what dependancy these controls would have taken.

It does require that these factories are constructable without passing information about the control they are expected to call, since that would defeat the point.

So what do you think... Would this be useful?... Is there a better way to achieve this? Is there already a way to achieve this?

答:
It would seem a useful language feature.  It's possible to have method parameters whose type is unknown other than its compliance with multiple constraints, but there's no way to store such a parameter in a field in such a way that it can ever be passed to such a function, or even typecast to be passed.

There is another way, however, of achieving the basic result you're after, though it's a little clunky.  See my question Storing an object that implements multiple interfaces and derives from a certain base (.net) where offer up the best approach I've been able to formulate.

OwnerDisplayName: Rory Becker

ContentLicense: CC BY-SA 2.5

Body:
Intro

This question prompted by Marc Gravell's suggestion that I post new language feature suggestions to this site to gather general opinion on them.

The idea is to gather if they might be helpful or maybe there is already another way to achieve what I am after.

Suggestion (Constrained Types)

A normal variable declaration in VB.Net is written thus:

Dim SomeVariable as SomeType

I suggest allowing the following form(s)

Dim SomeVariable1 as {SomeType, ISomeInterface}
Dim SomeVariable2 as {SomeType, ISomeInterface, ISomeOtherInterface}

This syntax is borrowed from Vb.Net's style of constraining Generics

Why allow this?...What is it good for?

Well the specific case I originally thought of was to define a particular subset of controls.
I wished to create an interface for a series of Control factories which would provide controls based on some business rules.

The consumer of these controls would require, through the interface, that all controls created, should also implement some series of interfaces (only one in my case) which gave all these controls additional facilities not found generally in normal controls.

It is worth noting that the following currently does not work.

Public Interface ISpecialControl
End Interface

Public Interface IControlProvider
    Function CreateControl(Of T As {Control, ISpecialControl})() As T
End Interface

Public Class SpecialTextBoxProvider
    Implements IControlProvider
    Public Function CreateControl(Of T As {Control, ISpecialControl})() As T Implements IControlProvider.CreateControl
        Return New SpecialTextBox
    End Function
End Class

Public Class SpecialTextBox
    Inherits TextBox
    Implements ISpecialControl
    Public Sub New()

    End Sub
End Class

I think this translates to C# as:

public interface ISpecialControl
{
}

public interface IControlProvider
{
    T CreateControl<T>()
        where T : Control, ISpecialControl;
}

public class SpecialTextBoxProvider : IControlProvider
{
    public T CreateControl<T>()
        where T : Control, ISpecialControl
    {
        return new SpecialTextBox();
    }
}

public class SpecialTextBox : TextBox, ISpecialControl
{
}

The attempt to return "New SpecialTextbox" fails due to an inability to cast SpecialTextbox to T.

"Value of type 'MyApp.SpecialTextBox' cannot be converted to 'T'"

I realize that my factories could be allowed to return simple controls and I could check at runtime if they implemented ISpecialControl, but this would yield runtime problems which I would rather check at compile time since it is a logical possibility even if not currently a practical one

Update: The idea is that these factories could sit in external (perhaps even third party) assemblies and could take a dependency on any control libraries they wanted, creating and returning derivatives of these controls which also implemented ISpecialControl.

These assemblies could be located through self-configuring-reflection (Reflection on first pass followed by configuration, which is then used on further runs) and used without any knowledge by the calling assembly on what dependancy these controls would have taken.

It does require that these factories are constructable without passing information about the control they are expected to call, since that would defeat the point.

So what do you think... Would this be useful?... Is there a better way to achieve this? Is there already a way to achieve this?

LastEditorDisplayName: Rory Becker


问:
Catching boto3 ClientError subclass
With code like the snippet below, we can catch AWS exceptions:

```<code>from aws_utils import make_session

session = make_session()
cf = session.resource("iam")
role = cf.Role("foo")
try:
    role.load()
except Exception as e:
    print(type(e))
    raise e
</code>```

The returned error is of type botocore.errorfactory.NoSuchEntityException. However, when I try to import this exception, I get this:

```<code>>>> import botocore.errorfactory.NoSuchEntityException
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named NoSuchEntityException
</code>```

The best method I could find of catching this specific error is:

```<code>from botocore.exceptions import ClientError
session = make_session()
cf = session.resource("iam")
role = cf.Role("foo")
try:
    role.load()
except ClientError as e:
    if e.response["Error"]["Code"] == "NoSuchEntity":
        # ignore the target exception
        pass
    else:
        # this is not the exception we are looking for
        raise e
</code>```

But this seems very "hackish". Is there a way to directly import and catch specific subclasses of ClientError in boto3?

EDIT: Note that if you catch errors in the second way and print the type, it will be ClientError.

答:
If you're using the client you can catch the exceptions like this:</p>

```<code>import boto3

def exists(role_name):
    client = boto3.client('iam')
    try:
        client.get_role(RoleName='foo')
        return True
    except client.exceptions.NoSuchEntityException:
        return False
</code>```

ContentLicense: CC BY-SA 3.0

Title: Catching boto3 ClientError subclass

Body:
With code like the snippet below, we can catch AWS exceptions:

from aws_utils import make_session

session = make_session()
cf = session.resource("iam")
role = cf.Role("foo")
try:
    role.load()
except Exception as e:
    print(type(e))
    raise e

The returned error is of type botocore.errorfactory.NoSuchEntityException. However, when I try to import this exception, I get this:

>>> import botocore.errorfactory.NoSuchEntityException
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named NoSuchEntityException

The best method I could find of catching this specific error is:

from botocore.exceptions import ClientError
session = make_session()
cf = session.resource("iam")
role = cf.Role("foo")
try:
    role.load()
except ClientError as e:
    if e.response["Error"]["Code"] == "NoSuchEntity":
        # ignore the target exception
        pass
    else:
        # this is not the exception we are looking for
        raise e

But this seems very "hackish". Is there a way to directly import and catch specific subclasses of ClientError in boto3?

EDIT: Note that if you catch errors in the second way and print the type, it will be ClientError.

Body:
If you're using the client you can catch the exceptions like this:

import boto3

def exists(role_name):
    client = boto3.client('iam')
    try:
        client.get_role(RoleName='foo')
        return True
    except client.exceptions.NoSuchEntityException:
        return False


问:
Ternary operation with a "negative" variable
What does the negative variable do in a ternary? Why is the output -10 is 10?

```<code>public class Ternary {
    public static void main(String[] args) {
        int i, k;
        i = -10;
        k = i < 0 ? -i : i;
        System.out.print(i + " is " + k);
    }
}
</code>```

Can anyone explain the function of the variable in this scenario? What does -i mean?

答:
It first checks

-10 < 0, which turns out to be true.

Thus, 'k' will be assigned with value -(-10) as i = -10. The result becomes 10.

Then you have the answer

-10 is 10 as value of i remains unchanged

Body:
What does the negative variable do in a ternary? Why is the output -10 is 10?

public class Ternary {
    public static void main(String[] args) {
        int i, k;
        i = -10;
        k = i < 0 ? -i : i;
        System.out.print(i + " is " + k);
    }
}

Can anyone explain the function of the variable in this scenario? What does -i mean?


问:
Return multiple React elements in a method without a wrapper element
I'm trying to return multiple React elements from a helper method. I could solve it simply by moving around some code, but I'm wondering if there's a cleaner way to solve it. I have a method that returns part of the render method, and that functions needs to return both a React element and some text. It's clearer through an example:

```<code>class Foo extends React.Component {
  _renderAuthor() {
    if (!this.props.author) {
      return null;
    }

    return [
      ' by ',
      <a href={getAuthorUrl(this.props.author)}>{this.props.author}</a>,
    ]; // Triggers warning: Each child in an array or iterator should have a unique "key" prop.

  render() {
    return (
      <div>
        {this.props.title}
        {this._renderAuthor()}
      </div>
    );
  }
}
</code>```

I know the render method has to return exactly 1 React element. Using a helper method like this would trigger a warning, and fixing the warning (by adding keys) would make the code too convoluted. Is there a clean way to do this without triggering a warning?

Edit:

Another use case:

```<code>render() {
  return (
    <div>
      {user
        ? <h2>{user.name}</h2>
          <p>{user.info}</p>
        : <p>User not found</p>}
    </div>
  );
}
</code>```

Edit 2:

Turns out this isn't possible yet, I wrote about 2 workarounds here: https://www.wptutor.io/web/js/react-multiple-elements-without-wrapper

答:
Try this:</p>

```<code>class Foo extends React.Component {
    _renderAuthor() {
        return <a href={getAuthorUrl(this.props.author)}>{this.props.author}</a>
    }

    render() {
        return (
          <div>
                {this.props.title}
                {this.props.author && " by "}
                {this.props.author && this._renderAuthor()}
          </div>
        );
    }
}
</code>```

Body:
I'm trying to return multiple React elements from a helper method. I could solve it simply by moving around some code, but I'm wondering if there's a cleaner way to solve it. I have a method that returns part of the render method, and that functions needs to return both a React element and some text. It's clearer through an example:

class Foo extends React.Component {
  _renderAuthor() {
    if (!this.props.author) {
      return null;
    }

    return [
      ' by ',
      {this.props.author},
    ]; // Triggers warning: Each child in an array or iterator should have a unique "key" prop.

  render() {
    return (

        {this.props.title}
        {this._renderAuthor()}

    );
  }
}

I know the render method has to return exactly 1 React element. Using a helper method like this would trigger a warning, and fixing the warning (by adding keys) would make the code too convoluted. Is there a clean way to do this without triggering a warning?

Edit:

Another use case:

render() {
  return (

      {user
        ?
{user.name}

{user.info}

        :
User not found
}

  );
}

Edit 2:

Turns out this isn't possible yet, I wrote about 2 workarounds here: https://www.wptutor.io/web/js/react-multiple-elements-without-wrapper

Body:
Try this:

class Foo extends React.Component {
    _renderAuthor() {
        return <a href={getAuthorUrl(this.props.author)}>{this.props.author}</a>
    }

    render() {
        return (
          <div>
                {this.props.title}
                {this.props.author && " by "}
                {this.props.author && this._renderAuthor()}
          </div>
        );
    }
}


问:
how to create a string from char array by adding char by char in java
How to create a String in Java by adding char by char.
I have to do it like this, because i have to add a "," between al letters.
I tried it like this, but it had not worked.</p>

```<code>String t;
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = null;

for (int i = 0; i<l; i++){
    a[i] = new Character(t.charAt(0));
}

for (int v = 0; v<l; v--){
    ret += a[v];
    ret += rel;
}
</code>```

答:
```<code>String text = "mydata";
char[] arrayText = text.toCharArray();
char[] arrayNew = new char[arrayText.length*2];
for(int i = 0, j = 0; i < arrayText.length; i++, j+=2){
    arrayNew[j] = arrayText[i];
    arrayNew[j+1] = ',';
}
String stringArray = new String(arrayNew);
System.out.println(stringArray);
</code>```

Results

```<code>m,y,d,a,t,a,
</code>```

Body:
How to create a String in Java by adding char by char.
I have to do it like this, because i have to add a "," between al letters.
I tried it like this, but it had not worked.

String t;
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = null;

for (int i = 0; i<l; i++){
    a[i] = new Character(t.charAt(0));
}

for (int v = 0; v<l; v--){
    ret += a[v];
    ret += rel;
}

Body:
String text = "mydata";
char[] arrayText = text.toCharArray();
char[] arrayNew = new char[arrayText.length*2];
for(int i = 0, j = 0; i < arrayText.length; i++, j+=2){
    arrayNew[j] = arrayText[i];
    arrayNew[j+1] = ',';
}
String stringArray = new String(arrayNew);
System.out.println(stringArray);

Results

m,y,d,a,t,a,


问:
I am losing a number when subtracting cpp integers
I am going through a C++ course and am asked to make a simple cashier program with change in dollars and cents, separately.

In doing so, I came across an instance where if I cout my calculation of cout<<change*100 - dollars*100<<endl; I get 40 cents correctly.

But when I set the int cents = change * 100 - dollars * 100; Then cout<<cents<<endl; I get 39.

Is this because of the data types I am using have some unintended consequences that I'm not aware of? Here is the whole program:

```<code>#include <iostream>
using namespace std;

int main()
{
    double price, paymentAmount, change;
    int dollars, cents;

    price = 23.00;
    paymentAmount = 24.40;

    cout<<"total: "<<price<<endl;
    cout<<"paid: "<<paymentAmount<<endl;

    change = paymentAmount-price;

    dollars = change; // implicit conversion from double -> int
    cents = change * 100 - dollars * 100;

    cout<<"dollars: "<<dollars<<endl;
    cout<<"cents: "<<change*100 - dollars*100<<endl; // outputs 40
    cout<<"cents: "<<cents<<endl; // outputs 39

    return 0;
}
</code>```

Thanks for the help

Edit:

Turns out this is from converting the double to int, which truncates the decimals. My number was something like 39.99999 but was truncated to 39 when converting to int. I think that conversion aspect makes this a non duplicate question

答:
It is related to decimal point precision. In line cents = change * 100 - dollars * 100; precision is lost because result is converted into int. But in line cout<<"cents: "<<change*100 - dollars*100<<endl; result is in double so precision is not lost.

You can verify it by following statement

```<code>double cent2=change * 100 - dollars * 100;
cout<<cent2<<endl;
</code>```

Body:
I am going through a C++ course and am asked to make a simple cashier program with change in dollars and cents, separately.

In doing so, I came across an instance where if I cout my calculation of cout<<change*100 - dollars*100<<endl; I get 40 cents correctly.

But when I set the int cents = change * 100 - dollars * 100; Then cout<<cents<<endl; I get 39.

Is this because of the data types I am using have some unintended consequences that I'm not aware of? Here is the whole program:

#include <iostream>
using namespace std;

int main()
{
    double price, paymentAmount, change;
    int dollars, cents;

    price = 23.00;
    paymentAmount = 24.40;

    cout<<"total: "<<price<<endl;
    cout<<"paid: "<<paymentAmount<<endl;

    change = paymentAmount-price;

    dollars = change; // implicit conversion from double -> int
    cents = change * 100 - dollars * 100;

    cout<<"dollars: "<<dollars<<endl;
    cout<<"cents: "<<change*100 - dollars*100<<endl; // outputs 40
    cout<<"cents: "<<cents<<endl; // outputs 39

    return 0;
}

Thanks for the help

Edit:

Turns out this is from converting the double to int, which truncates the decimals. My number was something like 39.99999 but was truncated to 39 when converting to int. I think that conversion aspect makes this a non duplicate question

Body:
It is related to decimal point precision. In line cents = change * 100 - dollars * 100; precision is lost because result is converted into int. But in line cout<<"cents: "<<change*100 - dollars*100<<endl; result is in double so precision is not lost.

You can verify it by following statement

double cent2=change * 100 - dollars * 100;
cout<<cent2<<endl;


问:
Converting a input (Password) into MD5
Hi I'm a bit new to this and can't exactly figure out how to get it working.

Here is my current code:

```<code>import hashlib

def PasswordCreate():
    password = input(str("Please enter a password next to this text"))
    password = hashlib.md5()
    password.update(password.encode('utf-8'))
    return password.hexdigest()

PasswordCreate()
</code>```

The error is:

```<code>AttributeError: '_hashlib.HASH' object has no attribute 'encode'
</code>```

答:
As simple as I can put:</p>

```<code>import hashlib
print(hashlib.md5(input().encode()).hexdigest())
</code>```

Title: Converting a input (Password) into MD5

Body:
Hi I'm a bit new to this and can't exactly figure out how to get it working.

Here is my current code:

import hashlib

def PasswordCreate():
    password = input(str("Please enter a password next to this text"))
    password = hashlib.md5()
    password.update(password.encode('utf-8'))
    return password.hexdigest()

PasswordCreate()

The error is:

AttributeError: '_hashlib.HASH' object has no attribute 'encode'

Body:
As simple as I can put:

import hashlib
print(hashlib.md5(input().encode()).hexdigest())


问:
How to convert lowercase characters of a string to uppercase characters in C++?
I have a question where all lowercase characters of a string should be converted into uppercase characters.But as per the question, certain lines in the code should not be changed. I have written the code below.

```<code> #include <iostream>
 #include <string>
 #include <stdio.h>
 #include <ctype.h>
 using namespace std;

 class StringOps {
 public:
   void stringToUpper(string &s) //This line should not be changed
  {
    char c;
    int i=0;
    while (s[i])
    {
     c=s[i];
     putchar (toupper(c));
     i++;
    }
  }
 };

 int main(void)
 {
   string str ="Hello World";
   StringOps obj;
   obj.stringToUpper(str);
   cout << str;            //This line should not be changed
   return 0;
   }
</code>```

I get the output as:

```<code>HELLO WORLDHello World
</code>```

But the required output is:

```<code>HELLO WORLD HELLO WORLD
</code>```

How do I make the

```<code> cout<<str;
</code>```

statement in main() to print the result computed in the function :

```<code> void stringToUpper(string &s)
</code>```

答:
Solution only for the lower part of ASCII characters.

```<code>class StringOps {
public:
  void stringToUpper(string& s) //This line should not be changed
  {
    for (size_t i = 0; i < s.size(); ++i) {
      if (s[i] > 96 && s[i] < 123)
        s[i] -= 32;
    }
  }
};
</code>```

and if you care about the higher part of the ASCII table:

```<code>class StringOps {
public:
  void stringToUpper(string& s) //This line should not be changed
  {
    for (size_t i = 0; i < s.size(); ++i) {
      s[i] = toupper(s[i]);
    }
  }
};
</code>```

If you have some multi-byte encoding, like UTF-8, you will need some library.

Body:
I have a question where all lowercase characters of a string should be converted into uppercase characters.But as per the question, certain lines in the code should not be changed. I have written the code below.

 #include <iostream>
 #include <string>
 #include <stdio.h>
 #include <ctype.h>
 using namespace std;

 class StringOps {
 public:
   void stringToUpper(string &s) //This line should not be changed
  {
    char c;
    int i=0;
    while (s[i])
    {
     c=s[i];
     putchar (toupper(c));
     i++;
    }
  }
 };

 int main(void)
 {
   string str ="Hello World";
   StringOps obj;
   obj.stringToUpper(str);
   cout << str;            //This line should not be changed
   return 0;
   }

I get the output as:

HELLO WORLDHello World

But the required output is:

HELLO WORLD HELLO WORLD

How do I make the

 cout<<str;

statement in main() to print the result computed in the function :

 void stringToUpper(string &s)

Body:
Solution only for the lower part of ASCII characters.

class StringOps {
public:
  void stringToUpper(string& s) //This line should not be changed
  {
    for (size_t i = 0; i < s.size(); ++i) {
      if (s[i] > 96 && s[i] < 123)
        s[i] -= 32;
    }
  }
};

and if you care about the higher part of the ASCII table:

class StringOps {
public:
  void stringToUpper(string& s) //This line should not be changed
  {
    for (size_t i = 0; i < s.size(); ++i) {
      s[i] = toupper(s[i]);
    }
  }
};

If you have some multi-byte encoding, like UTF-8, you will need some library.


问:
How to fix my index.html + bootstrap4

```<code>    *Whenever I reload the page the default bootstrap navbar style appears
 before my overridden styles apply
 Please any help
</code>```

- Whenever I reload the page the default bootstrap navbar style appears
       before my overridden styles apply
       Please any help w

ill be welcome
    Using bootstrap 4 Here my index.html file with custum CSS bellow*

Head

```<code><meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://use.fontawesome.com/75528e6985.js"></script>
<link rel="stylesheet" href="css/css/bootstrap.min.css">
<link href="css/style.css" rel="stylesheet">
</code>```

Style

```<code>.selector-for-some-widget {
        -webkit-box-sizing: content-box;
        -moz-box-sizing: content-box;
        box-sizing: content-box;
    }

    body {
        background: #e9ebee;
    }

    .logo {
        background-color: rgba(18, 101, 204, 0.82);
        padding-top: 2px;
        padding-bottom: 2px;
        padding-left: 7px;
        padding-right: 7px;
        font-size: 29px;
        font-weight: bold;
        border-radius: 11px;
    }

    a .navbar-brand {
        color: #baccce!important;
    }

    .pull-right {
        margin-right: 150px;
    }

    .bookUs-btn {
        color: #5d85b7;
        margin: -56px 88% 29px;
        border-color: #5d85b7;
        font-weight: bold;
    }

    .bookUs-btn:hover {
        background-color: #5d85b7;
    }

    .navbar-nav {
        margin-right: 20%!important;
    }
</code>```

Nav

```<code>    <nav class="navbar navbar-dark bg-light bg-faded" style="background: #172944;" role="navigation">
    <div class="container">
        <button class="navbar-toggler hidden-sm-up" type="button" data-toggle="collapse" data-target="#exCollapsingNavbar2">
  ☰
</button>
        <div class="collapse navbar-toggleable-xs" id="exCollapsingNavbar2">
            <a class="navbar-brand" href="#">
    <span class="logo">K
    </span>
    OMRIHE
  </a>
            <ul class="nav navbar-nav pull-right">
                <li class="nav-item ">
                    <a class="nav-link" href="#">PORTFOLIO
        <span class="sr-only">(current)
        </span>
      </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">BLOG
      </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">ABOUT ME
      </a>
                </li>
            </ul>
            <span class="">
    <button class=" btn btn-primary-outline bookUs-btn">
      <i class="fa fa-phone-square">
      </i> Contact Me
    </button>
  </span>
        </div>
    </div>
</nav>
</code>```

答:
bootstrap need jquery tether.js and boostrap.min.js

https://v4-alpha.getbootstrap.com/getting-started/introduction/#quick-start

Title: How to fix my index.html + bootstrap4

Body:
    *Whenever I reload the page the default bootstrap navbar style appears
 before my overridden styles apply
 Please any help

- Whenever I reload the page the default bootstrap navbar style appears
       before my overridden styles apply
       Please any help w

ill be welcome
    Using bootstrap 4 Here my index.html file with custum CSS bellow*

Head

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="css/css/bootstrap.min.css">
<link href="css/style.css" rel="stylesheet">

Style

.selector-for-some-widget {
        -webkit-box-sizing: content-box;
        -moz-box-sizing: content-box;
        box-sizing: content-box;
    }

    body {
        background: #e9ebee;
    }

    .logo {
        background-color: rgba(18, 101, 204, 0.82);
        padding-top: 2px;
        padding-bottom: 2px;
        padding-left: 7px;
        padding-right: 7px;
        font-size: 29px;
        font-weight: bold;
        border-radius: 11px;
    }

    a .navbar-brand {
        color: #baccce!important;
    }

    .pull-right {
        margin-right: 150px;
    }

    .bookUs-btn {
        color: #5d85b7;
        margin: -56px 88% 29px;
        border-color: #5d85b7;
        font-weight: bold;
    }

    .bookUs-btn:hover {
        background-color: #5d85b7;
    }

    .navbar-nav {
        margin-right: 20%!important;
    }

Nav

        <button class="navbar-toggler hidden-sm-up" type="button" data-toggle="collapse" data-target="#exCollapsingNavbar2">
  ☰
</button>

    K

    OMRIHE

                    PORTFOLIO
        (current)

                    BLOG

                    ABOUT ME

    <button class=" btn btn-primary-outline bookUs-btn">

       Contact Me
    </button>


问:
Producing subscripts in R markdown
I'm aware that R markdown can produce superscripts:

```<code>text^superscript
</code>```

But is it possible to produce proper subscripts? Or is the only way to do so to cheat and use LaTeX math mode:

```<code>$\sf{text_{subscript}}$
</code>```

The intended final output is HTML.

答:
R Markdown subscript is working normally as it should.

Maybe this is an old post. I'm using RStudio Version 0.99.902 + R Version 3.4 on a Mac.

Subscript: H~2~O is a liquid.

Superscript: 2^10^ is 1024.

Title: Producing subscripts in R markdown

Body:
I'm aware that R markdown can produce superscripts:

text^superscript

But is it possible to produce proper subscripts? Or is the only way to do so to cheat and use LaTeX math mode:

$\sf{text_{subscript}}$

The intended final output is HTML.


问:
How to take backup of a firebase database from Google Cloud Engine using cURL?
I was taking backup of my firebase db using cURL on Google Compute engine. The backups were successful last week. Two days before I changed the security of my db to allow only authenticated users to read or write.
Something like this

```<code>{
  "rules": {
        ".read": "auth != null",
        ".write": "auth != null"
  }
}
</code>```

Now my backup started failing. So, how do I add or grant the user in compute engine to successfully take backup of my firebase database? Thanks.

答:
Since, I enabled the authentication of the database, I am not able to take the backup without authenticating the server.

To overcome, I used Firebase Admin SDK with a service account. After that I am able to access the Firebase database using the APIs

Body:
I was taking backup of my firebase db using cURL on Google Compute engine. The backups were successful last week. Two days before I changed the security of my db to allow only authenticated users to read or write.
Something like this

{
  "rules": {
        ".read": "auth != null",
        ".write": "auth != null"
  }
}

Now my backup started failing. So, how do I add or grant the user in compute engine to successfully take backup of my firebase database? Thanks.


问:
How to update reactive Objects (and properties in general)?
Vue.js documentation on Reactivity in Depth mentions that

a property must be present in the data object in order for Vue to
convert it and make it reactive

(...)

you have to initialize Vue instances by declaring all root-level
reactive data properties upfront, even just with an empty value

Consider these two code snippets, where tags is defined as an empty object and updated in the course of the script, in two different ways:

var vm = new Vue({
  el: "#root",
  data: {
    tags: {}
  }
});

vm.tags = {
  hello: true,
  world: true
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<div id="root">
  {{tags}}
</div></code>```

var vm = new Vue({
  el: "#root",
  data: {
    tags: {}
  }
});

vm.tags["hello"] = true
vm.tags["world"] = true```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<div id="root">
  {{tags}}
</div></code>```

In the first case, the content is correctly updated, and in the second - not.

Why is it so, despite the fact that in both cases tags were declared at the VM instantiation?

答:
It's not that the tags object is declared, it's that the properties on the tags object do not exist when the Vue is instantiated.

In the second case you are adding two new properties to the tags object by using an indexer. Vue cannot detect that those properties were added.

This is why the $set method exists. When you add a new property to an object, you need to add it via $set or Vue.set

```<code> Vue.set(vm.tags, 'hello', true)
</code>```

or, if you are inside a Vue method,

```<code>this.$set(this.tags, 'hello', true)
</code>```

In the first case, you are adding a completely different object that has the properties. That being the case, Vue is aware of the properties and converts them into reactive properties when the new value is added to data.

If instead you added a new empty object and then added the properties, you would be back in the same case as your second example.

Typically, you just want to initialize the object with the empty properties.

```<code>data: {
    tags:{
        hello: false,
        world: false
    }
}
</code>```

In which case, the properties will be converted to reactive properties and changes will be detected.

Edit

@WoJ posted a comment with a pen with code that looks like this:

var vm = new Vue({
  el: "#root",
  data: {
    posts: {},
    tags: {}
  }
});

vm.tags = {
  hello: true,
  world: true
};

vm.posts["bonjour"] = true
vm.posts["monde"] = true```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<div id="root">
  <!-- show all tags which are on -->
  {{tags}}
  {{posts}}
</div></code>```

In this code it appears that the posts property of the Vue is updated with new reactive properties because they are displayed in the output when the Vue is rendered. What is happening here is that the properties are added to the posts object, that's just how javascript works, you can add properties to objects, but Vue doesn't know they are there. More specifically, these properties are not added as reactive properties (getters/setters) which is how Vue knows when changes occur to data that has been added to the Vue. In fact, adding these properties to the posts object does not trigger a render.

So, why do the new properties show up in the output? The reason the new posts properties show up in the output is because setting the tags property to a new object triggers a render to be scheduled. It's important to know that Vue renders are not synchronous, they are asynchronous (see here).

... Vue performs DOM updates
asynchronously. Whenever a data change is observed, it will open a
queue and buffer all the data changes that happen in the same event
loop.

For example, when you set vm.someData = 'new value', the component
will not re-render immediately. It will update in the next “tick”,
when the queue is flushed.

In the code example above, the update to tags triggers a render to be scheduled. Then, the posts object is updated with two new properties that are not converted to reactive properties because Vue doesn't know they exist. Then some time later, the scheduled render occurs and Vue updates the HTML with the current state of the objects in data. Since posts does have those two new properties, those properties are rendered to the screen. Updates to those properties, however, will never trigger an update to render.

To see this is the case, simply comment out the update to the tags property.

var vm = new Vue({
  el: "#root",
  data: {
    posts: {},
    tags: {}
  }
});

//vm.tags = {
//  hello: true,
//  world: true
//};

vm.posts["bonjour"] = true
vm.posts["monde"] = true```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<div id="root">
  <!-- show all tags which are on -->
  {{tags}}
  {{posts}}
</div></code>```

Notice, in this case, the rendered Vue never changes.

Body:
Vue.js documentation on Reactivity in Depth mentions that

a property must be present in the data object in order for Vue to
convert it and make it reactive

(...)

you have to initialize Vue instances by declaring all root-level
reactive data properties upfront, even just with an empty value

Consider these two code snippets, where tags is defined as an empty object and updated in the course of the script, in two different ways:

var vm = new Vue({
  el: "#root",
  data: {
    tags: {}
  }
});

vm.tags = {
  hello: true,
  world: true
};

  {{tags}}

var vm = new Vue({
  el: "#root",
  data: {
    tags: {}
  }
});

vm.tags["hello"] = true
vm.tags["world"] = true

  {{tags}}

In the first case, the content is correctly updated, and in the second - not.

Why is it so, despite the fact that in both cases tags were declared at the VM instantiation?

Body:
It's not that the tags object is declared, it's that the properties on the tags object do not exist when the Vue is instantiated.

In the second case you are adding two new properties to the tags object by using an indexer. Vue cannot detect that those properties were added.

This is why the $set method exists. When you add a new property to an object, you need to add it via $set or Vue.set

 Vue.set(vm.tags, 'hello', true)

or, if you are inside a Vue method,

this.$set(this.tags, 'hello', true)

In the first case, you are adding a completely different object that has the properties. That being the case, Vue is aware of the properties and converts them into reactive properties when the new value is added to data.

If instead you added a new empty object and then added the properties, you would be back in the same case as your second example.

Typically, you just want to initialize the object with the empty properties.

data: {
    tags:{
        hello: false,
        world: false
    }
}

In which case, the properties will be converted to reactive properties and changes will be detected.

Edit

@WoJ posted a comment with a pen with code that looks like this:

var vm = new Vue({
  el: "#root",
  data: {
    posts: {},
    tags: {}
  }
});

vm.tags = {
  hello: true,
  world: true
};

vm.posts["bonjour"] = true
vm.posts["monde"] = true

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<div id="root">
  <!-- show all tags which are on -->
  {{tags}}
  {{posts}}
</div>

In this code it appears that the posts property of the Vue is updated with new reactive properties because they are displayed in the output when the Vue is rendered. What is happening here is that the properties are added to the posts object, that's just how javascript works, you can add properties to objects, but Vue doesn't know they are there. More specifically, these properties are not added as reactive properties (getters/setters) which is how Vue knows when changes occur to data that has been added to the Vue. In fact, adding these properties to the posts object does not trigger a render.

So, why do the new properties show up in the output? The reason the new posts properties show up in the output is because setting the tags property to a new object triggers a render to be scheduled. It's important to know that Vue renders are not synchronous, they are asynchronous (see here).

... Vue performs DOM updates
asynchronously. Whenever a data change is observed, it will open a
queue and buffer all the data changes that happen in the same event
loop.

For example, when you set vm.someData = 'new value', the component
will not re-render immediately. It will update in the next “tick”,
when the queue is flushed.

In the code example above, the update to tags triggers a render to be scheduled. Then, the posts object is updated with two new properties that are not converted to reactive properties because Vue doesn't know they exist. Then some time later, the scheduled render occurs and Vue updates the HTML with the current state of the objects in data. Since posts does have those two new properties, those properties are rendered to the screen. Updates to those properties, however, will never trigger an update to render.

To see this is the case, simply comment out the update to the tags property.

var vm = new Vue({
  el: "#root",
  data: {
    posts: {},
    tags: {}
  }
});

//vm.tags = {
//  hello: true,
//  world: true
//};

vm.posts["bonjour"] = true
vm.posts["monde"] = true

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<div id="root">
  <!-- show all tags which are on -->
  {{tags}}
  {{posts}}
</div>

Notice, in this case, the rendered Vue never changes.


问:
Same key for all key-value pairs?
Can I use the same key for all key-value pairs in a SharedPreference file in Android? (I really don't need the key). I want to access the pairs only by value. Also how long can a key be ?</p>

答:
Then we can save ArrayList in Preferences</p>

```<code> public void saveArray(ArrayList<String> arrayList) {
        SharedPreferences sharedPreferences = getSharedPreferences(R.string.PREF_FILE + "", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("size", arrayList.size());
        for (int i = 0; i < arrayList.size(); i++) {
            editor.putString("task" + i, arrayList.get(i));

        }

        editor.commit();
    }
</code>```

Title: Same key for all key-value pairs?

Body:
Then we can save ArrayList in Preferences

 public void saveArray(ArrayList<String> arrayList) {
        SharedPreferences sharedPreferences = getSharedPreferences(R.string.PREF_FILE + "", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("size", arrayList.size());
        for (int i = 0; i < arrayList.size(); i++) {
            editor.putString("task" + i, arrayList.get(i));

        }

        editor.commit();
    }


问:
SQL Query to check if student1 has a course with student 2
I have one table and I need to check if two users, for whom I have the IDs (e.g. 20 and 21) share the same course, just true or false.

```
Table: jos_gj_users
Columns: id_user, id_group

Data Example: (20; 4)
              (20; 5)
              (20; 6)
              (21; 6)
              (21; 7)
```

The data above shows that user 20 and user 21 share the course 6 but how do I get this with SQL just by entering the IDs and without looping through the results with PHP?

答:
Try a self-join:

```<code>SELECT T1.id_group
FROM jos_gj_users T1
JOIN jos_gj_users T2
ON T1.id_group = T2.id_group
WHERE T1.id_user = 20
AND T2.id_user = 21
</code>```

To just get a "true or false" result you can check from the client to see if at least one row exists in the result set rather than fetching the entire results.

Alternatively you can do it in SQL by wrapping the above query in another SELECT that uses EXISTS:

```<code>SELECT CASE WHEN EXISTS
(
    SELECT T1.id_group
    FROM jos_gj_users T1
    JOIN jos_gj_users T2
    ON T1.id_group = T2.id_group
    WHERE T1.id_user = 20
    AND T2.id_user = 21
) THEN 1 ELSE 0 END AS result
</code>```

This query returns either 0 (false) or 1 (true).

Body:
I have one table and I need to check if two users, for whom I have the IDs (e.g. 20 and 21) share the same course, just true or false.

Table: jos_gj_users
Columns: id_user, id_group

Data Example: (20; 4)
              (20; 5)
              (20; 6)
              (21; 6)
              (21; 7)

The data above shows that user 20 and user 21 share the course 6 but how do I get this with SQL just by entering the IDs and without looping through the results with PHP?

Body:
Try a self-join:

SELECT T1.id_group
FROM jos_gj_users T1
JOIN jos_gj_users T2
ON T1.id_group = T2.id_group
WHERE T1.id_user = 20
AND T2.id_user = 21

To just get a "true or false" result you can check from the client to see if at least one row exists in the result set rather than fetching the entire results.

Alternatively you can do it in SQL by wrapping the above query in another SELECT that uses EXISTS:

SELECT CASE WHEN EXISTS
(
    SELECT T1.id_group
    FROM jos_gj_users T1
    JOIN jos_gj_users T2
    ON T1.id_group = T2.id_group
    WHERE T1.id_user = 20
    AND T2.id_user = 21
) THEN 1 ELSE 0 END AS result

This query returns either 0 (false) or 1 (true).


问:
jQuery Ajax function does not work?
I'm developing a simple login form for my website. And to do that I thought to use ajax to connect with php to validate users. However to do that I cannot get output from ajax.

```<code><script>
 function submitForLogin()
 {
    $.ajax({
            type: "POST",
            url: "php/login.php",
            data: { email: "example@abc.com",password:"123" }}).done(function(data){alert(data);});

 }

</script>
</code>```

When user clicks on login button it calls submitForLogin() function.

Above part of the code I've placed in my login.html file. To validate whether this works or not I simply replaced data values of email and password with hard coded values.

Note : example@abc.com and 123 both email and password stored in Wamp server database.

This is the PHP file :

```<code><?php
$userEmail=$_POST['email'];
$userPass=$_POST['password'];
$servername ="localhost";
    $username="root";
    $password="";
    $dbname="AS2014459";
    //To create a connection
    $con = mysqli_connect($servername,$username,$password,$dbname); //check connection
    if(!$con){
        die("Connection failed: ".mysqli_connect_error());
    }
    $sql="SELECT Email,Password FROM USERTABLE WHERE Email='".$userEmail."'";
    $results=mysqli_query($con,$sql);
    if(mysqli_num_rows($results)>0)
    {
        echo "userExist";
    }
    else
    {
        echo "fakeUser";
    }
    mysqli_close($con);

?>
</code>```

Whenever I run php file only (with $userEmail and $userPass having previous hard coded values) php prints userExist output. But using ajax I cannot get that in an alert box.

Is there something I missing? I'm running the website in wamp server too.

UPDATE

When I check console errors it shows;

And when I click on login.html line 112, it shows;

And ideas guys? Also, none of the solutions provided so far gave me successful answer for the question.

There was a jquery error and now it's fixed. But syntax error exists.

答:
```<code>$.ajax({
    type: "POST",
    url: "php/login.php",
     data: { email: "example@abc.com",password:"123" },
    success: function (data) {
        alert(data);

    }
});
</code>```

your data in AJAX call is in JSON format.
in your php script you should use json decode as below

```<code>$data = file_get_contents("php://input");
$data = json_decode($data,true);
$userEmail=$data['email'];
$userPass=$data['password'];
</code>```

i hope this might help you. your login will work as u expect it

Title: jQuery Ajax function does not work?

Body:
I'm developing a simple login form for my website. And to do that I thought to use ajax to connect with php to validate users. However to do that I cannot get output from ajax.

When user clicks on login button it calls submitForLogin() function.

Above part of the code I've placed in my login.html file. To validate whether this works or not I simply replaced data values of email and password with hard coded values.

Note : example@abc.com and 123 both email and password stored in Wamp server database.

This is the PHP file :

<?php
$userEmail=$_POST['email'];
$userPass=$_POST['password'];
$servername ="localhost";
    $username="root";
    $password="";
    $dbname="AS2014459";
    //To create a connection
    $con = mysqli_connect($servername,$username,$password,$dbname); //check connection
    if(!$con){
        die("Connection failed: ".mysqli_connect_error());
    }
    $sql="SELECT Email,Password FROM USERTABLE WHERE Email='".$userEmail."'";
    $results=mysqli_query($con,$sql);
    if(mysqli_num_rows($results)>0)
    {
        echo "userExist";
    }
    else
    {
        echo "fakeUser";
    }
    mysqli_close($con);

?>

Whenever I run php file only (with $userEmail and $userPass having previous hard coded values) php prints userExist output. But using ajax I cannot get that in an alert box.

Is there something I missing? I'm running the website in wamp server too.

UPDATE

When I check console errors it shows;

And when I click on login.html line 112, it shows;

And ideas guys? Also, none of the solutions provided so far gave me successful answer for the question.

There was a jquery error and now it's fixed. But syntax error exists.

Body:
$.ajax({
    type: "POST",
    url: "php/login.php",
     data: { email: "example@abc.com",password:"123" },
    success: function (data) {
        alert(data);

    }
});

your data in AJAX call is in JSON format.
in your php script you should use json decode as below

$data = file_get_contents("php://input");
$data = json_decode($data,true);
$userEmail=$data['email'];
$userPass=$data['password'];

i hope this might help you. your login will work as u expect it


问:
Linking to local video file for video background HTML/CSS
I've been stuck trying to make a video on my computer be the video in the background. My video is titled "runbg.avi" and it is in the same folder as my HTML and CSS files.

These are a couple of many websites that I visited to search for an answer.

Using file:// instead of http:// when trying to get video from my computer rather than the web.

I can point to video on the web but not locally.

My program so far.

/* BACKGROUND */
video#vid {
position: fixed;
right: 0;
bottom: 0;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
z-index: -100;
background-size: cover;
margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<head>
<title>Seb's Fitness</title>

<link rel = "stylesheet"
      type = "text/css"
      href = "css.css" />

      <video autoplay loop poster="" id="vid">
    <source src="file://runbg.avi" type="video/avi">
    </video></code>```

答:
EDIT: HTML5 video tag does not support AVI video types

You can use online video converter tool to convert to supported video type.
MP4, OGG, WEBM

Does HTML5 <video> playback support the .avi format?

Body:
I've been stuck trying to make a video on my computer be the video in the background. My video is titled "runbg.avi" and it is in the same folder as my HTML and CSS files.

These are a couple of many websites that I visited to search for an answer.

Using file:// instead of http:// when trying to get video from my computer rather than the web.

I can point to video on the web but not locally.

My program so far.

/* BACKGROUND */
video#vid {
position: fixed;
right: 0;
bottom: 0;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
z-index: -100;
background-size: cover;
margin: 0 auto;
}

<!DOCTYPE html>

<title>Seb's Fitness</title>

<link rel = "stylesheet"
      type = "text/css"
      href = "css.css" />

      <video autoplay loop poster="" id="vid">
    <source src="file://runbg.avi" type="video/avi">
    </video>


问:
Multiple errors on openpyxl GUI program
I am making an excel GUI program in python using openpyxl and tkinter. Here is my code:

```<code>import openpyxl
from tkinter import *
from tkinter import Tk
from tkinter.filedialog import askopenfilename
from openpyxl.utils import get_column_letter, column_index_from_string

root = Tk()
root.configure(background='light green')
root.geometry("500x500")
root.wm_title("BananaCell")

v1 = StringVar()
v2 = StringVar()
v3 = StringVar()
v4 = StringVar()

e1 = Entry(root, textvariable=v1)
e1.insert(10,'ddd')
e1.delete(0, END)
e1.pack()
e1.place(x=70, y=150)

e = Entry(root)
e.insert(10,"Sheet 1 Name: ")
e.delete(0, END)
e.pack()
e.place(x=300, y=150)

v1 = e.get()
print(v1)

def get_1():
    print(v1)

bf = Button(root, text="Enter", width=6, height=0, command=get_1)
bf.pack()
bf.place(x=15, y=147)

def askForFileName1():
    f1 = askopenfilename(title="Select Workbook 1")
    wb = openpyxl.load_workbook(str(f1))

def askForFileName2():
    f2 = askopenfilename(title="Select Workbook 2")
    wb1 = openpyxl.load_workbook(str(f2))

b = Button(root, text="Workbook 1", width=12, height=2, command=askForFileName1)
b.pack()
b.place(x=100, y=100)

b2 = Button(root, text="Workbook 2", width=12, height=2,
command=askForFileName2)
b2.pack()
b2.place(x=300, y=100)

mainloop()

col1 = input('Column letter from Sheet 1 to compare from: ')
col2 = input('Column letter  from Sheet 2 to compare from: ')

for (col, col_1) in zip(ws.iter_cols(min_col = column_index_from_string(col1), max_col=column_index_from_string(col1)),
ws1.iter_cols(min_col = column_index_from_string(col2),
max_col=column_index_from_string(col2))):
    for (cell, cell_1) in zip(col, col_1):
       if cell.value != cell_1.value and cell.row == cell_1.row:
           print('Row ' + str(cell.row) + ' ' + str(cell.value) + ' is not equal to ' + str(cell_1.value) + ' ' + 'Row ' + str(cell_1.row))

exit_if = input('Press x to exit when you\'re ready: ')
</code>```

I have two problems: A is that I need the variables f1 and f2 to be global somehow and B is when I press the Enter button in the program, it prints a blank space. Can anyone fix these problems? Any help is great

答:
for problem A: assign any value outside function i.e

```<code>f1,f2=0,0
</code>```

and make them global inside function

```<code>def ask_for_filename():
    global f1 #or global f2 whatever you want
</code>```

and everytime you use these variable outside function they give you your desired result dont forget to make them global inside function if you want them to modify as global:

```<code>global f1 or f2
</code>```

Title: Multiple errors on openpyxl GUI program

Body:
I am making an excel GUI program in python using openpyxl and tkinter. Here is my code:

import openpyxl
from tkinter import *
from tkinter import Tk
from tkinter.filedialog import askopenfilename
from openpyxl.utils import get_column_letter, column_index_from_string

root = Tk()
root.configure(background='light green')
root.geometry("500x500")
root.wm_title("BananaCell")

v1 = StringVar()
v2 = StringVar()
v3 = StringVar()
v4 = StringVar()

e1 = Entry(root, textvariable=v1)
e1.insert(10,'ddd')
e1.delete(0, END)
e1.pack()
e1.place(x=70, y=150)

e = Entry(root)
e.insert(10,"Sheet 1 Name: ")
e.delete(0, END)
e.pack()
e.place(x=300, y=150)

v1 = e.get()
print(v1)

def get_1():
    print(v1)

bf = Button(root, text="Enter", width=6, height=0, command=get_1)
bf.pack()
bf.place(x=15, y=147)

def askForFileName1():
    f1 = askopenfilename(title="Select Workbook 1")
    wb = openpyxl.load_workbook(str(f1))

def askForFileName2():
    f2 = askopenfilename(title="Select Workbook 2")
    wb1 = openpyxl.load_workbook(str(f2))

b = Button(root, text="Workbook 1", width=12, height=2, command=askForFileName1)
b.pack()
b.place(x=100, y=100)

b2 = Button(root, text="Workbook 2", width=12, height=2,
command=askForFileName2)
b2.pack()
b2.place(x=300, y=100)

mainloop()

col1 = input('Column letter from Sheet 1 to compare from: ')
col2 = input('Column letter  from Sheet 2 to compare from: ')

for (col, col_1) in zip(ws.iter_cols(min_col = column_index_from_string(col1), max_col=column_index_from_string(col1)),
ws1.iter_cols(min_col = column_index_from_string(col2),
max_col=column_index_from_string(col2))):
    for (cell, cell_1) in zip(col, col_1):
       if cell.value != cell_1.value and cell.row == cell_1.row:
           print('Row ' + str(cell.row) + ' ' + str(cell.value) + ' is not equal to ' + str(cell_1.value) + ' ' + 'Row ' + str(cell_1.row))

exit_if = input('Press x to exit when you\'re ready: ')

I have two problems: A is that I need the variables f1 and f2 to be global somehow and B is when I press the Enter button in the program, it prints a blank space. Can anyone fix these problems? Any help is great

Body:
for problem A: assign any value outside function i.e

f1,f2=0,0

and make them global inside function

def ask_for_filename():
    global f1 #or global f2 whatever you want

and everytime you use these variable outside function they give you your desired result dont forget to make them global inside function if you want them to modify as global:

global f1 or f2


问:
downloading geojson file into folium in jupyter
I want a map of Europe (as json file, so i can work with geojson) to place it on Folium map as layers so I am able to embed my data set onto it to show which country in Europe has the highest alcohol serving. I am having problems with getting the json file from GitHub to open in jyputer

This is what I have so far  and i have the file of europe country in geojson from github https://github.com/Leaflet/Leaflet.VectorGrid/blob/master/docs/eu-countries.geo.json

答:
You will have to download that file. Now you will be able to add the layer:</p>

```<code># geo_path is the path to your geojson file
map1.choropleth(geo_path=geo_path)
display(map1)
</code>```

Body:
You will have to download that file. Now you will be able to add the layer:

# geo_path is the path to your geojson file
map1.choropleth(geo_path=geo_path)
display(map1)


问:
TypeScript - Create an interface for complicated objects
The following variable contains a list of objects:

```<code>scenes = {
    sky: {
      image: 'assets/1.jpg',
      points: {
        blue_area: {
          x: 1,
          y: 2
        },
      }
    },
    blue_area: {
      image: 'assets/2.jpg',
      points: {
        sky: {
          x: 1,
          y: 2
        }
      }
    }
};
</code>```

How I can declare an interface for this kind of variable?

答:
You can declare the type of Scenes as:</p>

```<code>type Points = {
  [key: string]: {
    x: number;
    y: number;
  }
}

type Scenes = {
  [key: string]: {
    image: string;
    points: Points;
  }
}

let scenes: Scenes = {
    sky: {
      image: 'assets/1.jpg',
      points: {
        blue_area: {
          x: 1,
          y: 2
        },
      }
    },
    blue_area: {
      image: 'assets/2.jpg',
      points: {
        sky: {
          x: 1,
          y: 2
        }
      }
    }
};
</code>```

Body:
The following variable contains a list of objects:

scenes = {
    sky: {
      image: 'assets/1.jpg',
      points: {
        blue_area: {
          x: 1,
          y: 2
        },
      }
    },
    blue_area: {
      image: 'assets/2.jpg',
      points: {
        sky: {
          x: 1,
          y: 2
        }
      }
    }
};

How I can declare an interface for this kind of variable?

Body:
You can declare the type of Scenes as:

type Points = {
  [key: string]: {
    x: number;
    y: number;
  }
}

type Scenes = {
  [key: string]: {
    image: string;
    points: Points;
  }
}

let scenes: Scenes = {
    sky: {
      image: 'assets/1.jpg',
      points: {
        blue_area: {
          x: 1,
          y: 2
        },
      }
    },
    blue_area: {
      image: 'assets/2.jpg',
      points: {
        sky: {
          x: 1,
          y: 2
        }
      }
    }
};


答:
This is because in the first case, you are running a setter on tags (because you are reassigning it) - which Vue has wrapped and can detect. In the second case, you're running setters on nested properties that were not in your data: { tags: { definition, so they are not reactive.

The Change Detection Caveats section in the documentation covers this, though not exactly the same as your case (the nested properties situation). You would have to declare your data like:

```<code>data: {
  tags: {
    hello: null,
    world: null,
  }
}
</code>```

Title: How to update reactive Objects (and properties in general)?

Body:
This is because in the first case, you are running a setter on tags (because you are reassigning it) - which Vue has wrapped and can detect. In the second case, you're running setters on nested properties that were not in your data: { tags: { definition, so they are not reactive.

The Change Detection Caveats section in the documentation covers this, though not exactly the same as your case (the nested properties situation). You would have to declare your data like:

data: {
  tags: {
    hello: null,
    world: null,
  }
}


问:
Form not submitted in laravel?
I want to submit the form to usercontroller file and call function invitebyemail.

When I click on submit it gives me error like "Whoops, looks like something went wrong."

Below are the structure of my Files and code.

Route File:

```<code>Route::POST('event/inviteforevent', 'UserController@invitebyemail');
</code>```

Blade.php file

```<code>    <form action="{{ route('inviteforevent') }}" method="POST">
    <input type="email" class="form-control full-width" id="add-members-event-email" name="email" placeholder="Email address">
    <input type="hidden" class="form-control full-width" name="eventid" value="{{ $event->id }}" >
    <input type="submit" name="invite" value="submit" />
    </form>
</code>```

UserController File:

```<code>public function invitebyemail(Request $request){
 $event = Event::find($request->eventid);
 $timelineId = $event->timeline_id;
 $username = Auth::user()->username;
 $timelines = Timeline::find($timelineId);
  return redirect()->back()->with('message', 'Invitation send to user by email.');
 }
</code>```

答:
You have to add {{ csrf_field() }} which was suggested but one question? Where is your table names and id in your form opening? How that form have to know which table you want to add data in?
You have to add $events and $events->id into your form

Title: Form not submitted in laravel?

Body:
I want to submit the form to usercontroller file and call function invitebyemail.

When I click on submit it gives me error like "Whoops, looks like something went wrong."

Below are the structure of my Files and code.

Route File:

Route::POST('event/inviteforevent', 'UserController@invitebyemail');

Blade.php file

    <form action="{{ route('inviteforevent') }}" method="POST">
    <input type="email" class="form-control full-width" id="add-members-event-email" name="email" placeholder="Email address">
    <input type="hidden" class="form-control full-width" name="eventid" value="{{ $event->id }}" >
    <input type="submit" name="invite" value="submit" />
    </form>

UserController File:

public function invitebyemail(Request $request){
 $event = Event::find($request->eventid);
 $timelineId = $event->timeline_id;
 $username = Auth::user()->username;
 $timelines = Timeline::find($timelineId);
  return redirect()->back()->with('message', 'Invitation send to user by email.');
 }


问:
Can't make Mypy work with __init__.py aliases
Below is the minimal example of my problem:

```<code>[test/__init__.py]
from test.test1 import Test1
from test.test2 import Test2

[test/test1.py]
class Test1:
    pass

[test/test2.py]
from test import Test1

class Test2:
    pass
</code>```

Mypy output for module or __init__.py:

```<code>test/test2.py:1: error: Module 'test' has no attribute 'Test1'
</code>```

Code itself works well both on Python 2 and Python 3.

答:
This is because your code has an import cycle -- in order for mypy to parse test/__init__.py, it needs to understand exactly what Test2 is. (After all, what if you decide to use Test2 later on in that file/call one of its methods? Then mypy needs to know what the output is).

So, it hits that import, effectively pauses, and jumps to trying to understand what test/test2.py is doing*.

But within test/test2.py, we run into the exact same problem -- we see the import, and need to jump back to test/__init__.py in order to understand what Test1 is... But we haven't finished parsing that file!

This is where mypy differs from the Python runtime, fyi -- mypy can only parse entire files at a time, but the Python runtime will actually pause execution to run test/test2.py. That means when you do from test import Test1, the test module has a partially complete symbol space that happens to currently contain only Test1, instead of both Test1 and Test2, which is why your code works at runtime.

The fix, in this case, would be to modify the import in test/test2.py to:

```<code>from test.test1 import Test1
</code>```

This breaks the import cycle.

*This isn't actually what mypy does -- what it actually does is attempt to resolve import cycles by first identifying all strongly connected components (SCC) -- each SCC is basically an import cycle.

It then applies some heuristics to determine the order in which the files within the SCC should be processed, but it's an imperfect process and can't resolve all import cycles.

For example, in your case, whether we process test or test.test2 first, we're going to run into issues.

You can see the SCCs mypy identifies by re-running mypy using the -v flag (for verbose mode).

You can find more details about the algorithm mypy uses within the source code here. Specific details about the import cycle resolution algorithm can be found a little lower down, here.

(I suspect this entire comment is slightly out-of-date/incomplete, fyi -- there are several other wrinkles related to mypy's silent import mechanism and its incremental mode mechanism that aren't really explained.)

Info about the exact heuristics mypy uses to order SCCs can be found here. (Basically, the exact syntax we use for importing something can give some hints about how that SCC should be ordered).

Body:
Below is the minimal example of my problem:

[test/__init__.py]
from test.test1 import Test1
from test.test2 import Test2

[test/test1.py]
class Test1:
    pass

[test/test2.py]
from test import Test1

class Test2:
    pass

Mypy output for module or __init__.py:

test/test2.py:1: error: Module 'test' has no attribute 'Test1'

Code itself works well both on Python 2 and Python 3.

Body:
This is because your code has an import cycle -- in order for mypy to parse test/__init__.py, it needs to understand exactly what Test2 is. (After all, what if you decide to use Test2 later on in that file/call one of its methods? Then mypy needs to know what the output is).

So, it hits that import, effectively pauses, and jumps to trying to understand what test/test2.py is doing*.

But within test/test2.py, we run into the exact same problem -- we see the import, and need to jump back to test/__init__.py in order to understand what Test1 is... But we haven't finished parsing that file!

This is where mypy differs from the Python runtime, fyi -- mypy can only parse entire files at a time, but the Python runtime will actually pause execution to run test/test2.py. That means when you do from test import Test1, the test module has a partially complete symbol space that happens to currently contain only Test1, instead of both Test1 and Test2, which is why your code works at runtime.

The fix, in this case, would be to modify the import in test/test2.py to:

from test.test1 import Test1

This breaks the import cycle.

*This isn't actually what mypy does -- what it actually does is attempt to resolve import cycles by first identifying all strongly connected components (SCC) -- each SCC is basically an import cycle.

It then applies some heuristics to determine the order in which the files within the SCC should be processed, but it's an imperfect process and can't resolve all import cycles.

For example, in your case, whether we process test or test.test2 first, we're going to run into issues.

You can see the SCCs mypy identifies by re-running mypy using the -v flag (for verbose mode).

You can find more details about the algorithm mypy uses within the source code here. Specific details about the import cycle resolution algorithm can be found a little lower down, here.

(I suspect this entire comment is slightly out-of-date/incomplete, fyi -- there are several other wrinkles related to mypy's silent import mechanism and its incremental mode mechanism that aren't really explained.)

Info about the exact heuristics mypy uses to order SCCs can be found here. (Basically, the exact syntax we use for importing something can give some hints about how that SCC should be ordered).


问:
Recycle work good or not? in onDestroy()
I have question about use my recycle bitmap in imageview.

I use this code for recycle image in imageview.

```<code>drawable = imglist1.getDrawable();
    if (drawable instanceof BitmapDrawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        Bitmap bitmap = bitmapDrawable.getBitmap();
        bitmap.recycle();
    }
</code>```

I call it in onDestroy method

```<code>@Override
    protected void onDestroy() {
    super.onDestroy();
         ...
    }
</code>```

I have in imageviews images (bitmap)
when open new activity (call onDestroy() )

after open new activity can't seen changes In android monitor memory.

android monitor

How Can control if recycle work good, or how can decreas memory?

memory it's from the most part bitmaps in imageviews.

Thanks for ideas

答:
After marking a bitmap as recyclable, it will only be freed when GC execute.
Here you have more info: Android: Bitmap recycle() how does it work?

But your question is pretty unclear. If you are recycling bitmaps in the onDestroy, it does not make sense because in the onDestroy all views will be freed and the reference for the bitmap too, so it will be GCed in the next execution.

Probably the best option for you is to resample your images. The link I posted have more info.

Body:
I have question about use my recycle bitmap in imageview.

I use this code for recycle image in imageview.

drawable = imglist1.getDrawable();
    if (drawable instanceof BitmapDrawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        Bitmap bitmap = bitmapDrawable.getBitmap();
        bitmap.recycle();
    }

I call it in onDestroy method

@Override
    protected void onDestroy() {
    super.onDestroy();
         ...
    }

I have in imageviews images (bitmap)
when open new activity (call onDestroy() )

after open new activity can't seen changes In android monitor memory.

android monitor

How Can control if recycle work good, or how can decreas memory?

memory it's from the most part bitmaps in imageviews.

Thanks for ideas


问:
Linking issue with indirect dependencies on Mac OS X
we have some linking problems with indirect dependencies. Guessing from what I read on the web it may be because of two-level namespace usage.
This happens when we link against a boost library, boost_filesystem to be precise, which itself depends on boost_system. The linker doesn't resolve the dependency between boost_filesystem and boost_system.
Can someone give me some hints how this can be resolved? Adding boost_system manually to the dependencies feels ugly and besides, it works fine on other platforms.</p>

答:
If boost_filesystem is using symbols from boost_system (and your application isn't), and is itself linking directly against boost_system to resolve them, it should just work. The flat vs. two-level namespace problems generally rear their head when you expect symbols provided by a dependency of a library you're linking against to be available within your app.

If boost_filesystem isn't linking against boost_system (otool -L will tell you), then you've got little option—short of relinking it—except to add a manual dependency upon boost_system.

Am I right in thinking boost doesn't use GNU libtool (it handles inter-library dependencies in the correct platform-specific way for you)? If it does, that might be an easy workaround.

OwnerDisplayName: cgTobi

OwnerDisplayName: Mo