问:
Does a thread synchronize with with the previous thread with same id?
In C++11 there is std::this_thread::get_id() I can use to obtain an std::thread::id identifier of my thread. The standard says:

30.3.1.1

An object of type thread::id provides a unique identifier for each thread of execution and a single distinct value for all thread objects
  that do not represent a thread of execution (30.3.1). Each thread of
  execution has an associated thread::id object that is not equal to the
  thread::id object of any other thread of execution and that is not
  equal to the thread::id object of any std::thread object that does not
  represent threads of execution.

thread::id shall be a trivially copyable class (Clause 9). The library may reuse the value of a thread::id of a terminated thread
  that can no longer be joined.

My question is precisely about the case in which a new thread B, has the same id as an old thread A: will the thread B "see changes made by" thread A?

To be more specific consider this scenario:

Thread A does:

```<code>owner.store(std::this_thread::get_id()); //store A's 'id'
...some work...
owner.store(std::thread::id(),std::memory_order_relaxed); // clear
</code>```

Thread B does:

```<code>assert(owner.load(std::memory_order_relaxed) != std::this_thread::get_id());
</code>```

Will this assert hold?

The owner.load in Thread A and last owner.store in Thread B are intentionally "relaxed", as so there is no obvious "synchronize with" relation between the two, other than the one supposed in my question.

答:
[1] Considering what is written in the standard, and supposing the uniqueness is conceptualized considering physical time, that is at a given time no two threads id can be identical, then to ensure the standard requirement the system must ensure that the end of A happens before the start of B.

[2] The end of a stread happens after the execution of the function body that was launched at the start of this thread and the start of the thread happens before the execution of the body of this starting function. As specified in [basic.exec]/11:

When calling a function (whether or not the function is inline), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function. For each function invocation F, for every evaluation A that occurs within F and every evaluation B that does not occur within F but is evaluated on the same thread and as part of the same signal handler (if any), either A is sequenced before B or B is sequenced before A.

[1] and [2] implies that every computation in thread A happens before any computation in thread B.

Body:
In C++11 there is std::this_thread::get_id() I can use to obtain an std::thread::id identifier of my thread. The standard says:

30.3.1.1

An object of type thread::id provides a unique identifier for each thread of execution and a single distinct value for all thread objects
  that do not represent a thread of execution (30.3.1). Each thread of
  execution has an associated thread::id object that is not equal to the
  thread::id object of any other thread of execution and that is not
  equal to the thread::id object of any std::thread object that does not
  represent threads of execution.

thread::id shall be a trivially copyable class (Clause 9). The library may reuse the value of a thread::id of a terminated thread
  that can no longer be joined.

My question is precisely about the case in which a new thread B, has the same id as an old thread A: will the thread B "see changes made by" thread A?

To be more specific consider this scenario:

Thread A does:

owner.store(std::this_thread::get_id()); //store A's 'id'
...some work...
owner.store(std::thread::id(),std::memory_order_relaxed); // clear

Thread B does:

assert(owner.load(std::memory_order_relaxed) != std::this_thread::get_id());

Will this assert hold?

The owner.load in Thread A and last owner.store in Thread B are intentionally "relaxed", as so there is no obvious "synchronize with" relation between the two, other than the one supposed in my question.


来源: stackexchange

问:
Is there a way to combine annotations and filtered aggregations in Django Querysets?
I have a complex query that, although it is easily done in python code, I'm trying to do through Django Querysets.

Using the example models from https://docs.djangoproject.com/en/2.2/topics/db/aggregation/#aggregating-annotations, what I'm trying to do is to annotate each Publisher with the average of the total sales per author. However, the total sales per author should only include books from a given date range.

Is there any way to do this in one query? Of course, doing two separate queries and joining the results using pure Python would work. However, in my specific use case, there is a large amount of overhead for each database connection/disconnection, so it would be preferable to combine them into one query. Additionally, the real data set is quite large, so having the aggregation done server-side is vital.

Here is an example of the json output I would expect:

{
  "publishers": [{
    "name": "testpublisher",
    "avg_recent_sales": "11.2"
  }, {
    "name": "anotherpublisher",
    "avg_recent_sales": "2.4"
  }]
}

Where avg_recent_sales is the average amount of books each author sold through that publisher in the past 6 months.

答:
Django queryset is lazy. You can do filter or annotate as many times as you want until you iterate it (such as put it in "for" or convert it into a "list")

I've add "sold_amount" into Book model.

books = Book.objects.filter(pubdate__range=(date1, date2))  # filter by given date range.
books = books.values('publisher__id', 'authors__id')  # create group by clause.
books = books.annotate(total_sale_per_author=Avg(F('sold_amount') * F('price')))  # add an annotation.

