问:
Make switch, case structure in assembly
How to make switch, case structure in assembler? What is right way or more corect?

This is my code in C, what I want to write in assembler.

```<code>if (diode_on == 1)
    {
        switch(diode_num)
            {
            case 0:
                //score += 3;
                break;

            case 1:
                //score += 3;
                break;

            case 2:
                //score += 3;
                break;

            case 3:
                //score += 3;
                break;

            default:
                break;
            }
        diode_on = 0;
    }
</code>```

I need this for my project, MMSP430F5XX. The condition of the project is that one breaking routin is written in assembler. And this is code of breaking routin in C, what I try to write in assembler.

```<code>    #pragma vector=PORT2_VECTOR
__interrupt void port2handler(void)
{
    __delay_cycles(1000);

    if (diode_on == 1)
    {
        switch(diode_num)
            {
            case 0:
                if((P2IFG & BIT4)!=0)
                {
                    if ((P2IN & BIT4)==0)
                        //score += 3;
                        calculationScore(3);
                }
                else
                    //score--;
                    calculationScore(-1);
                break;

            case 1:
                if((P2IFG & BIT5)!=0)
                {
                    if ((P2IN & BIT5)==0)
                        //score += 3;
                        calculationScore(3);
                }
                else
                    //score--;
                    calculationScore(-1);
                break;

            case 2:
                if((P2IFG & BIT6)!=0)
                {
                    if ((P2IN & BIT6)==0)
                        //score += 3;
                        calculationScore(3);
                }
                else
                    //score--;
                    calculationScore(-1);
                break;

            case 3:
                if((P2IFG & BIT7)!=0)
                {
                    if ((P2IN & BIT7)==0)
                        //score += 3;
                        calculationScore(3);
                }
                else
                    //score--;
                    calculationScore(-1);
                break;

            default:
                break;
            }

        P4OUT &= ~(BIT3 | BIT4 | BIT5 | BIT6);          //gasimo diode
        diode_on = 0;
    }

    P2IFG &= ~(BIT4 | BIT5 | BIT6 | BIT7);              // brisanje flega
}
</code>```

答:
What did you see when you compiled this? How did your compiler solve it?

Off the top of my head there are three simple ways to implement this but not all can be used.  First and foremost an if-then-else tree will always work, and depending on your case values is sometimes the only sane way to do it.

Everything else beyond that is "it depends" so say for example you took your comments out and you wanted 0,1,2,3 to add three to the score and all other values not...AND...diode_num could be any one of those numbers or some other value like 75. or even 4.  then you could/implement this as:

```<code>if(diode_num&3) goto skip;
score+=3;
skip:
</code>```

of course in C (without the goto if you prefer) or in the syntax for your assembly language whatever target this is.

if the code you provided is such that diode_num can only be 0,1,2,3 then this is not dead code, but it optimizes down to score+=3 for all cases and the switch goes away.

assuming that is not the case another "it depends" is a jump table which not only depends on your case values but also depends on the instruction set and depends on all the possible values that can come in, say for example outside the code you have provided and assuming you actually did something for each case as the code you have provided is mostly dead code it becomes

```<code>if(diode_on == 1) diode_on = 0;
</code>```

you should have provided a better example.  but if the compiler and optimizer can see code you have not provided and lets say finds that the possible range of values for diode_num is 0-7 and you want to do something special for each of 0,1,2,3 and a jump table is possible in this instruction set you have not specified, then

```<code>load some_register,table_base_add
shift_left temp_register,diode_num,2 ;assuming 32 bit addresses
add some_register,temp_register
load another_register,[some_register]
branch_to another_register

table_base_add: .word table_base
.align
;jump table
table_base:
.word case0
.word case1
.word case2
.word case3
.word switch_end
.word switch_end
.word switch_end
.word switch_end

;case 0 code
case0:
do something
b switch_end
;case 1 code
case1:
do something
b switch_end
;case 2 code
case2:
do something
b switch_end
;case 3 code
case3:
do something
b switch_end
switch_end:
code after switch
</code>```

if the compiler cannot determine the range of input values it may or may not choose to try a jump table.

you can make it even more optimized, lets say the range of diode_num was strictly 0,1,2,3 and you wanted to do something different for each case but it was very simple and in this case I am using fixed sized instructions for this further optimization.

```<code>load some_register,base_add
shift_left temp_register,diode_num,4
add some_register,temp_register
branch_to some_register

base_add: .word base
base:
    ;case 0 code
    one instruction
    b switch_end
    nop
    nop
    ;case 1 code
    one instruction
    one instruction
    one instruction
    b switch_end
    ;case 2 code
    one instruction
    one instruction
    b switch_end
    nop
    ;case 3 code
    one instruction
    nop
    nop
    b switch_end
    switch_end:
</code>```

in this case assuming 16 bytes (four 32 bit words) per case you could just add or or the case times 16 to the base address and jump there, no jump table required just math.  if the cases were 1,2,3,4 you could subtract one then multiply by 16 (shift left 4) then add to base and jump there.

Since you are the optimizing compiler then you can always use an if then else tree to implement this, or if you know more about the specifics of the range of inputs, the number of cases, amount of code per case (which is the first thing you should code and build the skeleton around it) and instruction set then you can maybe optimize.

Title: Make switch, case structure in assembly

Body:
How to make switch, case structure in assembler? What is right way or more corect?

This is my code in C, what I want to write in assembler.

if (diode_on == 1)
    {
        switch(diode_num)
            {
            case 0:
                //score += 3;
                break;

            case 1:
                //score += 3;
                break;

            case 2:
                //score += 3;
                break;

            case 3:
                //score += 3;
                break;

            default:
                break;
            }
        diode_on = 0;
    }

I need this for my project, MMSP430F5XX. The condition of the project is that one breaking routin is written in assembler. And this is code of breaking routin in C, what I try to write in assembler.

    #pragma vector=PORT2_VECTOR
__interrupt void port2handler(void)
{
    __delay_cycles(1000);

    if (diode_on == 1)
    {
        switch(diode_num)
            {
            case 0:
                if((P2IFG & BIT4)!=0)
                {
                    if ((P2IN & BIT4)==0)
                        //score += 3;
                        calculationScore(3);
                }
                else
                    //score--;
                    calculationScore(-1);
                break;

            case 1:
                if((P2IFG & BIT5)!=0)
                {
                    if ((P2IN & BIT5)==0)
                        //score += 3;
                        calculationScore(3);
                }
                else
                    //score--;
                    calculationScore(-1);
                break;

            case 2:
                if((P2IFG & BIT6)!=0)
                {
                    if ((P2IN & BIT6)==0)
                        //score += 3;
                        calculationScore(3);
                }
                else
                    //score--;
                    calculationScore(-1);
                break;

            case 3:
                if((P2IFG & BIT7)!=0)
                {
                    if ((P2IN & BIT7)==0)
                        //score += 3;
                        calculationScore(3);
                }
                else
                    //score--;
                    calculationScore(-1);
                break;

            default:
                break;
            }

        P4OUT &= ~(BIT3 | BIT4 | BIT5 | BIT6);          //gasimo diode
        diode_on = 0;
    }

    P2IFG &= ~(BIT4 | BIT5 | BIT6 | BIT7);              // brisanje flega
}

Body:
What did you see when you compiled this? How did your compiler solve it?

Off the top of my head there are three simple ways to implement this but not all can be used.  First and foremost an if-then-else tree will always work, and depending on your case values is sometimes the only sane way to do it.

Everything else beyond that is "it depends" so say for example you took your comments out and you wanted 0,1,2,3 to add three to the score and all other values not...AND...diode_num could be any one of those numbers or some other value like 75. or even 4.  then you could/implement this as:

if(diode_num&3) goto skip;
score+=3;
skip:

of course in C (without the goto if you prefer) or in the syntax for your assembly language whatever target this is.

if the code you provided is such that diode_num can only be 0,1,2,3 then this is not dead code, but it optimizes down to score+=3 for all cases and the switch goes away.

assuming that is not the case another "it depends" is a jump table which not only depends on your case values but also depends on the instruction set and depends on all the possible values that can come in, say for example outside the code you have provided and assuming you actually did something for each case as the code you have provided is mostly dead code it becomes

if(diode_on == 1) diode_on = 0;

you should have provided a better example.  but if the compiler and optimizer can see code you have not provided and lets say finds that the possible range of values for diode_num is 0-7 and you want to do something special for each of 0,1,2,3 and a jump table is possible in this instruction set you have not specified, then

