问:
with python from csv to text files
I am trying to wrtie two txtfiles ( Test_8.txt and Test_9.txt ) from the csvfile.
From row COL4 i am getting single and double quotes and '['.

how can i get rid of them?

csvfie:

```<code>NR;COL1;COL2;COL3;COL4;COL5;COL6;COL7;REMARK

Test_9;96;0;4.26;4;5.25;-0.01;1;Test_9 tested, python

Test_9;96;0;4.26;4;11.75;2.35;1;Test_9 tested, python

Test_9;96;0;4.26;4;-3;-3;0.9;Test_9 tested, python

Test_8;95;0;4.25;3;4.75;-0.11;1;Test_8 tested, python

Test_8;95;0;4.25;3;-3;-3;0.9;Test_8 tested, python

Test_8;95;0;4.25;3;16.5;4.26;1;Test_8 tested, python

Test_8;95;0;4.25;3;12.751;2.861;1;Test_8 tested, python
</code>```

Expected ouput:

```<code>TYPE    1.0
NR  Test_8

COL1    95

COL2    0
COL3    4.250

COL4    3
-3.000  -3.000  0.900
4.750   -0.110  1.000
12.751  2.861   1.000
16.500  4.260   1.000

REMARK
Test_8 tested
with python
</code>```

mycode:

```<code>import os
import pandas as pd
pd.options.mode.chained_assignment = None
df=pd.read_csv(r'C:\Users\Desktop\test_map\test\mycsv_v1.csv',sep=';',index_col='NR')

df['COL3'] = df['COL3'].map('{:,.3f}'.format)

df['COL5'] = df['COL5'].map('{:,.3f}'.format)
df['COL6'] = df['COL6'].map('{:,.3f}'.format)
df['COL7'] = df['COL7'].map('{:,.3f}'.format)

ans = [[x,pd.DataFrame(y)] for x, y in df.groupby(df.index, as_index=True)]
#print ans

for table in ans:
    line1=table[1].iloc[0]
    #print line1
    line1['TYPE']=1.0
    line1['NR']=table[0]

    col567=table[1][['COL5','COL6','COL7']].sort_values(by=['COL5'], ascending=True)
    print col567

    for row in range(len(col567)):
        #print row
        line1[str(col567.values[row])[1:-1]] = None

    line1['']=None

    col8=table[1]['REMARK'].str.split(',')[0]
    col8=table[1]['REMARK'].str.split(', ')[1]
    line1['REMARK']=str(col8.values[0])
    line1['REMARK']=str(col8.values[1])

    line1=line1[['TYPE', 'NR','','COL1','', 'COL2','', 'COL3', 'COL4',
             str(col567.values[0:]), '', 'REMARK\n', col8.values[0],col8.values[1]]]

    line1.to_csv(table[0]+'.txt',sep='\t')
</code>```

myoutput;

```<code>TYPE    1.0
NR  Test_8

COL1    95

COL2    0

COL3    4.250
COL4    3
"[['-3.000' '-3.000' '0.900']
 ['12.751' '2.861' '1.000']
 ['16.500' '4.260' '1.000']
 ['4.750' '-0.110' '1.000']]"

"REMARK
"
Test_8 tested
python
</code>```

答:
If you want text without [] and quota then don't use str() and defalt formatting but create own funcion to format it. You can use " ".join() and for-loop for this

Example code

```<code>import numpy as np

data = np.array([['-3.000', '-3.000', '0.900'],
 ['12.751', '2.861', '1.000'],
 ['16.500', '4.260', '1.000'],
 ['4.750', '-0.110', '1.000']])

print('--- default format ---')
text = str(data)
print(text)

print('--- own format ---')
text = ''
for row in data:
    text += ' '.join(row) + '\n'
print(text)
</code>```

Result:

```<code>--- default format ---
[['-3.000' '-3.000' '0.900']
 ['12.751' '2.861' '1.000']
 ['16.500' '4.260' '1.000']
 ['4.750' '-0.110' '1.000']]

--- own format ---
-3.000 -3.000 0.900
12.751 2.861 1.000
16.500 4.260 1.000
4.750 -0.110 1.000
</code>```

BTW: You need to convert col567.values[0:]

```<code>print(str(col567.values[0:]))

text = ''
for row in col567.values[0:]:
    text += " ".join(row) + '\n'
print(text)
</code>```

And use this text in

```<code>line1=line1[['TYPE', 'NR','','COL1','', 'COL2','', 'COL3', 'COL4',
         text, '', 'REMARK\n', col8.values[0],col8.values[1]]]
</code>```

I tried to run your code but it has many mistakes and it never works.

Example code which use string-formating

I use io.StringIO only to emulate file with data but you use pd.read_csv

BTW: I had to change some elements beacuse to get correctly sorted data they have to be integer/float values not strings {:,.3f}

```<code>import os
import pandas as pd

pd.options.mode.chained_assignment = None

#df=pd.read_csv(r'C:\Users\Desktop\test_map\test\mycsv_v1.csv',sep=';',index_col='NR')

text = u'''NR;COL1;COL2;COL3;COL4;COL5;COL6;COL7;REMARK
Test_9;96;0;4.26;4;5.25;-0.01;1;Test_9 tested, python
Test_9;96;0;4.26;4;11.75;2.35;1;Test_9 tested, python
Test_9;96;0;4.26;4;-3;-3;0.9;Test_9 tested, python
Test_8;95;0;4.25;3;4.75;-0.11;1;Test_8 tested, python
Test_8;95;0;4.25;3;-3;-3;0.9;Test_8 tested, python
Test_8;95;0;4.25;3;16.5;4.26;1;Test_8 tested, python
Test_8;95;0;4.25;3;12.751;2.861;1;Test_8 tested, python'''

import io
df = pd.read_csv(io.StringIO(text), sep=';', index_col='NR')

df['COL3'] = df['COL3'].map('{:,.3f}'.format)
#df['COL5'] = df['COL5'].map('{:,.3f}'.format)
#df['COL6'] = df['COL6'].map('{:,.3f}'.format)
#df['COL7'] = df['COL7'].map('{:,.3f}'.format)

ans = df.groupby(df.index, as_index=True)

for table in ans:
    line1 = table[1].iloc[0]

    col567 = table[1][['COL5','COL6','COL7']].sort_values(by=['COL5'], ascending=True)
    col567_text = '\n'.join(' '.join('{:,.3f}'.format(item) for item in row) for row in col567.values[0:])

    col8 = table[1]['REMARK'][0].split(', ')

    text = '''TYPE    {type_}
NR  {nr}

COL1    {col1}

COL2    {col2}
COL3    {col3}

COL4    {col4}
{col567}

REMARK
{remark1}
{remark2}'''.format(
    type_ = 1.0,
    nr = table[0],
    col1 = table[1]['COL1'][0],
    col2 = table[1]['COL2'][0],
    col3 = table[1]['COL3'][0],
    col4 = table[1]['COL4'][0],
    col567 = col567_text,
    remark1 = col8[0],
    remark2 = col8[1],
)

    print(text)

    with open(table[0]+'.txt', 'w') as f:
        f.write(text)
</code>```

Title: with python from csv to text files

Body:
I am trying to wrtie two txtfiles ( Test_8.txt and Test_9.txt ) from the csvfile.
From row COL4 i am getting single and double quotes and '['.

how can i get rid of them?

csvfie:

NR;COL1;COL2;COL3;COL4;COL5;COL6;COL7;REMARK

Test_9;96;0;4.26;4;5.25;-0.01;1;Test_9 tested, python

Test_9;96;0;4.26;4;11.75;2.35;1;Test_9 tested, python

Test_9;96;0;4.26;4;-3;-3;0.9;Test_9 tested, python

Test_8;95;0;4.25;3;4.75;-0.11;1;Test_8 tested, python

Test_8;95;0;4.25;3;-3;-3;0.9;Test_8 tested, python

Test_8;95;0;4.25;3;16.5;4.26;1;Test_8 tested, python

Test_8;95;0;4.25;3;12.751;2.861;1;Test_8 tested, python

Expected ouput:

TYPE    1.0
NR  Test_8

COL1    95

COL2    0
COL3    4.250

COL4    3
-3.000  -3.000  0.900
4.750   -0.110  1.000
12.751  2.861   1.000
16.500  4.260   1.000

REMARK
Test_8 tested
with python

mycode:

import os
import pandas as pd
pd.options.mode.chained_assignment = None
df=pd.read_csv(r'C:\Users\Desktop\test_map\test\mycsv_v1.csv',sep=';',index_col='NR')

df['COL3'] = df['COL3'].map('{:,.3f}'.format)

df['COL5'] = df['COL5'].map('{:,.3f}'.format)
df['COL6'] = df['COL6'].map('{:,.3f}'.format)
df['COL7'] = df['COL7'].map('{:,.3f}'.format)

ans = [[x,pd.DataFrame(y)] for x, y in df.groupby(df.index, as_index=True)]
#print ans

for table in ans:
    line1=table[1].iloc[0]
    #print line1
    line1['TYPE']=1.0
    line1['NR']=table[0]

    col567=table[1][['COL5','COL6','COL7']].sort_values(by=['COL5'], ascending=True)
    print col567

    for row in range(len(col567)):
        #print row
        line1[str(col567.values[row])[1:-1]] = None

    line1['']=None

    col8=table[1]['REMARK'].str.split(',')[0]
    col8=table[1]['REMARK'].str.split(', ')[1]
    line1['REMARK']=str(col8.values[0])
    line1['REMARK']=str(col8.values[1])

    line1=line1[['TYPE', 'NR','','COL1','', 'COL2','', 'COL3', 'COL4',
             str(col567.values[0:]), '', 'REMARK\n', col8.values[0],col8.values[1]]]

    line1.to_csv(table[0]+'.txt',sep='\t')

