问:
Number of bytes used for Unicode characters in varchar

A common misconception is to think that CHAR(n) and VARCHAR(n), the n defines the number of characters. But in CHAR(n) and VARCHAR(n) the n defines the string length in bytes (0-8,000). n never defines numbers of characters that can be stored

According to this statement from Microsoft, I assume, n is the data length of a string and when we store unicode characters in varchar, a single character should take 2 bytes. But, when I try with a sample as below, I see varchar data taking 1 byte instead of 2 bytes.

```<code>declare @varchar varchar(6), @nvarchar nvarchar(6)

set @varchar = 'Ø'

select @varchar as VarcharString, len(@varchar) as VarcharStringLength, DATALENGTH(@varchar) as VarcharStringDataLength

</code>```

Could someone explain the reason behind it?

答:
You can store unicode in varchar (if you want to), however every byte is interpreted as a single character, while unicode (for sql server, utf16, ucs2) uses 2 bytes for a single character and you have to account for that, when displaying unicode stored in varchar.</p>

```<code>declare @nv nvarchar(10) = N'❤'
select @nv;

declare @v varchar(10) = cast(cast(@nv as varbinary(10)) as varchar(10))
select @v, len(@v); --two chars

select cast(@nv as varbinary(10)), cast(@v as varbinary(10)); --same bytes in both n/var char
--display nchar from char
select cast(cast(@v as varbinary(10)) as nvarchar(10));
</code>```

Body:
A common misconception is to think that CHAR(n) and VARCHAR(n), the n defines the number of characters. But in CHAR(n) and VARCHAR(n) the n defines the string length in bytes (0-8,000). n never defines numbers of characters that can be stored

According to this statement from Microsoft, I assume, n is the data length of a string and when we store unicode characters in varchar, a single character should take 2 bytes. But, when I try with a sample as below, I see varchar data taking 1 byte instead of 2 bytes.

declare @varchar varchar(6), @nvarchar nvarchar(6)

set @varchar = 'Ø'

select @varchar as VarcharString, len(@varchar) as VarcharStringLength, DATALENGTH(@varchar) as VarcharStringDataLength

Could someone explain the reason behind it?

Body:
You can store unicode in varchar (if you want to), however every byte is interpreted as a single character, while unicode (for sql server, utf16, ucs2) uses 2 bytes for a single character and you have to account for that, when displaying unicode stored in varchar.

declare @nv nvarchar(10) = N'❤'
select @nv;

declare @v varchar(10) = cast(cast(@nv as varbinary(10)) as varchar(10))
select @v, len(@v); --two chars

select cast(@nv as varbinary(10)), cast(@v as varbinary(10)); --same bytes in both n/var char
--display nchar from char
select cast(cast(@v as varbinary(10)) as nvarchar(10));


来源: stackexchange

问:
Python - Count Numbers of Different Digits in String
I'm very new to Python, please help.

I can only use if else statements, no loops or anything special like that.

This program asks the user for one string.
It counts the number of different digits in the string.  for
example a11111a1a1 contains a single digit, while a1s2d1d2d1d2d1
contains 2 digits.

Examples:

```<code>% python3 countNumbers.py
enter string: qwerty
there are no digits in string: "qwerty"

% python3 countNumbers.py
enter string: asdf1sdfg
there is one digit in string: "asdf1sdfg"

% python3 countNumbers.py
enter string: as1as2as333333
there are 3 different digits in string: "as1as2as333333"

% python3 countNumbers.py
enter string: a0123456789x
there are 10 different digits in string: "a0123456789x"
</code>```

```<code>num = input("enter string: ")
count = 0

if "0" in num:
    count = count + 1
if "1" in num:
    count = count + 1
if "2" in num:
    count = count + 1
if "3" in num:
    count = count + 1
if "4" in num:
    count = count + 1
if "5" in num:
    count = count + 1
if "6" in num:
    count = count + 1
if "7" in num:
    count = count + 1
if "8" in num:
    count = count + 1
if "9" in num:
    count = count + 1

if count >= 1:
    print("there is one digit in string: ", num)
elif count >= 2:
    print("there are two digits in string: ", num)
else:
    print("there are no digits in string: ", num)

</code>```

答:
Here it is</p>

```<code>count_dict = {}
for i in range(0, 10):
    if i in num and i not in count_dict:
        count_dict[i] = 1 # just adding the integer to a dict
    else:
        continue

print('there are {} different integers in string {}'.format(len(count_dict), num)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm very new to Python, please help.

I can only use if else statements, no loops or anything special like that.

This program asks the user for one string.
It counts the number of different digits in the string.  for
example a11111a1a1 contains a single digit, while a1s2d1d2d1d2d1
contains 2 digits.

Examples:

% python3 countNumbers.py
enter string: qwerty
there are no digits in string: "qwerty"

% python3 countNumbers.py
enter string: asdf1sdfg
there is one digit in string: "asdf1sdfg"

% python3 countNumbers.py
enter string: as1as2as333333
there are 3 different digits in string: "as1as2as333333"

% python3 countNumbers.py
enter string: a0123456789x
there are 10 different digits in string: "a0123456789x"

num = input("enter string: ")
count = 0

if "0" in num:
    count = count + 1
if "1" in num:
    count = count + 1
if "2" in num:
    count = count + 1
if "3" in num:
    count = count + 1
if "4" in num:
    count = count + 1
if "5" in num:
    count = count + 1
if "6" in num:
    count = count + 1
if "7" in num:
    count = count + 1
if "8" in num:
    count = count + 1
if "9" in num:
    count = count + 1

if count >= 1:
    print("there is one digit in string: ", num)
elif count >= 2:
    print("there are two digits in string: ", num)
else:
    print("there are no digits in string: ", num)

Body:
Here it is

count_dict = {}
for i in range(0, 10):
    if i in num and i not in count_dict:
        count_dict[i] = 1 # just adding the integer to a dict
    else:
        continue

print('there are {} different integers in string {}'.format(len(count_dict), num)


问:
How to retain the type of list elements after stored in a dictionary?
I have a nested dictionary, which is of following form.

```<code>import pickle

db = {'obj 1':
        {
        'a' : 1, 'b' : 2, 'c' : 3,
        'foo': [0, a, a+b, 2*a, 2*(b+c)],
        'bar': [c, c+a, c-b, 2*c, 2*a]
        },
    'obj 2':
        {
        'a' : 4, 'b' : 5, 'c' : 6,
        'foo': [0, a, a+b, 2*a, 2*(b+c), 0, 0],
        'bar': [c, c+a, c-b, 2*c, 2*a, 0, 0]
        },
}

with open("db.pkl", "wb") as pkl:
    pickle.dump(db, pkl)

print(db)
</code>```

It's throwing this error:

```<code>Traceback (most recent call last):
  File "dmy.py", line 8, in <module>
    'foo': [0, a, a+b, 2*a, 2*(b+c)],
NameError: name 'a' is not defined
</code>```

Is there anything I can do such that I'll get the output for dmy = db['obj 1']['foo'] to be [0, a, a+b, 2*a, 2*(b+c)] which is a list.
I understand what I am doing may not be the right approach, but I need the contents together like this.

Note: I already tried converting the list elements individually into strings, but while parsing, I couldn't get the content in this specified form i.e [0, a, a+b, 2*a, 2*(b+c)].

Closest I could find was this link Python - is there a way to store an operation(+ - * /) in a list or as a variable?

答:
The problem is that a, b and c are members of your (not-yet existing) dict. They are not variables, so

```<code>    {
    'a' : 1, 'b' : 2, 'c' : 3,
    'foo': [0, a, a+b, 2*a, 2*(b+c)],
    'bar': [c, c+a, c-b, 2*c, 2*a]
    },
</code>```

doesn't work.

You can solve this problem in the following way:

```<code>import pickle

def build_dict(a, b, c, add=None):
    if add is None: add = []
    return {
        'a': a, 'b': b, 'c' : c,
        'foo': [0, a, a+b, 2*a, 2*(b+c)] + add,
        'bar': [c, c+a, c-b, 2*c, 2*a] + add
    }

db = {'obj 1': build_dict(1, 2, 3),
      'obj 2': build_dict(4, 5, 6, [0, 0])}

with open("db.pkl", "wb") as pkl:
    pickle.dump(db, pkl)