load some_register,table_base_add
shift_left temp_register,diode_num,2 ;assuming 32 bit addresses
add some_register,temp_register
load another_register,[some_register]
branch_to another_register

table_base_add: .word table_base
.align
;jump table
table_base:
.word case0
.word case1
.word case2
.word case3
.word switch_end
.word switch_end
.word switch_end
.word switch_end

;case 0 code
case0:
do something
b switch_end
;case 1 code
case1:
do something
b switch_end
;case 2 code
case2:
do something
b switch_end
;case 3 code
case3:
do something
b switch_end
switch_end:
code after switch

if the compiler cannot determine the range of input values it may or may not choose to try a jump table.

you can make it even more optimized, lets say the range of diode_num was strictly 0,1,2,3 and you wanted to do something different for each case but it was very simple and in this case I am using fixed sized instructions for this further optimization.

load some_register,base_add
shift_left temp_register,diode_num,4
add some_register,temp_register
branch_to some_register

base_add: .word base
base:
    ;case 0 code
    one instruction
    b switch_end
    nop
    nop
    ;case 1 code
    one instruction
    one instruction
    one instruction
    b switch_end
    ;case 2 code
    one instruction
    one instruction
    b switch_end
    nop
    ;case 3 code
    one instruction
    nop
    nop
    b switch_end
    switch_end:

in this case assuming 16 bytes (four 32 bit words) per case you could just add or or the case times 16 to the base address and jump there, no jump table required just math.  if the cases were 1,2,3,4 you could subtract one then multiply by 16 (shift left 4) then add to base and jump there.

Since you are the optimizing compiler then you can always use an if then else tree to implement this, or if you know more about the specifics of the range of inputs, the number of cases, amount of code per case (which is the first thing you should code and build the skeleton around it) and instruction set then you can maybe optimize.


来源: stackexchange

答:
There is problem you have duplicated values in Stock column, duplicates starts with 1.

You can check it by:

```<code>print (df_mo[df_mo['Stock'].duplicated(keep=False)])
print (df_active[df_active['Stock'].duplicated(keep=False)])
</code>```

Solution is remove duplicates. E.g.:

```<code>df_active = df_active.drop_duplicates('Stock')
df_mo= df_mo.drop_duplicates('Stock')
</code>```

Sample:

```<code>print (df_mo)
  Stock  Momentum_
0   1A0        0.0
0   1A0        0.0
0   1A0        0.0
1   1A1        0.0
2   1A4        0.0
3   1A4        0.0

print (df_active)
  Stock  Active
0   1A0    0.35
0   1A0    0.55
1   1A1    0.35
2   1A4   -0.35
3   1A4    0.50

df = pd.merge(df_mo,df_active,how='outer',on='Stock')
print (df)
   Stock  Momentum_  Active
0    1A0        0.0    0.35
1    1A0        0.0    0.55
2    1A0        0.0    0.35
3    1A0        0.0    0.55
4    1A0        0.0    0.35
5    1A0        0.0    0.55
6    1A1        0.0    0.35
7    1A4        0.0   -0.35
8    1A4        0.0    0.50
9    1A4        0.0   -0.35
10   1A4        0.0    0.50
</code>```

```<code>print (df_mo[df_mo['Stock'].duplicated(keep=False)])
  Stock  Momentum_
0   1A0        0.0
0   1A0        0.0
0   1A0        0.0
2   1A4        0.0
3   1A4        0.0

print (df_active[df_active['Stock'].duplicated(keep=False)])
  Stock  Active
0   1A0    0.35
0   1A0    0.55
2   1A4   -0.35
3   1A4    0.50
</code>```

```<code>df_active = df_active.drop_duplicates('Stock')
df_mo= df_mo.drop_duplicates('Stock')

df = pd.merge(df_mo,df_active,how='outer',on='Stock')
print (df)
  Stock  Momentum_  Active
0   1A0        0.0    0.35
1   1A1        0.0    0.35
2   1A4        0.0   -0.35
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python: Pandas dataframe merge duplicates for item start with '1'

Body:
This is really weird as this only happen when merge two dataframe that has Stock start with '1'

>>> df_mo
    Stock  Momentum_
0     1A0       0.00
1     1A1       0.00
2     1A4       0.00
3     1B0       0.00
4     1B1       0.15
5     1B6       0.00
6     1C0       0.00
7     1C3       0.00
8     1C5       0.00
9     1D0       0.00
10    1D1       0.00
11    1D3      -0.50
12    1D4       0.00
13    1D5       0.00
14    1D8       0.00
15    40B      -0.15
16    40D       0.00
17    40E       0.00
18    40F       0.00
19    40N       0.00
20    40R       0.00
21    40S       0.15
22    40T       0.15
23    40U       0.00
24    40V       0.00
25    40W       0.00
26    41A       0.00
27    41B       0.15
28    41F       0.00
29    41H       0.00
..    ...        ...
757  T8JU       0.00
758   T8V       0.00
759   TQ5       0.00
760  TS0U       0.00
761   U04       0.00
762   U06       0.00
763   U09       0.00
764   U10       0.00
765   U11       0.00
766   U13       0.00
767   U14       0.00
768   U6C       0.00
769   U77       0.00
770   U96       0.00
771   U9E       0.00
772  UD1U       0.00
773   UD2       0.00
774   UV1       0.00
775   V01       0.00
776   V03       0.00
777   W05       0.00
778   Y03       0.00
779   Y06       0.00
780   Y35       0.00
781   Y45       0.00
782   Y92       0.00
783   Z25       0.00
784   Z59       0.00
785   Z74       0.00
786   Z77       0.00
[787 rows x 2 columns]

>>> df_active
    Stock  Active
0     1A0    0.35
1     1A1    0.35
2     1A4   -0.35
3     1B0    0.50
4     1B1   -0.35
5     1B6   -0.35
6     1C0    0.50
7     1C3   -0.35
8     1C5    0.35
9     1D0   -0.50
10    1D1    0.50
11    1D3    0.35
12    1D4   -0.50
13    1D5    0.35
14    1D8   -0.50
15    40B    0.35
16    40D   -0.35
17    40E   -0.50
18    40F   -0.35
19    40N    0.35
20    40R    0.25
21    40S    0.50
22    40T    0.50
23    40U    0.35
24    40V    0.35
25    40W   -0.35
26    41A   -0.35
27    41B   -0.35
28    41F    0.50
29    41H   -0.50
..    ...     ...
757  T8JU    0.35
758   T8V    0.35
759   TQ5   -0.50
760  TS0U    0.50
761   U04    0.50
762   U06    0.50
763   U09   -0.50
764   U10    0.50
765   U11    0.50
766   U13   -0.35
767   U14    0.50
768   U6C   -0.25
769   U77   -0.25
770   U96   -0.50
771   U9E   -0.50
772  UD1U    0.50
773   UD2   -0.50
774   UV1   -0.35
775   V01   -0.50
776   V03    0.50
777   W05    0.25
776   V03    0.50
778   Y03    0.20
779   Y06   -0.35
780   Y35    0.35
781   Y45   -0.25
782   Y92    0.50
783   Z25    0.50
784   Z59    0.50
785   Z74   -0.35
786   Z77    0.50
[787 rows x 2 columns]

But when I merged these two dataframe, the Stock that start with '1' all duplicated for 3 times extra.

>>> pd.merge(df_mo,df_active,how='outer',on='Stock')
    Stock  Momentum_  Active
11    1A4       0.00   -0.35
0     1A0       0.00    0.35
1     1A0       0.00    0.35
2     1A0       0.00    0.35
3     1A0       0.00    0.35
4     1A1       0.00    0.35
5     1A1       0.00    0.35
6     1A1       0.00    0.35
7     1A1       0.00    0.35
8     1A4       0.00   -0.35
9     1A4       0.00   -0.35
10    1A4       0.00   -0.35
11    1A4       0.00   -0.35
12    1B0       0.00    0.50
13    1B0       0.00    0.50
14    1B0       0.00    0.50
15    1B0       0.00    0.50
16    1B1       0.15   -0.35
17    1B1       0.15   -0.35
18    1B1       0.15   -0.35
19    1B1       0.15   -0.35
20    1B6       0.00   -0.35
21    1B6       0.00   -0.35
22    1B6       0.00   -0.35
23    1B6       0.00   -0.35
24    1C0       0.00    0.50
25    1C0       0.00    0.50
26    1C0       0.00    0.50
27    1C0       0.00    0.50
28    1C3       0.00   -0.35
29    1C3       0.00   -0.35
..    ...        ...     ...
787  T8JU       0.00    0.35
788   T8V       0.00    0.35
789   TQ5       0.00   -0.50
790  TS0U       0.00    0.50
791   U04       0.00    0.50
792   U06       0.00    0.50
793   U09       0.00   -0.50
794   U10       0.00    0.50
795   U11       0.00    0.50
796   U13       0.00   -0.35
797   U14       0.00    0.50
798   U6C       0.00   -0.25
799   U77       0.00   -0.25
800   U96       0.00   -0.50
801   U9E       0.00   -0.50
802  UD1U       0.00    0.50
803   UD2       0.00   -0.50
804   UV1       0.00   -0.35
805   V01       0.00   -0.50
806   V03       0.00    0.50
807   W05       0.00    0.25
808   Y03       0.00    0.20
809   Y06       0.00   -0.35
810   Y35       0.00    0.35
811   Y45       0.00   -0.25
812   Y92       0.00    0.50
813   Z25       0.00    0.50
814   Z59       0.00    0.50
815   Z74       0.00   -0.35
816   Z77       0.00    0.50
[817 rows x 3 columns]

As the merge result make it more row. I have many dataframe that need to merge and thus this end up much more rows that it supposed to.

The code actually works well for number start with '4' or any other number or string. It just has some issues for number start with '1'.

How to make it only able to merge correctly?

Body:
There is problem you have duplicated values in Stock column, duplicates starts with 1.

You can check it by:

print (df_mo[df_mo['Stock'].duplicated(keep=False)])
print (df_active[df_active['Stock'].duplicated(keep=False)])

Solution is remove duplicates. E.g.:

df_active = df_active.drop_duplicates('Stock')
df_mo= df_mo.drop_duplicates('Stock')

Sample:

print (df_mo)
  Stock  Momentum_
0   1A0        0.0
0   1A0        0.0
0   1A0        0.0
1   1A1        0.0
2   1A4        0.0
3   1A4        0.0

print (df_active)
  Stock  Active
0   1A0    0.35
0   1A0    0.55
1   1A1    0.35
2   1A4   -0.35
3   1A4    0.50

df = pd.merge(df_mo,df_active,how='outer',on='Stock')
print (df)
   Stock  Momentum_  Active
0    1A0        0.0    0.35
1    1A0        0.0    0.55
2    1A0        0.0    0.35
3    1A0        0.0    0.55
4    1A0        0.0    0.35
5    1A0        0.0    0.55
6    1A1        0.0    0.35
7    1A4        0.0   -0.35
8    1A4        0.0    0.50
9    1A4        0.0   -0.35
10   1A4        0.0    0.50

print (df_mo[df_mo['Stock'].duplicated(keep=False)])
  Stock  Momentum_
0   1A0        0.0
0   1A0        0.0
0   1A0        0.0
2   1A4        0.0
3   1A4        0.0

print (df_active[df_active['Stock'].duplicated(keep=False)])
  Stock  Active
0   1A0    0.35
0   1A0    0.55
2   1A4   -0.35
3   1A4    0.50

df_active = df_active.drop_duplicates('Stock')
df_mo= df_mo.drop_duplicates('Stock')

df = pd.merge(df_mo,df_active,how='outer',on='Stock')
print (df)
  Stock  Momentum_  Active
0   1A0        0.0    0.35
1   1A1        0.0    0.35
2   1A4        0.0   -0.35


问:
Get/Set global variable in Class in Laravel
I can't understand how to  make global variable, that I can in future change its value and get it over and over again?
My controller Example:

```<code>public function getProducts()
{
    // some stuff
    $products = SQLquery;
    config(['memoProducts' => $products]);
    $value = config('memoProducts');
    dd($value)//returns what I need

}