books = list(book)  # query will be occured here
```

ContentLicense: CC BY-SA 4.0


问:
How to use meta tags with dynamic value in react js?
Can anyone help me regarding how to use meta tags with dynamic value in react js?

Please see the image for my requirement,

I am using the extra metatag html tag here(because react require wrap complete html inside the single tag else it raise error). I can also use div/p any html tag, but is this right way to render the react component? having extra html tag than inside that meta tags. Will this work for SEO?

Please suggested me any other good way to use meta tags manually.

答:
Create React App produces a static bundle with HTML, JS, and CSS. It can’t possibly give you a dynamic <meta> tag because the result HTML is created ahead of time.

While changing document.title with something like React Helmet makes sense, changing <meta> tags doesn’t make sense unless your app is server rendered. Server rendering is not a supported feature of Create React App so if you want to use it, you might want to check out some alternatives such as Next.js.

That said, if you don’t want full server rendering and only need to change <meta> tags, you could do this by hand as described here.

I hope this helps!

ContentLicense: CC BY-SA 3.0


问:
When i call setstate in a picker it changes the value two times
Im trying to render a form dynamically using "for" loop, and its renders good but when I tried to change the value in a picker, it changed but it immediately changes to the default value, so what i need to do to fix this?

```<code>class Datos extends Component {
    cotizadorData: any;
    planesData: any;
    dataStructure =
    {
        id: 1,
        name: '',
        lastName: '',
        email: '',
        documentNumber: '',
        dateOfBirth: '',
        age: '',
        gender: 'M',
        areaCode: '',
        phoneNumber: '',
        medicalObservation: 'Sin Observaciones'
    };
    emergencyContactDataStructure =
    {
        name: '',
        email: '',
        areaCode: '',
        phoneNumber: ''
    };
    planCode: string = '';
    departurePlaceCode: string = '';
    arrivalPlaceCode: string = '';
    passengersArray: Array = [];
    additionalPassengersCount: number = 0;
    additionalPassengersArray: Array = [];
    additionalPassengersView: Array = [];
    __isMounted: string = 'false';
    mainPassengerAreaCodeRef: any;
    emergencyContactAreaCodeRef: any;

    apiKey: string = '';
    xmlForOrder: string = '';

    constructor(){
        super();
        this.state = {
            showLoader: false,
            countries : [ {
                label: '',
                value: ''
            } ],
            holderData: this.dataStructure,
            additionalPassengers: [],
            additionalPassengersView: [],
            emergencyContact: this.emergencyContactDataStructure
        };
    }

    async componentDidMount () : void {

        this.setState({
            showLoader: true
        });
        await AsyncStorage.setItem('dataComponentIsMounted', 'true');
        this.apiKey = await AsyncStorage.getItem('apiKey');
        this.xmlForCountries = getCountries(this.apiKey);
        this.countries = await getOrbisDataServer(this.xmlForCountries);
        this.processCotizadorData();
        this.setState({
            departurePlace: this.countries[0].description
        });
        this.formatArraysForPickers();
    };

    updateAsyncStorage = async() => {
        this.__isMounted = await AsyncStorage.getItem('dataComponentIsMounted');
        if(!isUndefinedOrNull(this.__isMounted))
        {
            if(this.__isMounted === 'true')
            {
                this.processCotizadorData();
            }
        }
    };

    processCotizadorData = async() => {
        this.additionalPassengersCount = 0;
        this.additionalPassengersArray = [];
        this.cotizadorData = await AsyncStorage.getItem('cotizadorData');
        this.planesData = JSON.parse(await AsyncStorage.getItem('planesData'));
        if(!isUndefinedOrNull(this.cotizadorData))
        {
            this.cotizadorData = JSON.parse(this.cotizadorData);
            this.additionalPassengersCount = (this.cotizadorData.youngs + this.cotizadorData.adults +
                this.cotizadorData.semiSeniors + this.cotizadorData.seniors) - 1;
            let id = 2;
            for(let i = 0; i < this.additionalPassengersCount; i++)
            {
                this.additionalPassengersArray.push({
                    id: id,
                    name: '',
                    lastName: '',
                    email: '',
                    documentNumber: '',
                    dateOfBirth: '',
                    age: '',
                    gender: 'M',
                    areaCode: '',
                    phoneNumber: '',
                    medicalObservation: 'Sin Observaciones'
                });
                id++;
            }
            this.setState({
                additionalPassengers: this.additionalPassengersArray
            });
            this.renderAdditionalPassengersForms();
        }
    };

setAdditionalPassengerGender = (additionalPassenger, value) => {
        let additionalPassengersModified = [...this.state.additionalPassengers];
        let index = additionalPassengersModified.findIndex(el => el.id === additionalPassenger.id);
        additionalPassengersModified[index] = {...additionalPassengersModified[index], gender: value};
        this.setState({
            additionalPassengers: additionalPassengersModified
        });
    };

renderAdditionalPassengersForms = () => {

        for(let i = 0; i < this.additionalPassengersArray.length; i++)
        {
            this.additionalPassengersView.push(
                        <View>
                            <Text style={[styles.normalFont, styles.label]}>SEX</Text>
                            <Picker
                                selectedValue={this.state.additionalPassengers[i].gender}
                                style={{height: 50, width: 100}}
                                onValueChange={(value) => {this.setAdditionalPassengerGender (this.additionalPassengersArray[i], value)}}>
                                <Picker.Item label="Male" value="M"/>
                                <Picker.Item label="Female" value="F"/>
                            </Picker>
                        </View>
)
}this.setState({
            additionalPassengersView: this.additionalPassengersView
        });

}

</code>```

I expect to change the picker value for selected one.

Edited: I added the whole component

答:
Since your UI has no issue pilling up views on this.additionalPassengersView, I suppose renderAdditionalPassengersForms is not called everytime the value in any of the additional passengers pickers change.

You problem is: selectedValue on Picker has to be updated when you make a choice. Otherwise, the picker will roll back to its non-updated selected value, as the behavior you describe.

I use redux-form to manage my forms. But, assuming you don't want to use it, you can make a new component for the picker, putting the picker selected value on the state and updating this state on onValueChange callback

Body:
Im trying to render a form dynamically using "for" loop, and its renders good but when I tried to change the value in a picker, it changed but it immediately changes to the default value, so what i need to do to fix this?

class Datos extends Component {
    cotizadorData: any;
    planesData: any;
    dataStructure =
    {
        id: 1,
        name: '',
        lastName: '',
        email: '',
        documentNumber: '',
        dateOfBirth: '',
        age: '',
        gender: 'M',
        areaCode: '',
        phoneNumber: '',
        medicalObservation: 'Sin Observaciones'
    };
    emergencyContactDataStructure =
    {
        name: '',
        email: '',
        areaCode: '',
        phoneNumber: ''
    };
    planCode: string = '';
    departurePlaceCode: string = '';
    arrivalPlaceCode: string = '';
    passengersArray: Array = [];
    additionalPassengersCount: number = 0;
    additionalPassengersArray: Array = [];
    additionalPassengersView: Array = [];
    __isMounted: string = 'false';
    mainPassengerAreaCodeRef: any;
    emergencyContactAreaCodeRef: any;

    apiKey: string = '';
    xmlForOrder: string = '';

    constructor(){
        super();
        this.state = {
            showLoader: false,
            countries : [ {
                label: '',
                value: ''
            } ],
            holderData: this.dataStructure,
            additionalPassengers: [],
            additionalPassengersView: [],
            emergencyContact: this.emergencyContactDataStructure
        };
    }

    async componentDidMount () : void {

        this.setState({
            showLoader: true
        });
        await AsyncStorage.setItem('dataComponentIsMounted', 'true');
        this.apiKey = await AsyncStorage.getItem('apiKey');
        this.xmlForCountries = getCountries(this.apiKey);
        this.countries = await getOrbisDataServer(this.xmlForCountries);
        this.processCotizadorData();
        this.setState({
            departurePlace: this.countries[0].description
        });
        this.formatArraysForPickers();
    };

    updateAsyncStorage = async() => {
        this.__isMounted = await AsyncStorage.getItem('dataComponentIsMounted');
        if(!isUndefinedOrNull(this.__isMounted))
        {
            if(this.__isMounted === 'true')
            {
                this.processCotizadorData();
            }
        }
    };

    processCotizadorData = async() => {
        this.additionalPassengersCount = 0;
        this.additionalPassengersArray = [];
        this.cotizadorData = await AsyncStorage.getItem('cotizadorData');
        this.planesData = JSON.parse(await AsyncStorage.getItem('planesData'));
        if(!isUndefinedOrNull(this.cotizadorData))
        {
            this.cotizadorData = JSON.parse(this.cotizadorData);
            this.additionalPassengersCount = (this.cotizadorData.youngs + this.cotizadorData.adults +
                this.cotizadorData.semiSeniors + this.cotizadorData.seniors) - 1;
            let id = 2;
            for(let i = 0; i < this.additionalPassengersCount; i++)
            {
                this.additionalPassengersArray.push({
                    id: id,
                    name: '',
                    lastName: '',
                    email: '',
                    documentNumber: '',
                    dateOfBirth: '',
                    age: '',
                    gender: 'M',
                    areaCode: '',
                    phoneNumber: '',
                    medicalObservation: 'Sin Observaciones'
                });
                id++;
            }
            this.setState({
                additionalPassengers: this.additionalPassengersArray
            });
            this.renderAdditionalPassengersForms();
        }
    };

setAdditionalPassengerGender = (additionalPassenger, value) => {
        let additionalPassengersModified = [...this.state.additionalPassengers];
        let index = additionalPassengersModified.findIndex(el => el.id === additionalPassenger.id);
        additionalPassengersModified[index] = {...additionalPassengersModified[index], gender: value};
        this.setState({
            additionalPassengers: additionalPassengersModified
        });
    };

renderAdditionalPassengersForms = () => {

        for(let i = 0; i < this.additionalPassengersArray.length; i++)
        {
            this.additionalPassengersView.push(
                        <View>
                            <Text style={[styles.normalFont, styles.label]}>SEX</Text>
                            <Picker
                                selectedValue={this.state.additionalPassengers[i].gender}
                                style={{height: 50, width: 100}}
                                onValueChange={(value) => {this.setAdditionalPassengerGender (this.additionalPassengersArray[i], value)}}>
                                <Picker.Item label="Male" value="M"/>
                                <Picker.Item label="Female" value="F"/>
                            </Picker>
                        </View>
)
}this.setState({
            additionalPassengersView: this.additionalPassengersView
        });

}

I expect to change the picker value for selected one.

Edited: I added the whole component


问:
Convert HEX to ASCII, data from GPS tracker
I have just bought a GPS Tracker, it can send SMS to cellphone just fine. It also supports reporting to a server via GPRS.

I have setup the device to contact my own server on port 8123, it's a FreeBSD server and i have checked that i recieve packets on that port.

I successfully have setup a listener server written in PHP, and i can receive data from the device. But how do i convert the partial HEX data to something usefull (ASCII)?

Example data string:

```$$^@T^@E Y'^WÿU210104.000,A,5534.4079,N,01146.2510,E,0.00,,170411,,*10|1.0|72|0000á```

Unfortunately i don't know how i can copy-paste the HEX parts

Now how do i get the ID part out? I have tried echo hexdec(mb_substr($data, 4, 7));

The data is following this protocol

From the document:

```
Command format of GPRS packets are as follows:

From server to tracker:
@@\r\n

From tracker to server:
$$\r\n

Note:
Do NOT input ‘’ when writing a command.
All multi-byte data complies with the following sequence: High byte prior to low byte.
The size of a GPRS packet (including data) is about 100 bytes

Item        Specification
@@          2 bytes. It means the header of packet from server to tracker.
            It is in ASCII code (Hex code: 0x40)

$$          2 bytes. It is the header of packet from tracker to server.
            It is in ASCII code (Hex code: 0x24)

L           2 bytes. It means the length of the whole packet including
            the header and ending character and it is in hex code

ID          7 bytes, ID must be digit and not over 14 digits, the unused byte
            will be stuffed by ‘f’ or ‘0xff’. It is in the format of hex code.
            For example, if ID is 13612345678, then it will be shown as
            follows: 0x13, 0x61, 0x23, 0x45, 0x67, 0x8f, 0xff.
            If all 7 bytes are 0xff, it is a broadcasting command. ID is in hex code

command     2 bytes. The command code is in hex code. Please refer to the
            command list below.

data        Min 0 byte and max 100 bytes. See Annex 1 for description of ‘data’.

checksum    2 bytes. It indicates CRC-CCITT (default is 0xffff) checksum of
            all data (not including CRC itself and the ending character).
            It is in hex code.
            For example: 24 24 00 11 13 61 23 45 67 8f ff 50 00 05 d8 0d 0a
            0x05d8 = CRC-CCITT (24 24 00 11 13 61 23 45 67 8f ff 50 00)

\r\n        2 bytes. It is the ending character and in hex code
            (0x0d,0x0a in hex code)
```

Update

With the answer from Anomie, i was able to piece this together

```<code>$arr = unpack('H4length/H14id/H4cmd/H4crc/H4end', mb_substr($data, 2, 11) . mb_substr($data, -4));

var_dump($arr);
</code>```

This will out put something like

```
array(5) {
  ["length"]=>
  string(4) "0054"
  ["id"]=>
  string(14) "004512345678ff"
  ["cmd"]=>
  string(4) "9955"
  ["crc"]=>
  string(4) "c97e"
  ["end"]=>
  string(4) "0d0a"
}
```

答:
*Edit 26 April:* I have changed the question a bit, thus this seems out of place. Initial question was more on how to read the data from TCP.

I found some great articles on writing a TCP/socket server in PHP (/me slaps PHP around a bit with a large trout)

http://devzone.zend.com/article/1086
http://kevin.vanzonneveld.net/techblog/article/create_daemons_in_php/

Can't wait to get this going :)

OwnerDisplayName: Phliplip

Body:
I have just bought a GPS Tracker, it can send SMS to cellphone just fine. It also supports reporting to a server via GPRS.

I have setup the device to contact my own server on port 8123, it's a FreeBSD server and i have checked that i recieve packets on that port.

I successfully have setup a listener server written in PHP, and i can receive data from the device. But how do i convert the partial HEX data to something usefull (ASCII)?

Example data string:

$$^@T^@E Y'^WÿU210104.000,A,5534.4079,N,01146.2510,E,0.00,,170411,,*10|1.0|72|0000á

Unfortunately i don't know how i can copy-paste the HEX parts

Now how do i get the ID part out? I have tried echo hexdec(mb_substr($data, 4, 7));

The data is following this protocol

From the document:

Command format of GPRS packets are as follows:

From server to tracker:
@@\r\n

From tracker to server:
$$\r\n

Note:
Do NOT input ‘’ when writing a command.
All multi-byte data complies with the following sequence: High byte prior to low byte.
The size of a GPRS packet (including data) is about 100 bytes

Item        Specification
@@          2 bytes. It means the header of packet from server to tracker.
            It is in ASCII code (Hex code: 0x40)

$$          2 bytes. It is the header of packet from tracker to server.
            It is in ASCII code (Hex code: 0x24)

L           2 bytes. It means the length of the whole packet including
            the header and ending character and it is in hex code

ID          7 bytes, ID must be digit and not over 14 digits, the unused byte
            will be stuffed by ‘f’ or ‘0xff’. It is in the format of hex code.
            For example, if ID is 13612345678, then it will be shown as
            follows: 0x13, 0x61, 0x23, 0x45, 0x67, 0x8f, 0xff.
            If all 7 bytes are 0xff, it is a broadcasting command. ID is in hex code

command     2 bytes. The command code is in hex code. Please refer to the
            command list below.

data        Min 0 byte and max 100 bytes. See Annex 1 for description of ‘data’.

checksum    2 bytes. It indicates CRC-CCITT (default is 0xffff) checksum of
            all data (not including CRC itself and the ending character).
            It is in hex code.
            For example: 24 24 00 11 13 61 23 45 67 8f ff 50 00 05 d8 0d 0a
            0x05d8 = CRC-CCITT (24 24 00 11 13 61 23 45 67 8f ff 50 00)

\r\n        2 bytes. It is the ending character and in hex code
            (0x0d,0x0a in hex code)

Update

With the answer from Anomie, i was able to piece this together

$arr = unpack('H4length/H14id/H4cmd/H4crc/H4end', mb_substr($data, 2, 11) . mb_substr($data, -4));

var_dump($arr);

This will out put something like

array(5) {
  ["length"]=>
  string(4) "0054"
  ["id"]=>
  string(14) "004512345678ff"
  ["cmd"]=>
  string(4) "9955"
  ["crc"]=>
  string(4) "c97e"
  ["end"]=>
  string(4) "0d0a"
}


问:
IllegalArgument Exception : Unable to compile
I am getting IlleagalArgument Exception while retreiving Xpath for a particular node

I need to retrieve the below webpage link which follows the title WebPages ,I  tried using the below expression but it is not able compile (Please see the comment section for the html )

```<code>page.getNode("//h3[. = 'Webpages:']/following-sibling::/ul[@class='list-entity-locations']/li/a/text()")
</code>```

This is what I tried but got Exception

java.lang.IllegalArgumentException: Unable to compile

答:
To looking into html which you have posted there is no : text inside
...
 tag.
Try the below code.

```<code>//h3[. = 'Webpages']/following-sibling::ul[@class='list-entity-locations']/li/a/text()
</code>```

Body:
I am getting IlleagalArgument Exception while retreiving Xpath for a particular node

I need to retrieve the below webpage link which follows the title WebPages ,I  tried using the below expression but it is not able compile (Please see the comment section for the html )

page.getNode("//h3[. = 'Webpages:']/following-sibling::/ul[@class='list-entity-locations']/li/a/text()")

This is what I tried but got Exception

java.lang.IllegalArgumentException: Unable to compile

Body:
To looking into html which you have posted there is no : text inside <h3>...</h3> tag.
Try the below code.

//h3[. = 'Webpages']/following-sibling::ul[@class='list-entity-locations']/li/a/text()


问:
How can I get detailed info on what Bot Connector Service does to messages sent from registered channels to my endpoint?
I'm using MBF for its channel integration with Facebook Messenger.

During development I've been using "ngrok" in order to debug directly sending and receiving messsages from Messenger.
After reaching a completition level, decided to deploy my bot in my work's server setting up an endpoint for channel registration with https as described here.

After deployment, I've been experiencing, what I thought at first, a delay in bot responses as I needed to send the same message or action like 3 times which turns into a terrible UX.

Moving my bot to azure didn't help.

On a second thought, maybe just messages aren't reaching my endpoint as suggested with what I tried

Deployed my bot to my local IIS and exposing an endpoint using ngrok monitoring all incoming HTTP Requests.

While interacting with my bot noticed that sometimes it takes like 3 up to 4 messages to reach my endpoint, which didn't happen while debugging. So maybe there might be some issues between my endpoint and Bot Connector Service that I'm missing

Some extra details

Bot Framework version: 4.4.4

AppId: dd6bec6b-3177-4930-82ef-45104a947367

答:
Turns out this issue wasn't related to Bot Connector.

During my research on bot development on Facebook Messenger, I forgot to delete old applications subscribed to the fan page I was using (reusing same fan page for multiple applications makes weird things apparently).

By deleting old applications and keeping only the one I was using with MBF did the trick. Bot is responding properly now, receiving every message sent.


问:
How can I use Rails routes to redirect from one domain to another?
My app used to run on foo.tld but now it runs on bar.tld. Requests will still come in for foo.tld, I want to redirect them to bar.tld.

How can I do this in rails routes?

答:
Bit more modern approach:</p>

```<code>constraints(host: 'www.mydomain.com') do
    get '/:param' => redirect('https://www.mynewurl.com/:param')
end
</code>```

Body:
Bit more modern approach:

constraints(host: 'www.mydomain.com') do
    get '/:param' => redirect('https://www.mynewurl.com/:param')
end


问:
How to do firebase phone auth in a flutter app
I've done all the steps to attach my database and proven I can get data that isn't protected by any auth rules.  Now I want to implement phone sign in and add auth rules.

flutter doctor and flutter analyze both return no errors.  I've copied the example code from here, the firebase_auth plugin example code

The important point is here:

```<code>await _auth.verifyPhoneNumber(
    phoneNumber: _phoneNumberController.text,
    timeout: const Duration(seconds: 5),
    verificationCompleted: verificationCompleted,
    verificationFailed: verificationFailed,
    codeSent: codeSent,
    codeAutoRetrievalTimeout: codeAutoRetrievalTimeout);
}
</code>```

When I run this line (iPhone simulator from VS code), I get no message on the console, the debug session ends, the simulator screen goes black, and seconds later returns to the home screen.

I'm new to all of this, but the only idea I have is this: when I print on the console _auth.verifyPhoneNumber, I get this

Closure: ({String phoneNumber, Duration timeout, int
  forceResendingToken, (AuthCredential) => void verificationCompleted,
  (AuthException) => void verificationFailed, (String, [int]) => void
  codeSent, (String) => void codeAutoRetrievalTimeout}) => Future
  from Function 'verifyPhoneNumber':.

Notice that the third parameter is int forceResendingToken, which is not in my code.  I can't find any doc about this.

Two questions:
 1. Can you help me get auth working, and
 2. Can you help me navigate docs on my own?  In flutter, I don't know which firebase docs to look at.  Can you show me the link, for example, for the auth methods that should be used in flutter?

Thanks!

答: Well, it turns out that a simple URL scheme with just an array inside the item dictionary isn't the right format for firebase.  It must look like this:

Body:
I've done all the steps to attach my database and proven I can get data that isn't protected by any auth rules.  Now I want to implement phone sign in and add auth rules.

flutter doctor and flutter analyze both return no errors.  I've copied the example code from here, the firebase_auth plugin example code

The important point is here:

await _auth.verifyPhoneNumber(
    phoneNumber: _phoneNumberController.text,
    timeout: const Duration(seconds: 5),
    verificationCompleted: verificationCompleted,
    verificationFailed: verificationFailed,
    codeSent: codeSent,
    codeAutoRetrievalTimeout: codeAutoRetrievalTimeout);
}