print(db)
</code>```

This makes the variables a, b and c exist and usable.

Another way to do it could be

```<code>    transform({'a' : 1, 'b' : 2, 'c' : 3, lambda a, b, c: {'foo': [0, a, a+b, 2*a, 2*(b+c)], 'bar': [c, c+a, c-b, 2*c, 2*a]})
    transform({'a' : 4, 'b' : 5, 'c' : 6, lambda a, b, c: {'foo': [0, a, a+b, 2*a, 2*(b+c), 0, 0], 'bar': [c, c+a, c-b, 2*c, 2*a, 0, 0]})
</code>```

with

```<code>def transform(base, transform):
    base.update(transform(**base))
    return base
</code>```

or

```<code>    transform({'a' : 1, 'b' : 2, 'c' : 3, lambda base: {'foo': [0, base['a'], base['a']+base['b'], 2*base['a'], 2*(base['b']+base['c'])], 'bar': [base['c'], base['c']+base['a'], base['c']-base['b']b, 2*base['c'], 2*base['a']]})
    transform({'a' : 4, 'b' : 5, 'c' : 6, lambda base: {'foo': 0, base['a'], base['a']+base['b'], 2*base['a'], 2*(base['b']+base['c']), 0, 0], 'bar': [base['c'], base['c']+base['a'], base['c']-base['b']b, 2*base['c'], 2*base['a'], 0, 0]})
</code>```

with

```<code>def transform(base, transform):
    base.update(transform(**base))
    return base
</code>```

Body:
I have a nested dictionary, which is of following form.

import pickle

db = {'obj 1':
        {
        'a' : 1, 'b' : 2, 'c' : 3,
        'foo': [0, a, a+b, 2*a, 2*(b+c)],
        'bar': [c, c+a, c-b, 2*c, 2*a]
        },
    'obj 2':
        {
        'a' : 4, 'b' : 5, 'c' : 6,
        'foo': [0, a, a+b, 2*a, 2*(b+c), 0, 0],
        'bar': [c, c+a, c-b, 2*c, 2*a, 0, 0]
        },
}

with open("db.pkl", "wb") as pkl:
    pickle.dump(db, pkl)

print(db)

It's throwing this error:

Traceback (most recent call last):
  File "dmy.py", line 8, in <module>
    'foo': [0, a, a+b, 2*a, 2*(b+c)],
NameError: name 'a' is not defined

Is there anything I can do such that I'll get the output for dmy = db['obj 1']['foo'] to be [0, a, a+b, 2*a, 2*(b+c)] which is a list.
I understand what I am doing may not be the right approach, but I need the contents together like this.

Note: I already tried converting the list elements individually into strings, but while parsing, I couldn't get the content in this specified form i.e [0, a, a+b, 2*a, 2*(b+c)].

Closest I could find was this link Python - is there a way to store an operation(+ - * /) in a list or as a variable?

Body:
The problem is that a, b and c are members of your (not-yet existing) dict. They are not variables, so

    {
    'a' : 1, 'b' : 2, 'c' : 3,
    'foo': [0, a, a+b, 2*a, 2*(b+c)],
    'bar': [c, c+a, c-b, 2*c, 2*a]
    },

doesn't work.

You can solve this problem in the following way:

import pickle

def build_dict(a, b, c, add=None):
    if add is None: add = []
    return {
        'a': a, 'b': b, 'c' : c,
        'foo': [0, a, a+b, 2*a, 2*(b+c)] + add,
        'bar': [c, c+a, c-b, 2*c, 2*a] + add
    }

db = {'obj 1': build_dict(1, 2, 3),
      'obj 2': build_dict(4, 5, 6, [0, 0])}

with open("db.pkl", "wb") as pkl:
    pickle.dump(db, pkl)

print(db)

This makes the variables a, b and c exist and usable.

Another way to do it could be

    transform({'a' : 1, 'b' : 2, 'c' : 3, lambda a, b, c: {'foo': [0, a, a+b, 2*a, 2*(b+c)], 'bar': [c, c+a, c-b, 2*c, 2*a]})
    transform({'a' : 4, 'b' : 5, 'c' : 6, lambda a, b, c: {'foo': [0, a, a+b, 2*a, 2*(b+c), 0, 0], 'bar': [c, c+a, c-b, 2*c, 2*a, 0, 0]})

with

def transform(base, transform):
    base.update(transform(**base))
    return base

or

    transform({'a' : 1, 'b' : 2, 'c' : 3, lambda base: {'foo': [0, base['a'], base['a']+base['b'], 2*base['a'], 2*(base['b']+base['c'])], 'bar': [base['c'], base['c']+base['a'], base['c']-base['b']b, 2*base['c'], 2*base['a']]})
    transform({'a' : 4, 'b' : 5, 'c' : 6, lambda base: {'foo': 0, base['a'], base['a']+base['b'], 2*base['a'], 2*(base['b']+base['c']), 0, 0], 'bar': [base['c'], base['c']+base['a'], base['c']-base['b']b, 2*base['c'], 2*base['a'], 0, 0]})

with

def transform(base, transform):
    base.update(transform(**base))
    return base


问:
flutter want call parent view upon its child to refresh main view
I have a Stateful widget that has a child buttons and set of stateful containers (visible and invisible).
I want to try here is when i call the specific button, the specific button will refresh all layout and change it on its specifict view by setting visible while the others are not visible.

like this:

```<code>button1 = view1;
button2 = view2;
button3 = view3;

if (button1 is pressed){
view1 is visible}
 else{
not visible}
</code>```

upon my code, upon my first view(login button),I've set to go with my main_page like this:

```<code>child: MaterialButton(
        minWidth: MediaQuery.of(context).size.width,
        padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => MainPage(change1: true,change2: false,change3: false,)),
          );
        },

now i was display my main_page view (with a child view  that has visibility property).
</code>```

this is my code on main_page:

```<code>class MainPage extends StatefulWidget {

  final bool change1 ;
  final bool change2;
  final bool change3 ;

  const MainPage({Key key, this.change1,this.change2,this.change3}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();

}

class _MainPageState extends State<MainPage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Container(
              constraints: BoxConstraints.expand(
                height: 280.0,
              ),
              decoration: BoxDecoration(
                image: new DecorationImage(
                  fit: BoxFit.cover,
                  colorFilter: new ColorFilter.mode(
                      Colors.blueAccent, BlendMode.colorBurn),
                  image: new ExactAssetImage("images/vector.jpg"),
                ),
              ),
              child: Stack(
                children: <Widget>[

                  Container(
                    alignment: Alignment.bottomCenter,
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: GestureDetector(
                            onTap: () {
                              setState(() {
                                print("i pressed Official Business");

                                 MainPage(change1: true,change2: false,change3: false);
                                  //TODO: here is my problem, when i call the main_page on its page,
                                //        the value of change1, change2, and chaange3 is not updating
                                 //       so that icanot update my view .

                              });
                            },
                            child: Container(
                              height: 50.0,
                              child: Padding(
                                padding: const EdgeInsets.all(10.0),
                                child: Center(
                                  child: Text(
                                    "Official Business",
                                    style: TextStyle(
                                        fontSize: 20.0, color: Colors.white),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                        Expanded(
                          child: GestureDetector(
                            onTap: () {
                              setState(() {
                                print("i pressed file an OB");
                                 MainPage(change1: false,change2: true,change3: false);

                                //TODO: here is my problem, when i call the main_page on its page,
                                //        the value of change1, change2, and chaange3 is not updating
                                 //       so that icanot update my view .

                              });
                            },
                            child: Container(
                              height: 50.0,
                              child: Padding(
                                padding: const EdgeInsets.all(10.0),
                                child: Center(
                                  child: Text(
                                    "File an OB",
                                    style: TextStyle(
                                        fontSize: 20.0, color: Colors.white),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),

                ],
              ),
            ),
            //TODO:
            new Visibility(
              //Called changed and viewOne
              visible: widget.change1,
              child: OfficialBusiness(),
            ),
            new Visibility(
              //Called not changed and viewTwo
              visible: widget.change2,
              child: FilingOb(),
            ),
            new Visibility(
              //Called not changed and viewTwo
              visible: widget.change3,
              child: ViewOfficialBusiness(),
            )

     ],
    ),
  ),
);
</code>```

}
}

the fillingob/officialbusiness/ViewOfficialBusiness includded was set of stateful layout, i didn't add the code to prevent over views.

sorry, in new on this programming language and i've like to enlighten with these problems i've encountered if my code is possible or not.Also if you need more reference just ping on comment so that i can provide my other codes

答:
```<code>  bool change1;
  bool change2;
  bool change3;

  @override
  initState() {
    super.initState();
    change1 = widget.change1;
    change2 = widget.change2;
    change3 = widget.change3;
  }

  void setChange1() {
    setState(() {
      change1 = true;
      change2 = change3 = false;
    });
  }

// GestureDetector(onTap: setChange1)

// Visibility(
//   visible: change1,
//   child: OfficialBusiness(),
// )

</code>```

Or use enum :

```<code>enum MyView {
  officialBusiness,
  filingOb,
  viewOfficialBusiness,
}
</code>```

```<code>MyView current;

// GestureDetector(onTap: () => setState(() { current = MyView.officialBusiness; }))

// Visibility(
//   visible: current == MyView.officialBusiness,
//   child: OfficialBusiness(),
// )
</code>```

Body:
I have a Stateful widget that has a child buttons and set of stateful containers (visible and invisible).
I want to try here is when i call the specific button, the specific button will refresh all layout and change it on its specifict view by setting visible while the others are not visible.

like this:

button1 = view1;
button2 = view2;
button3 = view3;

if (button1 is pressed){
view1 is visible}
 else{
not visible}

upon my code, upon my first view(login button),I've set to go with my main_page like this:

child: MaterialButton(
        minWidth: MediaQuery.of(context).size.width,
        padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => MainPage(change1: true,change2: false,change3: false,)),
          );
        },

now i was display my main_page view (with a child view  that has visibility property).

this is my code on main_page:

class MainPage extends StatefulWidget {

  final bool change1 ;
  final bool change2;
  final bool change3 ;

  const MainPage({Key key, this.change1,this.change2,this.change3}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();

}

class _MainPageState extends State<MainPage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Container(
              constraints: BoxConstraints.expand(
                height: 280.0,
              ),
              decoration: BoxDecoration(
                image: new DecorationImage(
                  fit: BoxFit.cover,
                  colorFilter: new ColorFilter.mode(
                      Colors.blueAccent, BlendMode.colorBurn),
                  image: new ExactAssetImage("images/vector.jpg"),
                ),
              ),
              child: Stack(
                children: <Widget>[

                  Container(
                    alignment: Alignment.bottomCenter,
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: GestureDetector(
                            onTap: () {
                              setState(() {
                                print("i pressed Official Business");

                                 MainPage(change1: true,change2: false,change3: false);
                                  //TODO: here is my problem, when i call the main_page on its page,
                                //        the value of change1, change2, and chaange3 is not updating
                                 //       so that icanot update my view .

                              });
                            },
                            child: Container(
                              height: 50.0,
                              child: Padding(
                                padding: const EdgeInsets.all(10.0),
                                child: Center(
                                  child: Text(
                                    "Official Business",
                                    style: TextStyle(
                                        fontSize: 20.0, color: Colors.white),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                        Expanded(
                          child: GestureDetector(
                            onTap: () {
                              setState(() {
                                print("i pressed file an OB");
                                 MainPage(change1: false,change2: true,change3: false);

                                //TODO: here is my problem, when i call the main_page on its page,
                                //        the value of change1, change2, and chaange3 is not updating
                                 //       so that icanot update my view .

                              });
                            },
                            child: Container(
                              height: 50.0,
                              child: Padding(
                                padding: const EdgeInsets.all(10.0),
                                child: Center(
                                  child: Text(
                                    "File an OB",
                                    style: TextStyle(
                                        fontSize: 20.0, color: Colors.white),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),

                ],
              ),
            ),
            //TODO:
            new Visibility(
              //Called changed and viewOne
              visible: widget.change1,
              child: OfficialBusiness(),
            ),
            new Visibility(
              //Called not changed and viewTwo
              visible: widget.change2,
              child: FilingOb(),
            ),
            new Visibility(
              //Called not changed and viewTwo
              visible: widget.change3,
              child: ViewOfficialBusiness(),
            )

     ],
    ),
  ),
);

}
}

the fillingob/officialbusiness/ViewOfficialBusiness includded was set of stateful layout, i didn't add the code to prevent over views.

sorry, in new on this programming language and i've like to enlighten with these problems i've encountered if my code is possible or not.Also if you need more reference just ping on comment so that i can provide my other codes

Body:
  bool change1;
  bool change2;
  bool change3;

  @override
  initState() {
    super.initState();
    change1 = widget.change1;
    change2 = widget.change2;
    change3 = widget.change3;
  }

  void setChange1() {
    setState(() {
      change1 = true;
      change2 = change3 = false;
    });
  }

// GestureDetector(onTap: setChange1)

// Visibility(
//   visible: change1,
//   child: OfficialBusiness(),
// )

Or use enum :

enum MyView {
  officialBusiness,
  filingOb,
  viewOfficialBusiness,
}

MyView current;

// GestureDetector(onTap: () => setState(() { current = MyView.officialBusiness; }))

// Visibility(
//   visible: current == MyView.officialBusiness,
//   child: OfficialBusiness(),
// )


问:
Does updating one field will download the whole document from the database or just update local version?
For example the document contains the following structure:

```<code>{
  fieldA: number,
  fieldB: {
    subFieldA: string,
    subFieldB: string,
  }
}
</code>```

... and is being listened with the onSnapshot method.

```<code>FirebaseDb
  .collection(`someCollection`).doc('documentAbove')
  .onSnapshot({ includeMetadataChanges: true }, (snapshot) => {
    // when the document being modified it becomes available at this stage
  })
</code>```

My question is if when the document will be modified will the firestore download it once again?

答: Yes, the document will be downloaded again in its entirety while that listener is active, and you will be charged for a read on that document for each change.</p>

Body:
For example the document contains the following structure:

{
  fieldA: number,
  fieldB: {
    subFieldA: string,
    subFieldB: string,
  }
}

... and is being listened with the onSnapshot method.

FirebaseDb
  .collection(`someCollection`).doc('documentAbove')
  .onSnapshot({ includeMetadataChanges: true }, (snapshot) => {
    // when the document being modified it becomes available at this stage
  })

My question is if when the document will be modified will the firestore download it once again?


问:
Try to filter ListView.builder inside StreamBuilder in Flutter
i'm newbie in Flutter and I'm  trying to develop an app, so nom have a trouble with how to show a filtered ListView.builder

This is the widget code:

```<code>@override
Widget build(BuildContext context) {

print('Favorites');
return Container(
  color: AppColors.hexToColor('F0F4F5'),
  alignment: Alignment.topCenter,
  child: Column(
    children: <Widget>[
      HeaderCity(),
      Expanded(
        child: Container(
          padding: EdgeInsets.only(left: 16.0, right: 16.0),
          child: Container(
            child: StreamBuilder<CoworkingState>(
                stream: Provider.coworkingBlocOf(context).streamCoworkingState,
                initialData: CoworkingState(),
                builder: (BuildContext context, AsyncSnapshot<CoworkingState> snapshot) {
                  return (snapshot.data.isLoading)
                      ? CustomCircularLoader()
                      : ListView.builder(
                          padding: EdgeInsets.all(0.0),
                          itemBuilder: (BuildContext context, int index) {
                            if (snapshot.data.coworking.any((isFavorite) => true)){
                              return CoworkingCellDetail(
                                onTap: () {
                                  Provider.coworkingBlocOf(context)
                                      .selectCoworking(coworking: snapshot.data.coworking[index]);
                                  Future.delayed(Duration.zero, () {
                                    changeRoute(context, Routes.coworkDetail, false);
                                  });
                                },
                                isFavorite: snapshot.data.coworking[index].isFavorite,
                                name: snapshot.data.coworking[index].name,
                                adress: snapshot.data.coworking[index].address,
                                phone: snapshot.data.coworking[index].phone,
                                hour: snapshot.data.coworking[index].openingHours,
                                urlImages: snapshot.data.coworking[index].imagesUrl,
                                onFavoriteTap: () {
                                  Provider.coworkingBlocOf(context).removeFavorite(snapshot.data.coworking[index].id);
                                }
                              );
                            } return null;
                          },
                          itemCount: snapshot.data.coworking.length,
                        );
                }),
          ),
        ),
      ),
    ],
  ),
);
</code>```

}

So now this  are returning a complete list and I only want to show items with isFavorite = true

答:
Assuming your isFavorite datatype is bool, if it is a String change the below if statement to this snapshot.data.coworking[index].isFavorite.toString() == "true"</p>

```<code>if(snapshot.data.coworking[index].isFavorite){
       return CoworkingCellDetail(
                                onTap: () {
                                  Provider.coworkingBlocOf(context)
                                      .selectCoworking(coworking: snapshot.data.coworking[index]);
                                  Future.delayed(Duration.zero, () {
                                    changeRoute(context, Routes.coworkDetail, false);
                                  });
                                },
                                isFavorite: snapshot.data.coworking[index].isFavorite,
                                name: snapshot.data.coworking[index].name,
                                adress: snapshot.data.coworking[index].address,
                                phone: snapshot.data.coworking[index].phone,
                                hour: snapshot.data.coworking[index].openingHours,
                                urlImages: snapshot.data.coworking[index].imagesUrl,
                                onFavoriteTap: () {
                                  Provider.coworkingBlocOf(context).removeFavorite(snapshot.data.coworking[index].id);
                                }
                              );
    }
</code>```

Body:
i'm newbie in Flutter and I'm  trying to develop an app, so nom have a trouble with how to show a filtered ListView.builder

This is the widget code:

@override
Widget build(BuildContext context) {

print('Favorites');
return Container(
  color: AppColors.hexToColor('F0F4F5'),
  alignment: Alignment.topCenter,
  child: Column(
    children: <Widget>[
      HeaderCity(),
      Expanded(
        child: Container(
          padding: EdgeInsets.only(left: 16.0, right: 16.0),
          child: Container(
            child: StreamBuilder<CoworkingState>(
                stream: Provider.coworkingBlocOf(context).streamCoworkingState,
                initialData: CoworkingState(),
                builder: (BuildContext context, AsyncSnapshot<CoworkingState> snapshot) {
                  return (snapshot.data.isLoading)
                      ? CustomCircularLoader()
                      : ListView.builder(
                          padding: EdgeInsets.all(0.0),
                          itemBuilder: (BuildContext context, int index) {
                            if (snapshot.data.coworking.any((isFavorite) => true)){
                              return CoworkingCellDetail(
                                onTap: () {
                                  Provider.coworkingBlocOf(context)
                                      .selectCoworking(coworking: snapshot.data.coworking[index]);
                                  Future.delayed(Duration.zero, () {
                                    changeRoute(context, Routes.coworkDetail, false);
                                  });
                                },
                                isFavorite: snapshot.data.coworking[index].isFavorite,
                                name: snapshot.data.coworking[index].name,
                                adress: snapshot.data.coworking[index].address,
                                phone: snapshot.data.coworking[index].phone,
                                hour: snapshot.data.coworking[index].openingHours,
                                urlImages: snapshot.data.coworking[index].imagesUrl,
                                onFavoriteTap: () {
                                  Provider.coworkingBlocOf(context).removeFavorite(snapshot.data.coworking[index].id);
                                }
                              );
                            } return null;
                          },
                          itemCount: snapshot.data.coworking.length,
                        );
                }),
          ),
        ),
      ),
    ],
  ),
);

}

So now this  are returning a complete list and I only want to show items with isFavorite = true

Body:
Assuming your isFavorite datatype is bool, if it is a String change the below if statement to this snapshot.data.coworking[index].isFavorite.toString() == "true"

if(snapshot.data.coworking[index].isFavorite){
       return CoworkingCellDetail(
                                onTap: () {
                                  Provider.coworkingBlocOf(context)
                                      .selectCoworking(coworking: snapshot.data.coworking[index]);
                                  Future.delayed(Duration.zero, () {
                                    changeRoute(context, Routes.coworkDetail, false);
                                  });
                                },
                                isFavorite: snapshot.data.coworking[index].isFavorite,
                                name: snapshot.data.coworking[index].name,
                                adress: snapshot.data.coworking[index].address,
                                phone: snapshot.data.coworking[index].phone,
                                hour: snapshot.data.coworking[index].openingHours,
                                urlImages: snapshot.data.coworking[index].imagesUrl,
                                onFavoriteTap: () {
                                  Provider.coworkingBlocOf(context).removeFavorite(snapshot.data.coworking[index].id);
                                }
                              );
    }


问:
how to update/replace list items inside a nested loop after matching the condition?
image is added so that you can look how my dataframe df2 will look like

i have written a code to check condition and if it matches it will update the items of my list but it's working at all it return me the same not updated or same previous list. is this code wrong?
please suggest

```<code>emp1=[]
for j in range(8,df.shape[0],10):
    for i in range(2,len(df.columns)):
        b=df.iloc[j][3]
        #values are appended from dataframe to list and values are like['3 : 3','4 : 4',.....]

ess=[]
for i in range(df2.shape[0]):
    a=df2.iloc[i][2]
    ess.append(a) #values taken from file which are(3,4,5,6,7,8,....etc i.e unique id number)
nm=[]
for i in range(df2.shape[0]):
    b=df2.iloc[i][3]
    nm.append(b) #this list contains name of the employees

ap= [i.split(' : ', 1)[0] for i in emp1]  #split it with ' : ' and stored in two another list(if 3 : 3 then it will store left 3)
bp= [i.split(' : ', 1)[1] for i in emp1] #if 3 : 3 the it will store right 3
cp=' : '

#the purpose is to replace right 3 with the name i.e 3 : nameabc and then again join to the list
for i in range(len(emp1)):
    for j in range(len(ess)):
        #print(i,j)
        if ap[i]==ess[j]:
           bp[i]=nm[j]

for i in range(df.shape[0]):
    ap[i]=ap[i]+cp      # adding ' : ' after left integer

emp = [i + j for i, j in zip(ap, bp)] # joining both the values
</code>```

expected output:
if emp1 contains 3 : 3
then after processing it should show like 3 : nameabc

答: May be I missed something, but I don't see you assigning any value to emp1. Its empty and for "ap" and "bp", you are looping over empty emp1. That may be the one causing problem.</p>

Body:
image is added so that you can look how my dataframe df2 will look like

i have written a code to check condition and if it matches it will update the items of my list but it's working at all it return me the same not updated or same previous list. is this code wrong?
please suggest

emp1=[]
for j in range(8,df.shape[0],10):
    for i in range(2,len(df.columns)):
        b=df.iloc[j][3]
        #values are appended from dataframe to list and values are like['3 : 3','4 : 4',.....]

ess=[]
for i in range(df2.shape[0]):
    a=df2.iloc[i][2]
    ess.append(a) #values taken from file which are(3,4,5,6,7,8,....etc i.e unique id number)
nm=[]
for i in range(df2.shape[0]):
    b=df2.iloc[i][3]
    nm.append(b) #this list contains name of the employees

ap= [i.split(' : ', 1)[0] for i in emp1]  #split it with ' : ' and stored in two another list(if 3 : 3 then it will store left 3)
bp= [i.split(' : ', 1)[1] for i in emp1] #if 3 : 3 the it will store right 3
cp=' : '

#the purpose is to replace right 3 with the name i.e 3 : nameabc and then again join to the list
for i in range(len(emp1)):
    for j in range(len(ess)):
        #print(i,j)
        if ap[i]==ess[j]:
           bp[i]=nm[j]

for i in range(df.shape[0]):
    ap[i]=ap[i]+cp      # adding ' : ' after left integer

emp = [i + j for i, j in zip(ap, bp)] # joining both the values

expected output:
if emp1 contains 3 : 3
then after processing it should show like 3 : nameabc


问:
Why does my function to adjust view according to keyboard height behave erratically?
I am trying to re-create a Facebook sign up page for practice; the set up of my viewController is as follows:
1)A profile image container at the top,
2)Email textfield
3)Password Textfield
4)Confirm Password textfield

To solve the issue of the keyboard blocking the "Confirm Password" field, I have used listeners as below.

The issue is that the very first time a user clicks on a textfield to type (no matter which one), the screen moves way too far up, such that the email textfield at the top ends up going beyond the screen size on top. However, when I dismiss the keyboard and re-click on any textfield, it goes up as intended: Only until the top textfield reaches the top of the screen.

I can find no other reason for this behaviour, it persisted even after I re-wrote some of my code.

My ViewController set up:

```<code>class ViewController: UIViewController {

@objc func dismissKeyboard() {
        view.endEditing(true)
}

let imageContainer: UIView = {
   let v = UIView()
    v.translatesAutoresizingMaskIntoConstraints = false
    v.backgroundColor = .red
    return v
}()

let emailTF: UITextField = {
   let tf = UITextField()
    tf.translatesAutoresizingMaskIntoConstraints = false
    tf.placeholder = "EMAIL"
    return tf
}()

let passwordTF: UITextField = {
   let tf = UITextField()
    tf.translatesAutoresizingMaskIntoConstraints = false
    tf.placeholder = "Password"
    return tf
}()

let confirmPasswordTF: UITextField = {
   let tf = UITextField()
    tf.translatesAutoresizingMaskIntoConstraints = false
    tf.placeholder = "Confirm password"
    return tf
}()

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0 {
            self.view.frame.origin.y -= keyboardSize.height
        }
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    if self.view.frame.origin.y != 0 {
        self.view.frame.origin.y = 0
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .lightGray

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
       NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

    view.addSubview(imageContainer)
    view.addSubview(emailTF)
    view.addSubview(passwordTF)
    view.addSubview(confirmPasswordTF)

            NSLayoutConstraint.activate([

            imageContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            imageContainer.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.275),
            imageContainer.widthAnchor.constraint(equalTo: view.heightAnchor),
            imageContainer.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),

            emailTF.topAnchor.constraint(equalTo: imageContainer.bottomAnchor),
            emailTF.heightAnchor.constraint(equalToConstant: 100),
            emailTF.widthAnchor.constraint(equalToConstant: 200),
            emailTF.centerXAnchor.constraint(equalTo: view.centerXAnchor),

            passwordTF.topAnchor.constraint(equalTo: emailTF.bottomAnchor, constant: 20),
            passwordTF.heightAnchor.constraint(equalToConstant: 100),
            passwordTF.widthAnchor.constraint(equalToConstant: 200),
            passwordTF.centerXAnchor.constraint(equalTo: view.centerXAnchor),

            confirmPasswordTF.topAnchor.constraint(equalTo: passwordTF.bottomAnchor, constant: 20),
            confirmPasswordTF.heightAnchor.constraint(equalToConstant: 100),
            confirmPasswordTF.widthAnchor.constraint(equalToConstant: 200),
            confirmPasswordTF.centerXAnchor.constraint(equalTo: view.centerXAnchor),

        ])

    let tapToDismissKeyboard: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
    view.addGestureRecognizer(tapToDismissKeyboard)

    }

}
</code>```

I'd really appreciate some help as to what I can do to correct this issue.

答:
Seems like this is a known issue raised here and other SO questions too..

Two points to make:-

1) Use UIResponder.keyboardFrameEndUserInfoKey instead of UIResponder.keyboardFrameBeginUserInfoKey at:

```<code>if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
</code>```

in keyboardWillShow()

2) Doing so, you will get the total height of the keyboard including the toolbar. Which means:

However, when I dismiss the keyboard and re-click on any textfield, it
  goes up as intended: Only until the top textfield reaches the top of
  the screen.

This is the buggy behaviour where you get an incorrect height excluding the toolbar and:

The issue is that the very first time a user clicks on a textfield to
  type (no matter which one), the screen moves way too far up, such that
  the email textfield at the top ends up going beyond the screen size on
  top.

This is actually the intended behaviour with actual height. You could calculate the height of the toolbar and reduce it from this height to achieve your goal! If your VC is embedded in a navigation controller, you could use this

Hope this helps.

Body:
I am trying to re-create a Facebook sign up page for practice; the set up of my viewController is as follows:
1)A profile image container at the top,
2)Email textfield
3)Password Textfield
4)Confirm Password textfield

To solve the issue of the keyboard blocking the "Confirm Password" field, I have used listeners as below.

The issue is that the very first time a user clicks on a textfield to type (no matter which one), the screen moves way too far up, such that the email textfield at the top ends up going beyond the screen size on top. However, when I dismiss the keyboard and re-click on any textfield, it goes up as intended: Only until the top textfield reaches the top of the screen.

I can find no other reason for this behaviour, it persisted even after I re-wrote some of my code.

My ViewController set up:

class ViewController: UIViewController {

@objc func dismissKeyboard() {
        view.endEditing(true)
}

let imageContainer: UIView = {
   let v = UIView()
    v.translatesAutoresizingMaskIntoConstraints = false
    v.backgroundColor = .red
    return v
}()

let emailTF: UITextField = {
   let tf = UITextField()
    tf.translatesAutoresizingMaskIntoConstraints = false
    tf.placeholder = "EMAIL"
    return tf
}()

let passwordTF: UITextField = {
   let tf = UITextField()
    tf.translatesAutoresizingMaskIntoConstraints = false
    tf.placeholder = "Password"
    return tf
}()

let confirmPasswordTF: UITextField = {
   let tf = UITextField()
    tf.translatesAutoresizingMaskIntoConstraints = false
    tf.placeholder = "Confirm password"
    return tf
}()

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0 {
            self.view.frame.origin.y -= keyboardSize.height
        }
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    if self.view.frame.origin.y != 0 {
        self.view.frame.origin.y = 0
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .lightGray

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
       NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

    view.addSubview(imageContainer)
    view.addSubview(emailTF)
    view.addSubview(passwordTF)
    view.addSubview(confirmPasswordTF)

            NSLayoutConstraint.activate([

            imageContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            imageContainer.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.275),
            imageContainer.widthAnchor.constraint(equalTo: view.heightAnchor),
            imageContainer.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),

            emailTF.topAnchor.constraint(equalTo: imageContainer.bottomAnchor),
            emailTF.heightAnchor.constraint(equalToConstant: 100),
            emailTF.widthAnchor.constraint(equalToConstant: 200),
            emailTF.centerXAnchor.constraint(equalTo: view.centerXAnchor),

            passwordTF.topAnchor.constraint(equalTo: emailTF.bottomAnchor, constant: 20),
            passwordTF.heightAnchor.constraint(equalToConstant: 100),
            passwordTF.widthAnchor.constraint(equalToConstant: 200),
            passwordTF.centerXAnchor.constraint(equalTo: view.centerXAnchor),

            confirmPasswordTF.topAnchor.constraint(equalTo: passwordTF.bottomAnchor, constant: 20),
            confirmPasswordTF.heightAnchor.constraint(equalToConstant: 100),
            confirmPasswordTF.widthAnchor.constraint(equalToConstant: 200),
            confirmPasswordTF.centerXAnchor.constraint(equalTo: view.centerXAnchor),

        ])

    let tapToDismissKeyboard: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
    view.addGestureRecognizer(tapToDismissKeyboard)

    }

}

I'd really appreciate some help as to what I can do to correct this issue.

Body:
Seems like this is a known issue raised here and other SO questions too..

Two points to make:-

1) Use UIResponder.keyboardFrameEndUserInfoKey instead of UIResponder.keyboardFrameBeginUserInfoKey at:

if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {

in keyboardWillShow()

2) Doing so, you will get the total height of the keyboard including the toolbar. Which means:

However, when I dismiss the keyboard and re-click on any textfield, it
  goes up as intended: Only until the top textfield reaches the top of
  the screen.

This is the buggy behaviour where you get an incorrect height excluding the toolbar and:

The issue is that the very first time a user clicks on a textfield to
  type (no matter which one), the screen moves way too far up, such that
  the email textfield at the top ends up going beyond the screen size on
  top.

This is actually the intended behaviour with actual height. You could calculate the height of the toolbar and reduce it from this height to achieve your goal! If your VC is embedded in a navigation controller, you could use this

Hope this helps.


问:
How to change words after match containing slash
Inside my file "input.txt" I have the following path written:

```<code>"/home/inputfiles/water_gen/5202_water.gen"
</code>```

I want to change "5202" by specific numbers (probably using a for loop) and save them as different files.

I thought the easiest way was to use sed to find "water_gen/" as a match and then change the rest.

But is there an easier approach? I've been having problems because of the slash.

答:
I assume you want to use sed. This can be nicely solved with awk as well.

You can just substitute the prefix of the basename part (filename) of the path. The snippets below will edit the file in-place:

```<code>NUM=0005
sed -Ei 's/(\/home\/inputfiles\/water_gen\/)[0-9]+(_water\.gen)/\1'"$NUM"'\2/' input.txt
cat input.txt
/home/inputfiles/water_gen/0005_water.gen
</code>```

You can also generalize the filename suffix, instead of hardcoding it, depending on your problem. For now I assume this is sufficient.

If you want to run this in a loop, do

```<code>for NUM in $(seq -f "%04g" 0 5); do
    sed -Ei 's/(\/home\/inputfiles\/water_gen\/)[0-9]+(_water\.gen)/\1'"$NUM"'\2/' input.txt;
    cat input.txt
done
/home/inputfiles/water_gen/0000_water.gen
/home/inputfiles/water_gen/0001_water.gen
/home/inputfiles/water_gen/0002_water.gen
/home/inputfiles/water_gen/0003_water.gen
/home/inputfiles/water_gen/0004_water.gen
/home/inputfiles/water_gen/0005_water.gen
</code>```

Body:
Inside my file "input.txt" I have the following path written:

"/home/inputfiles/water_gen/5202_water.gen"

I want to change "5202" by specific numbers (probably using a for loop) and save them as different files.

I thought the easiest way was to use sed to find "water_gen/" as a match and then change the rest.

But is there an easier approach? I've been having problems because of the slash.

Body:
I assume you want to use sed. This can be nicely solved with awk as well.

You can just substitute the prefix of the basename part (filename) of the path. The snippets below will edit the file in-place:

NUM=0005
sed -Ei 's/(\/home\/inputfiles\/water_gen\/)[0-9]+(_water\.gen)/\1'"$NUM"'\2/' input.txt
cat input.txt
/home/inputfiles/water_gen/0005_water.gen

You can also generalize the filename suffix, instead of hardcoding it, depending on your problem. For now I assume this is sufficient.

If you want to run this in a loop, do

for NUM in $(seq -f "%04g" 0 5); do
    sed -Ei 's/(\/home\/inputfiles\/water_gen\/)[0-9]+(_water\.gen)/\1'"$NUM"'\2/' input.txt;
    cat input.txt
done
/home/inputfiles/water_gen/0000_water.gen
/home/inputfiles/water_gen/0001_water.gen
/home/inputfiles/water_gen/0002_water.gen
/home/inputfiles/water_gen/0003_water.gen
/home/inputfiles/water_gen/0004_water.gen
/home/inputfiles/water_gen/0005_water.gen


问:
Django search_fields adding DUPLICATE left outer join to django query if it have .annotate
Django search_fields adding DUPLICATE left outer join with appliance table to Django query as it have .annotate(appliances_count=Count('appliances'))

View

```<code>class AppliancePoolViewSet(VneCommonViewSet):
    serializer_class = vne_serializers.AppliancePoolSerializer
    search_fields = ('pk', 'name', 'notes', 'appliances__name')

    # filter appliance pools by customer
    def get_queryset(self):
        customer = getattr(self.request.user, 'customer', None)
        if not customer:
            return models.AppliancePool.objects.none()
        return models.AppliancePool.objects.filter(
            customer=1).prefetch_related('appliances'
            ).annotate(appliance_count=Count('appliances'))
</code>```

First it is adding join for annotate, and later search_field is also adding the same join again as it have field 'appliances__name', which is causing incorrect data for appliance_count.

How can I restrict addition of duplicate join which is done by Django filters using search_fields attribute?

答:
There are some note when using Django ORM:

First, the table join will be duplicated by:
https://docs.djangoproject.com/en/3.0/topics/db/queries/#spanning-multi-valued-relationships

I also found that it will affect when we using same relation in different place like: filter, annotate
Django will consider all those are single and should not merge

After deeper look on Django code, I found this:
https://docs.djangoproject.com/en/3.0/ref/models/querysets/#filteredrelation-objects

This will help to avoid spanning relations, we will have only 1 table join.

Sorry that my post will NOT help on the case: prefetch_related
Hope this will help other, as I found this one when search the solution for https://code.djangoproject.com/ticket/18437

Body:
Django search_fields adding DUPLICATE left outer join with appliance table to Django query as it have .annotate(appliances_count=Count('appliances'))

View

class AppliancePoolViewSet(VneCommonViewSet):
    serializer_class = vne_serializers.AppliancePoolSerializer
    search_fields = ('pk', 'name', 'notes', 'appliances__name')

    # filter appliance pools by customer
    def get_queryset(self):
        customer = getattr(self.request.user, 'customer', None)
        if not customer:
            return models.AppliancePool.objects.none()
        return models.AppliancePool.objects.filter(
            customer=1).prefetch_related('appliances'
            ).annotate(appliance_count=Count('appliances'))

First it is adding join for annotate, and later search_field is also adding the same join again as it have field 'appliances__name', which is causing incorrect data for appliance_count.

How can I restrict addition of duplicate join which is done by Django filters using search_fields attribute?


问:
Trying to sort list of numbers in c++
I'm trying to sort a list of numbers by passing a list of user-set length that's filled with random values to a function that will sort the elements in ascending order.

I've done this problem before using arrays and had no issue. For some reason my code isn't working, and I'd appreciate it if you guys could help me find out why it isn't working. It will sort the numbers but the last number will be unsorted.

Here is the function:

```<code>void sort(std::list<int>& numbers)
{
    list<int>::iterator it;
    list<int>::iterator it2;
    for (it = numbers.begin(); it != numbers.end(); ++it)
    {
        for (it2 = ++numbers.begin(); it2 != numbers.end(); ++it2)
        {
            if (*it > *it2)
            {
                int temp = *it;
                *it = *it2;
                *it2 = temp;
            }
        }
    }
}
</code>```

答:
You algorithm didn't work, because second cycle always go through (almost) entire list again and again. What it should do, is only go through remaining portion.
I.e. second cycle should be:

```<code>for (it2 = std::next(it1); it2 != numbers.end(); ++it2)
</code>```

Also, since second cycle starts with "next" element, first cycle should go not until last element, but until second to last element.
I.e. something like this:

```<code>for (it = numbers.begin(); it != std::prev(numbers.end()); ++it)
</code>```

BUT, since std::prev() is defined only for bidirectional iterators, and std::list doesn't provide one, its probably easier rewrite it as:

```<code>for (it = numbers.begin(); std::next(it) != numbers.end(); ++it)
</code>```

Title: Trying to sort list of numbers in c++

Body:
I'm trying to sort a list of numbers by passing a list of user-set length that's filled with random values to a function that will sort the elements in ascending order.

I've done this problem before using arrays and had no issue. For some reason my code isn't working, and I'd appreciate it if you guys could help me find out why it isn't working. It will sort the numbers but the last number will be unsorted.

Here is the function:

void sort(std::list<int>& numbers)
{
    list<int>::iterator it;
    list<int>::iterator it2;
    for (it = numbers.begin(); it != numbers.end(); ++it)
    {
        for (it2 = ++numbers.begin(); it2 != numbers.end(); ++it2)
        {
            if (*it > *it2)
            {
                int temp = *it;
                *it = *it2;
                *it2 = temp;
            }
        }
    }
}

Body:
You algorithm didn't work, because second cycle always go through (almost) entire list again and again. What it should do, is only go through remaining portion.
I.e. second cycle should be:

for (it2 = std::next(it1); it2 != numbers.end(); ++it2)

Also, since second cycle starts with "next" element, first cycle should go not until last element, but until second to last element.
I.e. something like this:

for (it = numbers.begin(); it != std::prev(numbers.end()); ++it)

BUT, since std::prev() is defined only for bidirectional iterators, and std::list doesn't provide one, its probably easier rewrite it as:

for (it = numbers.begin(); std::next(it) != numbers.end(); ++it)


问:
Disabling Spring @Autowired by-name fallback
I have the following classes defined:

```<code>public interface Thingy { ... }
public class Foo implements Thingy { ... }
public class Bar implements Thingy { ... }
</code>```

Classes Foo and Bar are both instanciated as singleton beans with same names, as in

```<code><bean id="foo" class="Foo" />
<bean id="bar" class="Bar" />
</code>```

The problem happens then trying to autowire field with same name as bean, like

```<code>@Autowired
Thingy foo;
</code>```

Here, field is autowired with Foo instance, and i don't want that. If field name doesn't match bean name, autowiring falis and that's desired.
So, is there any way to disable such fallback, so autowiring in above case would fail?

答:
I don't think it's possible, the other way around it is, using setFallbackToDefaultTypeMatch:
javadoc: CommonAnnotationBeanPostProcessor

Why don't you just rename either your bean or your class?

ContentLicense: CC BY-SA 3.0

Body:
I have the following classes defined:

public interface Thingy { ... }
public class Foo implements Thingy { ... }
public class Bar implements Thingy { ... }

Classes Foo and Bar are both instanciated as singleton beans with same names, as in

<bean id="foo" class="Foo" />
<bean id="bar" class="Bar" />

The problem happens then trying to autowire field with same name as bean, like

@Autowired
Thingy foo;

Here, field is autowired with Foo instance, and i don't want that. If field name doesn't match bean name, autowiring falis and that's desired.
So, is there any way to disable such fallback, so autowiring in above case would fail?


问:
How can I determine the index path for the currently focused UITableViewCell using Voice Over?
I have a dynamic UITableView. For each cell, I add a UIAccessibilityCustomAction. When the action fires, I need to know the index path so I can respond accordingly and update my model.

In tableView(_:cellForRowAt:) I add my UIAccessibilityCustomAction like this...

```<code>cell.accessibilityCustomActions = [
    UIAccessibilityCustomAction(
        name: "Really Bad Name",
        target: self,
        selector: #selector(doSomething)
    )
]
</code>```

I have tried to use UIAccessibility.focusedElement to no avail...

```<code>@objc private func doSomething() {
    let focusedCell = UIAccessibility.focusedElement(using: UIAccessibility.AssistiveTechnologyIdentifier.notificationVoiceOver) as! UITableViewCell
    // Do something with the cell, like find the indexPath.
}
</code>```

The problem is that casting to a cell fails. The debugger says that the return value type is actually a UITableTextAccessibilityElement, which I could find no information on.

答:
When the action fires, I need to know the index path so I can respond accordingly and update my model.

The best way to reach your goal is to use the UIAccessibilityFocus informal protocol methods by overriding them in your object directly (the table view cell class in your case): you'll be able to catch the needed index path when a custom action is fired.

I suggest to take a look at this answer dealing with catching accessibility focus changed that contains a detailed solution with code snippets if need be.

Example snippet...

```<code>class SomeCell: UITableViewCell

    override open func accessibilityElementDidBecomeFocused() {
        // Notify view controller however you want (delegation, closure, etc.)
    }

}
</code>```

Body:
I have a dynamic UITableView. For each cell, I add a UIAccessibilityCustomAction. When the action fires, I need to know the index path so I can respond accordingly and update my model.

In tableView(_:cellForRowAt:) I add my UIAccessibilityCustomAction like this...

cell.accessibilityCustomActions = [
    UIAccessibilityCustomAction(
        name: "Really Bad Name",
        target: self,
        selector: #selector(doSomething)
    )
]

I have tried to use UIAccessibility.focusedElement to no avail...

@objc private func doSomething() {
    let focusedCell = UIAccessibility.focusedElement(using: UIAccessibility.AssistiveTechnologyIdentifier.notificationVoiceOver) as! UITableViewCell
    // Do something with the cell, like find the indexPath.
}

The problem is that casting to a cell fails. The debugger says that the return value type is actually a UITableTextAccessibilityElement, which I could find no information on.

Body:
When the action fires, I need to know the index path so I can respond accordingly and update my model.

The best way to reach your goal is to use the UIAccessibilityFocus informal protocol methods by overriding them in your object directly (the table view cell class in your case): you'll be able to catch the needed index path when a custom action is fired.

I suggest to take a look at this answer dealing with catching accessibility focus changed that contains a detailed solution with code snippets if need be.

Example snippet...

class SomeCell: UITableViewCell

    override open func accessibilityElementDidBecomeFocused() {
        // Notify view controller however you want (delegation, closure, etc.)
    }

}


问:
Is it possible to persistently display the react-dates calendar?
I'm trying to have Airbnb's react-dates library display the calendar persistently (i.e. not have it act like a drawer/modal that toggles it's visibility).

I've looked through the documentation and noticed the appendToBody prop, but that just puts the DayPickerRangeController behind the input fields. It gets somewhat close, in that the calendar is somewhat CSS blocked, but it's still a drawer/modal that disappears.

I've looked through the CSS and can get the calendar to display inline-block basically when an input field is focused by removing the position: absolute CSS value on the DateRangePicker_picker div element. However, it still disappears when the input focus is lost.

The other approach I tried was to use the internal components that DateRangePicker is using (e.g. DateRangePickerInputController and DayPickerRangeController). I am able to have more control from a visual layout standpoint, but I lose all built-in functionality that the DateRangePicker has in terms of selecting days/dates/ranges and sending that info back.

<DateRangePickerInputController
  readOnly
  endDate={endDate}
  endDateId="endDate"
  endDatePlaceholderText="mm/dd/yyyy"
  isEndDateFocused={focusedInput === 'endDate'}
  isStartDateFocused={focusedInput === 'startDate'}
  startDate={startDate}
  startDateId="startDate"
  startDatePlaceholderText="mm/dd/yyyy"
/>
<DayPickerRangeController
  noBorder
  endDate={endDate}
  focusedInput={focusedInput}
  initialVisibleMonth={() => !startDate ? moment().subtract(1, 'M') : startDate }
  isOutsideRange={isOutsideRange.bind(this)}
  minimumNights={0}
  numberOfMonths={numberOfMonths}
  onDatesChange={onDatesChange.bind(this)}
  onFocusChange={onFocusChange.bind(this)}
  orientation={orientation}
  startDate={startDate}
/>
```

As I mentioned, the elements render the way I want them to in that the calendar and inputs are persistent and stacked "on top" of each other.

And only 1 month shows up correctly, but when I click on a day in the calendar, the startDate input field does not update. Same for endDate. The hover highlighting over the days in the calendar is gone. And individual day highlights/coloring is gone when I click on them.

答: You may use props renderCalendarInfo and transfer the DateRangePickerInputController through it.

Body:
I'm trying to have Airbnb's react-dates library display the calendar persistently (i.e. not have it act like a drawer/modal that toggles it's visibility).

I've looked through the documentation and noticed the appendToBody prop, but that just puts the DayPickerRangeController behind the input fields. It gets somewhat close, in that the calendar is somewhat CSS blocked, but it's still a drawer/modal that disappears.

I've looked through the CSS and can get the calendar to display inline-block basically when an input field is focused by removing the position: absolute CSS value on the DateRangePicker_picker div element. However, it still disappears when the input focus is lost.

The other approach I tried was to use the internal components that DateRangePicker is using (e.g. DateRangePickerInputController and DayPickerRangeController). I am able to have more control from a visual layout standpoint, but I lose all built-in functionality that the DateRangePicker has in terms of selecting days/dates/ranges and sending that info back.

<DateRangePickerInputController
  readOnly
  endDate={endDate}
  endDateId="endDate"
  endDatePlaceholderText="mm/dd/yyyy"
  isEndDateFocused={focusedInput === 'endDate'}
  isStartDateFocused={focusedInput === 'startDate'}
  startDate={startDate}
  startDateId="startDate"
  startDatePlaceholderText="mm/dd/yyyy"
/>
<DayPickerRangeController
  noBorder
  endDate={endDate}
  focusedInput={focusedInput}
  initialVisibleMonth={() => !startDate ? moment().subtract(1, 'M') : startDate }
  isOutsideRange={isOutsideRange.bind(this)}
  minimumNights={0}
  numberOfMonths={numberOfMonths}
  onDatesChange={onDatesChange.bind(this)}
  onFocusChange={onFocusChange.bind(this)}
  orientation={orientation}
  startDate={startDate}
/>

As I mentioned, the elements render the way I want them to in that the calendar and inputs are persistent and stacked "on top" of each other.

And only 1 month shows up correctly, but when I click on a day in the calendar, the startDate input field does not update. Same for endDate. The hover highlighting over the days in the calendar is gone. And individual day highlights/coloring is gone when I click on them.


问:
How do I stop an airflow DAG?
Running Airflow 1.9.0 with python 2.7.  How do I gracefully stop a DAG?

In this case, I have a DAG that's running a file upload with bad code that causes everything to take 4 times as long, and I'd really prefer not to have to wait a day for it to finally time out (timeout is set to 10 hours).

The DAG looks for a tar file.  When it finds one, it goes through every file in the tar, looking for files to process, and processes them.

I could not find any way to stop the DAG.  I tried clicking on the "Running" circle in the "DAG Runs" column (the one to the right).  It let me select the process and mark it as "failed".  But it didn't stop running.

I tried clicking on the "Running" circle in the "Recent Tasks" column (the one to the left).  It let me select processes, but trying to set them to filed (or to success), generated an exception in Airflow

答:
You can add a Sensor Operator which runs in parallel with your Task which you want killed.

The sensor should monitor the value of some Variable and should complete when it detects a certain value in the Variable, like 'STOP' let's say.

The Sensor should be followed by a BashOperator Task which shoul d kill your long running Task using a command like below:

kill -9 $(ps -ef| grep  | grep  | grep -v grep | awk '{print $2;}')

Title: How do I stop an airflow DAG?


问:
Django - how to select unique values in col
I have a little problem with Django which I can't manage to solve.
Suppose that I have models like this:

```<code>class Game(models.Model):
# some attributes here

class Score(models.Model):
user = models.ForeignKey(User)
game = models.ForeignKey(Game)
val = models.IntegerField()
#...
</code>```

Now, I want to keep in DB all the scores from last games, but when it comes to show their values on page I want to choose only the best score for chosen player in each game.
How do I do that? Or maybe I have to change Score model?

答:
Depending on your version of Django, you could do this:</p>

```<code>from django.db.models import Max
player = User.objects.filter(username='user')
best_score = Score.objects.filter(user=player).aggregate(Max('val'))
</code>```

Body:
I have a little problem with Django which I can't manage to solve.
Suppose that I have models like this:

class Game(models.Model):
# some attributes here

class Score(models.Model):
user = models.ForeignKey(User)
game = models.ForeignKey(Game)
val = models.IntegerField()
#...

Now, I want to keep in DB all the scores from last games, but when it comes to show their values on page I want to choose only the best score for chosen player in each game.
How do I do that? Or maybe I have to change Score model?

Body:
Depending on your version of Django, you could do this:

from django.db.models import Max
player = User.objects.filter(username='user')
best_score = Score.objects.filter(user=player).aggregate(Max('val'))


问:
Pythonic way to iterate through the input which can be a string, list or dict
I'm new to programming and have a requirement wherein I have to iterate through the elements of an input. The input can be a string, a list (mostly) or a dict. I wrote some code to check if the given input is a string or a list or a dict etc., but I'm wondering if there is an easier way to do it.

For example, I check as follows:

```<code> if isinstance(vlan, list):
      for i in  vlan:
          <<do some operation here>>
 if isinstance(vlan, string):
      <<do some operation here>>
 if isinstance(vlan, dict):
      for i in vlan.keys()
         <<do some operation here>>
</code>```

This operation I have to carry out a lot of times (although I can write a function do expand and send the elements I'm just wondering if there is any alternate to it).

答:
```<code> if isinstance(vlan, list):
     for i in  vlan:
         <<do some operation here>>
 if isinstance(vlan, dict):
     for i in vlan.keys()
         <<do some operation here>>
</code>```

Python's dict iteration uses keys, so these are redundant and you can collapse then (and any other non-string iterable) as just:

for i in vlan:
    # some operation
```

<p>Then, assuming "do some operation here" is always the same thing and you want to apply the operation to a string if you get a string and to each item if you get a collection of strings, just wrap the string in a list beforehand:</p>

<pre class="lang-py prettyprint-override"><code>if isinstance(vlan, str):
    vlan = [vlan]
for i in vlan:
    # do some operation here
</code>```

It's common to do this sort of special-casing / wrapping of str specifically as Python's strings are iterable but it's often desirable to treat them as atomic instead.

Body:
I'm new to programming and have a requirement wherein I have to iterate through the elements of an input. The input can be a string, a list (mostly) or a dict. I wrote some code to check if the given input is a string or a list or a dict etc., but I'm wondering if there is an easier way to do it.

For example, I check as follows:

 if isinstance(vlan, list):
      for i in  vlan:
          <<do some operation here>>
 if isinstance(vlan, string):
      <<do some operation here>>
 if isinstance(vlan, dict):
      for i in vlan.keys()
         <<do some operation here>>

This operation I have to carry out a lot of times (although I can write a function do expand and send the elements I'm just wondering if there is any alternate to it).

Body:
 if isinstance(vlan, list):
     for i in  vlan:
         <<do some operation here>>
 if isinstance(vlan, dict):
     for i in vlan.keys()
         <<do some operation here>>

Python's dict iteration uses keys, so these are redundant and you can collapse then (and any other non-string iterable) as just:

for i in vlan:
    # some operation

Then, assuming "do some operation here" is always the same thing and you want to apply the operation to a string if you get a string and to each item if you get a collection of strings, just wrap the string in a list beforehand:

if isinstance(vlan, str):
    vlan = [vlan]
for i in vlan:
    # do some operation here

It's common to do this sort of special-casing / wrapping of str specifically as Python's strings are iterable but it's often desirable to treat them as atomic instead.


问:
How update user's current location in google map
Hi Friends
        I want to display user's current location  in Google map and add marker of his location in the map  and how can i Update their location in google map after every second ..???</p>

答:
```<code>myLocationOverlay = new MyLocationOverlay(this, mapView);
    mapView.getOverlays().add(myLocationOverlay);
    myLocationOverlay.enableMyLocation();
    myLocationOverlay.runOnFirstFix(addfirststandort);
</code>```


问:
Css Grid Can't Affect Input Items
I'm learning css grid and i'm trying to arrange a page with inputs and other stuff.
Nothing works for some reason and i can't figure out what the problem is.
The form doesn't show any reaction, doesn't move at all.
Here's the html code:

```<code><div className="shipment-page">
    <div className="shipment-form">
        <form onSubmit={this.handleSubmit}>
            <div className="first-input">
                <label className="sp-input-label" htmlFor="first_name">First Name</label>
                <input
                    type="text"
                    name='first_name'
                    className="sp-input first"
                    value={this.state.first_name}
                    onChange={this.handleChange}
                    required
                />
            </div>
            <div className="second-input">
                <label className="sp-input-label" htmlFor="last_name">Last Name</label>
                <input
                    type="text"
                    name='last_name'
                    className="sp-input second"
                    value={this.state.last_name}
                    onChange={this.handleChange}
                    required
                />
            </div>
            <div className="third-input">
                <label className="sp-input-label" htmlFor="address">Address</label>
                <input
                    type="text"
                    name='address'
                    className="sp-input"
                    value={this.state.address}
                    onChange={this.handleChange}
                    required
                />
            </div>
            <div className="fourth-input">
                    <label className="sp-input-label" htmlFor="Zip Code">Zip Code</label>
                    <input
                        type="number"
                        name='zip_code'
                        className="sp-input"
                        value={this.state.zip_code}
                        onChange={this.handleChange}
                        required
                    />
            </div>
            <div className="fifth-input">
                <label className="sp-input-label" htmlFor="phone_number">Phone Number</label>
                <input
                    type="number"
                    name='phone_number'
                    className="sp-input"
                    value={this.state.phone_number}
                    onChange={this.handleChange}
                    required
                />
            </div>
            <div className="check-current-address">
                <label htmlFor="current_address">Is this your current address? </label>
                <input
                    type="radio"
                    name="current_address"
                    value={true}
                    onChange={this.handleChange}
                    required
                /><span>Yes</span>
                <input
                    type="radio"
                    name="current_address"
                    value={false}
                    onChange={this.handleChange}
                    required
                /><span>No</span>
            </div>
            <CustomButton type='submit'>Add Address</CustomButton>
        </form>
    </div>
    <span className="progress-indicator">
        <StepProgress/>
    </span>
</div>
</code>```

and here's the sass code:

```<code>.shipment-page{
    margin: 100px;
    display: grid;
    grid-template-columns: repeat(2, minmax(375px, 1fr)) minmax(300px, 1fr);
    grid-template-rows: repeat(6, 50px) 1fr;
    grid-template-areas:
    "first second info-box"
    "third third info-box"
    "fourth fifth info-box"
    "check . ."
    "buttons . ."
    "progres progres progres";
    .shipment-form{
        grid-row: 1/6;
        grid-column: 1/3;

        .first-inputs{
            grid-area: first;
        }
        .second-inputs{
            grid-area: second;
        }
        .third-inputs{
            grid-area: third;
        }
        .fourth-inputs{
            grid-area: fourth;
        }
        .fifth-inputs{
            grid-area: fifth;
        }
        .sp-input{
            background: none;
            background-color: white;
            color: grey;
            font-size: 18px;
            padding: 10px 10px 10px 5px;
            width: 100%;
            border: none;
            border-radius: 0;
            border-bottom: 1px solid grey;
            &:focus{
                outline: none;
                color: black;
                border-bottom: 1px solid black;
            }
        }

        .check-current-address{
            margin-bottom: 25px;
        }
    }
    .progress-indicator{
        grid-area: progres;
    }
}
</code>```

how the page looks like now

how it should look like

Help.

答:
The form isn't responding the way you expect because only direct grid children matter (just like with flexbox). .shipment-form is a valid grid child because it's one level deep from the grid parent, .shipment-page.

```<code><div className="shipment-page">               <!-- grid parent -->
    <div className="shipment-form">           <!-- grid child -->
        <form onSubmit={this.handleSubmit}>   <!-- too deep—not a grid child -->
</code>```

Try to restructure your code so that the grid parent is one level above your form input containers. Also, you have a potential bug in your code. Your CSS is referencing the plural inputs but your HTML class is using the singular input

And then:

.first-inputs{ ... } /* Oops, that class does not exist in your HTML */

Title: Css Grid Can't Affect Input Items

Body:
I'm learning css grid and i'm trying to arrange a page with inputs and other stuff.
Nothing works for some reason and i can't figure out what the problem is.
The form doesn't show any reaction, doesn't move at all.
Here's the html code:

        <form onSubmit={this.handleSubmit}>

                First Name
                <input
                    type="text"
                    name='first_name'
                    className="sp-input first"
                    value={this.state.first_name}
                    onChange={this.handleChange}
                    required
                />

                Last Name
                <input
                    type="text"
                    name='last_name'
                    className="sp-input second"
                    value={this.state.last_name}
                    onChange={this.handleChange}
                    required
                />

                Address
                <input
                    type="text"
                    name='address'
                    className="sp-input"
                    value={this.state.address}
                    onChange={this.handleChange}
                    required
                />

                    Zip Code
                    <input
                        type="number"
                        name='zip_code'
                        className="sp-input"
                        value={this.state.zip_code}
                        onChange={this.handleChange}
                        required
                    />

                Phone Number
                <input
                    type="number"
                    name='phone_number'
                    className="sp-input"
                    value={this.state.phone_number}
                    onChange={this.handleChange}
                    required
                />

                Is this your current address?
                <input
                    type="radio"
                    name="current_address"
                    value={true}
                    onChange={this.handleChange}
                    required
                />Yes
                <input
                    type="radio"
                    name="current_address"
                    value={false}
                    onChange={this.handleChange}
                    required
                />No

            <CustomButton type='submit'>Add Address</CustomButton>
        </form>

        <StepProgress/>

and here's the sass code:

.shipment-page{
    margin: 100px;
    display: grid;
    grid-template-columns: repeat(2, minmax(375px, 1fr)) minmax(300px, 1fr);
    grid-template-rows: repeat(6, 50px) 1fr;
    grid-template-areas:
    "first second info-box"
    "third third info-box"
    "fourth fifth info-box"
    "check . ."
    "buttons . ."
    "progres progres progres";
    .shipment-form{
        grid-row: 1/6;
        grid-column: 1/3;

        .first-inputs{
            grid-area: first;
        }
        .second-inputs{
            grid-area: second;
        }
        .third-inputs{
            grid-area: third;
        }
        .fourth-inputs{
            grid-area: fourth;
        }
        .fifth-inputs{
            grid-area: fifth;
        }
        .sp-input{
            background: none;
            background-color: white;
            color: grey;
            font-size: 18px;
            padding: 10px 10px 10px 5px;
            width: 100%;
            border: none;
            border-radius: 0;
            border-bottom: 1px solid grey;
            &:focus{
                outline: none;
                color: black;
                border-bottom: 1px solid black;
            }
        }

        .check-current-address{
            margin-bottom: 25px;
        }
    }
    .progress-indicator{
        grid-area: progres;
    }
}

how the page looks like now

how it should look like

Help.

Body:
The form isn't responding the way you expect because only direct grid children matter (just like with flexbox). .shipment-form is a valid grid child because it's one level deep from the grid parent, .shipment-page.

<div className="shipment-page">               <!-- grid parent -->
    <div className="shipment-form">           <!-- grid child -->
        <form onSubmit={this.handleSubmit}>   <!-- too deep—not a grid child -->

Try to restructure your code so that the grid parent is one level above your form input containers. Also, you have a potential bug in your code. Your CSS is referencing the plural inputs but your HTML class is using the singular input

<div className="first-input">

And then:

.first-inputs{ ... } /* Oops, that class does not exist in your HTML */


问:
Localhost on Docker Has "conflicting server name" Problem
I am trying to launch a docker image with localhost. The code is open sourced and here:

https://github.com/Helium-MVC/Boilerplate

When I run docker-compose up, I get the following:

```<code>helium_nginx | 2018/12/11 07:43:31 [warn] 1#1: conflicting server name "localhost" on 0.0.0.0:80, ignored
helium_nginx | nginx: [warn] conflicting server name "localhost" on 0.0.0.0:80, ignored
</code>```

Now my docker site.conf only has 1 vhost:

```<code>server {
    #The port to listen on. SSL would listen on 443
    listen 80 default_server;

    #The name/alias the server listens for when deciding to use this configuration
    server_name  localhost _;

    #Where the lo files are being written too
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;

    #Location of our site
    location / {
            #The root of the site is in public_html
        root    /code/site/public_html/;
        index  index.php index.html index.htm;
        #important for pretty url and routing
        try_files $uri $uri/ /index.php?rt=$uri&$args;
    }
}
</code>```

With it set in the yml like so:

```<code>web:
    image: nginx:latest
    container_name: "helium_nginx"
    ports:
      - "8000:80"
    volumes:
      - ./:/code
      - ./site.conf:/etc/nginx/conf.d/site.conf
      - ./nginx_custom_settings.conf:/etc/nginx/conf.d/nginx_custom_settings.conf
    links: ['php']
</code>```

What is weird is that is if I change the server_name to something like www.example.com and place that name in my /etc/hosts file, it works! Otherwise using localhost I get only the nginx default page. What can be wrong?

答:
I'm using the nginx image in docker, which has a default.conf file with server_name localhost and listening port 80. I simply replace that file and get this resolved.

docker-compose.yml

```<code>version: '2'
services:
  nginx:
    image: nginx:latest
    volumes:
      - ./tmp/https_reverse_proxy.conf:/etc/nginx/conf.d/https_reverse_proxy.conf
      - ./tmp/http_reverse_proxy.conf:/etc/nginx/conf.d/default.conf
    ports:
      - 80:80
      - 443:443
</code>```

and http_reverse_proxy.conf

```<code>server {
  listen 80;

  server_name localhost;

  return 301 https://$host$request_uri;
}
</code>```

Body:
I am trying to launch a docker image with localhost. The code is open sourced and here:

https://github.com/Helium-MVC/Boilerplate

When I run docker-compose up, I get the following:

helium_nginx | 2018/12/11 07:43:31 [warn] 1#1: conflicting server name "localhost" on 0.0.0.0:80, ignored
helium_nginx | nginx: [warn] conflicting server name "localhost" on 0.0.0.0:80, ignored

Now my docker site.conf only has 1 vhost:

server {
    #The port to listen on. SSL would listen on 443
    listen 80 default_server;

    #The name/alias the server listens for when deciding to use this configuration
    server_name  localhost _;

    #Where the lo files are being written too
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;

    #Location of our site
    location / {
            #The root of the site is in public_html
        root    /code/site/public_html/;
        index  index.php index.html index.htm;
        #important for pretty url and routing
        try_files $uri $uri/ /index.php?rt=$uri&$args;
    }
}

With it set in the yml like so:

web:
    image: nginx:latest
    container_name: "helium_nginx"
    ports:
      - "8000:80"
    volumes:
      - ./:/code
      - ./site.conf:/etc/nginx/conf.d/site.conf
      - ./nginx_custom_settings.conf:/etc/nginx/conf.d/nginx_custom_settings.conf
    links: ['php']

What is weird is that is if I change the server_name to something like www.example.com and place that name in my /etc/hosts file, it works! Otherwise using localhost I get only the nginx default page. What can be wrong?

Body:
I'm using the nginx image in docker, which has a default.conf file with server_name localhost and listening port 80. I simply replace that file and get this resolved.

docker-compose.yml

version: '2'
services:
  nginx:
    image: nginx:latest
    volumes:
      - ./tmp/https_reverse_proxy.conf:/etc/nginx/conf.d/https_reverse_proxy.conf
      - ./tmp/http_reverse_proxy.conf:/etc/nginx/conf.d/default.conf
    ports:
      - 80:80
      - 443:443

and http_reverse_proxy.conf

server {
  listen 80;

  server_name localhost;

  return 301 https://$host$request_uri;
}


问:
Rust DRY traits and generics - impl Add and Mul nearly identical
I have the following toy code which makes use of generics to implement some operations on a 3d vector as a struct of 3 generic elements.

```<code>use std::ops::Add;
use std::ops::Mul;

#[derive(Debug)]
pub struct Vec3<T> {
    x: T,
    y: T,
    z: T,
}

impl<T> Vec3<T> {
    pub fn new(x: T, y: T, z: T) -> Vec3<T> {
        Vec3 { x, y, z }
    }
}

impl<T: Add<Output = T> + Copy> Add<T> for &Vec3<T> {
    type Output = Vec3<T>;
    fn add(self, other: T) -> Vec3<T> {
        Vec3 {
            x: self.x + other,
            y: self.y + other,
            z: self.z + other,
        }
    }
}

impl<T: Add<Output = T> + Copy> Add<&Vec3<T>> for &Vec3<T> {
    type Output = Vec3<T>;
    fn add(self, other: &Vec3<T>) -> Vec3<T> {
        Vec3 {
            x: self.x + other.x,
            y: self.y + other.y,
            z: self.z + other.z,
        }
    }
}

impl<T: Mul<Output = T> + Copy> Mul<T> for &Vec3<T> {
    type Output = Vec3<T>;
    fn mul(self, other: T) -> Vec3<T> {
        Vec3 {
            x: self.x * other,
            y: self.y * other,
            z: self.z * other,
        }
    }
}

impl<T: Mul<Output = T> + Copy> Mul<&Vec3<T>> for &Vec3<T> {
    type Output = Vec3<T>;
    fn mul(self, other: &Vec3<T>) -> Vec3<T> {
        Vec3 {
            x: self.x * other.x,
            y: self.y * other.y,
            z: self.z * other.z,
        }
    }
}
</code>```

It's pretty plain to see that all I did was copy and paste my impl Add's and replace Add for Mul and renamed the method names.

This slight repetition brings me to my question - Is there something in rust which generalizes this as well? That is something akin to a generic trait or perhaps "meta trait". In my scenario, a relevant "meta trait" Op would have some method op. Then, instead of implementing Add and Mul, one would implement Op and op would take the place of the + and * operators respectively.

I explored and found supertraits but I cannot imagine how they could be used as I hope beyond what I imagine would be the basic step:

```<code>trait Op<T>:Add<T>+Mul<T>{
    fn op(&self)->T;
}
</code>```

答:
Regarding your question for a more general trait for binary operations that will create impls of Add, Mul etc. for you: There is none as far as I'm aware, and I think you cannot define it yourself because of orphan rules. You could:

Write a macro for binary ops traits

Use an existing Vector3, like nalgebra's which implements those traits for you already

Try to generalize num_derive to work on structs with more than one member

Body:
I have the following toy code which makes use of generics to implement some operations on a 3d vector as a struct of 3 generic elements.

use std::ops::Add;
use std::ops::Mul;

#[derive(Debug)]
pub struct Vec3<T> {
    x: T,
    y: T,
    z: T,
}

impl<T> Vec3<T> {
    pub fn new(x: T, y: T, z: T) -> Vec3<T> {
        Vec3 { x, y, z }
    }
}

impl<T: Add<Output = T> + Copy> Add<T> for &Vec3<T> {
    type Output = Vec3<T>;
    fn add(self, other: T) -> Vec3<T> {
        Vec3 {
            x: self.x + other,
            y: self.y + other,
            z: self.z + other,
        }
    }
}

impl<T: Add<Output = T> + Copy> Add<&Vec3<T>> for &Vec3<T> {
    type Output = Vec3<T>;
    fn add(self, other: &Vec3<T>) -> Vec3<T> {
        Vec3 {
            x: self.x + other.x,
            y: self.y + other.y,
            z: self.z + other.z,
        }
    }
}

impl<T: Mul<Output = T> + Copy> Mul<T> for &Vec3<T> {
    type Output = Vec3<T>;
    fn mul(self, other: T) -> Vec3<T> {
        Vec3 {
            x: self.x * other,
            y: self.y * other,
            z: self.z * other,
        }
    }
}

impl<T: Mul<Output = T> + Copy> Mul<&Vec3<T>> for &Vec3<T> {
    type Output = Vec3<T>;
    fn mul(self, other: &Vec3<T>) -> Vec3<T> {
        Vec3 {
            x: self.x * other.x,
            y: self.y * other.y,
            z: self.z * other.z,
        }
    }
}

It's pretty plain to see that all I did was copy and paste my impl Add's and replace Add for Mul and renamed the method names.

This slight repetition brings me to my question - Is there something in rust which generalizes this as well? That is something akin to a generic trait or perhaps "meta trait". In my scenario, a relevant "meta trait" Op would have some method op. Then, instead of implementing Add and Mul, one would implement Op and op would take the place of the + and * operators respectively.

I explored and found supertraits but I cannot imagine how they could be used as I hope beyond what I imagine would be the basic step:

trait Op<T>:Add<T>+Mul<T>{
    fn op(&self)->T;
}


问:
How to get the list of checked items with jQuery?
Here I want the checked names in another div within the same page with the help of jQuery. How can I do it?

```<code><div class="w-100">
    <h6 class="approval--name">
        Name
    </h6>
    <p>Initiator</p>
</div>

<div class="form-group">
    <div class="checkbox">
        <input name="users" type="checkbox" value="1" id="1"/>
        <label for="1"></label>
    </div>
</div>

# I want checked names here
<div class="w-100">
    <h6 class="approval--name">Checked Name</h6>
    <p>Initiator</p>
</div>
</code>```

答:
This example below adds or removes the names if your checkbox is selected or not. Your checkbox element must have the attribute data-name with its name in it. I have added an ID to your div with the checked names in it, to identify it with jQuery.

$('input[type="checkbox"]').on('change', function() {
  var name = $(this).attr('data-name');

  if($(this).prop('checked')) {
    $('#checked-names').append('
' + name + '
');
  } else {
    $('#checked-names p[data-name="' + name + '"]').remove();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="w-100">
  <h6 class="approval--name">
      Name
  </h6>
  <p>Initiator</p>
</div>

<div class="form-group">
  <div class="checkbox">
    <input data-name="Initiator" name="users" type="checkbox" value="1" id="1"/>
    <label for="1">Initiator</label>
  </div>
</div>

<div class="form-group">
  <div class="checkbox">
    <input data-name="Initiator2" name="users2" type="checkbox" value="2" id="2"/>
    <label for="2">Initiator2</label>
  </div>
</div>

# I want checked names here
<div id="checked-names" class="w-100">
  <h6 class="approval--name">Checked Name</h6>
</div></code>```

Body:
Here I want the checked names in another div within the same page with the help of jQuery. How can I do it?

        Name

Initiator

        <input name="users" type="checkbox" value="1" id="1"/>

# I want checked names here

Checked Name

Initiator

Body:
This example below adds or removes the names if your checkbox is selected or not. Your checkbox element must have the attribute data-name with its name in it. I have added an ID to your div with the checked names in it, to identify it with jQuery.

$('input[type="checkbox"]').on('change', function() {
  var name = $(this).attr('data-name');

  if($(this).prop('checked')) {
    $('#checked-names').append('<p data-name="' + name + '">' + name + '</p>');
  } else {
    $('#checked-names p[data-name="' + name + '"]').remove();
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="w-100">
  <h6 class="approval--name">
      Name
  </h6>
  <p>Initiator</p>
</div>

<div class="form-group">
  <div class="checkbox">
    <input data-name="Initiator" name="users" type="checkbox" value="1" id="1"/>
    <label for="1">Initiator</label>
  </div>
</div>

<div class="form-group">
  <div class="checkbox">
    <input data-name="Initiator2" name="users2" type="checkbox" value="2" id="2"/>
    <label for="2">Initiator2</label>
  </div>
</div>

# I want checked names here
<div id="checked-names" class="w-100">
  <h6 class="approval--name">Checked Name</h6>
</div>


问:
Vb6 and access Date range
Used these queries with MySql Successfully but they arent working with SQL/VB.. any help appriciated

Present Month Records..Starting from 1st day of the current month till now.

```<code>SELECT * FROM `dt_table` WHERE  date between  DATE_FORMAT(CURDATE() ,'%Y-%m-01') AND CURDATE()
</code>```

Present Year Records..Starting from 1st Jan of the current Year till now.

```<code>SELECT * FROM `dt_table` WHERE  date between  DATE_FORMAT(CURDATE() ,'%Y-01-01') AND CURDATE()
</code>```

答:
It should be:

Select *
From dt_table
Where Fix([date]) Between DateSerial(Year(Date()), Month(Date()), 1) And Date()
```

<p>and</p>

<pre class="lang-sql prettyprint-override"><code>Select *
From dt_table
Where Fix([date]) Between DateSerial(Year(Date()), 1, 1) And Date()
</code>```

or

Select *
From dt_table
Where [date] >= DateSerial(Year(Date()), 1, 1) And [date] < DateAdd("d", 1, Date())
```

Title: Vb6 and access Date range

Body:
Used these queries with MySql Successfully but they arent working with SQL/VB.. any help appriciated

Present Month Records..Starting from 1st day of the current month till now.

SELECT * FROM `dt_table` WHERE  date between  DATE_FORMAT(CURDATE() ,'%Y-%m-01') AND CURDATE()

Present Year Records..Starting from 1st Jan of the current Year till now.

SELECT * FROM `dt_table` WHERE  date between  DATE_FORMAT(CURDATE() ,'%Y-01-01') AND CURDATE()

Body:
It should be:

Select *
From dt_table
Where Fix([date]) Between DateSerial(Year(Date()), Month(Date()), 1) And Date()

and

Select *
From dt_table
Where Fix([date]) Between DateSerial(Year(Date()), 1, 1) And Date()

or

Select *
From dt_table
Where [date] >= DateSerial(Year(Date()), 1, 1) And [date] < DateAdd("d", 1, Date())


问:
Accepting request from specific ip in Spring Boot
I referred this tutorial to restrict certain ip in jboss and Spring Boot application.
http://www.mastertheboss.com/jboss-web/jbosswebserver/how-to-restrict-access-to-jboss-web-application-by-ip-or-host

But the tutorial is not complete. Where should I place those codes? Are there any other methods to do that?

If any one know any other methods please mention that here. Thanks in advance.

答:
To me this concern should be handled on infrastructure level, not in application container. I would suggest to look into AWS Security Groups or equivalent concepts in other cloud providers.

If you are running it in private cloud/bare metal, you should investigate to restrict it on transport layer your infrastructure provides. There should be some possibility to configure firewall rules.