public function setProducts()
{
    //here I try to get $products from previous function
    $value = config('memoProducts');
    dd($value)//returns null
}
</code>```

What's my problem?

PS: thanks for thinking that I'm stupid af and minusing my question all day long, even though none of your answers  seem to help. Thanks a lot

答:
There are many ways to set and get global variables, one of them would be setting to config

```<code>config(['app.timezone' => 'America/Chicago']);
</code>```

and reading that value from config

```<code>$value = config('app.timezone', 'fallback value');
</code>```

Documentation

EDIT

Configuration values that are set at run-time are only set for the current request, and will not be carried over to subsequent requests.

so you could use other techniques like Cache

```<code>public function setProducts()
{
    $products = SQLquery;
    Cache::put('products', $products, 60); // Third parameter is the time limit
}

public function getProducts()
{
    //here I try to get $products from previous function
    $products = Cache::get('products');
}
</code>```

or use Session

```<code>public function setProducts()
{
    $products = SQLquery;
    session(['products' => $products]);
}

public function getProducts()
{
    //here I try to get $products from previous function
    $products = session('products');
}
</code>```

Body:
I can't understand how to  make global variable, that I can in future change its value and get it over and over again?
My controller Example:

public function getProducts()
{
    // some stuff
    $products = SQLquery;
    config(['memoProducts' => $products]);
    $value = config('memoProducts');
    dd($value)//returns what I need

}

public function setProducts()
{
    //here I try to get $products from previous function
    $value = config('memoProducts');
    dd($value)//returns null
}

What's my problem?

PS: thanks for thinking that I'm stupid af and minusing my question all day long, even though none of your answers  seem to help. Thanks a lot

Body:
There are many ways to set and get global variables, one of them would be setting to config

config(['app.timezone' => 'America/Chicago']);

and reading that value from config

$value = config('app.timezone', 'fallback value');

Documentation

EDIT

Configuration values that are set at run-time are only set for the current request, and will not be carried over to subsequent requests.

so you could use other techniques like Cache

public function setProducts()
{
    $products = SQLquery;
    Cache::put('products', $products, 60); // Third parameter is the time limit
}

public function getProducts()
{
    //here I try to get $products from previous function
    $products = Cache::get('products');
}

or use Session

public function setProducts()
{
    $products = SQLquery;
    session(['products' => $products]);
}

public function getProducts()
{
    //here I try to get $products from previous function
    $products = session('products');
}


问:
How to embed a UserControl in WIX installer?
Is there anyway to embed a usercontrol inside a WIX installer?

We're trying to replace an InstallShield installer with a WIX installer, however there are a couple of involved UserControls that the InstallShield installer embeds that would be easier to reuse than reimplement.

答: While you can wait for Burn (as mentioned in the other answers) you can also check out a program of mine called SharpSetup - it allows you to create installation logic using WiX (files, folders, registry entries, etc.) but create whole user interface using WinForms. This gives you great flexibility in what controls you can use (basically everything you have on VS toolbar), including custom UserControls.</p>

ContentLicense: CC BY-SA 2.5


问:
C++ generate random number based on mathematical equations.
I have three positive integers

distance1

distance2

distnace3

that sum up to 100.

distance1 + distance2 + distance3 = 100 (EQ1)

I have  additional information that

20 < distance2 < 90 (EQ2) and

distance1 + distance3 > 8 (EQ3)

I need in C++ to calculate fast three positive random values for distance1, distance2 and distance3 in order to support the equations EQ1, EQ2 and EQ3.

My first approach was to do the following

```<code>    std::list<...> solutions;
    //i for distance1, j for distance2, z for distance3
    for (int i = 1; i < 101; i++) {

       for (int j = 1; j < 101; j++)  {

           for (int z = 1; z < 101; z++)  {

              evaluate if i, j, z satisfy EQ1, EQ2,EQ3
              if ( evaluate == true )
                solutions.push_back(...i,j,z...); //pseudocode

           }
       }

    }