When I run this line (iPhone simulator from VS code), I get no message on the console, the debug session ends, the simulator screen goes black, and seconds later returns to the home screen.

I'm new to all of this, but the only idea I have is this: when I print on the console _auth.verifyPhoneNumber, I get this

Closure: ({String phoneNumber, Duration timeout, int
  forceResendingToken, (AuthCredential) => void verificationCompleted,
  (AuthException) => void verificationFailed, (String, [int]) => void
  codeSent, (String) => void codeAutoRetrievalTimeout}) => Future
  from Function 'verifyPhoneNumber':.

Notice that the third parameter is int forceResendingToken, which is not in my code.  I can't find any doc about this.

Two questions:
 1. Can you help me get auth working, and
 2. Can you help me navigate docs on my own?  In flutter, I don't know which firebase docs to look at.  Can you show me the link, for example, for the auth methods that should be used in flutter?

Thanks!


问:
System.Web.OData not defined when installing Microsoft.AspNet.Odata
I am trying to follow this Microsoft tutorial with no luck. https://learn.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/create-an-odata-v4-endpoint . I created the web api project on visual studio 2017, and runned "Install-Package Microsoft.AspNet.Odata" on Package Manager Console, but I still get System.Web.OData namespace undefined ("The type or namespace Odata does not exist on 'System.Web'"). Any clue why is this happening?. The version of Odata installed is 7.0.1. Should I get another version?</p>

答:
See https://github.com/Microsoft/aspnet-api-versioning/issues/315:

With Microsoft.AspNet.OData v7.0, namespaces were changed from System.Web.OData to Microsoft.AspNet.OData.


问:
Creating unit tests for Xcode project results in error : Showing Recent Messages :-1: Undefined symbol: _OBJC_CLASS_$_FBSDKCodelessIndexer
When adding this to my pods file ( for unit testing purposes )

```<code>target 'MY_PROJECT_TITLE_Tests' do
inherit! :search_paths
pod 'Firebase'
end
</code>```

I get the error when compiling:

```<code>Undefined symbols for architecture x86_64:
"_OBJC_CLASS_$_FBSDKCodelessIndexer", referenced from:
  objc-class-ref in FBSDKMarketingKit(FBSDKButtonIndexer.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see
invocation)
</code>```

there were no errors prior to the "pod install" of the above podfile change. Why is this / is there a fix? thank you.

答:
Likely a pod update is needed.

There could be an incompatibility between old versions of Firebase and FBSDK like How to fix build error with FBSDKLoginKit in Xcode

Body:
When adding this to my pods file ( for unit testing purposes )

target 'MY_PROJECT_TITLE_Tests' do
inherit! :search_paths
pod 'Firebase'
end

I get the error when compiling:

Undefined symbols for architecture x86_64:
"_OBJC_CLASS_$_FBSDKCodelessIndexer", referenced from:
  objc-class-ref in FBSDKMarketingKit(FBSDKButtonIndexer.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see
invocation)

there were no errors prior to the "pod install" of the above podfile change. Why is this / is there a fix? thank you.