myoutput;

TYPE    1.0
NR  Test_8

COL1    95

COL2    0

COL3    4.250
COL4    3
"[['-3.000' '-3.000' '0.900']
 ['12.751' '2.861' '1.000']
 ['16.500' '4.260' '1.000']
 ['4.750' '-0.110' '1.000']]"

"REMARK
"
Test_8 tested
python

Body:
If you want text without [] and quota then don't use str() and defalt formatting but create own funcion to format it. You can use " ".join() and for-loop for this

Example code

import numpy as np

data = np.array([['-3.000', '-3.000', '0.900'],
 ['12.751', '2.861', '1.000'],
 ['16.500', '4.260', '1.000'],
 ['4.750', '-0.110', '1.000']])

print('--- default format ---')
text = str(data)
print(text)

print('--- own format ---')
text = ''
for row in data:
    text += ' '.join(row) + '\n'
print(text)

Result:

--- default format ---
[['-3.000' '-3.000' '0.900']
 ['12.751' '2.861' '1.000']
 ['16.500' '4.260' '1.000']
 ['4.750' '-0.110' '1.000']]

--- own format ---
-3.000 -3.000 0.900
12.751 2.861 1.000
16.500 4.260 1.000
4.750 -0.110 1.000

BTW: You need to convert col567.values[0:]

print(str(col567.values[0:]))

text = ''
for row in col567.values[0:]:
    text += " ".join(row) + '\n'
print(text)

And use this text in

line1=line1[['TYPE', 'NR','','COL1','', 'COL2','', 'COL3', 'COL4',
         text, '', 'REMARK\n', col8.values[0],col8.values[1]]]

I tried to run your code but it has many mistakes and it never works.

Example code which use string-formating

I use io.StringIO only to emulate file with data but you use pd.read_csv

BTW: I had to change some elements beacuse to get correctly sorted data they have to be integer/float values not strings {:,.3f}

import os
import pandas as pd

pd.options.mode.chained_assignment = None

#df=pd.read_csv(r'C:\Users\Desktop\test_map\test\mycsv_v1.csv',sep=';',index_col='NR')

text = u'''NR;COL1;COL2;COL3;COL4;COL5;COL6;COL7;REMARK
Test_9;96;0;4.26;4;5.25;-0.01;1;Test_9 tested, python
Test_9;96;0;4.26;4;11.75;2.35;1;Test_9 tested, python
Test_9;96;0;4.26;4;-3;-3;0.9;Test_9 tested, python
Test_8;95;0;4.25;3;4.75;-0.11;1;Test_8 tested, python
Test_8;95;0;4.25;3;-3;-3;0.9;Test_8 tested, python
Test_8;95;0;4.25;3;16.5;4.26;1;Test_8 tested, python
Test_8;95;0;4.25;3;12.751;2.861;1;Test_8 tested, python'''

import io
df = pd.read_csv(io.StringIO(text), sep=';', index_col='NR')

df['COL3'] = df['COL3'].map('{:,.3f}'.format)
#df['COL5'] = df['COL5'].map('{:,.3f}'.format)
#df['COL6'] = df['COL6'].map('{:,.3f}'.format)
#df['COL7'] = df['COL7'].map('{:,.3f}'.format)

ans = df.groupby(df.index, as_index=True)

for table in ans:
    line1 = table[1].iloc[0]

    col567 = table[1][['COL5','COL6','COL7']].sort_values(by=['COL5'], ascending=True)
    col567_text = '\n'.join(' '.join('{:,.3f}'.format(item) for item in row) for row in col567.values[0:])

    col8 = table[1]['REMARK'][0].split(', ')

    text = '''TYPE    {type_}
NR  {nr}

COL1    {col1}

COL2    {col2}
COL3    {col3}

COL4    {col4}
{col567}

REMARK
{remark1}
{remark2}'''.format(
    type_ = 1.0,
    nr = table[0],
    col1 = table[1]['COL1'][0],
    col2 = table[1]['COL2'][0],
    col3 = table[1]['COL3'][0],
    col4 = table[1]['COL4'][0],
    col567 = col567_text,
    remark1 = col8[0],
    remark2 = col8[1],
)

    print(text)

    with open(table[0]+'.txt', 'w') as f:
        f.write(text)


来源: stackexchange

问:
Why 'unassigned local viariable' error appear in one function but not in second very similar function
so i trying to understand this thing
i have two similar functions

First function determine who win in paper,scissor, rock game using if/else blocks

Second function doing that same but using dictionares and key/values

The problem is first function work fine but in second function i got
'Use of unassigned local viarable' error
I know to repair this i should change string win1;
 to string win1 = "";
but i dont understand why

First function code:

```<code>static string whowin(int x, int y)
{
    string win;
    if (x == 1)
    {
        if (y == 2)
        {
            win = "player2";
        }
        else if (y == 3)
        {
            win = "player1";
        }
        else
        {
            win = "draw";
        }
    }
    else if (x == 2)
    {
        if (y == 1)
        {
            win = "player1";
        }
        else if (y == 3)
        {
            win = "player2";
        }
        else
        {
            win = "draw";
        }
    }
    else // player 1 choose 3 - scissors
    {
        if (y == 2)
        {
            win = "player1";
        }
        else if (y == 1)
        {
            win = "player2";
        }
        else
        {
            win = "draw";
        }
    }
    return win;
}
</code>```

and second function:

```<code>static string whowin2(int x, int y)
{
    // x- player 1 input, y- player 2 input
    // 1 - rock, 2- paper, 3 = scissors
    Dictionary<int, int> player1win = new Dictionary<int, int>() {
        { 1, 3 },
        { 2, 1 },
        { 3, 2 }
        };
     Dictionary<int, int> player2win = new Dictionary<int, int>() {
        { 1, 2 },
        { 2, 3 },
        { 3, 1 }
           };

    string win1;

    if (player1win.ContainsKey(x) && player1win[x].Equals(y))
    {
        win1 = "player1";
    }
    else if (player2win.ContainsKey(x) && player2win[x].Equals(y))
    {
        win1 = "player2";
    }
    else if (x == y)
    {
        win1 = "draw";
    }
    else
    {
        Console.WriteLine("Cos cos sie popsuo");
    }
    return win1;
}
</code>```

答: When the compiler looks at your code it sees that it could fall into the final else condition, and it that case it would return win1 without that being set to anything hence use of unassigned local.  If you initialize on declaration you have set the variable before it is used. </p>

ContentLicense: CC BY-SA 4.0

Body:
so i trying to understand this thing
i have two similar functions

First function determine who win in paper,scissor, rock game using if/else blocks

Second function doing that same but using dictionares and key/values

The problem is first function work fine but in second function i got
'Use of unassigned local viarable' error
I know to repair this i should change string win1;
 to string win1 = "";
but i dont understand why

First function code:

static string whowin(int x, int y)
{
    string win;
    if (x == 1)
    {
        if (y == 2)
        {
            win = "player2";
        }
        else if (y == 3)
        {
            win = "player1";
        }
        else
        {
            win = "draw";
        }
    }
    else if (x == 2)
    {
        if (y == 1)
        {
            win = "player1";
        }
        else if (y == 3)
        {
            win = "player2";
        }
        else
        {
            win = "draw";
        }
    }
    else // player 1 choose 3 - scissors
    {
        if (y == 2)
        {
            win = "player1";
        }
        else if (y == 1)
        {
            win = "player2";
        }
        else
        {
            win = "draw";
        }
    }
    return win;
}

and second function:

static string whowin2(int x, int y)
{
    // x- player 1 input, y- player 2 input
    // 1 - rock, 2- paper, 3 = scissors
    Dictionary<int, int> player1win = new Dictionary<int, int>() {
        { 1, 3 },
        { 2, 1 },
        { 3, 2 }
        };
     Dictionary<int, int> player2win = new Dictionary<int, int>() {
        { 1, 2 },
        { 2, 3 },
        { 3, 1 }
           };

    string win1;

    if (player1win.ContainsKey(x) && player1win[x].Equals(y))
    {
        win1 = "player1";
    }
    else if (player2win.ContainsKey(x) && player2win[x].Equals(y))
    {
        win1 = "player2";
    }
    else if (x == y)
    {
        win1 = "draw";
    }
    else
    {
        Console.WriteLine("Cos cos sie popsuo");
    }
    return win1;
}


答: The final else clause of the second function doesn't set win1 to any value.  Then your trying to return the value of win1, which the compiler sees has not been initialized.  So you are correct, declare win1 = String.Empty or "" and the compiler will be happy.</p>

Title: Why 'unassigned local viariable' error appear in one function but not in second very similar function


问:
Does using string_view lead to an unnecessary string copy in this scenario?
What I'm trying to do is have my class accept a string during construction. I read that string_view was a replacement for const string& so naturally I wrote a constructor like this. This allows me to accept c++ and c strings.

```<code>Url::Url(boost::string_view raw_url)
    : url_(static_cast<std::string>(raw_url)) {
</code>```

The problem which might be here is that when an rvalue is passed, there is a unnecessary copy instead of a move. Is the solution to make another constructor which takes string&&? What is the best practice here?

答:
Note: I'll write the answer considering std::string_view, but boost::string_view should be similar.

I read that string_view was a replacement for const string&

It is useful to understand the reason why std::string_view was added in the first place.

What is the problem with const string&?

It is certainly efficient if you pass an std::string object and you don't gain anything with std::string_view. But suppose now that you are passing a char* containing a large string. In that case a temporary std::string object will be created (and the whole string referenced by that char* will be copied) just so the function receives an std::string. That is when std::string_view shines. If you pass a char* or a std::string (or anything that can be converted to std::string_view) to a function accepting std::string_view (by value, no need to accept a std::string_view by reference) then the new std::string_view object that is created is very cheap, since it is only "a view" and it does not copy the underlying string.