// when all iterations are finished select a random from std::<list>
</code>```

Any better approach to do this? Is there any library that can help? Is this the correct way to perform combinations?

答:
distance1 + distance3 > 8 (EQ3)

If we take distance3 as 8, EQ3 holds good since distance1 is a positive number (>= 1).

20 < distance2 < 90 (EQ2)

Let distance2 be 21

Now calculate distance3 = 100 - distance1 - distance2. (constant value)

No need of generating random numbers ;)

If you really need that, just increment one of the variables by k and decrement the other by the same to achieve another combination. Just make sure this doesn't break EQ2.

Body:
I have three positive integers

distance1

distance2

distnace3

that sum up to 100.

distance1 + distance2 + distance3 = 100 (EQ1)

I have  additional information that

20 < distance2 < 90 (EQ2) and

distance1 + distance3 > 8 (EQ3)

I need in C++ to calculate fast three positive random values for distance1, distance2 and distance3 in order to support the equations EQ1, EQ2 and EQ3.

My first approach was to do the following

    std::list<...> solutions;
    //i for distance1, j for distance2, z for distance3
    for (int i = 1; i < 101; i++) {

       for (int j = 1; j < 101; j++)  {

           for (int z = 1; z < 101; z++)  {

              evaluate if i, j, z satisfy EQ1, EQ2,EQ3
              if ( evaluate == true )
                solutions.push_back(...i,j,z...); //pseudocode

           }
       }

    }
// when all iterations are finished select a random from std::<list>

Any better approach to do this? Is there any library that can help? Is this the correct way to perform combinations?


问:
Index versioning with Lucene.net
We are using Lucene to index objects from a RabbitMQ queue, in the event that there are multiple versions of the same object in RabbitMQ we will only ever have one document for it as we use updatedocument(which will find and delete existing records based on a search term and create a new one).

What i would like to do is have a way of ensuring the index is of the most recent object, so if for instance we have 2 updates of an object to RabbitMQ and they are pulled from RabbitMQ out of order, if i have the field 'Version' with the values 1 and 2, is there a way to tell Lucene "dont update document if this document version is lower than the existing document"?

Thanks

答:
In the event anyone else has a similar problem, ended up searching the index before updating. It's not the most efficient method but it gets the job done:

```<code>var doc = (from d in results
                       let ver = long.Parse(d.GetField("Version").StringValue)
                       where ver < model._Version
                       orderby ver descending
                       select d).FirstOrDefault();
</code>```

and then we update using the resulting doc.

Title: Index versioning with Lucene.net

Body:
In the event anyone else has a similar problem, ended up searching the index before updating. It's not the most efficient method but it gets the job done:

var doc = (from d in results
                       let ver = long.Parse(d.GetField("Version").StringValue)
                       where ver < model._Version
                       orderby ver descending
                       select d).FirstOrDefault();

and then we update using the resulting doc.


答:
You need to disable the automatic HTML escaping when injecting encoded JSON like that. You also don't need the surrounding " or brackets.

```<code>var theData = <%= raw Poison.Encoder.encode(@nodes, []) %>;
</code>```

There's no need to call JSON.parse anymore, theData will be set to the value itself, not a string containing a JSON.

Title: Unexpected token & in JSON when parsing object from string

Body:
I tried to parse data from elixir map converted to JSON using Poison.encode!(), in any case I got error:

Unexpected token & in JSON at position 1

How to escape double quotes inside this string, to prevent adding  "&quote;"?

Initial data:

%{"node_10_10@172.17.0.11" => ["40000000-5fffffff", "a0000000-bfffffff"],
  "node_1_10@172.17.0.2" => ["20000000-3fffffff", "a0000000-bfffffff"],
  "node_2_10@172.17.0.3" => ["20000000-3fffffff", "80000000-9fffffff"],
  "node_3_10@172.17.0.4" => ["20000000-3fffffff", "80000000-9fffffff",
   "e0000000-ffffffff"],
  "node_4_10@172.17.0.5" => ["00000000-1fffffff", "80000000-9fffffff",
   "e0000000-ffffffff"],
  "node_5_10@172.17.0.6" => ["00000000-1fffffff", "60000000-7fffffff",
   "e0000000-ffffffff"],
  "node_6_10@172.17.0.7" => ["00000000-1fffffff", "60000000-7fffffff",
   "c0000000-dfffffff"],
  "node_7_10@172.17.0.8" => ["60000000-7fffffff", "c0000000-dfffffff"],
  "node_8_10@172.17.0.9" => ["40000000-5fffffff", "c0000000-dfffffff"],
  "node_9_10@172.17.0.10" => ["40000000-5fffffff", "a0000000-bfffffff"]}

Mapped to new structure, using this method inside controller:

defp map_shards(nodes, :nodes), do: %{"nodes": Enum.map(nodes, fn{k, v} -> %{"node": k, "shards": v} end)}

Call inside index action:

nodes = map_shards(resp["by_node"], :nodes)

Now I have map as this:

%{nodes: [%{node: "node_10_10@172.17.0.11", shards: ["40000000-5fffffff", "a0000000-bfffffff"]}, %{node: "node_1_10@172.17.0.2", shards: ["20000000-3fffffff", "a0000000-bfffffff"]}, %{node: "node_2_10@172.17.0.3", shards: ["20000000-3fffffff", "80000000-9fffffff"]}, %{node: "node_3_10@172.17.0.4", shards: ["20000000-3fffffff", "80000000-9fffffff", "e0000000-ffffffff"]}, %{node: "node_4_10@172.17.0.5", shards: ["00000000-1fffffff", "80000000-9fffffff", "e0000000-ffffffff"]}, %{node: "node_5_10@172.17.0.6", shards: ["00000000-1fffffff", "60000000-7fffffff", "e0000000-ffffffff"]}, %{node: "node_6_10@172.17.0.7", shards: ["00000000-1fffffff", "60000000-7fffffff", "c0000000-dfffffff"]}, %{node: "node_7_10@172.17.0.8", shards: ["60000000-7fffffff", "c0000000-dfffffff"]}, %{node: "node_8_10@172.17.0.9", shards: ["40000000-5fffffff", "c0000000-dfffffff"]}, %{node: "node_9_10@172.17.0.10", shards: ["40000000-5fffffff", "a0000000-bfffffff"]}]}

JS code, with parser call inside template .eex:

var theData = ("<%= Poison.Encoder.encode(@nodes, []) %>");
theData = JSON.parse(theData);

What I see in JS console:

var theData = ("{"nodes":[{"shards":["40000000-5fffffff","a0000000-bfffffff"],"node":"node_10_10@172.17.0.11"},{"shards":["20000000-3fffffff","a0000000-bfffffff"],"node":"node_1_10@172.17.0.2"},{"shards":["20000000-3fffffff","80000000-9fffffff"],"node":"node_2_10@172.17.0.3"},{"shards":["20000000-3fffffff","80000000-9fffffff","e0000000-ffffffff"],"node":"node_3_10@172.17.0.4"},{"shards":["00000000-1fffffff","80000000-9fffffff","e0000000-ffffffff"],"node":"node_4_10@172.17.0.5"},{"shards":["00000000-1fffffff","60000000-7fffffff","e0000000-ffffffff"],"node":"node_5_10@172.17.0.6"},{"shards":["00000000-1fffffff","60000000-7fffffff","c0000000-dfffffff"],"node":"node_6_10@172.17.0.7"},{"shards":["60000000-7fffffff","c0000000-dfffffff"],"node":"node_7_10@172.17.0.8"},{"shards":["40000000-5fffffff","c0000000-dfffffff"],"node":"node_8_10@172.17.0.9"},{"shards":["40000000-5fffffff","a0000000-bfffffff"],"node":"node_9_10@172.17.0.10"}]}");

theData = JSON.parse(theData);

Body:
You need to disable the automatic HTML escaping when injecting encoded JSON like that. You also don't need the surrounding " or brackets.

var theData = <%= raw Poison.Encoder.encode(@nodes, []) %>;

There's no need to call JSON.parse anymore, theData will be set to the value itself, not a string containing a JSON.


问:
Why are the files downloaded by my app deleted after uninstalling it?
My application downloads files from Google Drive by the DownloadManager to the public Download directory. Everything works perfectly, except that when I uninstall my app, the downloded files are automatically deleted. Why?

my two test phones: 1 under Nougat and 1 under marshmallow

Is there something I did not follow and understood with Marshmallow and Nougat?

Thank you for enlightening me.

答:
It's a real regression !! I had not noticed it yet.

Solutions if you want your downloaded files to persist after uninstalling your app are:

1 not to use DownloadManager :))

2 rename your files after Download process

3 move your files away

Source:https://commonsware.com/blog/2016/02/09/changes-downloadmanager-behavior.html


问:
Is SQL injection possible when using MS Access linked tables to a SQL server back-end
I've been doing some research on this but so far have pulled a blank. So here's the situation.

I am developing an MS Access front-end that is linking to SQL Server back end.

I am, in part, using linked tables/forms in Access to the SQL DB - such that when the user updates a value in the form, Access automatically (with no code on my part) updates the values in the SQL DB.

So my question is this - is this vulnerable to SQL injection in any way? Or will Access 'parameterize' the update in such a way that any possible SQL injection code will simply be added to the DB 'as is', rather than be parsed on the server and potentially running some malicious code.

Thanks in advance for any pointers on this!

答:
Using bound forms and not running manually constructed queries:

is this vulnerable to SQL injection in any way?

No.

Or will Access 'parameterize' the update in such a way that any possible SQL injection code will simply be added to the DB 'as is'

Yes.

From https://www.pcreview.co.uk/threads/sql-injection-characters-cleaning-function.4021211/#post-14022015 by David Fenton:

SQL injection is most relevant for applications that do all their
  editing with SQL. While that would apply to a website backed by a
  Jet/ACE database (see #1), it doesn't apply to a standard Access
  app, which doesn't use SQL to edit bound data. That is, most of the
  data editing in an Access application is via bound forms rather than
  through SQL, so it's not really going to be susceptible to SQL
  injection.

Edit:

You can use Logging ODBC, SQL Server to see how exactly Access interacts with SQL Server via ODBC.


问:
Insert_batch Error Codeigniter 3.1.4

A PHP Error was encountered

Severity: Notice
Message: Array to string conversion
Filename: database/DB_query_builder.php
Line Number: 1539
Backtrace: File: D:\xampp\htdocs\visio\application\models\projectmodel.php
Line: 56
Function: insert_batch

A Database Error Occurred

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Array' at line 1

INSERT INTO paymentsize () VALUES ('8'), ('2017-06-07'), ('Residential'), ('L'), ('120'), ('200'), ('10000'), ('15000'), ('30'), ('12000'), ('40'), ('1000'), ('60'), ('125000'), ('10'), ('10000'), ('15000'), ('20000'), Array

Filename: D:/xampp/htdocs/visio/system/database/DB_driver.php

Line Number: 691

My Controller is:

```<code>public function store_payment()
{
    $post = array();
        $post = $this->input->post(NULL,TRUE);
        $count=count($this->input->post('pro_id'));
        echo CI_VERSION;

        for($i = 0; $i < $count; $i++){
            $post []= array(
                'pro_id'        => $post['pro_id'][$i],
                'date_add'      => $post['date_add'][$i],
                'category'      => $post['category'][$i],
                'type'          => $post['type'][$i],
                'size'          => $post['size'][$i],
                'counts'        => $post['counts'][$i],
                'booking'       => $post['booking'][$i],
                'confirmation'  => $post['confirmation'][$i],
                'confirm_days'  => $post['confirm_days'][$i],
                'allocation'    => $post['allocation'][$i],
                'allocate_days' => $post['allocate_days'][$i],
                'm_installment' => $post['m_installment'][$i],
                'month'         => $post['month'][$i],
                'y_instalment'  => $post['y_instalment'][$i],
                'halfyear'      => $post['halfyear'][$i],
                'leveling'      => $post['leveling'][$i],
                'demarcation'   => $post['demarcation'][$i],
                'possession'    => $post['possession'][$i]
                );
        }
    $this->projects->add_payment($post);
}
</code>```

My Model is:

```<code>public function add_payment($array)
{
     // echo "```";
     // print_r($array);
     // exit();
     return $this->db->insert_batch('paymentsize',$array);

}
```
<p>My View is:</p>
```

          <input type="hidden" name="pro_id[]"  value="<?= $project->pro_id; ?>" >

                Date
                  <input type="date" name="date_add[]" value="<?php echo date('Y-m-d'); ?>" class="form-control" >

                  Plot Category
                    <select name="category[]" class="form-control">
                      <option> </option>
                      <option>Residential</option>
                      <option>Commercial</option>
                    </select>