问:
how to make my LSTM model predict after training
I'm a begginer at ML and I'm using an LSTM model to forcast a future value of a column I think i succeded in training my model but I'm strugling to make my model predict the future values
my dataset is like this:
   c0            c1         c2        c3          c4          c5
 0.953202     0.998825   0.943329   0.762738    0.046798      0.0
....
I trained my model to predict the values of c5 based on the the other columns

# split into train and test sets
values = reframed.values
n_train_hours = 24*24
train = values[:n_train_hours, :]
test = values[n_train_hours:, :]

# split into input and outputs
train_X, train_y = train[:, :-1], train[:, -1]
test_X, test_y = test[:, :-1], test[:, -1]
# reshape input to be 3D [samples, timesteps, features]
train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))
test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape, try1.shape)

# design network
model = Sequential()
model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
# fit network
history = model.fit(train_X, train_y, epochs=50, batch_size=72, validation_data=(test_X, test_y), verbose=2, shuffle=False)

# make a prediction
      ???

```

答:
You can use your model to predict with:

```<code>print(model.predict('''your sample'''))
</code>```

This will print the predicted labels.

Body:
You can use your model to predict with:

print(model.predict('''your sample'''))

This will print the predicted labels.


问:
Deleting a cell in tableview, the cell also can be reused,why?
at first,i delete one cell in tableView,then i want to add another new cell in the tableView,but the  new cell is not new,it is just the cell which i delete. i know what dequeueReusableCellWithIdentifier means.i think when  delete one cell,the cache in dequeueReusableCellWithIdentifier is also deleted.why not?</p>

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"table reload");

    PDFModel* tempmodel=[PDFArray objectAtIndex:indexPath.row];
    NSString * CellIdentifier=tempmodel.PDFName;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSLog(@"cell %x",cell);
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
       //custom the cell
        cell.text=...
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle==UITableViewCellEditingStyleDelete)
    {
         [PDFArray removeObjectAtIndex:indexPath.row];
         NSMutableArray* array=[[NSMutableArray alloc] init];
         [array addObject:indexPath];
         [self.tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationRight];

    }
}
</code>```

答:
Your question is a bit weird, but I guess you're wondering what the following code does?

```<code>UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
</code>```

What the code does, is that it tries to retrieve a cached UITableView cell. This is to reduce memory usage on the iPhone.

Once you delete a cell, you should also remove the data from the datasource (usually an array), e.g.:

```<code>- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
       if (editingStyle==UITableViewCellEditingStyleDelete)
       {
           // remove object from array ...
           [dataArray removeObjectAtIndex:indexPath.row];
       }
}
</code>```

(Remember: you can only remove items from an NSMutableArray at runtime, not from a NSArray)

If the cell gets redrawn, you will first check which cell needs to be redrawn, then you retrieve the appropriate data from the datasource, this is all done by the UITableViewDataSource delegate methods. You only have to make sure to retrieve the right content from the array and update the cell's content on redraw, e.g. like this:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"CellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        // no cached cell is found, create a new cell ...
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        // add some defaults for cells in the initializer,
        // stuff that's done here should be important for
        // all displayed cells, for example background image.
    }

    // update the cell's content, e.g.: - it will only display content that's currently in the array, deleted objects shouldn't exist in the array at this point
    NSString *title = [dataArray objectAtIndex:indexPath.row];
    [cell.textLabel setText:title];

    return cell;
}
</code>```

Body:
at first,i delete one cell in tableView,then i want to add another new cell in the tableView,but the  new cell is not new,it is just the cell which i delete. i know what dequeueReusableCellWithIdentifier means.i think when  delete one cell,the cache in dequeueReusableCellWithIdentifier is also deleted.why not?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"table reload");

    PDFModel* tempmodel=[PDFArray objectAtIndex:indexPath.row];
    NSString * CellIdentifier=tempmodel.PDFName;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSLog(@"cell %x",cell);
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
       //custom the cell
        cell.text=...
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle==UITableViewCellEditingStyleDelete)
    {
         [PDFArray removeObjectAtIndex:indexPath.row];
         NSMutableArray* array=[[NSMutableArray alloc] init];
         [array addObject:indexPath];
         [self.tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationRight];

    }
}

Body:
Your question is a bit weird, but I guess you're wondering what the following code does?

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

What the code does, is that it tries to retrieve a cached UITableView cell. This is to reduce memory usage on the iPhone.

Once you delete a cell, you should also remove the data from the datasource (usually an array), e.g.:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
       if (editingStyle==UITableViewCellEditingStyleDelete)
       {
           // remove object from array ...
           [dataArray removeObjectAtIndex:indexPath.row];
       }
}

(Remember: you can only remove items from an NSMutableArray at runtime, not from a NSArray)

If the cell gets redrawn, you will first check which cell needs to be redrawn, then you retrieve the appropriate data from the datasource, this is all done by the UITableViewDataSource delegate methods. You only have to make sure to retrieve the right content from the array and update the cell's content on redraw, e.g. like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"CellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        // no cached cell is found, create a new cell ...
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        // add some defaults for cells in the initializer,
        // stuff that's done here should be important for
        // all displayed cells, for example background image.
    }

    // update the cell's content, e.g.: - it will only display content that's currently in the array, deleted objects shouldn't exist in the array at this point
    NSString *title = [dataArray objectAtIndex:indexPath.row];
    [cell.textLabel setText:title];

    return cell;
}


问:
BuildBot: execute build steps in parallel
Is it possible to instruct BuildBot to execute build steps in parallel?

I've been looking through documentation and it only seems to be possible by actually generating multiple builds / build factories.

I'm not entirely sure about Builders and Workers: I have seen that adding workers will allow me to run multiple build requests simultaneously (multiple programmers submitting PRs), but using multiple builders doesn't seem to be intended for anything like this.

So, is it possible?

答:
You can have multiple builders executing simultaneously, for example if they listen to incoming commits on the same repository; a single commit will start all listening builders. In this scenario you can control parallelism using BuilderConfig's canStartBuild argument. And beware to have the builders work on separate resources!

Alternatively if you trigger multiple builders from a single builder and
specify waitForFinish=False, the triggered builders will run simultaneoulsy.

I believe you cannot execute build steps in parallel within a single builder. Regarding the workers, I can't tell you.


问:
Preventing dangerous user input from django tinymce
Say we want to use tinymce to allow users to enter HTML formatted input. The django-tinymce package is a handy solution.

But to render this later as output, we have to use {{ userinput | safe }} to display it. But do we know for a fact the original user's input is ... safe?

What in particular are the kinds of malicious HTML tags we need to be wary of and sanitize? What would be a sound strategy to not strip out the legitimate tags tinymce utilizes while protecting future website users who will be presented with 'safe' user input?

答:
You can never assume that data provided to you client side is "clean" or "safe".  Nefarious people can bypass your front end and all of its validation if their goal is to cause harm to your system.

You should always configure your front end appropriately.  Validate data, configure TinyMCE to only allow those types of tags you want created, etc.

However, regardless of the front end design, you always have to re-check submitted content on the server to be safe. There is simply no way around that need.  What constitutes "safe" is likely a business decision based on what your application does and who uses it.

There are many different libraries you can use server side to do this sort of validation/cleansing so depending on your specific server side setup (guessing PHP) you can find libraries that allow you to "sanitize/purify" the submitted HTML.


问:
How can I load an XLSX spreadsheet with 52,4 MB into BigQuery?
I am trying to analyze millions of search queries in a webshop and aggregate it in Google Data Studio. Unfortunately the XLSX in my Google Cloud Storage due to the errors:

Error while reading data, error message: CSV table encountered too many errors, giving up. Rows: 1; errors: 1. Please look into the errors[] collection for more details.

Error while reading data, error message: Error detected while parsing row starting at position: 0. Error: Bad character (ASCII 0) encountered.

I uploaded an XLSX file from my computer to my Google Cloud Storage and I tried to create a table from it with Google BigQuery and while importing it, I get those error messages.

I want to use BigQuery as a data source for my Google Data Studio and aggregate the search strings from the XLSX file in a way that I may see which queries occur regularly without any results and which search strings are being searched for most often.

I would very much appreciate you for helping me fix the error and find an efficient way to aggregate the data without long loading time necessary.

答:
The supported data formats does not include XLSX.

A good way to achieve this would be to convert the XLSX to a CSV, and then load it to BigQuery.

Here you have an example on how to use Python with pandas to converted the file. Once is converted, you can upload it to Google Cloud Storage, and then load it to BigQuery.

Alternatively, you could upload it directly from your computer without using Google Cloud Storage.


问:
Splinter Is it possible to use browser.fill without name as a query
I would like to use an absolute xpath to fill in a search bar. The ids and classes are dynamically generated and there is no name variable or instance. So it feels like I'm stuck without a tool to fill in boxes without the named variable.

Is there a way around this? Can I somehow change the absolute xpath to look like its a name assignment and then query and fill based on the new 'type' I assigned the absolute xpath?

Is there a method for this in Selenium if not available in Splinter?

I've select by CSS and I'm finding this error 'selenium.common.exceptions.InvalidElementStateException: Message: Element is not currently interactable and may not be manipulated'

Edit:

```<code><div class="type-ahead-input-container" role="search">
<div class="type-ahead-input-wrapper">
<div class="type-ahead-input">
<label class="visually-hidden" for="a11y-ember10393">
Search
</label>
<!---->
<input id="a11y-ember10393" class="ember-text-field ember-view" aria-
autocomplete="list" autocomplete="off" spellcheck="false"
placeholder="Search" autocorrect="off" autocapitalize="off" role="combobox"
aria-expanded="true" aria-owns="ember11064" data-artdeco-is-focused="true"/>
<div class="type-ahead-input-icons">
<!---->
</div>
</div>
<!---->
</div>
</div>
</code>```

答:
When you get an error-message like that, it could be that your search result is not what you expected. It could be that you are getting more than one result, ie a list. On a list you can not input.

You can find the input boxes with an xpath, select the prefered one from the list (by trying) and put a text in it with the WebDriverElement _set_value method. That is not appropriate because of the _, but it is usefull.

input_list = browser.find_by_xpath('//div[@class="type-ahead-input"]/input[@class="ember-textfield ember-view"]')

input_list[1]._set_value('just a text to see whether it is working')

Body:
I would like to use an absolute xpath to fill in a search bar. The ids and classes are dynamically generated and there is no name variable or instance. So it feels like I'm stuck without a tool to fill in boxes without the named variable.

Is there a way around this? Can I somehow change the absolute xpath to look like its a name assignment and then query and fill based on the new 'type' I assigned the absolute xpath?

Is there a method for this in Selenium if not available in Splinter?

I've select by CSS and I'm finding this error 'selenium.common.exceptions.InvalidElementStateException: Message: Element is not currently interactable and may not be manipulated'

Edit:

Search

<input id="a11y-ember10393" class="ember-text-field ember-view" aria-
autocomplete="list" autocomplete="off" spellcheck="false"
placeholder="Search" autocorrect="off" autocapitalize="off" role="combobox"
aria-expanded="true" aria-owns="ember11064" data-artdeco-is-focused="true"/>


问:
Flutter equvalent Android-Toggle-Switch
is any flutter widget like with this library in android java?

```<code><belka.us.androidtoggleswitch.widgets.MultipleToggleSwitch
        android:id="@+id/multiple_toggle_switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        custom:textToggleCenter="Center"
        custom:textToggleLeft="Left"
        custom:textToggleRight="Right"
        android:layout_gravity="center"
        custom:toggleWidth="82dp"/>