But your case is different. Since you are copying the string anyway, then your function should just accept a string by value and move the string inside the function. Something such as

Url::Url(std::string raw_url)
    : url_(std::move(raw_url)) {
```

There is even a clang-tidy warning to tell you this.

The advantage is that if the user of your function pass an lvalue you make a copy (you need it anyway) and a move, but if they pass an rvalue then there is no copy and only a move.

Body:
What I'm trying to do is have my class accept a string during construction. I read that string_view was a replacement for const string& so naturally I wrote a constructor like this. This allows me to accept c++ and c strings.

Url::Url(boost::string_view raw_url)
    : url_(static_cast<std::string>(raw_url)) {

The problem which might be here is that when an rvalue is passed, there is a unnecessary copy instead of a move. Is the solution to make another constructor which takes string&&? What is the best practice here?

Body:
Note: I'll write the answer considering std::string_view, but boost::string_view should be similar.

I read that string_view was a replacement for const string&

It is useful to understand the reason why std::string_view was added in the first place.

What is the problem with const string&?

It is certainly efficient if you pass an std::string object and you don't gain anything with std::string_view. But suppose now that you are passing a char* containing a large string. In that case a temporary std::string object will be created (and the whole string referenced by that char* will be copied) just so the function receives an std::string. That is when std::string_view shines. If you pass a char* or a std::string (or anything that can be converted to std::string_view) to a function accepting std::string_view (by value, no need to accept a std::string_view by reference) then the new std::string_view object that is created is very cheap, since it is only "a view" and it does not copy the underlying string.

But your case is different. Since you are copying the string anyway, then your function should just accept a string by value and move the string inside the function. Something such as

Url::Url(std::string raw_url)
    : url_(std::move(raw_url)) {

There is even a clang-tidy warning to tell you this.

The advantage is that if the user of your function pass an lvalue you make a copy (you need it anyway) and a move, but if they pass an rvalue then there is no copy and only a move.


问:
npm install for react-navigation-drawer not working
Following is the error on the terminal after running the command.</p>

```<code>npm ERR! code ENOENT
npm ERR! syscall rename
npm ERR! path C:\react-native\reviewsApp\node_modules\@react-navigation\drawer
npm ERR! dest C:\react-native\reviewsApp\node_modules\@react-navigation\.drawer.DELETE
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, rename 'C:\react-native\reviewsApp\node_modules\@react-navigation\drawer' -> 'C:\react-native\reviewsApp\node_modules\@react-navigation\.drawer.DELETE'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\saumya bhatnagar\AppData\Roaming\npm-cache\_logs\2020-05-28T20_44_21_098Z-debug.log
</code>```

答: Try deleting node_module and try "npm install"</p>

Body:
Following is the error on the terminal after running the command.

npm ERR! code ENOENT
npm ERR! syscall rename
npm ERR! path C:\react-native\reviewsApp\node_modules\@react-navigation\drawer
npm ERR! dest C:\react-native\reviewsApp\node_modules\@react-navigation\.drawer.DELETE
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, rename 'C:\react-native\reviewsApp\node_modules\@react-navigation\drawer' -> 'C:\react-native\reviewsApp\node_modules\@react-navigation\.drawer.DELETE'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\saumya bhatnagar\AppData\Roaming\npm-cache\_logs\2020-05-28T20_44_21_098Z-debug.log


问:
Spring webflow: how to keep track of persisted entity ids?
I'm working on a webflow (SWF2). The entities are generated using Roo. One of the webflow views, multi-instance.jspx, may be called multiple times to allow for multiple, persisted instances of the same entity (MyClass).

I'd like to keep a list of those persisted entities so that I can reference them on a later point in the flow. So far, I've tried the following.

A simplified version of my flow.xml looks like this:

```<code><on-start>
    <evaluate expression="new java.util.ArrayList()" result="flowScope.myList" result-type="java.io.Serializable"/>
</on-start>

<view-state id="multi-instance" view="multi-instance" model="myClass">
    <binder>
        <binding property="field1"/>
        <binding property="field2"/>
    </binder>
    <on-entry>
        <evaluate expression="new com.test.MyClass()" result="flowScope.myClass" />
    </on-entry>
    <transition on="another_instance" to="multi-instance"/>
    <transition on="success" to="confirm"/>
    <transition on="cancel" to="abort"/>
    <on-exit>
        <evaluate expression="myClass.persist()"/>
        <evaluate expression="flowScope.myList.add(myClass)"/>
    </on-exit>
</view-state>
</code>```

The confirm and abort view-states are defined in flow.xml as well. The confirm.jspx looks like this:

```<code><div xmlns:spring="http://www.springframework.org/tags" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:fn="http://java.sun.com/jsp/jstl/functions" xmlns:form="http://www.springframework.org/tags/form" xmlns:util="urn:jsptagdir:/WEB-INF/tags/util" xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
<jsp:directive.page contentType="text/html;charset=UTF-8" />
<jsp:output omit-xml-declaration="yes" />
<form:form>
    <c:forEach items="${myList}" var="instance">
        <li>${instance.getField1()} ${instance.getField2()}</li>
</c:forEach>
    <div class="submit">
        <input type="submit" id="success" name="_eventId_success" value="success"/>
        <input type="submit" id="cancel" name="_eventId_cancel" value="cancel" />
    </div>
</form:form>
</div>
</code>```

So to the question:

Whenever I hit confirm.jspx, the web return says that there's an exception thrown at org.springframework.webflow.engine.impl.FlowExecutionImpl.wrap(FlowExecutionImpl.java:569).

EDIT: The Apache log is a little more enlightening. The following is a snippet of the top of the call stack:

```<code>SEVERE: Servlet.service() for servlet jsp threw exception org.apache.jasper.JasperException:
/WEB-INF/views/myflow/confirmation.jspx(6,7)
The function getField1 must be used with a prefix when a default namespace is not specified
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
</code>```

I'm not sure if the ArrayList-approach is possible; I believe I've read somewhere that the flowScope.myClass instance, as it is defined in the multi-instance-state, is picked up by the GC or at least falls out of scope. I'm not sure. If anyone can shed some light on that particular topic, I'd be thrilled.

(And if you happen to know a better way to keep a list of these persisted entities, please feel free to let me know!) Thanks in advance! :)

Update:
I'm able to count the number of elements in my list like so:

```<code><c:choose>
    <c:when test="${myList != null}">myList exists, it contains <c:out value="${fn:length(myList)}" /> items!</c:when>
    <c:otherwise>myList doesn't exist.</c:otherwise>
</c:choose>
</code>```

It shows the same number of elements as I've inserted. However, when I do this:

```<code><c:forEach items="${myList}" var="instance">
    <c:if test="${instance != null}">
        <li>${instance.field1} ${instance.field2}</li>
    </c:if>
</c:forEach>
</code>```

nothing is displayed. (I can confirm that there is a correct number of
-elements when the null-test is omitted. Note also that I'm trying to access the properties directly, as indicated here: jstl/jsp - iterating over a vector of beans) I don't know what to think, regarding the scope here, but it seems clear that I can't access my entities via an ArrayList.

答:
First, with regards to your question(s) around variable scoping, I would suggest looking at section 4.4 of the SWF documentation, where it describes all of the different available scopes.

Flow scope variables live through the lifetime of the flow.  So your myClass variable will not go away until the flow exits.  However keep in mind that your <on-entry> expression is assigning a new instance every time that view state is entered.

Second, I think you are probably on the right track with your solution.  I would note several things:

You are persisting and adding to your list in the <on-exit> element -- this means these two things will always happen when you leave the state, including when you are doing your cancel transition.  This may not be what you want.  Related:

Your <transition on="another_instance" to="multi-instance"/> is actually exiting the view-state and re-entering it, triggering the <on-exit> and <on-entry> logic.  It is possible to remain in the same state, by simply doing <transition on="another_instance">.  Doing this will execute any logic you have inside the transition, and then re-render the view without actually changing states.

You may want to consider using the <var> tag to initialize variables... what you are doing with <evaluate expression="new ..."/> works but using <var> may be cleaner.  Also, it is not necessary to say result-type="java.io.Serializable".  result-type should be used when you need to convert the return type to something elese.

Finally, the error you are getting looks like it is unrelated to webflow.  JSTL/EL allow you to access bean properties but not methods, and you are trying to invoke a method.  See this question for more info.

ContentLicense: CC BY-SA 3.0

Body:
I'm working on a webflow (SWF2). The entities are generated using Roo. One of the webflow views, multi-instance.jspx, may be called multiple times to allow for multiple, persisted instances of the same entity (MyClass).

I'd like to keep a list of those persisted entities so that I can reference them on a later point in the flow. So far, I've tried the following.

A simplified version of my flow.xml looks like this:

<on-start>
    <evaluate expression="new java.util.ArrayList()" result="flowScope.myList" result-type="java.io.Serializable"/>
</on-start>

<view-state id="multi-instance" view="multi-instance" model="myClass">
    <binder>
        <binding property="field1"/>
        <binding property="field2"/>
    </binder>
    <on-entry>
        <evaluate expression="new com.test.MyClass()" result="flowScope.myClass" />
    </on-entry>
    <transition on="another_instance" to="multi-instance"/>
    <transition on="success" to="confirm"/>
    <transition on="cancel" to="abort"/>
    <on-exit>
        <evaluate expression="myClass.persist()"/>
        <evaluate expression="flowScope.myList.add(myClass)"/>
    </on-exit>
</view-state>

The confirm and abort view-states are defined in flow.xml as well. The confirm.jspx looks like this:

<jsp:directive.page contentType="text/html;charset=UTF-8" />
<jsp:output omit-xml-declaration="yes" />
<form:form>
    <c:forEach items="${myList}" var="instance">

${instance.getField1()} ${instance.getField2()}

</c:forEach>

        <input type="submit" id="success" name="_eventId_success" value="success"/>
        <input type="submit" id="cancel" name="_eventId_cancel" value="cancel" />

</form:form>

So to the question:

Whenever I hit confirm.jspx, the web return says that there's an exception thrown at org.springframework.webflow.engine.impl.FlowExecutionImpl.wrap(FlowExecutionImpl.java:569).

EDIT: The Apache log is a little more enlightening. The following is a snippet of the top of the call stack:

SEVERE: Servlet.service() for servlet jsp threw exception org.apache.jasper.JasperException:
/WEB-INF/views/myflow/confirmation.jspx(6,7)
The function getField1 must be used with a prefix when a default namespace is not specified
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)

I'm not sure if the ArrayList-approach is possible; I believe I've read somewhere that the flowScope.myClass instance, as it is defined in the multi-instance-state, is picked up by the GC or at least falls out of scope. I'm not sure. If anyone can shed some light on that particular topic, I'd be thrilled.

(And if you happen to know a better way to keep a list of these persisted entities, please feel free to let me know!) Thanks in advance! :)

Update:
I'm able to count the number of elements in my list like so:

<c:choose>
    <c:when test="${myList != null}">myList exists, it contains <c:out value="${fn:length(myList)}" /> items!</c:when>
    <c:otherwise>myList doesn't exist.</c:otherwise>
</c:choose>

It shows the same number of elements as I've inserted. However, when I do this:

<c:forEach items="${myList}" var="instance">
    <c:if test="${instance != null}">

${instance.field1} ${instance.field2}

    </c:if>
</c:forEach>

nothing is displayed. (I can confirm that there is a correct number of
-elements when the null-test is omitted. Note also that I'm trying to access the properties directly, as indicated here: jstl/jsp - iterating over a vector of beans) I don't know what to think, regarding the scope here, but it seems clear that I can't access my entities via an ArrayList.


问:
How can I make all the points on a dense plot visible in matplotlib?
I'm using this basic code to display a plot using matplotlib. The lists for the x and y axis are large.

plt.plot(r,trajectory,"k.")
plt.title("Bifurcation diagram")
plt.xlabel("R")
plt.ylabel("Xn")
plt.show()
```

<p>How can I format my plot better to view all the details? </p>

<p>With the above configuration what I see is</p>

<p><img src="https://i.stack.imgur.com/VEFsP.png" alt="Initial"></p>

<p>But what I want to get to is something that looks like this with each point visible (atleast high enough resolution to zoom in)</p>

<p><img src="https://i.stack.imgur.com/trN4q.png" alt="final"></p>

<p>Update:
I found that tuning the available parameters iteratively can yield good results. Used a combination of the answers below to understand parameters and arrive at this configuration.</p>

<pre class="lang-py prettyprint-override"><code>f = plt.figure(figsize=(6,4),dpi=300)
plt.plot(r, trajectory, "k,", markersize=0.01, mew=0)
f.savefig("bifurcation_diag.png")
plt.title("Bifurcation diagram")
plt.xlabel("R")
plt.ylabel("Xn")
plt.show()
</code>```

答:
You need a comma as marker, not a dot. The comma marker is just one pixel, while the dot is one "point". Set mew=0 to avoid that an outline is drawn, as the outline would be much larger than a pixel. You can also add alpha=0.2 (or similar) to have semi-transparent pixels.

This is how it could look like with:

plt.plot(r, trajectory, 'b,', markersize=.1, mew=0, alpha=0.2)
```

<p><img src="https://i.stack.imgur.com/Do69y.jpg" alt="example plot"></p>

<p>PS: The full code to reproduce the plot:</p>

```import numpy as np
from matplotlib import pyplot as plt

def logistic_map(x0, r, num_iter):
    x = np.zeros(num_iter)
    xi = x0
    for i in range(num_iter):
        xi = r * xi * (1 - xi)
        x[i] = xi
    return x

def bifurcations(x0, r_min, r_max, r_steps, num_iter, iter_to_skip):
    r_values = np.linspace(r_min, r_max, r_steps)
    bifurcations = [logistic_map(x0, r, num_iter)[iter_to_skip:] for r in r_values]
    plt.plot(r_values, bifurcations, "b,", markersize=.1, mew=0, alpha=0.2)
    plt.show()

bifurcations(0.1, 2.4, 4, 500, 1000, 5)
```

Setting alpha=0.1 and bifurcations(0.1, 2.4, 4, 2000, 2000, 500):

Body:
I'm using this basic code to display a plot using matplotlib. The lists for the x and y axis are large.

plt.plot(r,trajectory,"k.")
plt.title("Bifurcation diagram")
plt.xlabel("R")
plt.ylabel("Xn")
plt.show()

How can I format my plot better to view all the details?

With the above configuration what I see is

But what I want to get to is something that looks like this with each point visible (atleast high enough resolution to zoom in)

Update:
I found that tuning the available parameters iteratively can yield good results. Used a combination of the answers below to understand parameters and arrive at this configuration.

f = plt.figure(figsize=(6,4),dpi=300)
plt.plot(r, trajectory, "k,", markersize=0.01, mew=0)
f.savefig("bifurcation_diag.png")
plt.title("Bifurcation diagram")
plt.xlabel("R")
plt.ylabel("Xn")
plt.show()

Body:
You need a comma as marker, not a dot. The comma marker is just one pixel, while the dot is one "point". Set mew=0 to avoid that an outline is drawn, as the outline would be much larger than a pixel. You can also add alpha=0.2 (or similar) to have semi-transparent pixels.

This is how it could look like with:

plt.plot(r, trajectory, 'b,', markersize=.1, mew=0, alpha=0.2)

PS: The full code to reproduce the plot:

import numpy as np
from matplotlib import pyplot as plt

def logistic_map(x0, r, num_iter):
    x = np.zeros(num_iter)
    xi = x0
    for i in range(num_iter):
        xi = r * xi * (1 - xi)
        x[i] = xi
    return x

def bifurcations(x0, r_min, r_max, r_steps, num_iter, iter_to_skip):
    r_values = np.linspace(r_min, r_max, r_steps)
    bifurcations = [logistic_map(x0, r, num_iter)[iter_to_skip:] for r in r_values]
    plt.plot(r_values, bifurcations, "b,", markersize=.1, mew=0, alpha=0.2)
    plt.show()

bifurcations(0.1, 2.4, 4, 500, 1000, 5)

Setting alpha=0.1 and bifurcations(0.1, 2.4, 4, 2000, 2000, 500):


问:
broadcast a web-cam to (YouTube, Twitch , facebook) using HTML5 and WebRTC
I'm working on a project where i need to broadcast a live video on youtube,  twitch , Facebook  or other platforms from my website using HTML5 , rtmp , webrtc, nodejs....

so instead of going to youtube and start a live video, i want to start the video from my website

but  im new to webrtc and live streaming and i don't know what to do or how to start this so please if anyone have any ideas or suggestions about how to do this please contact me or leave a comment here

this is what i did

SERVER SIDE (NodeJs)

io.on('connection', (socket) =>{

    socket.on('stream', stream =>{
        console.log(stream)
        socket.broadcast.emit('stream', stream);

    });

})

```
<h3>Client Side</h3>
Html (video.html)
<pre class="lang-html prettyprint-override"><code>
<div id="videos">
    <video id="video" autoplay>

    </video>

</div>

 <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script src="js/video.js"></script>

</code>```
Javascript (video.js)

var socket = io();
navigator.mediaDevices.getUserMedia({
    video  : true,
    audio: true
})
.then(stream =>{
    document.getElementById('video').srcObject = stream
    socket.emit("stream", stream);
})

socket.on('stream', stream=>{

    video = document.createElement("video")
    video.srcObject = stream
    video.setAttribute('autoplay')
    document.getElementById("videos").appendChild(video)
})
```

答:
You will need to do a WebRTC to RTMP bridge on your backend.

There are a lot of things to consider, but this is a common question so I threw together twitch. It is an example of doing this.

Body:
I'm working on a project where i need to broadcast a live video on youtube,  twitch , Facebook  or other platforms from my website using HTML5 , rtmp , webrtc, nodejs....

so instead of going to youtube and start a live video, i want to start the video from my website

but  im new to webrtc and live streaming and i don't know what to do or how to start this so please if anyone have any ideas or suggestions about how to do this please contact me or leave a comment here

this is what i did

SERVER SIDE (NodeJs)

io.on('connection', (socket) =>{

    socket.on('stream', stream =>{
        console.log(stream)
        socket.broadcast.emit('stream', stream);

    });

})

Client Side

Html (video.html)

    <video id="video" autoplay>

    </video>

Javascript (video.js)

var socket = io();
navigator.mediaDevices.getUserMedia({
    video  : true,
    audio: true
})
.then(stream =>{
    document.getElementById('video').srcObject = stream
    socket.emit("stream", stream);
})

socket.on('stream', stream=>{

    video = document.createElement("video")
    video.srcObject = stream
    video.setAttribute('autoplay')
    document.getElementById("videos").appendChild(video)
})


问:
Android Webview in Viewpager with enabled Hardware Acceleration
I have a ViewPager containing a WebView. After some lacks of scroll performance and consulting StackOverflow, I finally disabled hardware acceleration for the WebView. This solves the problem, but now I need to display Youtube videos and other multimedia stuff in my WebView. According to the dokumentation, I need to re-enable hardware acceleration for this :(

Because the scroll issue appears again, I added a ViewPager.OnPageChangeListener() to my ViewPager where I disable hardware acceleration when the pager is scrolling and enable it, when the pager is idle:

```<code>pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrollStateChanged(int arg0) {
                if(arg0 == ViewPager.SCROLL_STATE_IDLE){

                    webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
                }
                else{
                    // disable hardware acceleration
                    webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
                }
            }
        });