```

if i use print_r it shows all array elements with respective Values.. but it is not inserting in DB Table..
my view has a table with 17 text fields... i just mention few for an Example...
waiting for help.... :)
Thank you in advance...

答:
Change your controller as following code, </p>

```<code>public function store_payment()
{
    $post = array();
        $post = $this->input->post(NULL,TRUE);
        $count=count($this->input->post('pro_id'));
        echo CI_VERSION;

        for($i = 0; $i < $count; $i++){
            $post = array(
                'pro_id'        => $post['pro_id'][$i],
                'date_add'      => $post['date_add'][$i],
                'category'      => $post['category'][$i],
                'type'          => $post['type'][$i],
                'size'          => $post['size'][$i],
                'counts'        => $post['counts'][$i],
                'booking'       => $post['booking'][$i],
                'confirmation'  => $post['confirmation'][$i],
                'confirm_days'  => $post['confirm_days'][$i],
                'allocation'    => $post['allocation'][$i],
                'allocate_days' => $post['allocate_days'][$i],
                'm_installment' => $post['m_installment'][$i],
                'month'         => $post['month'][$i],
                'y_instalment'  => $post['y_instalment'][$i],
                'halfyear'      => $post['halfyear'][$i],
                'leveling'      => $post['leveling'][$i],
                'demarcation'   => $post['demarcation'][$i],
                'possession'    => $post['possession'][$i]
                );
        }
    $this->projects->add_payment($post);
}
</code>```

Title: Insert_batch Error Codeigniter 3.1.4

Body:
A PHP Error was encountered

Severity: Notice
Message: Array to string conversion
Filename: database/DB_query_builder.php
Line Number: 1539
Backtrace: File: D:\xampp\htdocs\visio\application\models\projectmodel.php
Line: 56
Function: insert_batch

A Database Error Occurred

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Array' at line 1

INSERT INTO paymentsize () VALUES ('8'), ('2017-06-07'), ('Residential'), ('L'), ('120'), ('200'), ('10000'), ('15000'), ('30'), ('12000'), ('40'), ('1000'), ('60'), ('125000'), ('10'), ('10000'), ('15000'), ('20000'), Array

Filename: D:/xampp/htdocs/visio/system/database/DB_driver.php

Line Number: 691

My Controller is:

public function store_payment()
{
    $post = array();
        $post = $this->input->post(NULL,TRUE);
        $count=count($this->input->post('pro_id'));
        echo CI_VERSION;

        for($i = 0; $i < $count; $i++){
            $post []= array(
                'pro_id'        => $post['pro_id'][$i],
                'date_add'      => $post['date_add'][$i],
                'category'      => $post['category'][$i],
                'type'          => $post['type'][$i],
                'size'          => $post['size'][$i],
                'counts'        => $post['counts'][$i],
                'booking'       => $post['booking'][$i],
                'confirmation'  => $post['confirmation'][$i],
                'confirm_days'  => $post['confirm_days'][$i],
                'allocation'    => $post['allocation'][$i],
                'allocate_days' => $post['allocate_days'][$i],
                'm_installment' => $post['m_installment'][$i],
                'month'         => $post['month'][$i],
                'y_instalment'  => $post['y_instalment'][$i],
                'halfyear'      => $post['halfyear'][$i],
                'leveling'      => $post['leveling'][$i],
                'demarcation'   => $post['demarcation'][$i],
                'possession'    => $post['possession'][$i]
                );
        }
    $this->projects->add_payment($post);
}

My Model is:

public function add_payment($array)
{
     // echo "
";
     // print_r($array);
     // exit();
     return $this->db->insert_batch('paymentsize',$array);

}

My View is:

          <input type="hidden" name="pro_id[]"  value="<?= $project->pro_id; ?>" >

                Date
                  <input type="date" name="date_add[]" value="<?php echo date('Y-m-d'); ?>" class="form-control" >

                  Plot Category
                    <select name="category[]" class="form-control">
                      <option> </option>
                      <option>Residential</option>
                      <option>Commercial</option>
                    </select>

if i use print_r it shows all array elements with respective Values.. but it is not inserting in DB Table..
my view has a table with 17 text fields... i just mention few for an Example...
waiting for help.... :)
Thank you in advance...

Body:
Change your controller as following code,

public function store_payment()
{
    $post = array();
        $post = $this->input->post(NULL,TRUE);
        $count=count($this->input->post('pro_id'));
        echo CI_VERSION;

        for($i = 0; $i < $count; $i++){
            $post = array(
                'pro_id'        => $post['pro_id'][$i],
                'date_add'      => $post['date_add'][$i],
                'category'      => $post['category'][$i],
                'type'          => $post['type'][$i],
                'size'          => $post['size'][$i],
                'counts'        => $post['counts'][$i],
                'booking'       => $post['booking'][$i],
                'confirmation'  => $post['confirmation'][$i],
                'confirm_days'  => $post['confirm_days'][$i],
                'allocation'    => $post['allocation'][$i],
                'allocate_days' => $post['allocate_days'][$i],
                'm_installment' => $post['m_installment'][$i],
                'month'         => $post['month'][$i],
                'y_instalment'  => $post['y_instalment'][$i],
                'halfyear'      => $post['halfyear'][$i],
                'leveling'      => $post['leveling'][$i],
                'demarcation'   => $post['demarcation'][$i],
                'possession'    => $post['possession'][$i]
                );
        }
    $this->projects->add_payment($post);
}


问:
Is is possible to calibrate fish eye camera using standard openCV?
I try to calibrate camera with ultra wide angle lens > 180 degrees. I use OpenCV 3.2 and camera calibration code from opencv/samples/cpp/tutorial_code/calib3d/camera_calibration, as a result I get image similar to this one from this post. I found numerous movies on youtube.com on which people show how they calibrate fisheye cameras, for example this video.

I know that calibration of ultra wide lenses cameras could be tricky. I also found that there are another then standard model for fisheye camera calibrations in openCV contrib

Is it possible to use camera calibration model from standard OpenCV to calibrate such a wide angle camera or should I use another model e.g., from openCV contrib?

答:
There are specific calibration functions for fisheye calibrations: see http://docs.opencv.org/trunk/db/d58/group__calib3d__fisheye.html

Make sure you get images in the borders of the image with various poses and distances to the camera for a good calibration. Adapt the calibration example to use the fisheye functions.


问:
Haskell: What is immutable data?
in most articles about Haskell you'll find a statement like "Data in Haskell is immutable". I don't quite understand why. For example:

```<code>let a = 123
let a = 456
</code>```

in the main method works. I just changed the data of a from 123 to 456. What am I missing? It's probably a stupid mistake in my train of thought :/

Have a good day!

答:
Actually, a hasn't changed. Try this in ghci to see:

```<code>> a = 123
> action = print a
> a = 456
> action
123
</code>```

Compare with a language that has mutable variables, e.g. python:

```<code>>>> a = 123
>>> def action(): print a
...
>>> a = 456
>>> action()
456
</code>```

Title: Haskell: What is immutable data?

Body:
in most articles about Haskell you'll find a statement like "Data in Haskell is immutable". I don't quite understand why. For example:

let a = 123
let a = 456

in the main method works. I just changed the data of a from 123 to 456. What am I missing? It's probably a stupid mistake in my train of thought :/

Have a good day!

Body:
Actually, a hasn't changed. Try this in ghci to see:

> a = 123
> action = print a
> a = 456
> action
123

Compare with a language that has mutable variables, e.g. python:

>>> a = 123
>>> def action(): print a
...
>>> a = 456
>>> action()
456


问:
mongoDB: cursor notimeout setting isn't working in java client
i set an 'notimeout' option to a dbcursor in java:

```<code>    BasicDBObject nearbyQueries = new BasicDBObject("$gt", 0)
            .append("$lte", 2);
    DBCursor trueClassInstances = locationsCollection.find(new BasicDBObject("distanceFromHotel", nearbyQueries)).addOption(Bytes.QUERYOPTION_NOTIMEOUT).limit(100000);
    double counter = 0;
    int currentPresent = 0;
    for (DBObject instance : trueClassInstances) {

        ...
    }