</code>```

i did try to search to find this implementation on flutter but i can't

答:
as an option, how to use

```<code>import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ToggleWidget(
                initialLabel: 2,
                activeBgColor: Colors.indigo,
                activeTextColor: Colors.white,
                inactiveBgColor: Colors.grey,
                inactiveTextColor: Colors.grey[900],
                labels: ['OR', 'XOR', 'AND', 'NOT'],
                onToggle: (index) {
                  print('switched to: $index');
                },
              ),
              SizedBox(height: 16),
              ToggleWidget(
                cornerRadius: 20,
                activeBgColor: Colors.redAccent,
                activeTextColor: Colors.yellow,
                inactiveBgColor: Colors.grey,
                inactiveTextColor: Colors.white,
                labels: ['YES', 'NO'],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

and the widget itself

```<code>typedef OnToggle = void Function(int index);

class ToggleWidget extends StatefulWidget {
  final Color activeBgColor;
  final Color activeTextColor;
  final Color inactiveBgColor;
  final Color inactiveTextColor;
  final List<String> labels;
  final double cornerRadius;
  final OnToggle onToggle;
  final int initialLabel;
  final double minWidth;

  ToggleWidget({
    Key key,
    @required this.activeBgColor,
    @required this.activeTextColor,
    @required this.inactiveBgColor,
    @required this.inactiveTextColor,
    @required this.labels,
    this.onToggle,
    this.cornerRadius = 8.0,
    this.initialLabel = 0,
    this.minWidth = 72,
  }) : super(key: key);

  @override
  _ToggleWidgetState createState() => _ToggleWidgetState();
}

class _ToggleWidgetState extends State<ToggleWidget> {
  int current;

  @override
  void initState() {
    current = widget.initialLabel;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(widget.cornerRadius),
      child: Container(
        height: 40,
        color: widget.inactiveBgColor,
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: List.generate(widget.labels.length * 2 - 1, (index) {
            final active = index ~/ 2 == current;
            final textColor = active ? widget.activeTextColor : widget.inactiveTextColor;
            final bgColor = active ? widget.activeBgColor : Colors.transparent;
            if (index % 2 == 1) {
              final activeDivider = active || index ~/ 2 == current - 1;
              return Container(
                width: 1,
                color: activeDivider ? widget.activeBgColor : Colors.white30,
                margin: EdgeInsets.symmetric(vertical: activeDivider ? 0 : 8),
              );
            } else {
              return GestureDetector(
                onTap: () => _handleOnTap(index ~/ 2),
                child: Container(
                  constraints: BoxConstraints(minWidth: widget.minWidth),
                  alignment: Alignment.center,
                  color: bgColor,
                  child: Text(widget.labels[index ~/ 2], style: TextStyle(color: textColor)),
                ),
              );
            }
          }),
        ),
      ),
    );
  }

  void _handleOnTap(int index) async {
    setState(() => current = index);
    if (widget.onToggle != null) {
      widget.onToggle(index);
    }
  }
}
</code>```

result:

Title: Flutter equvalent Android-Toggle-Switch

Body:
is any flutter widget like with this library in android java?

<belka.us.androidtoggleswitch.widgets.MultipleToggleSwitch
        android:id="@+id/multiple_toggle_switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        custom:textToggleCenter="Center"
        custom:textToggleLeft="Left"
        custom:textToggleRight="Right"
        android:layout_gravity="center"
        custom:toggleWidth="82dp"/>

i did try to search to find this implementation on flutter but i can't

Body:
as an option, how to use

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ToggleWidget(
                initialLabel: 2,
                activeBgColor: Colors.indigo,
                activeTextColor: Colors.white,
                inactiveBgColor: Colors.grey,
                inactiveTextColor: Colors.grey[900],
                labels: ['OR', 'XOR', 'AND', 'NOT'],
                onToggle: (index) {
                  print('switched to: $index');
                },
              ),
              SizedBox(height: 16),
              ToggleWidget(
                cornerRadius: 20,
                activeBgColor: Colors.redAccent,
                activeTextColor: Colors.yellow,
                inactiveBgColor: Colors.grey,
                inactiveTextColor: Colors.white,
                labels: ['YES', 'NO'],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

and the widget itself

typedef OnToggle = void Function(int index);

class ToggleWidget extends StatefulWidget {
  final Color activeBgColor;
  final Color activeTextColor;
  final Color inactiveBgColor;
  final Color inactiveTextColor;
  final List<String> labels;
  final double cornerRadius;
  final OnToggle onToggle;
  final int initialLabel;
  final double minWidth;

  ToggleWidget({
    Key key,
    @required this.activeBgColor,
    @required this.activeTextColor,
    @required this.inactiveBgColor,
    @required this.inactiveTextColor,
    @required this.labels,
    this.onToggle,
    this.cornerRadius = 8.0,
    this.initialLabel = 0,
    this.minWidth = 72,
  }) : super(key: key);

  @override
  _ToggleWidgetState createState() => _ToggleWidgetState();
}

class _ToggleWidgetState extends State<ToggleWidget> {
  int current;

  @override
  void initState() {
    current = widget.initialLabel;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(widget.cornerRadius),
      child: Container(
        height: 40,
        color: widget.inactiveBgColor,
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: List.generate(widget.labels.length * 2 - 1, (index) {
            final active = index ~/ 2 == current;
            final textColor = active ? widget.activeTextColor : widget.inactiveTextColor;
            final bgColor = active ? widget.activeBgColor : Colors.transparent;
            if (index % 2 == 1) {
              final activeDivider = active || index ~/ 2 == current - 1;
              return Container(
                width: 1,
                color: activeDivider ? widget.activeBgColor : Colors.white30,
                margin: EdgeInsets.symmetric(vertical: activeDivider ? 0 : 8),
              );
            } else {
              return GestureDetector(
                onTap: () => _handleOnTap(index ~/ 2),
                child: Container(
                  constraints: BoxConstraints(minWidth: widget.minWidth),
                  alignment: Alignment.center,
                  color: bgColor,
                  child: Text(widget.labels[index ~/ 2], style: TextStyle(color: textColor)),
                ),
              );
            }
          }),
        ),
      ),
    );
  }

  void _handleOnTap(int index) async {
    setState(() => current = index);
    if (widget.onToggle != null) {
      widget.onToggle(index);
    }
  }
}

result:


问:
Parse a JSON object with the value as JSON string array
I am trying to parse a JSON string which is of the following format

```<code>{"edgeNodeRegistrationStatus": ["{\"CONFIRMED\":\"TRUE\"}"]}
</code>```

I have written a code to parse it.

```<code>import groovy.json.JsonOutput
import groovy.json.JsonSlurper

def jsonSlurper = new JsonSlurper()

def object = jsonSlurper.parseText('{"edgeNodeRegistrationStatus": ["{\"CONFIRMED\":\"TRUE\"}"]}')

println(object["edgeNodeRegistrationStatus"][0])
</code>```

I expect the code to print {"CONFIRMED":"TRUE"}. But its throwing an error

```<code>Caught: groovy.json.JsonException: expecting a ',' or a ']',  but got
the current character of  'C' with an int value of 67  on array index of 1

The current character read is 'C' with an int value of 67
expecting a ',' or a ']',  but got
the current character of  'C' with an int value of 67  on array index of 1

line number 1
index number 35
{"edgeNodeRegistrationStatus": ["{"CONFIRMED":"TRUE"}"]}
...................................^
groovy.json.JsonException: expecting a ',' or a ']',  but got
the current character of  'C' with an int value of 67  on array index of 1

The current character read is 'C' with an int value of 67
expecting a ',' or a ']',  but got
the current character of  'C' with an int value of 67  on array index of 1

line number 1
index number 35
{"edgeNodeRegistrationStatus": ["{"CONFIRMED":"TRUE"}"]}
...................................^
    at jdoodle.run(jdoodle.groovy:4)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Command exited with non-zero status 1
</code>```

答:
Using \" inside a ''-String will give you just " inside the string itself (same as in a ""-String). But you want to quote the \" for the JSON (not groovy).  So you need to use \\" instead.

Unless you really want to have that string for testing, you are better off just generating the JSON you expect there in your code.  So you don't have to battle that. E.g.

```<code>JsonOutput.toJson([edgeNodeRegistrationStatus: [JsonOutput.toJson([CONFIRMED: "TRUE"])]])
</code>```

Body:
I am trying to parse a JSON string which is of the following format

{"edgeNodeRegistrationStatus": ["{\"CONFIRMED\":\"TRUE\"}"]}

I have written a code to parse it.