</code>```

It seems to work a bit, but when the hardware acceleration is enabled, the WebView flickers a short time, which is annoying. I have no idea what I can try next... any sugestions?

答:
You should add webview inside the NestedScrollView. In this way i can scroll any html content such as youtube video in the webview without lack of scroll performance.</p>

```<code>  <androidx.core.widget.NestedScrollView
        android:id="@+id/constraintLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <WebView
            android:id="@+id/webView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </androidx.core.widget.NestedScrollView>
</code>```

Body:
I have a ViewPager containing a WebView. After some lacks of scroll performance and consulting StackOverflow, I finally disabled hardware acceleration for the WebView. This solves the problem, but now I need to display Youtube videos and other multimedia stuff in my WebView. According to the dokumentation, I need to re-enable hardware acceleration for this :(

Because the scroll issue appears again, I added a ViewPager.OnPageChangeListener() to my ViewPager where I disable hardware acceleration when the pager is scrolling and enable it, when the pager is idle:

pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrollStateChanged(int arg0) {
                if(arg0 == ViewPager.SCROLL_STATE_IDLE){

                    webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
                }
                else{
                    // disable hardware acceleration
                    webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
                }
            }
        });

It seems to work a bit, but when the hardware acceleration is enabled, the WebView flickers a short time, which is annoying. I have no idea what I can try next... any sugestions?

Body:
You should add webview inside the NestedScrollView. In this way i can scroll any html content such as youtube video in the webview without lack of scroll performance.

  <androidx.core.widget.NestedScrollView
        android:id="@+id/constraintLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <WebView
            android:id="@+id/webView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </androidx.core.widget.NestedScrollView>


问:
Opposite of combo box .Dropdown method?
Is there a way to toggle the dropdown of a combo box through VBA?  .Dropdown is a method and it only works in one direction.  I'm looking for the following functionality:

```<code>MyCombo.Dropdown = True
MyCombo.Dropdown = False
</code>```

Obviously the above does not work in MS Access.  I'm guessing I'll need to use some sort of hack/workaround for this.  I'd like to avoid a .Requery.  That would probably work, but there could be a major performance penalty depending on what the source of the combo box is.

答:
I know this is an old thread but I had the same problem and tried several solutions. The .ListWidth didn't work for me.  It did close the dropdown, but it displayed the bound column values (the IDs) in the 'text box' part of the combobox after the dropdown was closed.  Mine is also a multi-select combobox bound to a multi-value field; may be different that the OP.

I was able to solve it by doing .Requery

Title: Opposite of combo box .Dropdown method?

Body:
Is there a way to toggle the dropdown of a combo box through VBA?  .Dropdown is a method and it only works in one direction.  I'm looking for the following functionality:

MyCombo.Dropdown = True
MyCombo.Dropdown = False

Obviously the above does not work in MS Access.  I'm guessing I'll need to use some sort of hack/workaround for this.  I'd like to avoid a .Requery.  That would probably work, but there could be a major performance penalty depending on what the source of the combo box is.


问:
ASP.NET Core - Swashbuckle not creating swagger.json file
I am having trouble getting the Swashbuckle.AspNetCore (1.0.0) package to generate any output.  I read the swagger.json file should be written to '~/swagger/docs/v1'.  However, I am not getting any output.

I started with a brand new ASP.NET Core API project. I should mention this is ASP.NET Core 2. The API works, and I am able to retrieve values from the values controller just fine.

My startup class has the configuration exactly as described in this article (Swashbuckle.AspNetCore on GitHub).

```<code>public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAPI V1");
            });
        }
        else
        {
            app.UseExceptionHandler();
        }

        app.UseStatusCodePages();
        app.UseMvc();

        //throw new Exception();
    }
}
</code>```

You can see the NuGet references...

Again, this is all the default template, but I include the ValuesController for reference...

```<code>[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}
</code>```

答:
i had the same Error , but due to different issue ,i was using a 3rd party library which cause this issue, and i did not need to have this library in my exposure ,so i used the below solution that is posted here .

Create somewhere class ApiExplorerIgnores with following content

```<code>public class ApiExplorerIgnores : IActionModelConvention
{
    public void Apply(ActionModel action)
    {
        if (action.Controller.ControllerName.Equals("ImportExport"))
            action.ApiExplorer.IsVisible = false;
    }
}
</code>```

Add following code to method ConfigureServices in Startup.cs

```<code>services.AddMvc(c => c.Conventions.Add(new ApiExplorerIgnores()))
</code>```

this will get read of all methods in that controller ,you can also use a specific level ,like method name or so ,also you can remove one Method only  and so one ,

Body:
I am having trouble getting the Swashbuckle.AspNetCore (1.0.0) package to generate any output.  I read the swagger.json file should be written to '~/swagger/docs/v1'.  However, I am not getting any output.

I started with a brand new ASP.NET Core API project. I should mention this is ASP.NET Core 2. The API works, and I am able to retrieve values from the values controller just fine.

My startup class has the configuration exactly as described in this article (Swashbuckle.AspNetCore on GitHub).

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAPI V1");
            });
        }
        else
        {
            app.UseExceptionHandler();
        }

        app.UseStatusCodePages();
        app.UseMvc();

        //throw new Exception();
    }
}

You can see the NuGet references...

Again, this is all the default template, but I include the ValuesController for reference...

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

Body:
i had the same Error , but due to different issue ,i was using a 3rd party library which cause this issue, and i did not need to have this library in my exposure ,so i used the below solution that is posted here .

Create somewhere class ApiExplorerIgnores with following content

public class ApiExplorerIgnores : IActionModelConvention
{
    public void Apply(ActionModel action)
    {
        if (action.Controller.ControllerName.Equals("ImportExport"))
            action.ApiExplorer.IsVisible = false;
    }
}

Add following code to method ConfigureServices in Startup.cs

services.AddMvc(c => c.Conventions.Add(new ApiExplorerIgnores()))

this will get read of all methods in that controller ,you can also use a specific level ,like method name or so ,also you can remove one Method only  and so one ,


问:
Mocking classes in Rhino Mocks
Lets say there is an Interface ICreateFileStrategy. Lets say there are classes A and B that implement these two interfaces. Both these classes implement method

```<code>long CreateFile(ExportFile exportFile)
</code>```

Now when I want to write a unit test I want to test method CreateFile of class A. How is this possible. How do I set the expectations exactly.

Thanks,
Sai

答: for starters you test the class not the interface, so you just create an instance of Class A mock all of the dependencies and then test the method  </p>

Title: Mocking classes in Rhino Mocks

Body:
Lets say there is an Interface ICreateFileStrategy. Lets say there are classes A and B that implement these two interfaces. Both these classes implement method

long CreateFile(ExportFile exportFile)

Now when I want to write a unit test I want to test method CreateFile of class A. How is this possible. How do I set the expectations exactly.

Thanks,
Sai


答:
In your second method, there is an execution path where the win1 variable is not set:

```<code>string win1;