</code>```

even with this option i set, this exception is thrown:

```<code>Exception in thread "main" com.mongodb.MongoCursorNotFoundException: Query failed with error code -5 and error message 'Cursor 1876954464377 not found on server XXXXXX:27017' on server XXXXXXXX:27017
    at com.mongodb.connection.GetMoreProtocol.receiveMessage(GetMoreProtocol.java:115)
    at com.mongodb.connection.GetMoreProtocol.execute(GetMoreProtocol.java:68)
    at com.mongodb.connection.GetMoreProtocol.execute(GetMoreProtocol.java:37)
    at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:155)
    at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:219)
    at com.mongodb.connection.DefaultServerConnection.getMore(DefaultServerConnection.java:194)
    at com.mongodb.operation.QueryBatchCursor.getMore(QueryBatchCursor.java:197)
    at com.mongodb.operation.QueryBatchCursor.hasNext(QueryBatchCursor.java:93)
    at com.mongodb.MongoBatchCursorAdapter.hasNext(MongoBatchCursorAdapter.java:46)
    at com.mongodb.DBCursor.hasNext(DBCursor.java:152)
    at locationExtraction.DistanceClassification.FeatureAnalyzer.main(FeatureAnalyzer.java:27)
</code>```

FeatureAnalyzer.java:27 is the for loop line.

this problem appear in other project with similar setting...

what am i doing wrong? maybe my choice of 'for' loop instead of this kind of iteration can cause this strange behavior?

```<code>while(cursor.hasNext())
{
      DBObject next = cursor.next();
}
</code>```

Thanks

答:
Looks like you are not able to process each batch within time limit. Try reducing batch size so that each batch could be consumed before time runs out. This should help.

cursor.addOption(com.mongodb.Bytes.QUERYOPTION_NOTIMEOUT).batchSize(100)

Body:
i set an 'notimeout' option to a dbcursor in java:

    BasicDBObject nearbyQueries = new BasicDBObject("$gt", 0)
            .append("$lte", 2);
    DBCursor trueClassInstances = locationsCollection.find(new BasicDBObject("distanceFromHotel", nearbyQueries)).addOption(Bytes.QUERYOPTION_NOTIMEOUT).limit(100000);
    double counter = 0;
    int currentPresent = 0;
    for (DBObject instance : trueClassInstances) {

        ...
    }

even with this option i set, this exception is thrown:

Exception in thread "main" com.mongodb.MongoCursorNotFoundException: Query failed with error code -5 and error message 'Cursor 1876954464377 not found on server XXXXXX:27017' on server XXXXXXXX:27017
    at com.mongodb.connection.GetMoreProtocol.receiveMessage(GetMoreProtocol.java:115)
    at com.mongodb.connection.GetMoreProtocol.execute(GetMoreProtocol.java:68)
    at com.mongodb.connection.GetMoreProtocol.execute(GetMoreProtocol.java:37)
    at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:155)
    at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:219)
    at com.mongodb.connection.DefaultServerConnection.getMore(DefaultServerConnection.java:194)
    at com.mongodb.operation.QueryBatchCursor.getMore(QueryBatchCursor.java:197)
    at com.mongodb.operation.QueryBatchCursor.hasNext(QueryBatchCursor.java:93)
    at com.mongodb.MongoBatchCursorAdapter.hasNext(MongoBatchCursorAdapter.java:46)
    at com.mongodb.DBCursor.hasNext(DBCursor.java:152)
    at locationExtraction.DistanceClassification.FeatureAnalyzer.main(FeatureAnalyzer.java:27)

FeatureAnalyzer.java:27 is the for loop line.

this problem appear in other project with similar setting...

what am i doing wrong? maybe my choice of 'for' loop instead of this kind of iteration can cause this strange behavior?

while(cursor.hasNext())
{
      DBObject next = cursor.next();
}

Thanks


问:
How to match two values independently of their respectiv postions in a string
I'm searching for the best way to match two values simultaneously.

I'd like to get a true value if both values are in a string but i don't know in which order they appear in the string (e.g. abcdef or bedfa in case i want to match a and b)

Is there a better solution (especially if later I would need more complex values to match) than:

```<code>$string =~ m/(a.*b)|(b.*a)/i
</code>```

答:
```<code>$string =~ /a/i && $string =~ /b/i;
</code>```

Body:
I'm searching for the best way to match two values simultaneously.

I'd like to get a true value if both values are in a string but i don't know in which order they appear in the string (e.g. abcdef or bedfa in case i want to match a and b)

Is there a better solution (especially if later I would need more complex values to match) than:

$string =~ m/(a.*b)|(b.*a)/i

Body: $string =~ /a/i && $string =~ /b/i;


问:
How to show selected action in UIAlertAction?
I am trying to achieve the view with a few green actions, and get the selected action to be bold in UIAlertController. And one of the actions, which is dismiss button has to be divided from others and be colored with red.

I am trying to add them with the styles .cancel allows to show dismiss button, but it is bold, but green.
How do I achieve this?

expected view:

my current code:

```<code>let alertController
        = UIAlertController(title: nil,
                            message: nil,
                            preferredStyle: .actionSheet)

    let sortByDateAction = UIAlertAction(title: "По дате",
                                         style: .default,
                                         handler: {(action: UIAlertAction!) in
                                            if self.sortBy != "date" {
                                                self.page = 1
                                                self.sortBy = "date"
                                                self.loadTenders()
                                            }
    })
    let moreExpensiveSortAction = UIAlertAction(title: "Дороже",
                                                style: .destructive,
                                                handler: {(action: UIAlertAction!) in
                                                    if self.sortBy != "priceHigh" {
                                                        self.page = 1
                                                        self.sortBy = "priceHigh"
                                                        self.loadTenders()
                                                    }
    })
    let cheaperSortAction = UIAlertAction(title: "Дешевле",
                                          style: .default,
                                          handler: {(action: UIAlertAction!) in
                                            if self.sortBy != "priceLow" {
                                                self.page = 1
                                                self.sortBy = "priceLow"
                                                self.loadTenders()
                                            }
    })

    alertController
        .addAction(sortByDateAction)
    alertController
        .addAction(moreExpensiveSortAction)
    alertController
        .addAction(cheaperSortAction)

    alertController.preferredAction = sortByDateAction

    alertController
        .addAction(UIAlertAction(title: "Dismiss",
                                 style: .cancel,
                                 handler: nil))