import groovy.json.JsonOutput
import groovy.json.JsonSlurper

def jsonSlurper = new JsonSlurper()

def object = jsonSlurper.parseText('{"edgeNodeRegistrationStatus": ["{\"CONFIRMED\":\"TRUE\"}"]}')

println(object["edgeNodeRegistrationStatus"][0])

I expect the code to print {"CONFIRMED":"TRUE"}. But its throwing an error

Caught: groovy.json.JsonException: expecting a ',' or a ']',  but got
the current character of  'C' with an int value of 67  on array index of 1

The current character read is 'C' with an int value of 67
expecting a ',' or a ']',  but got
the current character of  'C' with an int value of 67  on array index of 1

line number 1
index number 35
{"edgeNodeRegistrationStatus": ["{"CONFIRMED":"TRUE"}"]}
...................................^
groovy.json.JsonException: expecting a ',' or a ']',  but got
the current character of  'C' with an int value of 67  on array index of 1

The current character read is 'C' with an int value of 67
expecting a ',' or a ']',  but got
the current character of  'C' with an int value of 67  on array index of 1

line number 1
index number 35
{"edgeNodeRegistrationStatus": ["{"CONFIRMED":"TRUE"}"]}
...................................^
    at jdoodle.run(jdoodle.groovy:4)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Command exited with non-zero status 1

Body:
Using \" inside a ''-String will give you just " inside the string itself (same as in a ""-String). But you want to quote the \" for the JSON (not groovy).  So you need to use \\" instead.

Unless you really want to have that string for testing, you are better off just generating the JSON you expect there in your code.  So you don't have to battle that. E.g.

JsonOutput.toJson([edgeNodeRegistrationStatus: [JsonOutput.toJson([CONFIRMED: "TRUE"])]])


问:
Dynamically setting a absolute DIV with a Dynamic Height?
Please see the following: http://jsfiddle.net/GWJMf/

What I'm trying to do is have the TITLE fixed, not scroll. But the content scrollable.

Problem is, having a fixed title, makes it very hard to deal with the dynamic range of a title, which can have anywhere from 5 - 250 characters.

Is there a way to have the TITLE be fixed, not scroll, but have the height set based on the title length?

Is this possible w CSS? Ideas? Thanks

答:
Not sure why you have all that extra styling. You don't need to style the h2 or any wrapping elements to have it expand based on the length of the text.

http://jsfiddle.net/xd7a4/

I'm not sure of the height you're desiring for the scrolling container however here I set it to 200px.

```<code><h2>title</h2>
<div class="scroll">content</div>
</code>```

```<code>
H2 {
    background-color: #FF0000;
}
.scroll {
    height: 200px;
    overflow: scroll;
    overflow-x: hidden;
}
</code>```

Body:
Not sure why you have all that extra styling. You don't need to style the h2 or any wrapping elements to have it expand based on the length of the text.

http://jsfiddle.net/xd7a4/

I'm not sure of the height you're desiring for the scrolling container however here I set it to 200px.

<h2>title</h2>
<div class="scroll">content</div>

H2 {
    background-color: #FF0000;
}
.scroll {
    height: 200px;
    overflow: scroll;
    overflow-x: hidden;
}


问:
done is not a function in passport.js
```<code>const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');

var User = mongoose.model('User');

passport.use(
    new localStrategy({ usernameField: 'email' },
        (req, username, password, done) => {
            User.findOne({ email: username },
                (err, user) => {

                    if (err)
                        return done(err);
                    // unknown user
                    else if (!user)
                        return done(null, false, { message: 'Email is not registered' });
                    // wrong password
                    else if (!user.verifyPassword(password))
                        return done(null, false, { message: 'Wrong password.' });
                    // wrong type
                    else if (!user.verifyType(req.body.type))
                        return done(null, false, { message: 'Wrong type.' });
                    // authentication succeeded
                    else
                        return done(null, user);
                });
        })
);
</code>```

done is not a function is the error
Using PassportJS, how pass one additional form fields to the local authentication strategy?

答:
```<code>passport.use(
    new localStrategy({ usernameField: 'email' },
        yourParameter
        (req, username, password, done) => {
            User.findOne({ email: username },
                (err, user) => {

                    if (err)
                        return done(err);
                    // unknown user
                    else if (!user)
                        return done(null, false, { message: 'Email is not registered' });
                    // wrong password
                    else if (!user.verifyPassword(password))
                        return done(null, false, { message: 'Wrong password.' });
                    // wrong type
                    else if (!user.verifyType(yourParameter))
                        return done(null, false, { message: 'Wrong type.' });
                    // authentication succeeded
                    else
                        return done(null, user);
                });
        })
);
</code>```

Title: done is not a function in passport.js

Body:
const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');

var User = mongoose.model('User');

passport.use(
    new localStrategy({ usernameField: 'email' },
        (req, username, password, done) => {
            User.findOne({ email: username },
                (err, user) => {

                    if (err)
                        return done(err);
                    // unknown user
                    else if (!user)
                        return done(null, false, { message: 'Email is not registered' });
                    // wrong password
                    else if (!user.verifyPassword(password))
                        return done(null, false, { message: 'Wrong password.' });
                    // wrong type
                    else if (!user.verifyType(req.body.type))
                        return done(null, false, { message: 'Wrong type.' });
                    // authentication succeeded
                    else
                        return done(null, user);
                });
        })
);

done is not a function is the error
Using PassportJS, how pass one additional form fields to the local authentication strategy?


问:
Automatic low level testing generation based on high level desired behavioral examples

Top Level Problem

Our team has inherited a very large and brittle python 2 (and C,C++, few others) codebase that is very difficult and costly to update. Tons of dependencies. Very few tests. Adding behavior improvement and converting to python 3 both have appeared to be monumental tasks. Even making small changes for a new release we've had to revert many times as it's broken something.

It's a story of insufficient testing and its major technical debt.

Still, the project is so big and helpful, that it seems a no brainer to update it than re-invent everything it does.

Sub Problem

How to add a massive amount of missing small tests. How can we automatically generate even simple input/output acceptance unit tests from the high level user acceptance tests?

Attempted Solution

There are about 50 large high level behavioral tests that this codebase needs to handle. Unfortunately, it takes days to run them all, not seconds. These exercise all the code we care the most about, but they are just too slow. (Also a nerdy observation, 80% of the same code is exercised in each one). Is there a way to automatically generate the input/output unit tests from automatic stack examination while running these?

In other words, I have high level tests, but I would like to automatically create low level unit and integration tests based on the execution of these high level tests.

Mirroring the high level tests with unit tests does exactly zero for added code coverage, but what it does do is make the tests far faster and far less brittle. It will allow quick and confident refactoring of the pieces.

I'm very familiar with using TDD to mitigate this massive brittle blob issue in the first place as it actually speeds up development in a lot of cases and prevents this issue, but this is a sort of unique beast of a problem to solve as the codebase already exists and "works" ;).

Any automated test tool tips? I googled around a lot, and I found some things that may work for C, but I can't find anything for python to generate pytests/unittest/nose or whatever. I don't care what python test framework it uses (although would prefer pytest). I must be searching the wrong terms as it seems unbelievable a test generation tool doesn't exist for python.

答:
I've taken a very lazy and practical imperfect solution, and it took me about 40hrs: 20 of which was wrapping my head around the C part enough to write unit tests for it and fix it, which amounted to about 30 lines -- the other 20 was fixing mostly trivial bytes/strings issues that futurize couldn't possbly handle and setting up CI.

Run futurize

Run the most desirable use case as an E2E test and fix issues, complete with new critical unit tests

CI w/ tox on 2.7/3.x for these

End result is an unchanged 2.7 codebase and a minimally working beta 3.7 codebase, the long tail 3.7 support for secondary use cases to be solved over time, see Dirk's long term answer.


问:
how can this SQL be done in LINQ?
i have this simple SQL query...

```<code>-- BestSeller
SELECT TOP(1) v.make, v.model, COUNT(v.make) AS NoSold
FROM Vehicles v
group by v.make, v.model
order by NoSold DESC
</code>```

Im using entity framwork and want to do the same thing using linq. so far i have...

```<code>                var tester = (from v in DB.VP_Historical_Vehicles
                         group v by v.make into g
                         orderby g.Count() descending
                         select new { make = g.Key, model = g, count = g.Count() }).Take(1);

            foreach(var t in tester)
            {
                BestSeller.Make = t.make;
                BestSeller.Model = t.make;
                BestSeller.CountValue = t.count;
            }
</code>```

i keep getting timeouts, the database is large but the SQL runs very quick

any sugestions?

thanks

truegilly

答:
thanks to Scott Weinstein answer i was able to get it working

please comment if there is a more efficiant way of doing this...

```<code>        VehicleStatsObject BestSeller = new VehicleStatsObject();

        using (var DB = DataContext.Get_DataContext)
        {
            var t = (from v in DB.VP_Historical_Vehicles
                     group v by new { v.make, v.model } into g
                     orderby g.Count() ascending
                     select new { make = g.Key.make, model = g.Key.model, count = g.Count() }).OrderByDescending(x => x.count).First();

                BestSeller.Make = t.make;
                BestSeller.Model = t.model;
                BestSeller.CountValue = t.count;
        }

        return BestSeller;
</code>```

Title: how can this SQL be done in LINQ?

Body:
i have this simple SQL query...

-- BestSeller
SELECT TOP(1) v.make, v.model, COUNT(v.make) AS NoSold
FROM Vehicles v
group by v.make, v.model
order by NoSold DESC

Im using entity framwork and want to do the same thing using linq. so far i have...

                var tester = (from v in DB.VP_Historical_Vehicles
                         group v by v.make into g
                         orderby g.Count() descending
                         select new { make = g.Key, model = g, count = g.Count() }).Take(1);

            foreach(var t in tester)
            {
                BestSeller.Make = t.make;
                BestSeller.Model = t.make;
                BestSeller.CountValue = t.count;
            }

i keep getting timeouts, the database is large but the SQL runs very quick

any sugestions?

thanks

truegilly