if (...)
    [...]
else if (...)
    [...]
else if (...)
    [...]
else
{
    Console.WriteLine("Cos cos sie popsuo");
    // HERE
}
return win1;
</code>```

When you enter the else branch your variable win1 will not be set, so it is an "unassigned local viarable".

Body:
In your second method, there is an execution path where the win1 variable is not set:

string win1;

if (...)
    [...]
else if (...)
    [...]
else if (...)
    [...]
else
{
    Console.WriteLine("Cos cos sie popsuo");
    // HERE
}
return win1;

When you enter the else branch your variable win1 will not be set, so it is an "unassigned local viarable".


问:
on iOS/iPhone: "Too many open files": need to list open files (like lsof)
We've discovered our complex iPhone app (ObjC, C++, JavaScript/WebKit) is leaking file descriptors under unusual circumstances.

I need to know which files (by file path) we are leaving open.

I want something like the BSD command "lsof", which, of course, isn't available in iOS 4, at least not to me.  Ideally a C or ObjC function.  Or a tool, like shark or Instruments.  Just need the files for our running app, not (as with lsof) for all apps/processes.

We do all sorts of things with files, and the code that is failing with "Too many open files" hasn't changed in ages, and since the circumstances are unusual, this could have crept in months ago.  So there's no need to remind me to look at code that opens files and make sure I close them.  I know that already.  Would be nice to narrow it down with something lsof-esque.  Thanks.

答:
For future reference, I ran into a similar problem on an iPhone 11 with iOS 13; I was creating too many file descriptors (FDs) by creating too many files and sockets. My solution was to increase FDs at runtime with setrlimit().

First I got the FD limits on my iPhone 11, with the following code:

// This goes somewhere in your code
struct rlimit rlim;

if (getrlimit(RLIMIT_NOFILE, &rlim) == 0) {
    std::cout << "Soft limit: " << rlim.rlim_cur << std::endl;
    std::cout << "Hard limit: " << rlim.rlim_max << std::endl;
} else {
    std::cout << "Unable to get file descriptor limits" << std::endl;
}
```

<p>After running <code>getrlimit()</code>, I could confirm that on iOS 13, the soft limit is 256 FDs, and the hard limit is infinite FDs. Since I was creating > 300 FDs between files and sockets, my app was crashing.</p>

<p>In my case I couldn't decrease the number of FDs, so I decided to increase the FD soft limit instead, with this code:</p>

<pre class="lang-cpp prettyprint-override"><code>// This goes somewhere in your code
struct rlimit rlim;

rlim.rlim_cur = NEW_SOFT_LIMIT;
rlim.rlim_max = NEW_HARD_LIMIT;