</code>```

答:
The color of the text in the action sheet is nothing but the tint color of the view. Set this as per your color requirement.

Furthermore, To change the font color of cancel button: Set the value for the titleTextColor property of the UIAlertAction

Here is a sample code:

```<code>func showCaptureOptions() {

                let actionSheet = UIAlertController(title: "Capture Type", message: "", preferredStyle: .actionSheet)

                let cameraAction = UIAlertAction(title: "Camera", style: .default) { [weak self](action) in
                    self?.initializeImagePicker(captureType: .camera)
                }

                let photoLibraryAction = UIAlertAction(title: "Photo Library", style: .default) { [weak self](action) in
                    self?.initializeImagePicker(captureType: .photoLibrary)
                }

                let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
                }

                cancelAction.setValue(UIColor.red, forKey: "titleTextColor"). /// The cancel button will be red

                actionSheet.view.tintColor = UIColor.green /// The action sheet options would be green

                actionSheet.addAction(cameraAction)
                actionSheet.addAction(photoLibraryAction)
                actionSheet.addAction(cancelAction)

                DispatchQueue.main.async {
                    self.present(actionSheet, animated: true, completion: nil)
                }
            }
</code>```

Body:
I am trying to achieve the view with a few green actions, and get the selected action to be bold in UIAlertController. And one of the actions, which is dismiss button has to be divided from others and be colored with red.

I am trying to add them with the styles .cancel allows to show dismiss button, but it is bold, but green.
How do I achieve this?

expected view:

my current code:

let alertController
        = UIAlertController(title: nil,
                            message: nil,
                            preferredStyle: .actionSheet)

    let sortByDateAction = UIAlertAction(title: "По дате",
                                         style: .default,
                                         handler: {(action: UIAlertAction!) in
                                            if self.sortBy != "date" {
                                                self.page = 1
                                                self.sortBy = "date"
                                                self.loadTenders()
                                            }
    })
    let moreExpensiveSortAction = UIAlertAction(title: "Дороже",
                                                style: .destructive,
                                                handler: {(action: UIAlertAction!) in
                                                    if self.sortBy != "priceHigh" {
                                                        self.page = 1
                                                        self.sortBy = "priceHigh"
                                                        self.loadTenders()
                                                    }
    })
    let cheaperSortAction = UIAlertAction(title: "Дешевле",
                                          style: .default,
                                          handler: {(action: UIAlertAction!) in
                                            if self.sortBy != "priceLow" {
                                                self.page = 1
                                                self.sortBy = "priceLow"
                                                self.loadTenders()
                                            }
    })

    alertController
        .addAction(sortByDateAction)
    alertController
        .addAction(moreExpensiveSortAction)
    alertController
        .addAction(cheaperSortAction)

    alertController.preferredAction = sortByDateAction

    alertController
        .addAction(UIAlertAction(title: "Dismiss",
                                 style: .cancel,
                                 handler: nil))

Body:
The color of the text in the action sheet is nothing but the tint color of the view. Set this as per your color requirement.

Furthermore, To change the font color of cancel button: Set the value for the titleTextColor property of the UIAlertAction

Here is a sample code:

func showCaptureOptions() {

                let actionSheet = UIAlertController(title: "Capture Type", message: "", preferredStyle: .actionSheet)

                let cameraAction = UIAlertAction(title: "Camera", style: .default) { [weak self](action) in
                    self?.initializeImagePicker(captureType: .camera)
                }

                let photoLibraryAction = UIAlertAction(title: "Photo Library", style: .default) { [weak self](action) in
                    self?.initializeImagePicker(captureType: .photoLibrary)
                }

                let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
                }

                cancelAction.setValue(UIColor.red, forKey: "titleTextColor"). /// The cancel button will be red

                actionSheet.view.tintColor = UIColor.green /// The action sheet options would be green

                actionSheet.addAction(cameraAction)
                actionSheet.addAction(photoLibraryAction)
                actionSheet.addAction(cancelAction)

                DispatchQueue.main.async {
                    self.present(actionSheet, animated: true, completion: nil)
                }
            }


问:
Failure to generate user instance of SQL Server error, when setup application is run on another computer
I am unable to run my c# application on a different computer other than my own computer. I have an attached mdf database file in my project. I have 'SQL SERVER 2008' as pre-requisite in the setup project. The application is installing & running fine on my machine, but when i install and run it on another machine, it shows the following error:

```<code>Description:
Stopped working

Problem signature:
Problem Event Name: CLR20r3
Problem Signature 01:   esbi.exe
Problem Signature 02:   1.0.0.0
Problem Signature 03:   4dd8feca
Problem Signature 04:   System.Data
Problem Signature 05:   2.0.0.0
Problem Signature 06:   4a274a01
Problem Signature 07:   2744
Problem Signature 08:   11
Problem Signature 09:   System.Data.SqlClient.Sql
OS Version: 6.1.7600.2.0.0.256.1
Locale ID:  1033
</code>```

So, I planted a try-catch block on the first opening of connection to the database & caught the following error:

System.Data.SqlClient.SqlException: Failed to generate a user interface of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.

The connection string i am using to connect to the database is

```<code>Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\esbi.mdf;Integrated Security=True;User Instance=True
</code>```

what am i doing wrong?? Is it something with the connection string??
any suggestions?

答:
I had a wpf app that ran on my development machine but gave the System.Data.SqlClient.Sql error when deployed to a server. In my project I changed the "Target profile:" on the "Application" tab from
".NET Framework 4 Client_profile" to
".NET Framework 4" and then closed, opened and relinked it.
The app then ran without the error as the server had a matching .NET framework</p>

Body:
I am unable to run my c# application on a different computer other than my own computer. I have an attached mdf database file in my project. I have 'SQL SERVER 2008' as pre-requisite in the setup project. The application is installing & running fine on my machine, but when i install and run it on another machine, it shows the following error:

Description:
Stopped working

Problem signature:
Problem Event Name: CLR20r3
Problem Signature 01:   esbi.exe
Problem Signature 02:   1.0.0.0
Problem Signature 03:   4dd8feca
Problem Signature 04:   System.Data
Problem Signature 05:   2.0.0.0
Problem Signature 06:   4a274a01
Problem Signature 07:   2744
Problem Signature 08:   11
Problem Signature 09:   System.Data.SqlClient.Sql
OS Version: 6.1.7600.2.0.0.256.1
Locale ID:  1033

So, I planted a try-catch block on the first opening of connection to the database & caught the following error:

System.Data.SqlClient.SqlException: Failed to generate a user interface of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.

The connection string i am using to connect to the database is

Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\esbi.mdf;Integrated Security=True;User Instance=True

what am i doing wrong?? Is it something with the connection string??
any suggestions?


问:
Where the type mismatch error 13 comes from in this case?
One of my Excel worksheets contains many data and the cells are in number format. (for instance it is filled with numbers like 1,02458)

In another worksheet I am trying to do some calculus based on the first worksheet, and for this I am using VBA code:

```<code>Dim sum, price, strike As Double
sum= 0
strike = 0.02

For k = 1 To 5000