Body:
thanks to Scott Weinstein answer i was able to get it working

please comment if there is a more efficiant way of doing this...

        VehicleStatsObject BestSeller = new VehicleStatsObject();

        using (var DB = DataContext.Get_DataContext)
        {
            var t = (from v in DB.VP_Historical_Vehicles
                     group v by new { v.make, v.model } into g
                     orderby g.Count() ascending
                     select new { make = g.Key.make, model = g.Key.model, count = g.Count() }).OrderByDescending(x => x.count).First();

                BestSeller.Make = t.make;
                BestSeller.Model = t.model;
                BestSeller.CountValue = t.count;
        }

        return BestSeller;


问:
Execute Task in new background thread
I know there are a million questions on this and I am trying their solutions but it does not seem to behave as I would expect.

With the following code:

```<code>await Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("I'm running after Thread.Sleep"); });
Console.WriteLine("I'm running after Task.Run");
</code>```

I get the output:

```<code>[ 5 seconds elapses ]
I'm running after Thread.Sleep
I'm running after Task.Run
</code>```

Which is the same output I would get without using Task.Run

What I want is the output:

```<code>I'm running after Task.Run
[ 5 seconds elapses ]
I'm running after Thread.Sleep
</code>```

Where execution of the 'parent' thread continues and the long-running task is executed 'in the background' in a way which does not affect the 'parent' thread.

答:
One thing to keep in mind when working with await is that your code awaits objects. These objects are just like any other objects. Specifically, they can be assigned to local variables or class variables.

So, this code:

```<code>await Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("I'm running after Thread.Sleep"); });
Console.WriteLine("I'm running after Task.Run");
</code>```

is essentially the same as this code:

```<code>var task = Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("I'm running after Thread.Sleep"); });
await task;
Console.WriteLine("I'm running after Task.Run");
</code>```

In other words:

Start a task running on a background thread.

Asynchronously wait (await) for that task to complete.

Display "I'm running after Task.Run".

So the output is expected.

What I want is the output:

I'm running after Task.Run

[ 5 seconds elapses ]

I'm running after Thread.Sleep

In that case, start the task running on the background thread, but don't await it until later:

```<code>var task = Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("I'm running after Thread.Sleep"); });
Console.WriteLine("I'm running after Task.Run");
await task;
</code>```

Title: Execute Task in new background thread

Body:
I know there are a million questions on this and I am trying their solutions but it does not seem to behave as I would expect.

With the following code:

await Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("I'm running after Thread.Sleep"); });
Console.WriteLine("I'm running after Task.Run");

I get the output:

[ 5 seconds elapses ]
I'm running after Thread.Sleep
I'm running after Task.Run

Which is the same output I would get without using Task.Run

What I want is the output:

I'm running after Task.Run
[ 5 seconds elapses ]
I'm running after Thread.Sleep

Where execution of the 'parent' thread continues and the long-running task is executed 'in the background' in a way which does not affect the 'parent' thread.

Body:
One thing to keep in mind when working with await is that your code awaits objects. These objects are just like any other objects. Specifically, they can be assigned to local variables or class variables.

So, this code:

await Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("I'm running after Thread.Sleep"); });
Console.WriteLine("I'm running after Task.Run");

is essentially the same as this code:

var task = Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("I'm running after Thread.Sleep"); });
await task;
Console.WriteLine("I'm running after Task.Run");

In other words:

Start a task running on a background thread.

Asynchronously wait (await) for that task to complete.

Display "I'm running after Task.Run".

So the output is expected.

What I want is the output:

I'm running after Task.Run

[ 5 seconds elapses ]

I'm running after Thread.Sleep

In that case, start the task running on the background thread, but don't await it until later:

var task = Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("I'm running after Thread.Sleep"); });
Console.WriteLine("I'm running after Task.Run");
await task;


问:
Why is this query adding null to the table instead of the selected string?
I am running the below query in Oracle SQL. Table has 2 columns, first is rowid type and second is a varchar.

```<code>INSERT INTO MYTABLE SELECT 'AAAAAAAAAAAAAAAAAA' RID, NULL FROM DUAL;
</code>```

The result is adding null in both columns.

Why is this happening?

Shouldn't 'AAAAAAAAAAAAAAAAAA' be added to the first column of the table?

答:
ROWID is a pseudocolumn that you don't store, and can only select from. So your RID is not a row ID.

Without any other details, it seems like you are using EXTENDED ROWID instead:

Extended rowids are stored as base 64 values that can contain the characters A-Z, a-z, 0-9, and the plus sign (+) and forward slash (/). Extended rowids are not available directly. You can use a supplied package, DBMS_ROWID, to interpret extended rowid contents. The package functions extract and provide information that would be available directly from a restricted rowid as well as information specific to extended rowids.

As noted in documentation, you can't just simply select it, you must use DBMS_ROWID to store, or get them.

Body:
I am running the below query in Oracle SQL. Table has 2 columns, first is rowid type and second is a varchar.

INSERT INTO MYTABLE SELECT 'AAAAAAAAAAAAAAAAAA' RID, NULL FROM DUAL;

The result is adding null in both columns.

Why is this happening?

Shouldn't 'AAAAAAAAAAAAAAAAAA' be added to the first column of the table?


问:
What is the special gitlab-ci-token user?
The docs for gitlab's container registry (https://gitlab.com/help/container_registry/README.md) provide a config example with this instruction:

- docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN registry.example.com

and this explanation:

You have to use the credentials of the special gitlab-ci-token user with its password stored in $CI_BUILD_TOKEN in order to push to the Registry connected to your project. This allows you to automated building and deployment of your Docker images.

I cannot find any documentation about this special gitlab-ci-token user, nor about the $CI_BUILD_TOKEN var.

What is this special user? Is it automatically available? Does it have to be defined somewhere? What value should be given to the $CI_BUILD_TOKEN var?

答: In my case upgrading of gitlab-runner helped me</p>


问:
I have an error in my registration routes
During the course of testing if my user's registration route is working fine using postman as a testing machine, it throw an error that I don't know what it means.

I have tried using an async function to catch the error, but it didn't work out

```<code>const express = require('express');
const router = express.Router();
// Use to help set a default image for users
const gravatar = require('gravatar');
// Use to encrypt our password from bringing plain text
const bcrypt = require('bcryptjs');

// I add the user model from my model
// So i can be able to check create a new registration
// and also check if email exist
const User = require('../../models/User');

// @route   GET api/users/register
// @desc    Register user
// @access  Public
router.post('/register', (req, res) => {

  User.findOne({ email: req.body.email }).then(user => {
    if (user) {
      errors.email = 'Email already exists';
      return res.status(400).json(errors);
    } else {
      const avatar = gravatar.url(req.body.email, {
        s: '200', // Size
        r: 'pg', // Rating
        d: 'mm' // Default
      });

      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        avatar,
        password: req.body.password
      });

      bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err;
          newUser.password = hash;
          newUser
            .save()
            .then(user => res.json(user))
            .catch(err => console.log(err));
        });
      });
    }
  });
});

module.exports = router;
</code>```

I want the user input on postman should be able to post the form so I can know if the route is actually working fine. And this is the error I got on my console

```<code>(node:14164) UnhandledPromiseRejectionWarning: ReferenceError: errors is not defined
    at User.findOne.then.user (the working director/name.js:26:7)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:14164) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:14164) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

答:
Normally we should handle the error in a kind of this way:</p>

```<code> User.findOne({ email: req.body.email }).then(user => {
   // ...
 }).catch(error => {
    console.log('error', error)
    res.json({error: error})
 })