if (setrlimit(RLIMIT_NOFILE, &rlim) == -1) {
    std::cout << "Unable to set file descriptor limits" << std::endl;
}
</code>```

NOTE: You can find more information on gettrlimit() and setrlimit() here and here.

ContentLicense: CC BY-SA 2.5

Body:
For future reference, I ran into a similar problem on an iPhone 11 with iOS 13; I was creating too many file descriptors (FDs) by creating too many files and sockets. My solution was to increase FDs at runtime with setrlimit().

First I got the FD limits on my iPhone 11, with the following code:

// This goes somewhere in your code
struct rlimit rlim;

if (getrlimit(RLIMIT_NOFILE, &rlim) == 0) {
    std::cout << "Soft limit: " << rlim.rlim_cur << std::endl;
    std::cout << "Hard limit: " << rlim.rlim_max << std::endl;
} else {
    std::cout << "Unable to get file descriptor limits" << std::endl;
}

After running getrlimit(), I could confirm that on iOS 13, the soft limit is 256 FDs, and the hard limit is infinite FDs. Since I was creating > 300 FDs between files and sockets, my app was crashing.

In my case I couldn't decrease the number of FDs, so I decided to increase the FD soft limit instead, with this code:

// This goes somewhere in your code
struct rlimit rlim;

rlim.rlim_cur = NEW_SOFT_LIMIT;
rlim.rlim_max = NEW_HARD_LIMIT;

if (setrlimit(RLIMIT_NOFILE, &rlim) == -1) {
    std::cout << "Unable to set file descriptor limits" << std::endl;
}

NOTE: You can find more information on gettrlimit() and setrlimit() here and here.


问:
Threejs: make custom shader match the standard rendering
For performance reasons I need to display hundred of moving tetrahedrons in a scene. There for I use instancedbuffergeometry which requires a custom shader.

The scene also contains objects with regular geometry (non-buffer) and some lights (I prepared boiled-down snippet: https://jsfiddle.net/negan/xs3k1yz4/ ).

My problem is that the tetrahedrons are not shaded such that their lighting plausibly fits to the rest of the scene. The reason is probably the primitive shader I built:

```

Is there a way to make the custom shader fit the lights I defined in the scene? The shader also renders the faces in such a way which does not make the impression of directed light. I'd rather like to have single faces lit evenly rather that have the color interpolated from the vertices but I was unable to achieve that.

Any pointer or help is appreciated.

答:
There's InstancedMesh module for three.js . It allows mesh instancing without using shader materials. It patches the existing material.
https://github.com/pailhead/three-instanced-mesh</p>

Body:
For performance reasons I need to display hundred of moving tetrahedrons in a scene. There for I use instancedbuffergeometry which requires a custom shader.