sum= sum+ Worksheets("Feuille1").Cells(k, 7).Value - strike

Next k
</code>```

When I try to run this the line with the sum corresponds to the error 13 type mismatch.

I have tried things such as changing the cell format, and even using Variant instead of Double but it changed nothing. How to avoid the type mismatch ?

答:
Is there a header in Sheet "Feuille1" range "G1"?
In that case you're trying to add a string to the sum, which will lead to type mismatch. If the digits start at row 2, then change your loop to</p>

```<code>For k = 2 to 5000
</code>```

Body:
One of my Excel worksheets contains many data and the cells are in number format. (for instance it is filled with numbers like 1,02458)

In another worksheet I am trying to do some calculus based on the first worksheet, and for this I am using VBA code:

Dim sum, price, strike As Double
sum= 0
strike = 0.02

For k = 1 To 5000

sum= sum+ Worksheets("Feuille1").Cells(k, 7).Value - strike

Next k

When I try to run this the line with the sum corresponds to the error 13 type mismatch.

I have tried things such as changing the cell format, and even using Variant instead of Double but it changed nothing. How to avoid the type mismatch ?

Body:
Is there a header in Sheet "Feuille1" range "G1"?
In that case you're trying to add a string to the sum, which will lead to type mismatch. If the digits start at row 2, then change your loop to

For k = 2 to 5000


问:
Django not loading static files (Pycharm)
I am working on a project which requires loading on a CSS stylesheet and a logo file. But my Django server also returns 404 resource not found while loading these files. I have checked other questions like this but none of them is using the format to specify static files I used.
This is the html code i am using

```<code>{% block stylesheets %}
    <link rel="stylesheet" type="text/css" href="/static/Emu86/style.css">
{% endblock stylesheets %}
</code>```

This is my settings.py file:

```<code>    """
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 1.9.1.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# Application definition

INSTALLED_APPS = [
    'Emu86',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',

]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] \
                %(message)s",
                'datefmt': "%d%b%Y %H:%M:%S"
         },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'Emu86.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'propagate': True,
            'level': 'DEBUG',
        },
        'Emu86': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    },
}
</code>```

Project Structure:

```<code>Emu86/
  mysite/
      static/
        Emu86/
</code>```

答:
You have to load the static template tag at the top of your template and then use it for getting the url to your static files:

```<code>{% load static %}

{% block stylesheets %}
    <link rel="stylesheet" type="text/css" href="{% static "Emu86/style.css" %}">
{% endblock stylesheets %}
</code>```

edit

You have to define in your settings.py file the STATICFILES_DIRS constant to look for your static folder from the project directory:

```<code>STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "mysite", "static"),
]
</code>```

Body:
I am working on a project which requires loading on a CSS stylesheet and a logo file. But my Django server also returns 404 resource not found while loading these files. I have checked other questions like this but none of them is using the format to specify static files I used.
This is the html code i am using

{% block stylesheets %}
    <link rel="stylesheet" type="text/css" href="/static/Emu86/style.css">
{% endblock stylesheets %}

This is my settings.py file:

    """
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 1.9.1.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# Application definition

INSTALLED_APPS = [
    'Emu86',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',

]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] \
                %(message)s",
                'datefmt': "%d%b%Y %H:%M:%S"
         },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'Emu86.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'propagate': True,
            'level': 'DEBUG',
        },
        'Emu86': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    },
}

Project Structure:

Emu86/
  mysite/
      static/
        Emu86/

Body:
You have to load the static template tag at the top of your template and then use it for getting the url to your static files:

{% load static %}

{% block stylesheets %}
    <link rel="stylesheet" type="text/css" href="{% static "Emu86/style.css" %}">
{% endblock stylesheets %}

edit

You have to define in your settings.py file the STATICFILES_DIRS constant to look for your static folder from the project directory:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "mysite", "static"),
]


问:
Swift 3: how to change the button image in UITableView?
```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

   ...

 let doLikeBtn = detailCell.contentView.viewWithTag(106) as! UIButton
                doLikeBtn.setTitle(String(indexPath.row), for: UIControlState.normal)
                doLikeBtn.addTarget(self, action: #selector(doLike(sender:)), for: UIControlEvents.touchUpInside)

...

 }

...

 func doLike(sender: UIButton) {
        selectUserIndex = sender.title(for: UIControlState.normal)!

    if sender.image(for: UIControlState.normal) == UIImage(named: "btn_Like.png") {
        sender.setImage(UIImage(named: "btn_not_Like.png"), for: UIControlState.normal)
    }else {
        sender.setImage(UIImage(named: "btn_Like.png"), for: UIControlState.normal)
    }
 }
</code>```

If I click one button in table, and then change the image of button, but other some button's images also are changed repeatedly.
I can't understand this.
Please help me!
Best regards.

答:
a UITableViewCell object is reusable—that is for performance reasons,
  you should only reset attributes of the cell that are not related to
  content.

So you need to update your cell every time cellForRowAt invoked:

also you need to keep track of which cell getting "liked or dislike" so you can add for example a boolean isLike property to YourCustomCell
and toggle it true or false upon doLike func triggered

```<code>            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                let cell = tableView.deque... as! YourCustomCell

                if cell.isLiked == false {
                        cell.btnSomething.setImage(UIImage(named: "btn_not_Like.png"), for: UIControlState.normal)
                    }else {
                        cell.btnSomething.setImage(UIImage(named: "btn_Like.png"), for: UIControlState.normal)
                    }

                }
</code>```

Body:
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

   ...

 let doLikeBtn = detailCell.contentView.viewWithTag(106) as! UIButton
                doLikeBtn.setTitle(String(indexPath.row), for: UIControlState.normal)
                doLikeBtn.addTarget(self, action: #selector(doLike(sender:)), for: UIControlEvents.touchUpInside)

...

 }

...

 func doLike(sender: UIButton) {
        selectUserIndex = sender.title(for: UIControlState.normal)!

    if sender.image(for: UIControlState.normal) == UIImage(named: "btn_Like.png") {
        sender.setImage(UIImage(named: "btn_not_Like.png"), for: UIControlState.normal)
    }else {
        sender.setImage(UIImage(named: "btn_Like.png"), for: UIControlState.normal)
    }
 }

If I click one button in table, and then change the image of button, but other some button's images also are changed repeatedly.
I can't understand this.
Please help me!
Best regards.

Body:
a UITableViewCell object is reusable—that is for performance reasons,
  you should only reset attributes of the cell that are not related to
  content.

So you need to update your cell every time cellForRowAt invoked:

also you need to keep track of which cell getting "liked or dislike" so you can add for example a boolean isLike property to YourCustomCell
and toggle it true or false upon doLike func triggered

            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                let cell = tableView.deque... as! YourCustomCell

                if cell.isLiked == false {
                        cell.btnSomething.setImage(UIImage(named: "btn_not_Like.png"), for: UIControlState.normal)
                    }else {
                        cell.btnSomething.setImage(UIImage(named: "btn_Like.png"), for: UIControlState.normal)
                    }

                }


问:
what is difference of "develop" and "origin/develop" in command git
I'm newbie and starting use git for project.
I not notice the difference of "Branch" and "origin/Branch"
Please guide me.

答:
Branch is your local branch and origin/Branch is your remote branch.

To make sure which branches are local or remote just use the following git commands.

```<code>$ git branch     # see local branches
$ git branch -r  # see remote branches
$ git branch -a  # see local and remote branches
</code>```

Body:
Branch is your local branch and origin/Branch is your remote branch.

To make sure which branches are local or remote just use the following git commands.

$ git branch     # see local branches
$ git branch -r  # see remote branches
$ git branch -a  # see local and remote branches


问:
spring prefixjson with responsebody
when controller method return is @responsebody  , even if i put

```<code><bean
    class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
     <property name="prefixJson" value="true" />
</bean>
</code>```

there will no && {} insert at the front of json data. anyone knows what is reason?

答:
JSON in @RequestBody/@ResponseBody is handled by MappingJacksonHttpMessageConverter which is configured in AnnotationMethodHandlerAdapter.messageConverters.

The easy way to configure it without interference with other features is to create a BeanPostProcessor to intercept creation of AnnotationMethodHandlerAdapter, see, for example, here.

Title: spring prefixjson with responsebody

Body:
when controller method return is @responsebody  , even if i put

<bean
    class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
     <property name="prefixJson" value="true" />
</bean>

there will no && {} insert at the front of json data. anyone knows what is reason?