</code>```

Body:
During the course of testing if my user's registration route is working fine using postman as a testing machine, it throw an error that I don't know what it means.

I have tried using an async function to catch the error, but it didn't work out

const express = require('express');
const router = express.Router();
// Use to help set a default image for users
const gravatar = require('gravatar');
// Use to encrypt our password from bringing plain text
const bcrypt = require('bcryptjs');

// I add the user model from my model
// So i can be able to check create a new registration
// and also check if email exist
const User = require('../../models/User');

// @route   GET api/users/register
// @desc    Register user
// @access  Public
router.post('/register', (req, res) => {

  User.findOne({ email: req.body.email }).then(user => {
    if (user) {
      errors.email = 'Email already exists';
      return res.status(400).json(errors);
    } else {
      const avatar = gravatar.url(req.body.email, {
        s: '200', // Size
        r: 'pg', // Rating
        d: 'mm' // Default
      });

      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        avatar,
        password: req.body.password
      });

      bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err;
          newUser.password = hash;
          newUser
            .save()
            .then(user => res.json(user))
            .catch(err => console.log(err));
        });
      });
    }
  });
});

module.exports = router;

I want the user input on postman should be able to post the form so I can know if the route is actually working fine. And this is the error I got on my console

(node:14164) UnhandledPromiseRejectionWarning: ReferenceError: errors is not defined
    at User.findOne.then.user (the working director/name.js:26:7)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:14164) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:14164) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Body:
Normally we should handle the error in a kind of this way:

 User.findOne({ email: req.body.email }).then(user => {
   // ...
 }).catch(error => {
    console.log('error', error)
    res.json({error: error})
 })


问:
To get the date difference between a datetime and nullable datetime
I have two dates where one field is a datetime field and the other is a nullable datetime field. I want to subtract date2 from date 1 and if date2 is null subtract it from today.

My code :

Model :

```<code>public class SampleViewModel
{
    public DateTime Date1 {get;set;}
    public DateTime? Date2 {get;set;}
    public int Diff {get;set;}
}
</code>```

Controller Action :

```<code>public ActionResult Index()
{
    var today = DateTime.Now;
    SampleViewModel model = new SampleViewModel();
    model.Date1=today;
    model.Date2 = today.AddDays(5);
    model.Diff = (model.Date1 - (model.Date2 != null ? model.Date2 : today)).Days;//Error
    return View(model);
}
</code>```

I am getting a compilation error

Error CS1061  'TimeSpan?' does not contain a definition for 'Days' and no accessible extension method 'Days' accepting a first argument of type 'TimeSpan?' could be found (are you missing a using directive or an assembly reference?)

What am I doing wrong?

答:
TimeSpan? means Nullable<TimeSpan> which is a different structure from TimeSpan and it doesn't have a Days property.

Instead of that, you can use it's Value property and you can call it's Days after it like;

```<code>model.Diff = (model.Date1 - (model.Date2 != null ? model.Date2 : today)).Value.Days;
</code>```

Or as commented by juharr, you can use model.Date2 ?? today which returns model.Date2 if it's not null or returns today if model.Date2 is null like;

```<code>model.Diff = (model.Date1 - (model.Date2 ?? today)).Days;
</code>```

Body:
I have two dates where one field is a datetime field and the other is a nullable datetime field. I want to subtract date2 from date 1 and if date2 is null subtract it from today.

My code :

Model :

public class SampleViewModel
{
    public DateTime Date1 {get;set;}
    public DateTime? Date2 {get;set;}
    public int Diff {get;set;}
}

Controller Action :

public ActionResult Index()
{
    var today = DateTime.Now;
    SampleViewModel model = new SampleViewModel();
    model.Date1=today;
    model.Date2 = today.AddDays(5);
    model.Diff = (model.Date1 - (model.Date2 != null ? model.Date2 : today)).Days;//Error
    return View(model);
}

I am getting a compilation error

Error CS1061  'TimeSpan?' does not contain a definition for 'Days' and no accessible extension method 'Days' accepting a first argument of type 'TimeSpan?' could be found (are you missing a using directive or an assembly reference?)

What am I doing wrong?

Body:
TimeSpan? means Nullable<TimeSpan> which is a different structure from TimeSpan and it doesn't have a Days property.

Instead of that, you can use it's Value property and you can call it's Days after it like;

model.Diff = (model.Date1 - (model.Date2 != null ? model.Date2 : today)).Value.Days;

Or as commented by juharr, you can use model.Date2 ?? today which returns model.Date2 if it's not null or returns today if model.Date2 is null like;

model.Diff = (model.Date1 - (model.Date2 ?? today)).Days;


问:
upgrade react-spring code that uses animate and transition to latest react-spring
I have this code that uses react-spring 4.0.1 code:

```<code>export const Nodes: React.FunctionComponent<NodesProps> = ({nodes, nodeClickHandler}) => {
  return (
    <Transition
      native={true}
      items={nodes}
      keys={keyAccessor}
      config={{ tension: 1000, friction: 130, mass: 5 }}
      from={(node: HierarchyPointNode<GraphicalNode>) => {
        const parentTopLeft = !!node.parent
                              ? {left: node.parent.x, top: node.parent.y}
                              : {left: 0, top: 0};
        return {
          left: parentTopLeft.left,
          opacity: 0,
          top: parentTopLeft.top,
        };
      }}
      enter={(node: HierarchyPointNode<GraphicalNode>) => {
        return {
          left: node.x,
          opacity: 1,
          top: node.y,
        };
      }}
      update={(node: HierarchyPointNode<GraphicalNode>) => {
        return {
          left: node.x,
          opacity: 1,
          top: node.y,
        };
      }}
      leave={(node: HierarchyPointNode<GraphicalNode>) => {
          return {
            left: node.x,
            opacity: 0,
            top: node.y,
          };
      }}
    >
    {nodes.map((node: HierarchyPointNode<GraphicalNode>) => (styles: CSSProperties) => {
        const key = keyAccessor(node);
        return (
          <animated.g
            className="cx-group"
            style={{
              cursor: "pointer",
              pointerEvents: (styles.opacity as any).interpolate((v: any) => v < 0.5 ? "none" : "all") }
            }
            width={40}
            height={20}
            opacity={styles.opacity}
            transform={template`translate(${styles.left}, ${styles.top})`}
            key={keyAccessor(node)}
          >
            <Node node={node} nodeClickHandler={nodeClickHandler} key={key} />
          </animated.g>
        );
      })}
    </Transition>
  );
};
</code>```

In react-spring 8, there is no transition and animate.

How can I upgrade this code to the latest version.

答:
In version 8 the renderProps api can be accessed from react-spring/renderprops. So you can try with the following import.

```<code>import {Transition, animated} from 'react-spring/renderprops';
</code>```

You can also try the hooks api. I think the code is more simple, I love it.

Body:
I have this code that uses react-spring 4.0.1 code:

export const Nodes: React.FunctionComponent<NodesProps> = ({nodes, nodeClickHandler}) => {
  return (
    <Transition
      native={true}
      items={nodes}
      keys={keyAccessor}
      config={{ tension: 1000, friction: 130, mass: 5 }}
      from={(node: HierarchyPointNode<GraphicalNode>) => {
        const parentTopLeft = !!node.parent
                              ? {left: node.parent.x, top: node.parent.y}
                              : {left: 0, top: 0};
        return {
          left: parentTopLeft.left,
          opacity: 0,
          top: parentTopLeft.top,
        };
      }}
      enter={(node: HierarchyPointNode<GraphicalNode>) => {
        return {
          left: node.x,
          opacity: 1,
          top: node.y,
        };
      }}
      update={(node: HierarchyPointNode<GraphicalNode>) => {
        return {
          left: node.x,
          opacity: 1,
          top: node.y,
        };
      }}
      leave={(node: HierarchyPointNode<GraphicalNode>) => {
          return {
            left: node.x,
            opacity: 0,
            top: node.y,
          };
      }}
    >
    {nodes.map((node: HierarchyPointNode<GraphicalNode>) => (styles: CSSProperties) => {
        const key = keyAccessor(node);
        return (
          <animated.g
            className="cx-group"
            style={{
              cursor: "pointer",
              pointerEvents: (styles.opacity as any).interpolate((v: any) => v < 0.5 ? "none" : "all") }
            }
            width={40}
            height={20}
            opacity={styles.opacity}
            transform={template`translate(${styles.left}, ${styles.top})`}
            key={keyAccessor(node)}
          >
            <Node node={node} nodeClickHandler={nodeClickHandler} key={key} />
          </animated.g>
        );
      })}
    </Transition>
  );
};

In react-spring 8, there is no transition and animate.

How can I upgrade this code to the latest version.

Body:
In version 8 the renderProps api can be accessed from react-spring/renderprops. So you can try with the following import.

import {Transition, animated} from 'react-spring/renderprops';

You can also try the hooks api. I think the code is more simple, I love it.


问:
regexp to match simple markdown
I'm trying to figure out the regexp to match all the occurences of *this kind of strings*. Two additional rules unfortunately made this thing more complicated than I thought:

tagged string should start with * followed by non-whitespace character (so * this one* should not be matched

tagged string should end with non-whitespace followed by * followed by whitespace (so *this one * and *this o*ne should not be matched

I started with simplest regexp \*\S([^\*]+)?\* which for my testing string:

*foo 1 * 2 bar* foo *b* azz *qu **ux*

matches places in square brackets:

[*foo 1 *] 2 bar* foo [*b*] azz [*qu *][*ux*]

and this is what I'd like to achieve:

[*foo 1 * 2 bar*] foo [*b*] azz [*qu **ux*]

so 2 problems appear:

how to express in a regexp a rule from 2. "search till first non-whitespace followed * followed by whitespace appears"? positive lookahead?

how to match whitespace from rule 2. but not include it into result, which \*\S([^\*]+)?\*\s would do?

答:
If you want to start matching from the rightmost *, you may use

```<code>\*(?=[^\s*]).*?(?<=[^\s*])\*(?!\S)
</code>```

To start a match from a left-most * (as in ``), remove the * from the first lookaround (or replace its pattern with \S):

```<code>\*(?=\S).*?(?<=[^\s*])\*(?!\S)
</code>```

See the regex demo #1 and regex demo #2. Add (?s) at the start or compile with Pattern.DOTALL to match texts across lines.

Details

\* - a * char

(?=[^\s*]) - the next char must be a non-whitespace and not a *

.*? - any 0+ chars as few as possible

(?<=[^\s*]) - the preceding char should be a non-whitespace and not a *

\* -  a * char

(?!\S) - a whitespace boundary pattern, the next char can be a whitespace, or end of string can be at this location in the string.

In Java:

```<code>String regex = "\\*(?=[^\\s*]).*?(?<=[^\\s*])\\*(?!\\S)";
</code>```

Title: regexp to match simple markdown

Body:
If you want to start matching from the rightmost *, you may use

\*(?=[^\s*]).*?(?<=[^\s*])\*(?!\S)

To start a match from a left-most * (as in ``), remove the * from the first lookaround (or replace its pattern with \S):

\*(?=\S).*?(?<=[^\s*])\*(?!\S)

See the regex demo #1 and regex demo #2. Add (?s) at the start or compile with Pattern.DOTALL to match texts across lines.

Details

\* - a * char

(?=[^\s*]) - the next char must be a non-whitespace and not a *

.*? - any 0+ chars as few as possible

(?<=[^\s*]) - the preceding char should be a non-whitespace and not a *

\* -  a * char

(?!\S) - a whitespace boundary pattern, the next char can be a whitespace, or end of string can be at this location in the string.

In Java:

String regex = "\\*(?=[^\\s*]).*?(?<=[^\\s*])\\*(?!\\S)";


问:
How do you debug heavily templated code in c++?
I find it very hard to figure out what is wrong with my code when using C++ template meta-programming. It might be that I am just not very good at understanding the error messages, but as far as I'm aware I can't resort to putting in print statements or breakpoints to figure out what's going on.

What tips or advice can you offer when trying to figure out why something is not compiling other than just picking through the code manually and hoping it will come to me?

答:
You can try using a newer compiler.  If you're using Visual C++ 6.0, switch to 9.0 and you'll see a huge jump in the helpfulness of the compiler errors.

Otherwise, my techniques are usually been to test out as small a section of code as possible until I get the errors isolated.  This is probably the template system's greatest failing - there is no sensible way of debugging them.

In your own code, make liberal use of compile-time asserts to make usage problems a little easier to diagnose.

OwnerDisplayName: Dan

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: David Segonds

OwnerDisplayName: Josh