The scene also contains objects with regular geometry (non-buffer) and some lights (I prepared boiled-down snippet: https://jsfiddle.net/negan/xs3k1yz4/ ).

My problem is that the tetrahedrons are not shaded such that their lighting plausibly fits to the rest of the scene. The reason is probably the primitive shader I built:

Is there a way to make the custom shader fit the lights I defined in the scene? The shader also renders the faces in such a way which does not make the impression of directed light. I'd rather like to have single faces lit evenly rather that have the color interpolated from the vertices but I was unable to achieve that.

Any pointer or help is appreciated.


问:
How do you save the state of a widget in a Jupyter notebook?
I have a radio button widget in a Jupyter notebook and I want to save the selected state, preferrably in the notebook json. That doesn't seem to be happening when I save the notebook. The state gets lost and reset when you reopen the notebook. Is there a way to save the state and have it reload?</p>

答:
To save a widget state in a jupyter notebook use Save Notebook Widget State menu item (Widgets>Save Notebook Widget State).  From ipywidgets:

A notebook file may be saved with the current widget state as
  metadata. This allows the notebook file to be rendered with rendered
  widgets


问:
How can this MYSQL query be better
I have a table that has all the photos from a user. For some reason (dont care why) some users can be deleted (using DELETE FROM) from the users table, but the photos are kept on the photos tables.

I need to know how many photos are from users that actually exists on the users table.

The first solution I came up with is this:

```<code>SELECT COUNT(DISTINCT user_id) FROM photos WHERE user_id IN (SELECT id FROM users)
</code>```

But I'm not sure if doing two Queries is the best one. Is there a better way to do this?

答:
Cascading delete in MyISAM

To expand on AJ's answer. If you don't want to alter the table. Or you don't have InnoDB tables.

You can still have cascading deletes.

Put a after delete trigger on the leading table and put code in like this:

You can have y'r cake and eat her too

```<code>DELIMITER $$

CREATE TRIGGER ad_users_each AFTER DELETE ON users FOR EACH ROW
BEGIN
  DELETE FROM photos WHERE photos.user_id = old.id;
END $$

DELIMITER ;
</code>```

Voila, cascading deletes in MyISAM.

How does it work?

The trigger fires after each successful deletion of a row in table users.

The old virtual table in the triggers holds the value of users.id before it was deleted. I use that id to find all the matching user_id in table photos and delete those that are/were linked to the now deleted user.

Title: How can this MYSQL query be better

Body:
I have a table that has all the photos from a user. For some reason (dont care why) some users can be deleted (using DELETE FROM) from the users table, but the photos are kept on the photos tables.

I need to know how many photos are from users that actually exists on the users table.

The first solution I came up with is this:

SELECT COUNT(DISTINCT user_id) FROM photos WHERE user_id IN (SELECT id FROM users)

But I'm not sure if doing two Queries is the best one. Is there a better way to do this?

Body:
Cascading delete in MyISAM

To expand on AJ's answer. If you don't want to alter the table. Or you don't have InnoDB tables.

You can still have cascading deletes.

Put a after delete trigger on the leading table and put code in like this:

You can have y'r cake and eat her too

DELIMITER $$

CREATE TRIGGER ad_users_each AFTER DELETE ON users FOR EACH ROW
BEGIN
  DELETE FROM photos WHERE photos.user_id = old.id;
END $$

DELIMITER ;

Voila, cascading deletes in MyISAM.

How does it work?

The trigger fires after each successful deletion of a row in table users.

The old virtual table in the triggers holds the value of users.id before it was deleted. I use that id to find all the matching user_id in table photos and delete those that are/were linked to the now deleted user.


问:
How do I get the desired grid layout in bootstrap
I've been plugging away at this for some time and I get close to the desired output but there's always an issue with centering. It's the thumbnail charts to the right that I can seem to get aligned in a square as shown in the attached figure. I know that my understanding of div code isn't where it should be and that's where I'm sure my issues stem from. Any help would be most appreciated.

```<code><div class="container-fluid">
    <div class="row bg-secondary text-light">
        <div class="col-sm-12">

  </div>

  <div class="container-fluid">
    <div class="row">
        <div class="col-sm-3 bg-secondary text-light">
            <div>
              <h4><b>Project Summary</b></h4>
                <p>Here is  bunch of that doesn't mean anything for the purposes of sharing this code
                  latitude location. The adsfasdf includes analysis of asfdd, fdfdf sdsd, dfdf Index
                  and Humidity. These data are then asdfasdfasdfas fsadf asdf asdf asdfof latitude. The data was
                  drawn from other stff adsfasdfasdfasdfadsfasdfasdfasdfsdfasdf  adsfasdfdfadsfadsfsdfsdf
                  using Python API calls to that site, then stored in CSV files and integrated into Panda Dataframes and plotted
                  with Matplotlib.<br></p>

                 <p></p>  asfasdf asdf d d fsdf sadf d d adsf asdf sd d d asdf d df sd fadsa fsd f
                </p>
            </div>
        </div>
        <div class="col-sm-9">
            <div class="row">
                <div class="col-sm-6">
                 <br>
                    <img src="fig1.png" alt="Bootcamp" width="500" height="500">"

                </div>

            <div class="col-sm-3 bg-secondary text-light">
              <div class="row">
                  <h5>Visualizations</h5>

            <div class="col-sm-3 bg-secondary text-light justify-content-cente">
            </div>
                  <img src="Fig1.png" class="img-thumbnail" alt="Temp v Alt" width="195" height="236">
                  <img src="Fig2.png" class="img-thumbnail" alt="Temp v Alt" width="195" height="236">

                  <div class="col-sm-3 bg-secondary text-light">
                  </div>
                        <img src="Fig3.png" class="img-thumbnail" alt="Temp v Alt" width="195" height="236">
                        <img src="Fig4.png" class="img-thumbnail" alt="Temp v Alt" width="195" height="236">
            </div>

            </div>
        </div>
        <!-- Add second row -->
        <br>
        <div class="col-sm-12 bg-secondary text-light">
            <div>
                <p>Text 2</p>
            </div>
        </div>
        <div class="col-sm-12 bg-secondary text-light">
            <div>

            </div>
        </div>

        <div class="col-sm-12 row justify-content-center">
            <div class="row">
                <div class="col-sm-12">

                </div>
                <div class="col-sm-1bg-secondary text-light">

                </div>
            </div>
        </div>
    </div>
</div>

</body>
</html>
</code>```

答:
I would personally recommend trying this out in raw HTML and CSS before diving in the world of Bootstrap.

Although this is not the 100% ideal solution, here's a quick solution that fulfils your design.

* {
  margin: 0;
  padding: 0;
  border: 0;
}

body {
  position: relative;
  margin-left: 10%;
  margin-right: 10%;
}

.boxes-left {
  float: left;
  padding-top: 5vh;
  height: 90vh;
  width: 20%;
}

.box1,
.box2 {
  width: 100%;
  height: 50%;
}

.box1 {
  background: red;
}

.box2 {
  background: green;
}

.box-centre {
  float: left;
  padding-top: 10vh;
  height: 80vh;
  width: 50%;
}

.box3 {
  width: 100%;
  height: 100%;
  background: blue;
}

.boxes-right {
  float: left;
  padding-top: 5vh;
  width: 30%;
  height: 90vh;
}

.boxes-right > h1 {
  text-align: center;
}

.box-r {
  position: relative;
  float: left;
  margin: 5%;
  width: 40%;
  height: 20%;
  background: orange;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <link rel="stylesheet" href="style.css" />
    </head>
    <body>
        <div class="boxes-left">
        <div class="box1"></div>
        <div class="box2"></div>
        </div>

        <div class="box-centre">
        <div class="box3"></div>
        </div>

        <div class="boxes-right">
        <h1>Your Text Here</h1>
        <div class="box-r"></div>
        <div class="box-r"></div>
        <div class="box-r"></div>
        <div class="box-r"></div>
        </div>
    </body>
    </html></code>```

Let me know if this is the solution you were after!

Body:
I've been plugging away at this for some time and I get close to the desired output but there's always an issue with centering. It's the thumbnail charts to the right that I can seem to get aligned in a square as shown in the attached figure. I know that my understanding of div code isn't where it should be and that's where I'm sure my issues stem from. Any help would be most appreciated.

Project Summary

Here is  bunch of that doesn't mean anything for the purposes of sharing this code
                  latitude location. The adsfasdf includes analysis of asfdd, fdfdf sdsd, dfdf Index
                  and Humidity. These data are then asdfasdfasdfas fsadf asdf asdf asdfof latitude. The data was
                  drawn from other stff adsfasdfasdfasdfadsfasdfasdfasdfsdfasdf  adsfasdfdfadsfadsfsdfsdf
                  using Python API calls to that site, then stored in CSV files and integrated into Panda Dataframes and plotted
                  with Matplotlib.

  asfasdf asdf d d fsdf sadf d d adsf asdf sd d d asdf d df sd fadsa fsd f

                    "

Visualizations

Text 2

Body:
I would personally recommend trying this out in raw HTML and CSS before diving in the world of Bootstrap.

Although this is not the 100% ideal solution, here's a quick solution that fulfils your design.

* {
  margin: 0;
  padding: 0;
  border: 0;
}

body {
  position: relative;
  margin-left: 10%;
  margin-right: 10%;
}

.boxes-left {
  float: left;
  padding-top: 5vh;
  height: 90vh;
  width: 20%;
}

.box1,
.box2 {
  width: 100%;
  height: 50%;
}

.box1 {
  background: red;
}

.box2 {
  background: green;
}

.box-centre {
  float: left;
  padding-top: 10vh;
  height: 80vh;
  width: 50%;
}

.box3 {
  width: 100%;
  height: 100%;
  background: blue;
}

.boxes-right {
  float: left;
  padding-top: 5vh;
  width: 30%;
  height: 90vh;
}

.boxes-right > h1 {
  text-align: center;
}

.box-r {
  position: relative;
  float: left;
  margin: 5%;
  width: 40%;
  height: 20%;
  background: orange;
}

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <link rel="stylesheet" href="style.css" />
    </head>
    <body>
        <div class="boxes-left">
        <div class="box1"></div>
        <div class="box2"></div>
        </div>

        <div class="box-centre">
        <div class="box3"></div>
        </div>

        <div class="boxes-right">
        <h1>Your Text Here</h1>
        <div class="box-r"></div>
        <div class="box-r"></div>
        <div class="box-r"></div>
        <div class="box-r"></div>
        </div>
    </body>
    </html>

Let me know if this is the solution you were after!


问:
How to add more spaces to array using realloc?
I'm trying to make a simple program to ask for user input (name and age) using a structure and allocating memory. I start with an array of 2 spaces, however when i try to assign more it overwrite the previous input. </p>

<p>Can someone show me where i'm being wrong? </p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stdio_ext.h>
typedef struct
{
    char nombre[20];
    int edad;
}Persona;

int main()
{
    int sizeArrayPersonas = 2;
    Persona listaPersonas[sizeArrayPersonas];
    Persona* pArrayPersona = NULL;
    char respuesta = 's';

    int i;

    pArrayPersona = listaPersonas;

    while(respuesta == 's')
    {
        pArrayPersona = (Persona*)malloc(sizeof(Persona)*sizeArrayPersonas);
        for(i=0;i<sizeArrayPersonas;i++)
        {
            printf("Ingrese nombre: ");
            __fpurge(stdin);
            fgets((pArrayPersona+i)->nombre,20,stdin);

            printf("Ingrese edad: ");
            scanf("%d", &(pArrayPersona+i)->edad);
        }

        printf("Desea ingresar otro usuario? (s o n): ");
        __fpurge(stdin);
        scanf("%c", &respuesta);

        if(respuesta == 's')
        {
            Persona* pAuxArray;
            pAuxArray = (Persona*)realloc(pArrayPersona,sizeof(Persona)*(sizeArrayPersonas+1));
            if(pAuxArray != NULL)
            {
                pArrayPersona = pAuxArray;
                sizeArrayPersonas++;
                pAuxArray = NULL;
            }
        }
    }

    //Mostrar array de estructura
    for(i=0;i<sizeArrayPersonas;i++)
    {
        printf("Nombre: %s Edad: %d \n", (pArrayPersona+i)->nombre, (pArrayPersona+i)->edad);
    }

    return 0;
}
</code>```

答:
when i try to assign more it overwrite the previous input.

Because in your code below:

```<code>for(i=0;i<sizeArrayPersonas;i++)
{
      printf("Ingrese nombre: ");
       __fpurge(stdin);
      fgets((pArrayPersona+i)->nombre,20,stdin);

      printf("Ingrese edad: ");
      scanf("%d", &(pArrayPersona+i)->edad);
}
</code>```

You always input the value for pArrayPersona from 0 to sizeArrayPersonas - 1

In the next iteration, you have to input value for pArrayPersona[sizeArrayPersonas], it means the value of old sizeArrayPersonas+1_th elements (for example, in first iteration you input 2 values, then in the next iteration, after type s, you have to input for 3rd element, you do not need to re-enter the value of 1st and 2nd elements of pArrayPersona).

Your code in if condition can change it to:

```<code>Persona* pAuxArray = realloc(pArrayPersona,sizeof(Persona)*(sizeArrayPersonas+1));
if(pAuxArray == NULL) {
   free(pArrayPersona);
   return -1;
} else {
   pArrayPersona = pAuxArray;
   sizeArrayPersonas++;
}
</code>```

You have to malloc for pArrayPersona before while loop instead of at the beginning of the while loop.

BTW, your while loop can be:

```<code>    int i = 0;
    pArrayPersona = malloc(sizeof(Persona)*sizeArrayPersonas);
    while(respuesta == 's')
    {
        for( ;i<sizeArrayPersonas;i++)
        {
            printf("Ingrese nombre: ");
            fgets((pArrayPersona+i)->nombre,20,stdin);

            printf("Ingrese edad: ");
            scanf("%d", &(pArrayPersona+i)->edad);
        }

        printf("Desea ingresar otro usuario? (s o n): ");
        scanf(" %c", &respuesta);

        if(respuesta == 's')
        {
            Persona* pAuxArray = realloc(pArrayPersona,sizeof(Persona)*(sizeArrayPersonas+1));
            if(pAuxArray == NULL) {
                free(pArrayPersona);
                return -1;
            } else {
                pArrayPersona = pAuxArray;
                sizeArrayPersonas++;
            }
        }
    }
</code>```

Do not forget to free(pArrayPersona); at the end of program (when you do not need to use it).

Body:
I'm trying to make a simple program to ask for user input (name and age) using a structure and allocating memory. I start with an array of 2 spaces, however when i try to assign more it overwrite the previous input.

Can someone show me where i'm being wrong?

#include <stdio.h>
#include <stdlib.h>
#include <stdio_ext.h>
typedef struct
{
    char nombre[20];
    int edad;
}Persona;

int main()
{
    int sizeArrayPersonas = 2;
    Persona listaPersonas[sizeArrayPersonas];
    Persona* pArrayPersona = NULL;
    char respuesta = 's';

    int i;

    pArrayPersona = listaPersonas;

    while(respuesta == 's')
    {
        pArrayPersona = (Persona*)malloc(sizeof(Persona)*sizeArrayPersonas);
        for(i=0;i<sizeArrayPersonas;i++)
        {
            printf("Ingrese nombre: ");
            __fpurge(stdin);
            fgets((pArrayPersona+i)->nombre,20,stdin);

            printf("Ingrese edad: ");
            scanf("%d", &(pArrayPersona+i)->edad);
        }

        printf("Desea ingresar otro usuario? (s o n): ");
        __fpurge(stdin);
        scanf("%c", &respuesta);

        if(respuesta == 's')
        {
            Persona* pAuxArray;
            pAuxArray = (Persona*)realloc(pArrayPersona,sizeof(Persona)*(sizeArrayPersonas+1));
            if(pAuxArray != NULL)
            {
                pArrayPersona = pAuxArray;
                sizeArrayPersonas++;
                pAuxArray = NULL;
            }
        }
    }

    //Mostrar array de estructura
    for(i=0;i<sizeArrayPersonas;i++)
    {
        printf("Nombre: %s Edad: %d \n", (pArrayPersona+i)->nombre, (pArrayPersona+i)->edad);
    }

    return 0;
}

Body:
when i try to assign more it overwrite the previous input.

Because in your code below:

for(i=0;i<sizeArrayPersonas;i++)
{
      printf("Ingrese nombre: ");
       __fpurge(stdin);
      fgets((pArrayPersona+i)->nombre,20,stdin);

      printf("Ingrese edad: ");
      scanf("%d", &(pArrayPersona+i)->edad);
}

You always input the value for pArrayPersona from 0 to sizeArrayPersonas - 1

In the next iteration, you have to input value for pArrayPersona[sizeArrayPersonas], it means the value of old sizeArrayPersonas+1_th elements (for example, in first iteration you input 2 values, then in the next iteration, after type s, you have to input for 3rd element, you do not need to re-enter the value of 1st and 2nd elements of pArrayPersona).

Your code in if condition can change it to:

Persona* pAuxArray = realloc(pArrayPersona,sizeof(Persona)*(sizeArrayPersonas+1));
if(pAuxArray == NULL) {
   free(pArrayPersona);
   return -1;
} else {
   pArrayPersona = pAuxArray;
   sizeArrayPersonas++;
}

You have to malloc for pArrayPersona before while loop instead of at the beginning of the while loop.

BTW, your while loop can be:

    int i = 0;
    pArrayPersona = malloc(sizeof(Persona)*sizeArrayPersonas);
    while(respuesta == 's')
    {
        for( ;i<sizeArrayPersonas;i++)
        {
            printf("Ingrese nombre: ");
            fgets((pArrayPersona+i)->nombre,20,stdin);

            printf("Ingrese edad: ");
            scanf("%d", &(pArrayPersona+i)->edad);
        }

        printf("Desea ingresar otro usuario? (s o n): ");
        scanf(" %c", &respuesta);

        if(respuesta == 's')
        {
            Persona* pAuxArray = realloc(pArrayPersona,sizeof(Persona)*(sizeArrayPersonas+1));
            if(pAuxArray == NULL) {
                free(pArrayPersona);
                return -1;
            } else {
                pArrayPersona = pAuxArray;
                sizeArrayPersonas++;
            }
        }
    }

Do not forget to free(pArrayPersona); at the end of program (when you do not need to use it).


问:
Add whitespace to string in Coldfusion
I need to add whitespace onto the end of a string.

ColdFusion seems to be automatically removing any whitespace I try to add, I'll sometimes get 1 empty space character but that's it.

I have an input field, a string, that can be up to 7 characters long. If the input is less than 7 characters, I'm to pad the end with spaces.

Does anyone know of a quick, easy, intuitive way to accomplish this using coldfusion. As little code as possible is preferred.

Some of the solutions I tried were:

```<code> #LEFT(FORM.strInput & '       ', 7)#

 #LEFT(FORM.strInput & '        0', 7)#

 #REPLACE(LEFT(FORM.strInput & 0000000, 7), '0', ' ', 'all')#

<CFLOOP FROM="1" TO="7 - LEN(FORM.strInput)">
  <CFSET FORM.strInput = FORM.strInput & ' '>
</CFLOOP>

<CFLOOP FROM="1" TO="7 - LEN(FORM.strInput)">
  <CFSET FORM.strInput = FORM.strInput & ' '>
</CFLOOP>
</code>```

答:
I like Scott's answer, but I would refine it a bit.</p>

```<code><script>
form.strInput &= repeatString(' ', max(7 - len(form.strInput), 0));
</script>
</code>```

Title: Add whitespace to string in Coldfusion

Body:
I need to add whitespace onto the end of a string.

ColdFusion seems to be automatically removing any whitespace I try to add, I'll sometimes get 1 empty space character but that's it.

I have an input field, a string, that can be up to 7 characters long. If the input is less than 7 characters, I'm to pad the end with spaces.

Does anyone know of a quick, easy, intuitive way to accomplish this using coldfusion. As little code as possible is preferred.

Some of the solutions I tried were:

 #LEFT(FORM.strInput & '       ', 7)#

 #LEFT(FORM.strInput & '        0', 7)#

 #REPLACE(LEFT(FORM.strInput & 0000000, 7), '0', ' ', 'all')#

<CFLOOP FROM="1" TO="7 - LEN(FORM.strInput)">
  <CFSET FORM.strInput = FORM.strInput & ' '>
</CFLOOP>

<CFLOOP FROM="1" TO="7 - LEN(FORM.strInput)">
  <CFSET FORM.strInput = FORM.strInput & ' '>
</CFLOOP>

Body:
I like Scott's answer, but I would refine it a bit.

<script>
form.strInput &= repeatString(' ', max(7 - len(form.strInput), 0));
</script>


问:
Why is the overloading operator "=" not working properly on my class for Dynamic Arrays? C++
I'm trying to work with dynamic arrays. When I try to overload the "=" operator it does not work. When debugging the file it doesn't execute the void function to overload the operator.

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

class cppArray {
public:
    cppArray(int size);
    ~cppArray();
    int read(int index);
    void write(int content, int index);
    void operator=(cppArray& s);
    int search(int target);
    int size();
private:
    int* myArray;
    int arraySize;
};

cppArray::cppArray(int size) {
    myArray = new int[size];
    arraySize = size;
}

//delete the memory space assigned to myArray
cppArray::~cppArray() {
    delete[] myArray;
    myArray = 0;
}

int cppArray::read(int index) {
    if (index < arraySize) {
        return myArray[index];
    }
    else {
        cout << "Out of range" << endl;
        exit(1);
    }
}
</code>```

Here I'm trying to copy the content of the original array to an auxiliar one, and then redefine the size of the original array so I can add more content to the original array

```<code>void cppArray::write(int content, int index) {
    if (index < arraySize) {
        myArray[index] = content;
    }
    else {
        cppArray auxArray(arraySize);
        auxArray.myArray = myArray;
        delete[] myArray;
        arraySize = index + 1;
        myArray = new int[arraySize];
        myArray = auxArray.myArray;
        myArray[index] = content;
    }
}
</code>```

I'm pretty sure this is wrong, but I can't figure out a way to overload it correctly

```<code>void cppArray::operator=(cppArray& s) {
    delete[] s.myArray;
    s.myArray = new int[arraySize];
    for (int i = 0; i < arraySize; i++)
    {
        myArray[i] = s.myArray[i];
    }
}

int cppArray::size() {
    return arraySize;
}

int main(int argc, char** argv) {
    cppArray dsArray(3);

    dsArray.write(1, 0);
    dsArray.write(2, 1);
    dsArray.write(3, 2);
    dsArray.write(4, 3);

    for (int i = 0; i < dsArray.size(); i++) {
        cout << dsArray.read(i) << "\t";
    }

    cout << endl;

    return 0;
}```
```

答:
Your implementation is almost correct, but you delete the wrong array. You should only modify *this object, and not s. Also, you should follow conventions, or people will be very surprised when using your class.

Here's corrected version:

```<code>//return *this - a very expected convention
cppArray& cppArray::operator=(const cppArray& s) {
// Make sure s is not modified ^^^^
    if (this == &s) {
        return *this; //protection against self writing, things would get bad if you did that
    }

    arraySize = s.arraySize; //copy size first
    delete[] myArray; //delete array from this object
    myArray = new int[arraySize]; //recreate array
    for (int i = 0; i < arraySize; i++)
    {
        myArray[i] = s.myArray[i]; //no changes here
    }

    return *this;
}
</code>```

Body:
I'm trying to work with dynamic arrays. When I try to overload the "=" operator it does not work. When debugging the file it doesn't execute the void function to overload the operator.

#include <iostream>
using namespace std;

class cppArray {
public:
    cppArray(int size);
    ~cppArray();
    int read(int index);
    void write(int content, int index);
    void operator=(cppArray& s);
    int search(int target);
    int size();
private:
    int* myArray;
    int arraySize;
};

cppArray::cppArray(int size) {
    myArray = new int[size];
    arraySize = size;
}

//delete the memory space assigned to myArray
cppArray::~cppArray() {
    delete[] myArray;
    myArray = 0;
}

int cppArray::read(int index) {
    if (index < arraySize) {
        return myArray[index];
    }
    else {
        cout << "Out of range" << endl;
        exit(1);
    }
}

Here I'm trying to copy the content of the original array to an auxiliar one, and then redefine the size of the original array so I can add more content to the original array

void cppArray::write(int content, int index) {
    if (index < arraySize) {
        myArray[index] = content;
    }
    else {
        cppArray auxArray(arraySize);
        auxArray.myArray = myArray;
        delete[] myArray;
        arraySize = index + 1;
        myArray = new int[arraySize];
        myArray = auxArray.myArray;
        myArray[index] = content;
    }
}

I'm pretty sure this is wrong, but I can't figure out a way to overload it correctly

void cppArray::operator=(cppArray& s) {
    delete[] s.myArray;
    s.myArray = new int[arraySize];
    for (int i = 0; i < arraySize; i++)
    {
        myArray[i] = s.myArray[i];
    }
}

int cppArray::size() {
    return arraySize;
}

int main(int argc, char** argv) {
    cppArray dsArray(3);

    dsArray.write(1, 0);
    dsArray.write(2, 1);
    dsArray.write(3, 2);
    dsArray.write(4, 3);

    for (int i = 0; i < dsArray.size(); i++) {
        cout << dsArray.read(i) << "\t";
    }

    cout << endl;

    return 0;
}```

Body:
Your implementation is almost correct, but you delete the wrong array. You should only modify *this object, and not s. Also, you should follow conventions, or people will be very surprised when using your class.

Here's corrected version:

//return *this - a very expected convention
cppArray& cppArray::operator=(const cppArray& s) {
// Make sure s is not modified ^^^^
    if (this == &s) {
        return *this; //protection against self writing, things would get bad if you did that
    }

    arraySize = s.arraySize; //copy size first
    delete[] myArray; //delete array from this object
    myArray = new int[arraySize]; //recreate array
    for (int i = 0; i < arraySize; i++)
    {
        myArray[i] = s.myArray[i]; //no changes here
    }

    return *this;
}