问:
How to clear timeout in React upon state change?
I have a React alert component which renders a Modal. There are two ways for the modal to close either by manually pressing close or if the modal is not closed by pressing close then the modal should close automatically by X seconds

hideAlert() is called when the modal is closed
So far both works however if the modal is closed by the user, hideAlert() will be called twice - from the method called after pressing close and inside setTimeout().

Probably simple enough my question is how do I cancel the timer that will call hideAlert() if the modal was already closed by the user?

p.s. when hideAlert() is called this dispatches an action to Redux and the reducer sets the state to:

```<code>        case LandingActionTypes.HideAlert:
            return {
                ...state,
                ...{
                    alertMessage: {
                        title: '',
                        message: ''
                    },
                    showAlert: false,
                    type: "danger" as MessageType,
                    icon: "danger" as MessageType,
                    autoHide: true,
                    duration: 5000
                }
            }
</code>```

I've tried to clear the timeout by checking state change using useEffect() without success

```<code>useEffect(() => {
    if (!showAlert) {
        clearTimeout(timer)
    }
}, [showAlert])
</code>```

Full component code

Thanks

```<code>// @ts-ignore
import Modal from "modal-enhanced-react-native-web";
import React, { useEffect } from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { MessageType } from "react-native-flash-message";
import { IAlertMessage } from '../../models/IAlertMessage';
import { HideAlertAction } from '../../state/contexts/alert/Actions';
import styles from "./styles";

export interface IPropsFromState {
    alertMsg: IAlertMessage
    showAlert: boolean
    type?: MessageType
    icon?: MessageType
    autoHide?: boolean
    duration?: number
}

export interface IPropsFromDispatch {
    hideAlert: typeof HideAlertAction.creator
}

type AllProps = IPropsFromState & IPropsFromDispatch

const AlertMessage: React.FC<AllProps> = (props) => {

    let timer: any

    const {
        alertMsg,
        type,
        icon,
        showAlert,
        autoHide,
        duration,
        hideAlert,
    } = props

    if (!showAlert) {
        return null
    }

    const {
        title,
        message,
        cancelText,
        confirmText
    } = alertMsg

    useEffect(() => {
        if (autoHide) {
            timer = setTimeout(() => {
                hideAlert()
            }, duration)
        }
    }, [alertMsg])

    const renderButton = (text: string) => (
        <TouchableOpacity onPress={hideAlert}>
            <View style={styles.button}>
                <Text>{text}</Text>
            </View>
        </TouchableOpacity>
    );

    const renderModalContent = () => (
        <View style={styles.modalContent}>
            <Text style={{ fontWeight: 'bold', marginTop: 10 }}>{title}</Text>
            <Text>{message}</Text>
            {renderButton("Close")}
        </View>
    );

    console.log("*[ALERT] " + JSON.stringify(alertMsg, null, 2))

    return (
        <Modal
            style={styles.bottomModal}
            isVisible={showAlert}
            animationIn="slideInDown"
            animationOut="slideOutUp"
            onBackdropPress={hideAlert}
        >
            {renderModalContent()}
        </Modal>
    );

}

export default AlertMessage
</code>```

答:
Resolved changed useEffect hook

```<code>useEffect(() => {
    if (autoHide) {
        const timeoutId = setTimeout(() => {
            if (!showAlert) return;

            hideAlert()
        }, duration)

        return () => clearTimeout(timeoutId)
    }
}, [alertMsg, showAlert])
</code>```

and moved just before the render method.

```<code>if (!showAlert) {
    return null
}
</code>```

Body:
I have a React alert component which renders a Modal. There are two ways for the modal to close either by manually pressing close or if the modal is not closed by pressing close then the modal should close automatically by X seconds

hideAlert() is called when the modal is closed
So far both works however if the modal is closed by the user, hideAlert() will be called twice - from the method called after pressing close and inside setTimeout().

Probably simple enough my question is how do I cancel the timer that will call hideAlert() if the modal was already closed by the user?

p.s. when hideAlert() is called this dispatches an action to Redux and the reducer sets the state to:

        case LandingActionTypes.HideAlert:
            return {
                ...state,
                ...{
                    alertMessage: {
                        title: '',
                        message: ''
                    },
                    showAlert: false,
                    type: "danger" as MessageType,
                    icon: "danger" as MessageType,
                    autoHide: true,
                    duration: 5000
                }
            }

I've tried to clear the timeout by checking state change using useEffect() without success

useEffect(() => {
    if (!showAlert) {
        clearTimeout(timer)
    }
}, [showAlert])

Full component code

Thanks

// @ts-ignore
import Modal from "modal-enhanced-react-native-web";
import React, { useEffect } from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { MessageType } from "react-native-flash-message";
import { IAlertMessage } from '../../models/IAlertMessage';
import { HideAlertAction } from '../../state/contexts/alert/Actions';
import styles from "./styles";

export interface IPropsFromState {
    alertMsg: IAlertMessage
    showAlert: boolean
    type?: MessageType
    icon?: MessageType
    autoHide?: boolean
    duration?: number
}

export interface IPropsFromDispatch {
    hideAlert: typeof HideAlertAction.creator
}

type AllProps = IPropsFromState & IPropsFromDispatch

const AlertMessage: React.FC<AllProps> = (props) => {

    let timer: any

    const {
        alertMsg,
        type,
        icon,
        showAlert,
        autoHide,
        duration,
        hideAlert,
    } = props

    if (!showAlert) {
        return null
    }

    const {
        title,
        message,
        cancelText,
        confirmText
    } = alertMsg

    useEffect(() => {
        if (autoHide) {
            timer = setTimeout(() => {
                hideAlert()
            }, duration)
        }
    }, [alertMsg])

    const renderButton = (text: string) => (
        <TouchableOpacity onPress={hideAlert}>
            <View style={styles.button}>
                <Text>{text}</Text>
            </View>
        </TouchableOpacity>
    );

    const renderModalContent = () => (
        <View style={styles.modalContent}>
            <Text style={{ fontWeight: 'bold', marginTop: 10 }}>{title}</Text>
            <Text>{message}</Text>
            {renderButton("Close")}
        </View>
    );

    console.log("*[ALERT] " + JSON.stringify(alertMsg, null, 2))

    return (
        <Modal
            style={styles.bottomModal}
            isVisible={showAlert}
            animationIn="slideInDown"
            animationOut="slideOutUp"
            onBackdropPress={hideAlert}
        >
            {renderModalContent()}
        </Modal>
    );

}

export default AlertMessage

Body:
Resolved changed useEffect hook

useEffect(() => {
    if (autoHide) {
        const timeoutId = setTimeout(() => {
            if (!showAlert) return;

            hideAlert()
        }, duration)

        return () => clearTimeout(timeoutId)
    }
}, [alertMsg, showAlert])

and moved just before the render method.

if (!showAlert) {
    return null
}


来源: stackexchange

问:
Correct answer button green
I am creating a quiz, and I am trying to turn my answer button green when correct and when incorrect red and then save this information and move onto the next question. However the code at the moment is not working. This is my JavaScript code:</p>
```<code>let shuffledQuestions, currentQuestionIndex;

const setNextQuestion = () => {
    showQuestion(shuffledQuestions[currentQuestionIndex]);
}

const showQuestion = (gameData) => {
    questionElement.innerText = gameData.question;
    let answersBlock = '';
    gameData.answer.forEach((answer, index) => {
        const answerButton = `
            <div class="answers-wrapper col-lg-6 col-md-6 col-lg-3">
                <button class="btn answer-button" id="answersbutton-${index + 1}" onclick="selectAnswer()">
                    ${answer.text}
                </button>
            </div>
        `;
        answersBlock += answerButton;
    });
    answerButtonsElement.innerHTML = answersBlock;
}

const selectAnswer = (e) => {
    const selectedButton = e.target;
    const correct = selectedButton.dataset.correct;
    setStatusClass(document.body, correct);
    Array.from(answerButtonsElement.children).forEach(button => {
        setStatusClass(button, button.dataset.correct);
    })
}

function setStatusClass(element, correct) {
    clearStatusClass(element);
    if (correct) {
        element.classList.add('correct');
    } else {
        element.classList.add('wrong');
    }
}

function clearStatusClass(element) {
    element.classList.remove('correct');
    element.classList.remove('wrong');
}

const gameData = [
    {
        question: 'What is the smallest country in the world?',
        answer: [
            { text: 'Vatican City', correct: true },
            { text: 'Malta', correct: false },
            { text: 'Italy', correct: false },
            { text: 'Monaco', correct: false }
        ]
    },
</code>```

答:
You must pass the event as a parameter in onclick because you are using the event in HTML and calling it directly.

const answerButton = `

                <button class="btn answer-button" id="answersbutton-${index + 1}" onclick="selectAnswer(event)">
                    ${answer.text}
                </button>

        `;
```
<p>And get it as <code>event.target</code> in <code>selectAnswer</code> function.</p>
<pre class="lang-js prettyprint-override"><code>function selectAnswer(event) {
  console.log("Button", event.target)
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Correct answer button green

Body:
I am creating a quiz, and I am trying to turn my answer button green when correct and when incorrect red and then save this information and move onto the next question. However the code at the moment is not working. This is my JavaScript code:

let shuffledQuestions, currentQuestionIndex;

const setNextQuestion = () => {
    showQuestion(shuffledQuestions[currentQuestionIndex]);
}

const showQuestion = (gameData) => {
    questionElement.innerText = gameData.question;
    let answersBlock = '';
    gameData.answer.forEach((answer, index) => {
        const answerButton = `

                <button class="btn answer-button" id="answersbutton-${index + 1}" onclick="selectAnswer()">
                    ${answer.text}
                </button>

        `;
        answersBlock += answerButton;
    });
    answerButtonsElement.innerHTML = answersBlock;
}

const selectAnswer = (e) => {
    const selectedButton = e.target;
    const correct = selectedButton.dataset.correct;
    setStatusClass(document.body, correct);
    Array.from(answerButtonsElement.children).forEach(button => {
        setStatusClass(button, button.dataset.correct);
    })
}

function setStatusClass(element, correct) {
    clearStatusClass(element);
    if (correct) {
        element.classList.add('correct');
    } else {
        element.classList.add('wrong');
    }
}

function clearStatusClass(element) {
    element.classList.remove('correct');
    element.classList.remove('wrong');
}

const gameData = [
    {
        question: 'What is the smallest country in the world?',
        answer: [
            { text: 'Vatican City', correct: true },
            { text: 'Malta', correct: false },
            { text: 'Italy', correct: false },
            { text: 'Monaco', correct: false }
        ]
    },

Body:
You must pass the event as a parameter in onclick because you are using the event in HTML and calling it directly.

const answerButton = `
            <div class="answers-wrapper col-lg-6 col-md-6 col-lg-3">
                <button class="btn answer-button" id="answersbutton-${index + 1}" onclick="selectAnswer(event)">
                    ${answer.text}
                </button>
            </div>
        `;

And get it as event.target in selectAnswer function.

function selectAnswer(event) {
  console.log("Button", event.target)
}


问:
Error with urllib3 and the python-telegram-bot API
when i try to run my script (my telegram bot) the following appears in terminal:

```<code>/usr/local/lib/python3.7/dist-packages/python_telegram_bot-12.4.2-
py3.7.egg/telegram/utils/request.py:47: UserWarning: python-telegram-bot is using upstream urllib3.
This is allowed but not supported by python-telegram-bot maintainers.
</code>```

what I do?

Thanks a lot

答:
Originally, python-telegram-bot only shipped with a vendored version of urllib3 that was created to fix a bug that could not be fixed upstream.

To allow python-telegram-bot to be shipped as part of Linux distributions, the dependency on the vendored urllib3 has been made optional, allowing python-telegram-bot to work with the standard urllib3.

So the message you're seeing is expected behavior if you installed python-telegram-bot through your distribution's packet manager. If your bot works fine, you don't have to change anything.

Body:
when i try to run my script (my telegram bot) the following appears in terminal:

/usr/local/lib/python3.7/dist-packages/python_telegram_bot-12.4.2-
py3.7.egg/telegram/utils/request.py:47: UserWarning: python-telegram-bot is using upstream urllib3.
This is allowed but not supported by python-telegram-bot maintainers.

what I do?

Thanks a lot


问:
list changed function names or signatures with git diff (c++)
I'm working on a git diff parser. The main task is to find all changed function signatures. Sometimes in the chunk line with @@@ .... @@@ contains these information but sometimes not.
Last time I changed in greet() cout message and it is visible on first image as changed line and it is correct, but above in @@@... line appears "void functOne() {" and that is not changed.
The second picture is about a dummy cpp source code to test git diff.

The main questions are

How can I list all changed function's signatures?

Why sometimes appears unchanged function name ?

Why sometimes doesn't appears any function name/signature in line with @@@.... ?

答:
The git diff command doesn't care about any functions. git repositories can contain any kind of text files (binary files too, but that's immaterial here), not just C++ source.

The diff command doesn't attempt to interpret the file in any way. Only a C++ compiler can fully understand a C++ file and process all function declarations.

The diff command only looks for discrete lines of text that changed and shows them together with a few unchanged lines that precede and follow them.

If the changed lines happen to be at the beginning of a function declaration, then this would include the function declaration. If they are in the middle of a long function, you only see the few preceding lines, that's it.

There are git diff options that control how many unchanged lines are shown (check git's documentation). Specifying a million lines, for example, results in the entire file getting shown, with all the changed lines marked up.

You can do that if you wish, then try to figure out the names of all the changed functions yourself, but until you write a complete C++ compiler, yourself, your heuristic parsing attempts won't be 100% correct. You might've noticed, tucked away in git diff output an indication of what git guessed the changed function might be. But, since git is also not a C++ compiler, that's also wrong, occasionally.


问:
nullPointerException when replacing char sequence
I developed a very simple android app and then I obfuscated the code. A nullPointerException is throwed when, probably, I replace a char sequence.

Here is my stack trace:

```<code>java.lang.NullPointerException
at com.xpandit.pemobile.android.loadactivity.ak.d(Unknown Source)
at com.xpandit.pemobile.android.loadactivity.g.onTextChanged(Unknown Source)
at android.widget.TextView.sendOnTextChanged(TextView.java:6335)
at android.widget.TextView.handleTextChanged(TextView.java:6376)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:6520)
at android.text.SpannableStringBuilder.sendTextChange(SpannableStringBuilder.java:889)
at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:352)
at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:269)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:432)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:409)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:28)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:583)
at android.view.inputmethod.BaseInputConnection.commitText(BaseInputConnection.java:174)
at com.android.internal.widget.EditableInputConnection.commitText(EditableInputConnection.java:120)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:257)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at dalvik.system.NativeStart.main(Native Method)
</code>```

As i said the code is obfuscated and by the mapping file I've found the right method (at least I think). The question is: In what situation can a replace method throw a null pointer?

Maybe the problem is not the replace method! Can anyone tell me where is the problem and how to resolve it? Thanks in advance...

EDIT:
I think the problem must be on that simple if instruction.

```<code>if (aux.contains(" ")){
    aux = aux.replace(" ", "%20");
}
</code>```

答:
Use replaceAll() instead of replace()

```<code>if (aux.contains(" ")){
     aux.replaceAll(" ", "%20");
}
</code>```

Reference:

```<code>String  replace(CharSequence target, CharSequence replacement)
</code>```

Copies this string replacing occurrences of the specified target sequence with another sequence.

```<code>String  replaceAll(String regularExpression, String replacement)
</code>```

Replaces all matches for regularExpression within this string with the given replacement.

ContentLicense: CC BY-SA 3.0

Body:
I developed a very simple android app and then I obfuscated the code. A nullPointerException is throwed when, probably, I replace a char sequence.

Here is my stack trace:

java.lang.NullPointerException
at com.xpandit.pemobile.android.loadactivity.ak.d(Unknown Source)
at com.xpandit.pemobile.android.loadactivity.g.onTextChanged(Unknown Source)
at android.widget.TextView.sendOnTextChanged(TextView.java:6335)
at android.widget.TextView.handleTextChanged(TextView.java:6376)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:6520)
at android.text.SpannableStringBuilder.sendTextChange(SpannableStringBuilder.java:889)
at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:352)
at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:269)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:432)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:409)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:28)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:583)
at android.view.inputmethod.BaseInputConnection.commitText(BaseInputConnection.java:174)
at com.android.internal.widget.EditableInputConnection.commitText(EditableInputConnection.java:120)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:257)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at dalvik.system.NativeStart.main(Native Method)

As i said the code is obfuscated and by the mapping file I've found the right method (at least I think). The question is: In what situation can a replace method throw a null pointer?

Maybe the problem is not the replace method! Can anyone tell me where is the problem and how to resolve it? Thanks in advance...

EDIT:
I think the problem must be on that simple if instruction.

if (aux.contains(" ")){
    aux = aux.replace(" ", "%20");
}

Body:
Use replaceAll() instead of replace()

if (aux.contains(" ")){
     aux.replaceAll(" ", "%20");
}

Reference:

String  replace(CharSequence target, CharSequence replacement)

Copies this string replacing occurrences of the specified target sequence with another sequence.

String  replaceAll(String regularExpression, String replacement)

Replaces all matches for regularExpression within this string with the given replacement.


问:
How to add whitespaces to json_encode function?
I run json_encode (PHP 8.0.15) and it will return: {"test":[0.1,0.2],"test2":"Hello World"}.
When I use jsom.dumps (Python 3.8.6) it will return: {"test": [0.1, 0.2], "test2": "Hello World"}. Seems like PHP doesn't add whitespaces but I need them, because I need to rebuild the exact string and compare them.

答:
Converting to string is not a good way to compare data structures unless you have a fully deterministic algorithm that always produces the same normalised output for structures you consider identical. JSON is not such algorithm. It isn't just nitpicking about obscure format specs. Is it really okay for your application to have both arrays with "test" and "test2" in different order where everything else is identical? Is your application code designed to handle those as different?

If the sample you've shared is representative of what data structures you can expect, decoding JSON and applying a simple equality operator will render more reliable results than your current approach:

```<code>$a = '{"test":[0.1,0.2],"test2":"Hello World"}';
$b = '{"test": [0.1, 0.2], "test2": "Hello World"}';
$c = '{"test2":"Hello World", "test":[0.1,0.2]}';
$d = '{"test":[0.1,0.3],"test2":"Hello World"}';

$obj_a = json_decode($a);
$obj_b = json_decode($b);
$obj_c = json_decode($c);
$obj_d = json_decode($d);

var_dump($obj_a == $obj_b); // true (same keys and values, same order)
var_dump($obj_a == $obj_c); // true (same keys and values, different order)
var_dump($obj_a == $obj_d); // false (same keys, different values)
</code>```

Reference: object comparison

When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values (values are compared with ==), and are instances of the same class.

Beware that this may or may not work as expected with nested data structures.

Body:
Converting to string is not a good way to compare data structures unless you have a fully deterministic algorithm that always produces the same normalised output for structures you consider identical. JSON is not such algorithm. It isn't just nitpicking about obscure format specs. Is it really okay for your application to have both arrays with "test" and "test2" in different order where everything else is identical? Is your application code designed to handle those as different?

If the sample you've shared is representative of what data structures you can expect, decoding JSON and applying a simple equality operator will render more reliable results than your current approach:

$a = '{"test":[0.1,0.2],"test2":"Hello World"}';
$b = '{"test": [0.1, 0.2], "test2": "Hello World"}';
$c = '{"test2":"Hello World", "test":[0.1,0.2]}';
$d = '{"test":[0.1,0.3],"test2":"Hello World"}';

$obj_a = json_decode($a);
$obj_b = json_decode($b);
$obj_c = json_decode($c);
$obj_d = json_decode($d);

var_dump($obj_a == $obj_b); // true (same keys and values, same order)
var_dump($obj_a == $obj_c); // true (same keys and values, different order)
var_dump($obj_a == $obj_d); // false (same keys, different values)

Reference: object comparison

When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values (values are compared with ==), and are instances of the same class.

Beware that this may or may not work as expected with nested data structures.


问:
How to filter/sort view based on date range in android using java?

```<code>    else if (item.getItemId() == R.id.sort_by_unprofitable_trades){
        Collections.sort(notesList, Model.UnProfitableTrades);
        adapter.notifyDataSetChanged();
    }
    else if(item.getItemId() == R.id.sort_by_date_range){
        materialDatePicker.show(getSupportFragmentManager(), "Tag_picker");
        materialDatePicker.addOnPositiveButtonClickListener(new
        MaterialPickerOnPositiveButtonClickListener<Pair<Long, Long>>() {
            @Override
            public void onPositiveButtonClick(Pair<Long,Long> selection) {
                Long selctedstartDate = selection.first;
                Long selectedendDate = selection.second;
                startDateString = DateFormat.format("yyyy/MM/dd", new
                Date(selctedstartDate)).toString();
                endDateString = DateFormat.format("yyyy/MM/dd", new
                 Date(selectedendDate)).toString();
                //Collections.sort(notesList, Model.SortByDaterange);
                sortByDateRange();
                adapter.notifyDataSetChanged();
</code>```

DataBase class:- void sortbyDateRange(String startDate, String endDate){
SQLiteDatabase database = this.getWritableDatabase();
String query = "SELECT * FROM " + TableName + " WHERE " + ColumnTradeDate + " BETWEEN " +
startDate + " AND " + endDate ;
database.execSQL(query);
}

In Database Inspector the SQL query is giving correct results but no change is happening in the recycler view. What am I missing?

答:
between query doesn't support any string value. Because in string value comparison not possible so you need to do the operation with float, Int and long type data .. I have  faced the same problem then I converted my date to in long type data by using calender.timeInMillis .if u do like that you have to make a column in your table long type than send in to your database then do between query

pick your date and convert it to long type

```<code>   val datepickerdialog =
            DatePickerDialog(requireContext(), { view, year, monthOfYear, dayOfMonth ->

                srchDate2_id.text = "$dayOfMonth-$month-$year"

                calender2 = Calendar.getInstance()
                calender2.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                calender2.set(Calendar.MONTH, monthOfYear)
                calender2.set(Calendar.YEAR, year)

                dt2 = calender2 .timeInMillis// send it to database you can do the between query with this value
                Log.d(TAG, "first time: $dt2")

            }, y, m, d)

        datepickerdialog.show()
    }
</code>```

still problem comment below.

Body:
    else if (item.getItemId() == R.id.sort_by_unprofitable_trades){
        Collections.sort(notesList, Model.UnProfitableTrades);
        adapter.notifyDataSetChanged();
    }
    else if(item.getItemId() == R.id.sort_by_date_range){
        materialDatePicker.show(getSupportFragmentManager(), "Tag_picker");
        materialDatePicker.addOnPositiveButtonClickListener(new
        MaterialPickerOnPositiveButtonClickListener<Pair<Long, Long>>() {
            @Override
            public void onPositiveButtonClick(Pair<Long,Long> selection) {
                Long selctedstartDate = selection.first;
                Long selectedendDate = selection.second;
                startDateString = DateFormat.format("yyyy/MM/dd", new
                Date(selctedstartDate)).toString();
                endDateString = DateFormat.format("yyyy/MM/dd", new
                 Date(selectedendDate)).toString();
                //Collections.sort(notesList, Model.SortByDaterange);
                sortByDateRange();
                adapter.notifyDataSetChanged();

DataBase class:- void sortbyDateRange(String startDate, String endDate){
SQLiteDatabase database = this.getWritableDatabase();
String query = "SELECT * FROM " + TableName + " WHERE " + ColumnTradeDate + " BETWEEN " +
startDate + " AND " + endDate ;
database.execSQL(query);
}

In Database Inspector the SQL query is giving correct results but no change is happening in the recycler view. What am I missing?

Body:
between query doesn't support any string value. Because in string value comparison not possible so you need to do the operation with float, Int and long type data .. I have  faced the same problem then I converted my date to in long type data by using calender.timeInMillis .if u do like that you have to make a column in your table long type than send in to your database then do between query

pick your date and convert it to long type

   val datepickerdialog =
            DatePickerDialog(requireContext(), { view, year, monthOfYear, dayOfMonth ->

                srchDate2_id.text = "$dayOfMonth-$month-$year"

                calender2 = Calendar.getInstance()
                calender2.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                calender2.set(Calendar.MONTH, monthOfYear)
                calender2.set(Calendar.YEAR, year)

                dt2 = calender2 .timeInMillis// send it to database you can do the between query with this value
                Log.d(TAG, "first time: $dt2")

            }, y, m, d)

        datepickerdialog.show()
    }

still problem comment below.


问:
Class constructor FormControl cannot be invoked without 'new'
I have a simple Angular 13 repo where @ng-stack/forms is used like

```<code>import { Component } from '@angular/core';
import { FormControl } from '@ng-stack/forms';

@Component({
  selector: 'app-root',
})
export class AppComponent {
  control = new FormControl<string>('');
}
</code>```

When I run Jest test I got an error:

```<code>> example-app-v13@13.0.0 test
> jest --no-cache

 FAIL  src/app/app.component.spec.ts
  AppComponent
    × should create the app (54 ms)

  ● AppComponent › should create the app

    TypeError: Class constructor FormControl cannot be invoked without 'new'

       7 | })
       8 | export class AppComponent {
    >  9 |   control = new FormControl<string>('');
         |             ^
      10 | }
      11 |

      at new FormControl (node_modules/projects/forms/src/lib/form-control.ts:42:5)
      at new AppComponent (src/app/app.component.ts:9:13)
      at NodeInjectorFactory.AppComponent_Factory [as factory] (ng:\AppComponent\ɵfac.js:5:10)
      at src/app/app.component.spec.ts:16:29

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        5.825 s
Ran all test suites.
</code>```

Can anyone explain where is this error coming from and how to fix it?

答: Fixed by upgrade of @ng-stack/forms to version 3.0.0beta

Body:
I have a simple Angular 13 repo where @ng-stack/forms is used like

import { Component } from '@angular/core';
import { FormControl } from '@ng-stack/forms';

@Component({
  selector: 'app-root',
})
export class AppComponent {
  control = new FormControl<string>('');
}

When I run Jest test I got an error:

> example-app-v13@13.0.0 test
> jest --no-cache

 FAIL  src/app/app.component.spec.ts
  AppComponent
    × should create the app (54 ms)

  ● AppComponent › should create the app

    TypeError: Class constructor FormControl cannot be invoked without 'new'

       7 | })
       8 | export class AppComponent {
    >  9 |   control = new FormControl<string>('');
         |             ^
      10 | }
      11 |

      at new FormControl (node_modules/projects/forms/src/lib/form-control.ts:42:5)
      at new AppComponent (src/app/app.component.ts:9:13)
      at NodeInjectorFactory.AppComponent_Factory [as factory] (ng:\AppComponent\ɵfac.js:5:10)
      at src/app/app.component.spec.ts:16:29

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        5.825 s
Ran all test suites.

Can anyone explain where is this error coming from and how to fix it?


问:
Running uvicorn with -OO flag
When I run a uvicorn server from the commandline by $ uvicorn example:app or $ gunicorn -w 4 -k uvicorn.workers.UvicornWorker, how can I pass the optimization flag -OO to the Python interpreter? Any help would be appreciated!

答:
For example, we have the following app:

from fastapi import FastAPI

app = FastAPI()

@app.on_event('startup')
async def startup_event():
    print('__debug__', __debug__)
```
<p>unicorn can be run like this:</p>
```$ python -O -m uvicorn example:app
INFO:     Started server process [49759]
INFO:     Waiting for application startup.
__debug__ False
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
<p>gunicorn run with:</p>
```$ python -O -m gunicorn --workers 4 --worker-class uvicorn.workers.UvicornWorker example:app
[2022-02-13 15:17:39 +0300] [49801] [INFO] Starting gunicorn 20.1.0
[2022-02-13 15:17:39 +0300] [49801] [INFO] Listening at: http://127.0.0.1:8000 (49801)
[2022-02-13 15:17:39 +0300] [49801] [INFO] Using worker: uvicorn.workers.UvicornWorker
[2022-02-13 15:17:39 +0300] [49802] [INFO] Booting worker with pid: 49802
[2022-02-13 15:17:39 +0300] [49802] [INFO] Started server process [49802]
[2022-02-13 15:17:39 +0300] [49802] [INFO] Waiting for application startup.
__debug__ False
[2022-02-13 15:17:39 +0300] [49802] [INFO] Application startup complete.
[2022-02-13 15:17:39 +0300] [49804] [INFO] Booting worker with pid: 49804
[2022-02-13 15:17:39 +0300] [49805] [INFO] Booting worker with pid: 49805
[2022-02-13 15:17:39 +0300] [49804] [INFO] Started server process [49804]
[2022-02-13 15:17:39 +0300] [49804] [INFO] Waiting for application startup.
__debug__ False
[2022-02-13 15:17:39 +0300] [49804] [INFO] Application startup complete.
[2022-02-13 15:17:39 +0300] [49805] [INFO] Started server process [49805]
[2022-02-13 15:17:39 +0300] [49805] [INFO] Waiting for application startup.
__debug__ False
[2022-02-13 15:17:39 +0300] [49805] [INFO] Application startup complete.
[2022-02-13 15:17:39 +0300] [49806] [INFO] Booting worker with pid: 49806
[2022-02-13 15:17:39 +0300] [49806] [INFO] Started server process [49806]
[2022-02-13 15:17:39 +0300] [49806] [INFO] Waiting for application startup.
__debug__ False
[2022-02-13 15:17:39 +0300] [49806] [INFO] Application startup complete.
```

Title: Running uvicorn with -OO flag

Body:
For example, we have the following app:

from fastapi import FastAPI

app = FastAPI()

@app.on_event('startup')
async def startup_event():
    print('__debug__', __debug__)

unicorn can be run like this:

$ python -O -m uvicorn example:app
INFO:     Started server process [49759]
INFO:     Waiting for application startup.
__debug__ False
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

gunicorn run with:

$ python -O -m gunicorn --workers 4 --worker-class uvicorn.workers.UvicornWorker example:app
[2022-02-13 15:17:39 +0300] [49801] [INFO] Starting gunicorn 20.1.0
[2022-02-13 15:17:39 +0300] [49801] [INFO] Listening at: http://127.0.0.1:8000 (49801)
[2022-02-13 15:17:39 +0300] [49801] [INFO] Using worker: uvicorn.workers.UvicornWorker
[2022-02-13 15:17:39 +0300] [49802] [INFO] Booting worker with pid: 49802
[2022-02-13 15:17:39 +0300] [49802] [INFO] Started server process [49802]
[2022-02-13 15:17:39 +0300] [49802] [INFO] Waiting for application startup.
__debug__ False
[2022-02-13 15:17:39 +0300] [49802] [INFO] Application startup complete.
[2022-02-13 15:17:39 +0300] [49804] [INFO] Booting worker with pid: 49804
[2022-02-13 15:17:39 +0300] [49805] [INFO] Booting worker with pid: 49805
[2022-02-13 15:17:39 +0300] [49804] [INFO] Started server process [49804]
[2022-02-13 15:17:39 +0300] [49804] [INFO] Waiting for application startup.
__debug__ False
[2022-02-13 15:17:39 +0300] [49804] [INFO] Application startup complete.
[2022-02-13 15:17:39 +0300] [49805] [INFO] Started server process [49805]
[2022-02-13 15:17:39 +0300] [49805] [INFO] Waiting for application startup.
__debug__ False
[2022-02-13 15:17:39 +0300] [49805] [INFO] Application startup complete.
[2022-02-13 15:17:39 +0300] [49806] [INFO] Booting worker with pid: 49806
[2022-02-13 15:17:39 +0300] [49806] [INFO] Started server process [49806]
[2022-02-13 15:17:39 +0300] [49806] [INFO] Waiting for application startup.
__debug__ False
[2022-02-13 15:17:39 +0300] [49806] [INFO] Application startup complete.


问:
AudioSource continues playing old clip after new clip assigned
My game is playing background music and I want to switch it based on game attributes.
Here is my solution:

```<code>AudioSource audioSource;
[SerializeField] AudioClip audioClipLowZombies;
[SerializeField] AudioClip audioClipMediumZombies;
[SerializeField] AudioClip audioClipHighZombies;
AudioClip currentMusic;

public void ChangeAudio()
{
    if (zombieCount < 10)
    {
        audioSource.Stop();
        audioSource.clip = audioClipLowZombies;
        audioSource.Play();
    }

    if (zombieCount > 10 & zombieCount < 20)
    {
        audioSource.Stop();
        audioSource.clip = audioClipMediumZombies;
        audioSource.Play();
    }

    if (zombieCount > 20)
    {
        audioSource.Stop();
        audioSource.clip = audioClipHighZombies;
        audioSource.Play();
    }
}
</code>```

The problem is that after changing the clip, the old clip continues playing as well as the new one.

答: make sure (if you have multiple audio sources) you are referencing the correct audio source. Sadly that's all I can really think of since your code seems fine.</p>

Body:
My game is playing background music and I want to switch it based on game attributes.
Here is my solution:

AudioSource audioSource;
[SerializeField] AudioClip audioClipLowZombies;
[SerializeField] AudioClip audioClipMediumZombies;
[SerializeField] AudioClip audioClipHighZombies;
AudioClip currentMusic;

public void ChangeAudio()
{
    if (zombieCount < 10)
    {
        audioSource.Stop();
        audioSource.clip = audioClipLowZombies;
        audioSource.Play();
    }

    if (zombieCount > 10 & zombieCount < 20)
    {
        audioSource.Stop();
        audioSource.clip = audioClipMediumZombies;
        audioSource.Play();
    }

    if (zombieCount > 20)
    {
        audioSource.Stop();
        audioSource.clip = audioClipHighZombies;
        audioSource.Play();
    }
}

The problem is that after changing the clip, the old clip continues playing as well as the new one.


问:
What is difference between primary and onPrimary properties in ColorScheme Flutter
While defining ThemeData of the Flutter app, we can define colorScheme property.
This property has inner-properties such as background & onBackground, primary & onPrimary, secondary & onSecondary, etc. Also, all these properties are set as required.

```<code>  static final ThemeData lightTheme = ThemeData(
    colorScheme: ColorScheme(
      background: appBackgroundColor,
      brightness: Brightness.light,
      error: Colors.white,
      onBackground: primaryColor,
      onError: null,
      onPrimary: null,
      onSecondary: null,
      onSurface: null,
      primary: null,
      secondary: secondaryColor,
      surface: null,
    ),
  );
</code>```

I tried referring the documentation of Flutter but I was not quite able to understand the difference between them.

答:
"On" colors
App surfaces use colors from specific categories in your color palette, such as a primary color. Whenever elements, such as text or icons, appear in front of those surfaces, those elements should use colors designed to be clear and legible against the colors behind them.

This category of colors is called “on” colors, referring to the fact that they color elements that appear “on” top of surfaces that use the following colors: a primary color, secondary color, surface color, background color, or error color. When a color appears “on” top of a primary color, it’s called an “on primary color.” They are labelled using the original color category (such as primary color) with the prefix “on.”

“On” colors are primarily applied to text, iconography, and strokes. Sometimes, they are applied to surfaces.

The default values for “on” colors are #FFFFFF and #000000.

check this :
The color system

Body:
While defining ThemeData of the Flutter app, we can define colorScheme property.
This property has inner-properties such as background & onBackground, primary & onPrimary, secondary & onSecondary, etc. Also, all these properties are set as required.

  static final ThemeData lightTheme = ThemeData(
    colorScheme: ColorScheme(
      background: appBackgroundColor,
      brightness: Brightness.light,
      error: Colors.white,
      onBackground: primaryColor,
      onError: null,
      onPrimary: null,
      onSecondary: null,
      onSurface: null,
      primary: null,
      secondary: secondaryColor,
      surface: null,
    ),
  );

I tried referring the documentation of Flutter but I was not quite able to understand the difference between them.


问:
MySQL REGEXP matching positive numbers
I have a column varchar[25] with this data inside :

886,-886

-886

0,-1234

1234

(empty)

0

the numbers might change in size from a 1 digit to a n digits.
and I need to be able to pull any row that has at least one positive number in it

I was thinking that something like

```<code>REGEXP '[^-,][0-9]+'
</code>```

but this pulls -886 as 88 matches the regexp

答:
Try

```<code>REGEXP '[[:<:]][^-,][0-9]+[[:>:]]'
</code>```

The :<: and :>: portions indicate word boundaries.

Title: MySQL REGEXP matching positive numbers

Body:
I have a column varchar[25] with this data inside :

886,-886

-886

0,-1234

1234

(empty)

0

the numbers might change in size from a 1 digit to a n digits.
and I need to be able to pull any row that has at least one positive number in it

I was thinking that something like

REGEXP '[^-,][0-9]+'

but this pulls -886 as 88 matches the regexp

Body:
Try

REGEXP '[[:<:]][^-,][0-9]+[[:>:]]'

The :<: and :>: portions indicate word boundaries.


问:
How to print values in dataframes column by their indexes?
I have a dataframe:

```<code>id   value
742  aa
1711 bb
1731 qq
1799 ff
2741 pp

</code>```

id is the index column. I want to print only those values from column "value" which are in this list: [742, 1731, 1799]. So the output must be:

```<code>aa
qq
ff
</code>```

How to do that?

I tried this:

```<code>for i in [742, 1731, 1799]:
    print(df[df.index == i]["value"])
</code>```

but the output is:

```<code>value
742    aa
Name: value, dtype: object
value
1731    qq
Name: value, dtype: object
value
1799    ff
Name: value, dtype: object
</code>```

答:
This should do it:

Restating the problem:

ids = [
    {"id":"742", "value":"aa"},
    {"id":"1711", "value":"bb"},
    {"id":"1731", "value":"qq"},
    {"id":"1799", "value":"ff"},
    {"id":"2741", "value":"pp"}]

df = pd.DataFrame(data=ids)
df = df.set_index(["id"])
```
<p>This gets you the filtered list:</p>
<pre class="lang-py prettyprint-override"><code>filtered_df = df[df.index.isin(["742","1731","1799"])]

</code>```

Body:
I have a dataframe:

id   value
742  aa
1711 bb
1731 qq
1799 ff
2741 pp

id is the index column. I want to print only those values from column "value" which are in this list: [742, 1731, 1799]. So the output must be:

aa
qq
ff

How to do that?

I tried this:

for i in [742, 1731, 1799]:
    print(df[df.index == i]["value"])

but the output is:

value
742    aa
Name: value, dtype: object
value
1731    qq
Name: value, dtype: object
value
1799    ff
Name: value, dtype: object

Body:
This should do it:

Restating the problem:

ids = [
    {"id":"742", "value":"aa"},
    {"id":"1711", "value":"bb"},
    {"id":"1731", "value":"qq"},
    {"id":"1799", "value":"ff"},
    {"id":"2741", "value":"pp"}]

df = pd.DataFrame(data=ids)
df = df.set_index(["id"])

This gets you the filtered list:

filtered_df = df[df.index.isin(["742","1731","1799"])]


问:
IntelliJ IDEA highlights @Entity class names with "Cannot resolve symbol" in JPQL
IntelliJ IDEA highlights persistent @Entity class names with "Cannot resolve symbol" in red in JPQL which is distracting and buries real issues.

So, for example, I declare a query in my repository:

```<code>private static final String READ_BY_CANDIDATE_KEY = "SELECT cr FROM Entity AS cr left join cr.relationship AS re left join fetch cr.relationship2 WHERE re.candidateKey=:ID";
</code>```

.. and "Entity" is underlined, even though "Entity" is a valid class name, and has the @Entity annotation. When the code actually runs, there are no problems.

I imagine some sort of configuration is required to let the IDE know what classes are valid? How is that configuration done?

Update: I do have a JPA facet, but it doesn't see the annotated classes. It seems to require a persistence.xml or orm.xml (which my project does not use)

答: Sometimes JPA Buddy plugin brakes the springboot JPA configuration. Make sure this is not causing the issue.</p>

Body:
IntelliJ IDEA highlights persistent @Entity class names with "Cannot resolve symbol" in red in JPQL which is distracting and buries real issues.

So, for example, I declare a query in my repository:

private static final String READ_BY_CANDIDATE_KEY = "SELECT cr FROM Entity AS cr left join cr.relationship AS re left join fetch cr.relationship2 WHERE re.candidateKey=:ID";

.. and "Entity" is underlined, even though "Entity" is a valid class name, and has the @Entity annotation. When the code actually runs, there are no problems.

I imagine some sort of configuration is required to let the IDE know what classes are valid? How is that configuration done?

Update: I do have a JPA facet, but it doesn't see the annotated classes. It seems to require a persistence.xml or orm.xml (which my project does not use)


问:
What is the T-SQL to list all elastic pools in an Azure SQL Server?
I have more than one Azure SQL Server which each may contain at least one SQL Elastic Pool. I am trying to build a SQL script that can execute a CREATE DATABASE statement on any of those servers and select one of the available pools on that server. To that end, I would like to know the T-SQL statement which would list all the available elastic pools on this server. I have found the SQL below which will list all the databases on the server and which pool they are in:

```<code>SELECT d.database_id, d.name, elastic_pool_name
FROM sys.databases d
JOIN sys.database_service_objectives dso ON d.database_id = dso.database_id
</code>```

However, this only returns master on a new server so I can't tell what the pool name(s) are to create a new database in a pool on the server. I also found this REST API endpoint to list all elastic pools on a server, but I need to execute this in SQL and not via HTTP.

答:
You can get the list of elastic pools on the server from sys.elastic_pool_resource_stats

```<code>select distinct @@servername as servername, elastic_pool_name from sys.elastic_pool_resource_stats
</code>```

Body:
I have more than one Azure SQL Server which each may contain at least one SQL Elastic Pool. I am trying to build a SQL script that can execute a CREATE DATABASE statement on any of those servers and select one of the available pools on that server. To that end, I would like to know the T-SQL statement which would list all the available elastic pools on this server. I have found the SQL below which will list all the databases on the server and which pool they are in:

SELECT d.database_id, d.name, elastic_pool_name
FROM sys.databases d
JOIN sys.database_service_objectives dso ON d.database_id = dso.database_id

However, this only returns master on a new server so I can't tell what the pool name(s) are to create a new database in a pool on the server. I also found this REST API endpoint to list all elastic pools on a server, but I need to execute this in SQL and not via HTTP.

Body:
You can get the list of elastic pools on the server from sys.elastic_pool_resource_stats

select distinct @@servername as servername, elastic_pool_name from sys.elastic_pool_resource_stats


问:
Upload user's profile pics to imgur without making user authenticate to imgur
How do you upload user images to imgur without making user authenticate to imgur ie, I would like to upload on behalf of the application(subscribed to freemium plan) not the user. I came across the oauth api for imgur but I think I don't want that ?

I want to upload profile pics of users to imgur but without making users aware of this fact or them needing to register/sign in for imgur.

答:
Register your imgur app from this link and save client keys.

After that you can upload images anonymously and retrieve image link as this API doc guide.


问:
extract quarter from date field and display like Q4:YYYY format in query results
trouble with formatting using to_char

extract (quarter FROM reviewedon) AS quarter

returns 4

I need it to display as 'Q4:YYYY'

Here is my script:
extract to_char((quarter FROM reviewedon),'"Q"Q:yyyy') AS quarter

this is the error I am getting:
ERROR:  syntax error at or near "("
LINE 66: extract to_char((quarter FROM reviewedon),'"Q"Q:yyyy') AS qu...

答:
you only need to_char()

```<code>to_char(reviewdon, '"Q"q:yyyy')
</code>```

Body:
you only need to_char()

to_char(reviewdon, '"Q"q:yyyy')


问:
Apollo client: How to simply debug a 400 code error?
I'm using Apollo-client and I don't understand why this is so hard to debug my error:
I'm trying to perform a mutate call on my graphene python implementation of GraphQL. It end up with a 400 error code, and I have no way to retrieve the info.

For example: when I try my graphene service on the /graphQL interface, it return me helpful errors as bad input or bad methode name.
Here, on apollo client, It only throw me a 400 code error. That doesn't help me at all. So is it possible to have the error info from graphene from my apolo client, instead of an unhelpful 400 code error?

Here an example, from my graphene interface (/graphQL):

```<code>mutation myMutation {
  uploadFile(input:"") {
    success
  }
}
</code>```

will output:

```<code>{
  "errors": [
    {
      "message": "Argument \"input\" has invalid value \"\".\nExpected \"UploadFileMutationInput\", found not an object.",
      "locations": [
        {
          "column": 20,
          "line": 2
        }
      ]
    }
  ]
}
</code>```

When I try the same on apollo client (js):

```<code>client.mutate({
  mutation: gql`
    mutation($file: Upload!) {
      uploadFile(input: $file) {
        success
      }
    }
  `,
  variables: { file } })
  .then(console.log)
  .catch((e) => { console.log("catch", e) })
</code>```

I get
Error: Network error: Response not successful: Received status code 400

My catch is never called, and the documentation is not helping me at all.

What I want is get the mutation detail errors of my calls: When I use improper method call or bad input type, I should not fall in a 400 without any information of what made my request bad.

答:
None of the other suggested answers, let alone apollo-link-error and its code that you can allegedly copy and paste (and solve easily), worked for me.

I'm only posting this since I managed to solve this problem without the use of installing any additional packages or libraries or pasting in any code (that won't even work). And this is to remind myself should I google this problem again.

The easy solution: Look in the Network tab of the console in Google Chrome. You can see the stack trace and more details of the error.

Body:
I'm using Apollo-client and I don't understand why this is so hard to debug my error:
I'm trying to perform a mutate call on my graphene python implementation of GraphQL. It end up with a 400 error code, and I have no way to retrieve the info.

For example: when I try my graphene service on the /graphQL interface, it return me helpful errors as bad input or bad methode name.
Here, on apollo client, It only throw me a 400 code error. That doesn't help me at all. So is it possible to have the error info from graphene from my apolo client, instead of an unhelpful 400 code error?

Here an example, from my graphene interface (/graphQL):

mutation myMutation {
  uploadFile(input:"") {
    success
  }
}

will output:

{
  "errors": [
    {
      "message": "Argument \"input\" has invalid value \"\".\nExpected \"UploadFileMutationInput\", found not an object.",
      "locations": [
        {
          "column": 20,
          "line": 2
        }
      ]
    }
  ]
}

When I try the same on apollo client (js):

client.mutate({
  mutation: gql`
    mutation($file: Upload!) {
      uploadFile(input: $file) {
        success
      }
    }
  `,
  variables: { file } })
  .then(console.log)
  .catch((e) => { console.log("catch", e) })

I get
Error: Network error: Response not successful: Received status code 400

My catch is never called, and the documentation is not helping me at all.

What I want is get the mutation detail errors of my calls: When I use improper method call or bad input type, I should not fall in a 400 without any information of what made my request bad.


问:
Universal Render Pipeline 2D lighting not working
2D light sources from URP are not displayed on Android. Everything works on PC. As far as I know, URP can work on Android, but it doesn't work for me. Everything is displayed except for the light.</p>

答:
check through the quality settings under project settings > quality since switching to android might've changed some quality settings involving lighting.

Also make sure that you have the URP material applied to your sprites since they require it to be lit.


问:
Python _ Project Euler Question 2 - Why my answer code is wrong?
Q: By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

My Code:

```<code>x = 1
y = 2
ans = 0
evens = []
while x <= 4000000:
    ans = x + y
    x = y
    y = ans
    if ans % 2 == 0:
        evens.append(ans)
print(sum(evens))
</code>```

My result is 4613730 while it should be 4613732.
What am I don't understand here?

答:
You can use print(evens) inside loop to see what you missed. Now, first 2 is not printed.

First even, 2, is not inserted to the evens, so one of ways to correct the code is  inserting 2 into evens right before starting a loop. There might be many ways to solve this issue.

x = 1
y = 2
ans = 0
evens = [2]
while x <= 4000000:
    ans = x + y
    x = y
    y = ans
    if ans % 2 == 0:
        evens.append(ans)
    print(evens) # to debug what are in in a 'evens' list
print(sum(evens))
# 4613730
```

Body:
Q: By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

My Code:

x = 1
y = 2
ans = 0
evens = []
while x <= 4000000:
    ans = x + y
    x = y
    y = ans
    if ans % 2 == 0:
        evens.append(ans)
print(sum(evens))

My result is 4613730 while it should be 4613732.
What am I don't understand here?


问:
Unable to copy files in full over a network share
I'm trying to read in an Excel spreadsheet with C#/ASP.net. This entry here works great if the workbook is on my local drive.

However, when I attempt to access any workbook on a network share, I only get the first 30 rows of data.

When I used File.Copy to copy the file to the local drive of the server, I only get 35kb (and the resulting file only has 30 rows of data in it when I open it in Excel).

How can I get the file to open in full over the network, or how can I copy the full file to the local drive first?

Edit: I should note that manually copying the file works perfectly fine. Opening the file over the network shows the full contents of the file in Excel. Only when accessing the file through the ASP.NET application does it limit it's self to 35kb. There must be a setting that terminates the connection after this limit, but I don't know where it is.

Edit2: Code I am using to copy the file:

```<code>File.Copy("\\\\server\\share\\path\\to\\file\\workbook.xls","c:\\workbook.xls");
</code>```

答: The usual problem with network shares is that you didn't call WNetAddConnection2. However 35kb makes this confusing, so I don't know. Maybe still worth an attempt. </p>

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to read in an Excel spreadsheet with C#/ASP.net. This entry here works great if the workbook is on my local drive.

However, when I attempt to access any workbook on a network share, I only get the first 30 rows of data.

When I used File.Copy to copy the file to the local drive of the server, I only get 35kb (and the resulting file only has 30 rows of data in it when I open it in Excel).

How can I get the file to open in full over the network, or how can I copy the full file to the local drive first?

Edit: I should note that manually copying the file works perfectly fine. Opening the file over the network shows the full contents of the file in Excel. Only when accessing the file through the ASP.NET application does it limit it's self to 35kb. There must be a setting that terminates the connection after this limit, but I don't know where it is.

Edit2: Code I am using to copy the file:

File.Copy("\\\\server\\share\\path\\to\\file\\workbook.xls","c:\\workbook.xls");


问:
Can't figure out the Terraform configuration equivalent for creating address for VPC Peering and networking service for GCP
I'd like to access my CloudSQL instance from my GKE Cluster pods. Since I am setting up I need to bring everything GCP related to the Terraform configuration files.

Following this tutorial: https://cloud.google.com/sql/docs/mysql/quickstart-kubernetes-engine#gcloud_2

I am stuck with two steps that describe the creating of a peering vpc connection.

So my question is what are the Terraform equivalents for the following two commands:

gcloud compute addresses create google-managed-services-default \
--global \
--purpose=VPC_PEERING \
--prefix-length=16 \
--description="peering range for Google" \
--network=default
```
<p>and</p>
<pre class="lang-sh prettyprint-override"><code>gcloud services vpc-peerings connect \
--service=servicenetworking.googleapis.com \
--ranges=google-managed-services-default \
--network=default
</code>```

I tried to find it in https://registry.terraform.io/providers/hashicorp/google/latest/docs but could not find the proper ones.

答:
Creating the address would be like this:

```<code>resource "google_compute_global_address" "address_resource" {
  provider      = google-beta # from docs
  name          = "google-managed-services-default"
  address_type  = "INTERNAL"
  purpose       = "VPC_PEERING"
  prefix_length = "16"
  network       = google_compute_network.network_resource.id
  address       = "REPLACE_WITH_VALUE" # or remove it to automatically select an unused address range in your VPC network
}
</code>```

and the service connection would be like this:

```<code>resource "google_service_networking_connection" "foobar" {
  network                 = google_compute_network.network_resource.id
  service                 = "servicenetworking.googleapis.com"
  reserved_peering_ranges = [google_compute_global_address.address_resource.name]
}
</code>```

links:

Example Usage - Global Address Private Services Connect

Google Service Networking Connection

Body:
I'd like to access my CloudSQL instance from my GKE Cluster pods. Since I am setting up I need to bring everything GCP related to the Terraform configuration files.

Following this tutorial: https://cloud.google.com/sql/docs/mysql/quickstart-kubernetes-engine#gcloud_2

I am stuck with two steps that describe the creating of a peering vpc connection.

So my question is what are the Terraform equivalents for the following two commands:

gcloud compute addresses create google-managed-services-default \
--global \
--purpose=VPC_PEERING \
--prefix-length=16 \
--description="peering range for Google" \
--network=default

and

gcloud services vpc-peerings connect \
--service=servicenetworking.googleapis.com \
--ranges=google-managed-services-default \
--network=default

I tried to find it in https://registry.terraform.io/providers/hashicorp/google/latest/docs but could not find the proper ones.

Body:
Creating the address would be like this:

resource "google_compute_global_address" "address_resource" {
  provider      = google-beta # from docs
  name          = "google-managed-services-default"
  address_type  = "INTERNAL"
  purpose       = "VPC_PEERING"
  prefix_length = "16"
  network       = google_compute_network.network_resource.id
  address       = "REPLACE_WITH_VALUE" # or remove it to automatically select an unused address range in your VPC network
}

and the service connection would be like this:

resource "google_service_networking_connection" "foobar" {
  network                 = google_compute_network.network_resource.id
  service                 = "servicenetworking.googleapis.com"
  reserved_peering_ranges = [google_compute_global_address.address_resource.name]
}

links:

Example Usage - Global Address Private Services Connect

Google Service Networking Connection


问:
can ranges split be used with a predicate?
Can this double loop be rewritten using ranges views split() ?

```<code>#include <vector>
#include <span>

struct MyPair
{
    int a;
    char b;
};

vector<MyPair> path = {{1,'a'},{1,'z'},{2,'b'},{2,'y'}};
vector<span<MyPair> > spans;

for (int i=0; i < path.size();)
{
    auto r = path | ranges::views::drop(i) | views::take_while([&](const MyPair& p){return p.a == path[i].a;});
    int size = ranges::distance(r);
    span<Range> ranges(&path[i], size);
    spans.push_back(ranges);
    i += size ;
}
</code>```

I want a view of views looking like

```<code>{{{1,'a'},{1,'z'}},{{2,'b'},{2,'y'}}}
</code>```

答:
Can this double loop be rewritten using ranges views split() ?

Since you're not using a range as a delimiter to split the original range, instead you're using a predicate to split the range,  views::split doesn't actually solve the problem.

However, C++23 adopted views::chunk_by, and according to its description in [range.chunk.by.overview]:

chunk_by_view takes a view and a predicate, and splits the view into
subranges between each pair of adjacent elements for which the
predicate returns false.

The for-loop can be rewritten using views::chunk_by with the appropriate predicate:

```<code>vector<MyPair> path = ...
auto spans = path | std::views::chunk_by([](const auto& l, const auto& r) {
                                           return l.a == r.a;
                                         });
</code>```

But currently, no compiler implements this range adaptor, the alternative is to use range-v3's views::group_by.

Demo

It is worth noting that ranges::views::group_by is not functionally equivalent to std::views::chunk_by: the former always compares the first element in each subrange with each subsequent one, while the latter always compare consecutive elements.

Body:
Can this double loop be rewritten using ranges views split() ?

#include <vector>
#include

struct MyPair
{
    int a;
    char b;
};

vector<MyPair> path = {{1,'a'},{1,'z'},{2,'b'},{2,'y'}};
vector<span<MyPair> > spans;

for (int i=0; i < path.size();)
{
    auto r = path | ranges::views::drop(i) | views::take_while([&](const MyPair& p){return p.a == path[i].a;});
    int size = ranges::distance(r);
    span<Range> ranges(&path[i], size);
    spans.push_back(ranges);
    i += size ;
}

I want a view of views looking like

{{{1,'a'},{1,'z'}},{{2,'b'},{2,'y'}}}

Body:
Can this double loop be rewritten using ranges views split() ?

Since you're not using a range as a delimiter to split the original range, instead you're using a predicate to split the range,  views::split doesn't actually solve the problem.

However, C++23 adopted views::chunk_by, and according to its description in [range.chunk.by.overview]:

chunk_by_view takes a view and a predicate, and splits the view into
subranges between each pair of adjacent elements for which the
predicate returns false.

The for-loop can be rewritten using views::chunk_by with the appropriate predicate:

vector<MyPair> path = ...
auto spans = path | std::views::chunk_by([](const auto& l, const auto& r) {
                                           return l.a == r.a;
                                         });

But currently, no compiler implements this range adaptor, the alternative is to use range-v3's views::group_by.

Demo

It is worth noting that ranges::views::group_by is not functionally equivalent to std::views::chunk_by: the former always compares the first element in each subrange with each subsequent one, while the latter always compare consecutive elements.


问:
Nested class conversion operator usage
I'm reading -

Thinking in C++, Volume 1, 2nd Edition by Bruce Eckel

Consider the class given in the book -

```<code>class Game {
    GameBoard gb; // Composition
public:

  ...
    class Other{
    public:
        Other() { Log(std::cout); }
        ~Other() { Log(std::cout); }
    }; // Nested class

    // Automatic type conversion:
    operator Other() const { Log(std::cout); return Other(); }

    ~Game() { Log(std::cout); }
};
</code>```

Wondering how can I use operator Other() ?

Please help .

答:
```<code>Here’s an example of the functions that
</code>```

are synthesized by the compiler:

```<code>// Functions that are synthesized by the compiler
#include <iostream>
using namespace std;
class GameBoard {
public:
 GameBoard() { cout << "GameBoard()\n"; }
 GameBoard(const GameBoard&) {
 cout << "GameBoard(const GameBoard&)\n";
 }
 GameBoard& operator=(const GameBoard&) {
 cout << "GameBoard::operator=()\n";
 return *this;
 }
 ~GameBoard() { cout << "~GameBoard()\n"; }
};
class Game {
 GameBoard gb; // Composition
public:
 // Default GameBoard constructor called:
 Game() { cout << "Game()\n"; }
 // You must explicitly call the GameBoard
 // copy-constructor or the default constructor
 // is automatically called instead:
 Game(const Game& g) : gb(g.gb) {
 cout << "Game(const Game&)\n";
 }
 Game(int) { cout << "Game(int)\n"; }
 Game& operator=(const Game& g) {
 // You must explicitly call the GameBoard
 // assignment operator or no assignment at
 // all happens for gb!
 gb = g.gb;
 cout << "Game::operator=()\n";
 return *this;
 }
 class Other {}; // Nested class
 // Automatic type conversion:
 operator Other() const {
 cout << "Game::operator Other()\n";
 return Other();
 }
 ~Game() { cout << "~Game()\n"; }
};
class Chess : public Game {};
void f(Game::Other) {}
class Checkers : public Game {
public:
 // Default base-class constructor called:
 Checkers() { cout << "Checkers()\n"; }
 // You must explicitly call the base-class
 // copy constructor or the default constructor
 // will be automatically called instead:
 Checkers(const Checkers& c) : Game(c) {
 cout << "Checkers(const Checkers& c)\n";
 }
 Checkers& operator=(const Checkers& c) {
 // You must explicitly call the base-class
 // version of operator=() or no base-class
 // assignment will happen:
Game::operator=(c);
 cout << "Checkers::operator=()\n";
 return *this;
 }
};
int main() {
 Chess d1; // Default constructor
 Chess d2(d1); // Copy-constructor
//! Chess d3(1); // Error: no int constructor
 d1 = d2; // Operator= synthesized
 f(d1); // Type-conversion IS inherited
 Game::Other go;
//! d1 = go; // Operator= not synthesized
 // for differing types
 Checkers c1, c2(c1);
 c1 = c2;
}
</code>```

The constructors and the operator= for GameBoardand Game announce themselves so you can see when they’re used by the compiler. In addition, the operator Other( performs automatic ) type conversion from a Game object to an object of the nested class Other. The class Chess simply inherits from Game and creates no functions (to see how the compiler responds). The function f( ) takes an Other object to test the automatic type conversion function. In main( ), the synthesized default constructor and copyconstructor for the derived class Chess are called. The Game versions of these constructors are called as part of the constructorcall hierarchy. Even though it looks like inheritance, new constructors are actually synthesized by the compiler. As you might expect, no constructors with arguments are automatically created because that’s too much for the compiler to intuit. The operator= is also synthesized as a new function in Chess using memberwise assignment (thus, the base-class version is called) because that function was not explicitly written in the new class.

Title: Nested class conversion operator usage

Body:
I'm reading -

Thinking in C++, Volume 1, 2nd Edition by Bruce Eckel

Consider the class given in the book -

class Game {
    GameBoard gb; // Composition
public:

  ...
    class Other{
    public:
        Other() { Log(std::cout); }
        ~Other() { Log(std::cout); }
    }; // Nested class

    // Automatic type conversion:
    operator Other() const { Log(std::cout); return Other(); }

    ~Game() { Log(std::cout); }
};

Wondering how can I use operator Other() ?

Please help .

Body:
Here’s an example of the functions that

are synthesized by the compiler:

// Functions that are synthesized by the compiler
#include <iostream>
using namespace std;
class GameBoard {
public:
 GameBoard() { cout << "GameBoard()\n"; }
 GameBoard(const GameBoard&) {
 cout << "GameBoard(const GameBoard&)\n";
 }
 GameBoard& operator=(const GameBoard&) {
 cout << "GameBoard::operator=()\n";
 return *this;
 }
 ~GameBoard() { cout << "~GameBoard()\n"; }
};
class Game {
 GameBoard gb; // Composition
public:
 // Default GameBoard constructor called:
 Game() { cout << "Game()\n"; }
 // You must explicitly call the GameBoard
 // copy-constructor or the default constructor
 // is automatically called instead:
 Game(const Game& g) : gb(g.gb) {
 cout << "Game(const Game&)\n";
 }
 Game(int) { cout << "Game(int)\n"; }
 Game& operator=(const Game& g) {
 // You must explicitly call the GameBoard
 // assignment operator or no assignment at
 // all happens for gb!
 gb = g.gb;
 cout << "Game::operator=()\n";
 return *this;
 }
 class Other {}; // Nested class
 // Automatic type conversion:
 operator Other() const {
 cout << "Game::operator Other()\n";
 return Other();
 }
 ~Game() { cout << "~Game()\n"; }
};
class Chess : public Game {};
void f(Game::Other) {}
class Checkers : public Game {
public:
 // Default base-class constructor called:
 Checkers() { cout << "Checkers()\n"; }
 // You must explicitly call the base-class
 // copy constructor or the default constructor
 // will be automatically called instead:
 Checkers(const Checkers& c) : Game(c) {
 cout << "Checkers(const Checkers& c)\n";
 }
 Checkers& operator=(const Checkers& c) {
 // You must explicitly call the base-class
 // version of operator=() or no base-class
 // assignment will happen:
Game::operator=(c);
 cout << "Checkers::operator=()\n";
 return *this;
 }
};
int main() {
 Chess d1; // Default constructor
 Chess d2(d1); // Copy-constructor
//! Chess d3(1); // Error: no int constructor
 d1 = d2; // Operator= synthesized
 f(d1); // Type-conversion IS inherited
 Game::Other go;
//! d1 = go; // Operator= not synthesized
 // for differing types
 Checkers c1, c2(c1);
 c1 = c2;
}

The constructors and the operator= for GameBoardand Game announce themselves so you can see when they’re used by the compiler. In addition, the operator Other( performs automatic ) type conversion from a Game object to an object of the nested class Other. The class Chess simply inherits from Game and creates no functions (to see how the compiler responds). The function f( ) takes an Other object to test the automatic type conversion function. In main( ), the synthesized default constructor and copyconstructor for the derived class Chess are called. The Game versions of these constructors are called as part of the constructorcall hierarchy. Even though it looks like inheritance, new constructors are actually synthesized by the compiler. As you might expect, no constructors with arguments are automatically created because that’s too much for the compiler to intuit. The operator= is also synthesized as a new function in Chess using memberwise assignment (thus, the base-class version is called) because that function was not explicitly written in the new class.


问:
Reload UITableViewController
I'm trying to reload data in a UITableViewController after a location is found. This also means after the viewDidLoad method. My class is extending a UITableViewController with this interface:

```<code>@interface RootViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate>
</code>```

in the implementation I try to reload data using

```<code>[self.view reloadData];
</code>```

reloadData doesn't seem to be a method of UITableViewController or the view because I get an error:

```<code>Messages without a matching method signature will be assumed to return 'id' and accept '...' as arguments
</code>```

Can someone please post some code of how to reload a table view extended like in my case?

答: you have to do it on the UITableView over [self.tableView reloadData];

OwnerDisplayName: Joe Estes

Title: Reload UITableViewController

Body:
I'm trying to reload data in a UITableViewController after a location is found. This also means after the viewDidLoad method. My class is extending a UITableViewController with this interface:

@interface RootViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate>

in the implementation I try to reload data using

[self.view reloadData];

reloadData doesn't seem to be a method of UITableViewController or the view because I get an error:

Messages without a matching method signature will be assumed to return 'id' and accept '...' as arguments

Can someone please post some code of how to reload a table view extended like in my case?

OwnerDisplayName: catlan


问:
Is it meaningful to model mixed effect with center as random intercept when each center is given the same treatment?
I have 3 treatments (A, B, C) and 30 centers. Each center only administers one treatment to its participants. Example, center1 administers Treatment A to its participants, center2 administers Treatment B, and so on.

Data on outcome and demographics are collected from the participants.

I would like to find out the effect of the treatments on the outcome after controlling for demographics. So fixed effects are treatments and demographics.

Participants in the same center are dependent. Hence, would like to model center as 2nd level random intercept. Question: is it meaningful to model center as random intercept given that each center only administers one treatment?

答:
Question: is it meaningful to model center as random intercept given that each center only administers one treatment?

Yes. The main point here is your previous two sentences:

Participants in the same center are dependent. Hence, would like to model center as 2nd level random intercept.

Exactly. We fit random intercepts for groups when we expect dependencies within those groups. That each center administers the same treatment is not important, except that it may lead to a loss in statistical power, so a sample size study should be conducted. This type of study design is used in cluster-randomised controlled trials.


问:
Why does useState cause this simple code to behave incorrectly?
I have written a simple component to reproduce the problem I am having in a much larger project component.

Say I have an arrayA where I'd like to continuously add the value 1 on every button click and a state arrayB I would like to update on the button click.

```<code>export default function UseStateTest(props) {
  const arrayA = [];
  const [arrayB, setArrayB] = useState([1, 2]);

  function handleClick() {
    arrayA.push(1);
    setArrayB([3, 4]);
    console.log(arrayA);
  }

  return <button onClick={handleClick}>Test</button>;
}
</code>```

With the setArrayB there, the code behaves incorrectly and when I click the button: arrayA will always have 1 element 1 (I think, from experience in my other code where I'm having a similar problem, that the code is actually replacing the element instead of pushing).

When I comment the setArrayB out, the code behaves correctly, with a new element '1' being added to the array on every button click.

Please may someone help me understand what is causing this behaviour.

答:
Your component function is called each time your component needs to be re-rendered. You get a different arrayA on each call to your component (as with any other function). That's why there's a useState hook (and some others, like useRef): So you can persist stateful information across renders.

Without the call to setArrayB, your component doesn't change its state, so React doesn't re-render it (doesn't call your function again). With the call to setArrayB, you're changing the component's state, causing a re-render, which does a new call, which creates a new arrayA (and a new handleClick).

You can't store any information that should persist between renders in simple variables/constants within the function, since those are recreated on each function call. Instead, use useState (for state information that, when changed, should cause your component to re-render), useRef (for stateful information that shouldn't cause your component to re-render [rare]), and various other hooks.

Body:
I have written a simple component to reproduce the problem I am having in a much larger project component.

Say I have an arrayA where I'd like to continuously add the value 1 on every button click and a state arrayB I would like to update on the button click.

export default function UseStateTest(props) {
  const arrayA = [];
  const [arrayB, setArrayB] = useState([1, 2]);

  function handleClick() {
    arrayA.push(1);
    setArrayB([3, 4]);
    console.log(arrayA);
  }

  return <button onClick={handleClick}>Test</button>;
}

With the setArrayB there, the code behaves incorrectly and when I click the button: arrayA will always have 1 element 1 (I think, from experience in my other code where I'm having a similar problem, that the code is actually replacing the element instead of pushing).

When I comment the setArrayB out, the code behaves correctly, with a new element '1' being added to the array on every button click.

Please may someone help me understand what is causing this behaviour.


问:
React Native app opens and closes quickly after installation on ios simulator
I've been developing an App using React Native and when I switched to a Mac environment to set up the configurations for ios, after all the setup has been done, the app opens very quickly and closes after the installation, showing that powered by react native screen. I noticed that in my packager screen, the line from the bundle which shows a progress of how much has been loaded does not appear, as if it has never been loaded. Same thing happens if I try to run the code from Xcode.

Here is the screen I'm talking about, for a test project I started for comparisson purposes:

And here is the same screen for my App, without the progress indicator being displayed:

I tried following some solutions provided by the comunity for similar issues but none of them worked. Note that no error message is displayed in my terminal window, as if the build and installation has been succesfull.

Can someone help me with this one? I've been strugling with this App for quite some time, as react native always seems to crash and display error messages for me. Any help would be much appreciated :)

Edit: forgot to mention that I'm trying to run the app on the simulator since I don't have an actual device.

答:
Add firebase crashlytics or open again and again that app, so it navigates to the log screen to find the issue. Mainly it caused by the misconfigured pod settings. So please check your Podfile. because all the other errors are comes in app's internal error console. I'm attaching the Non error formed Podfile for your reference. It's only the example

Podfile

```<code>require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
platform :ios, '12.0'

target 'iospodapp' do
  config = use_native_modules!
  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => false
  )
  permissions_path = '../node_modules/react-native-permissions/ios'
  pod 'Permission-LocationAlways', :path => "#{permissions_path}/LocationAlways.podspec"
  pod 'Permission-LocationWhenInUse', :path => "#{permissions_path}/LocationWhenInUse.podspec"
  pod 'Permission-MediaLibrary', :path => "#{permissions_path}/MediaLibrary.podspec"
  pod 'Permission-Notifications', :path => "#{permissions_path}/Notifications.podspec"
  pod 'Permission-PhotoLibrary', :path => "#{permissions_path}/PhotoLibrary.podspec"

  pod 'YogaKit'
  pod 'Firebase/Performance'
  pod 'Firebase/Messaging'
  pod 'RNVectorIcons', :path => '../node_modules/react-native-vector-icons'
  pod 'react-native-orientation', :path => '../node_modules/react-native-orientation'
  pod 'RNFS', :path => '../node_modules/react-native-fs'

  target 'iospodappTests' do
    inherit! :complete
    # Pods for testing
  end

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.

  use_flipper!()

  post_install do |installer|
    flipper_post_install(installer)
    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
        config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '12.0'
       end
    end
  end
end
</code>```

Note:

If you're using the firebase, don't forget to add the GoogleService-Info.plist into your ios directory through xcode.

If you're using firebase analytics that also makes the crash. because it needs too more configurations to avoid the crash. so check your build without firebase analytics first. If everything is fine, you can add the analytics later

Body:
Add firebase crashlytics or open again and again that app, so it navigates to the log screen to find the issue. Mainly it caused by the misconfigured pod settings. So please check your Podfile. because all the other errors are comes in app's internal error console. I'm attaching the Non error formed Podfile for your reference. It's only the example

Podfile

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
platform :ios, '12.0'

target 'iospodapp' do
  config = use_native_modules!
  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => false
  )
  permissions_path = '../node_modules/react-native-permissions/ios'
  pod 'Permission-LocationAlways', :path => "#{permissions_path}/LocationAlways.podspec"
  pod 'Permission-LocationWhenInUse', :path => "#{permissions_path}/LocationWhenInUse.podspec"
  pod 'Permission-MediaLibrary', :path => "#{permissions_path}/MediaLibrary.podspec"
  pod 'Permission-Notifications', :path => "#{permissions_path}/Notifications.podspec"
  pod 'Permission-PhotoLibrary', :path => "#{permissions_path}/PhotoLibrary.podspec"

  pod 'YogaKit'
  pod 'Firebase/Performance'
  pod 'Firebase/Messaging'
  pod 'RNVectorIcons', :path => '../node_modules/react-native-vector-icons'
  pod 'react-native-orientation', :path => '../node_modules/react-native-orientation'
  pod 'RNFS', :path => '../node_modules/react-native-fs'

  target 'iospodappTests' do
    inherit! :complete
    # Pods for testing
  end

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.

  use_flipper!()

  post_install do |installer|
    flipper_post_install(installer)
    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
        config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '12.0'
       end
    end
  end
end

Note:

If you're using the firebase, don't forget to add the GoogleService-Info.plist into your ios directory through xcode.

If you're using firebase analytics that also makes the crash. because it needs too more configurations to avoid the crash. so check your build without firebase analytics first. If everything is fine, you can add the analytics later


问:
How to check the Docker Desktop installed version?
I'm having Docker Desktop on my Windows PC. While checking the version of the docker in the registry it shows the version as 2.1.0.5. But when I running the below command in the Windows CMD, it returns the version as 19.03.5.

Which one is the correct version and why it's showing two different versions for a single application?

答:
On Windows 10:

Go to Settings -> Apps & Features

click on the Docker-App

click on "Uninstall" - version-number of Docker Desktop is displayed


问:
Why ESLint no-await-in-loop not working with for await of?
for await of — supposed to be used with asynchronous iterators, it awaits each promise within iterator and handles response of each awaited promise in its body. From MDN docs this syntax can be used also with sync iterators, so

I have the following code examples that work similar:

(async () => {
    const entityIds = [1, 2, 3, 4];

    for await (const id of entityIds) {
        console.log(await getEntityById(id));
    }
})();
```
<p>And:</p>
<pre class="lang-js prettyprint-override"><code>(async () => {
    const entityIds = [1, 2, 3, 4];

    for (const id of entityIds) {
        console.log(await getEntityById(id)); // ESLint: Unexpected `await` inside a loop.(no-await-in-loop)
    }
})();
</code>```

But in the 2nd example I'm getting eslint warning about the rule no-await-in-loop. The question is: why? Each iteration of these 2 loops will await for async function completes, but the eslint is not gonna react on 1st case at all.

答:
The no-await-in-loop rule in ESLint is supposed to protect you from accidentally processing some data sequentially. The reasoning is that often having an await in a loop is not intentional because it is more efficient to process the data in parallel. Thus all usages of await in a loop are considered a "mistake" when the rule is turned on.

Using for await...of is explicitly considered "intentional" by the rule. Checking the rule's tests (bottom of the documentation page) the following part is listed as valid code:

```<code>valid: [
    // ...

    // Asynchronous iteration intentionally
    "async function foo() { for await (var x of xs) { await f(x) } }"
],
</code>```

while any usage of await in any other loop construct is invalid. Including using await inside a loop inside a for await...of:

```<code>invalid: [
    // ...

    // In a nested loop of for-await-of
    { code: "async function foo() { for await (var x of xs) { while (1) await f(x) } }", errors: [error] }
]
</code>```

The reasoning most likely is that using for await...of you opt into sequential processing. If you process an asynchronous iterable, chances are very high that you cannot do that in parallel and it would be an error if you try. If you are processing a synchronous iterable which produces promises there is still a chance that you cannot correctly do this in parallel.

ESLint cannot actually detect if you instead have a synchronous iterable which produces synchronous results like an array iterator, therefore, it assumes it is one of the first two options.

In my opinion, the rule is flawed as it is all or nothing. Enabling it means you want no loops with await in them. There are still valid cases where you want sequential processing with for...of and an await inside. Which means that your code is likely to be littered with temporary disables of the rule whenever you do not need it.

My suggestion is to disable the no-await-in-loop rule and exercise common sense for when you use sequential and when you use parallel processing.

Body:
for await of — supposed to be used with asynchronous iterators, it awaits each promise within iterator and handles response of each awaited promise in its body. From MDN docs this syntax can be used also with sync iterators, so

I have the following code examples that work similar:

(async () => {
    const entityIds = [1, 2, 3, 4];

    for await (const id of entityIds) {
        console.log(await getEntityById(id));
    }
})();

And:

(async () => {
    const entityIds = [1, 2, 3, 4];

    for (const id of entityIds) {
        console.log(await getEntityById(id)); // ESLint: Unexpected `await` inside a loop.(no-await-in-loop)
    }
})();

But in the 2nd example I'm getting eslint warning about the rule no-await-in-loop. The question is: why? Each iteration of these 2 loops will await for async function completes, but the eslint is not gonna react on 1st case at all.

Body:
The no-await-in-loop rule in ESLint is supposed to protect you from accidentally processing some data sequentially. The reasoning is that often having an await in a loop is not intentional because it is more efficient to process the data in parallel. Thus all usages of await in a loop are considered a "mistake" when the rule is turned on.

Using for await...of is explicitly considered "intentional" by the rule. Checking the rule's tests (bottom of the documentation page) the following part is listed as valid code:

valid: [
    // ...

    // Asynchronous iteration intentionally
    "async function foo() { for await (var x of xs) { await f(x) } }"
],

while any usage of await in any other loop construct is invalid. Including using await inside a loop inside a for await...of:

invalid: [
    // ...

    // In a nested loop of for-await-of
    { code: "async function foo() { for await (var x of xs) { while (1) await f(x) } }", errors: [error] }
]

The reasoning most likely is that using for await...of you opt into sequential processing. If you process an asynchronous iterable, chances are very high that you cannot do that in parallel and it would be an error if you try. If you are processing a synchronous iterable which produces promises there is still a chance that you cannot correctly do this in parallel.

ESLint cannot actually detect if you instead have a synchronous iterable which produces synchronous results like an array iterator, therefore, it assumes it is one of the first two options.

In my opinion, the rule is flawed as it is all or nothing. Enabling it means you want no loops with await in them. There are still valid cases where you want sequential processing with for...of and an await inside. Which means that your code is likely to be littered with temporary disables of the rule whenever you do not need it.

My suggestion is to disable the no-await-in-loop rule and exercise common sense for when you use sequential and when you use parallel processing.


问:
filtering data from redux store using useSelector?
I have an array that is stored in the store and I want to access a specific item in that array.

My question is this implementation practical ?
Or is there a better way to find that specific item in the array in redux ??

```<code>const category = useSelector((state) =>
    state?.user?.userData?.businessInfo?.categories?.find(
      (item) => item.name === type
    )
  );
</code>```

答:
Would you please add the reducer to better understand the problem ;
otherwise, you should access the reducer by useSelector and affect that array into the const category ;</p>
```<code>const categories =useSelector((state) => state.user.userData.businessInfo )
//and then
const category = categories.find((item) => item.name === type)
</code>```

Body:
I have an array that is stored in the store and I want to access a specific item in that array.

My question is this implementation practical ?
Or is there a better way to find that specific item in the array in redux ??

const category = useSelector((state) =>
    state?.user?.userData?.businessInfo?.categories?.find(
      (item) => item.name === type
    )
  );

Body:
Would you please add the reducer to better understand the problem ;
otherwise, you should access the reducer by useSelector and affect that array into the const category ;

const categories =useSelector((state) => state.user.userData.businessInfo )
//and then
const category = categories.find((item) => item.name === type)


问:
how to use ajax in rails3.1?
As we know, Rails 3.1 is using CoffeeScript and JQuery.

The old way that I  handle the ajax request is respond the request to a template which name is some_action.js.erb

Now that we have CoffeeScript and I want my template could use coffeescript syntax.So what can I do?

Just changing the template file's suffix name?

some_file.js.coffee this works fine in the assets/javascript directory.

But I am handle the ajax request and its template is under the folder views,if just simply change the template name from some_action.js.erb to some_action.js.coffee.erb or some_action.js.coffee,it won't work,rails treat it like normal file and will not compile it from coffeescript syntax to normal javascript.

I am very sorry about my Enlgish ability,hope this time my question will explain my purpose.

答:
Assuming you have upgraded to Rails 3.1, taking advantage of the new syntax is, like you suggested, as easy as converting your files over to CoffeeScript.

Now, you can't just name the file *.js.coffee and expect a conversion, but Ryan Bates at Railscasts recommends changing your files over manually as a great way of learning the syntax yourself. In fact, he has a screencast posted of him doing just that: http://railscasts.com/episodes/267-coffeescript-basics

Rails, then, will handle the compilation from js.coffee into .js for you.

Title: how to use ajax in rails3.1?


问:
Template Constraints C++
In C# we can define a generic type that imposes constraints on the types that can be used as the generic parameter. The following example illustrates the usage of generic constraints:

```<code>interface IFoo
{
}

class Foo<T> where T : IFoo
{
}

class Bar : IFoo
{
}

class Simpson
{
}

class Program
{
    static void Main(string[] args)
    {
        Foo<Bar> a = new Foo<Bar>();
        Foo<Simpson> b = new Foo<Simpson>(); // error CS0309
    }
}
</code>```

Is there a way we can impose constraints for template parameters in C++.

C++0x has native support for this but I am talking about current standard C++.

答:
Using C++20, yes there is: Constraints and concepts

Perhaps you want to guarantee a template is derived from a specific class:

```<code>#include <concepts>

template<class T, class U>
concept Derived = std::is_base_of<U, T>::value;

class ABase { };
class ADerived : ABase { };

template<Derived<ABase> T>
class AClass {
    T aMemberDerivedFromABase;
};
</code>```

The following then compiles like normal:

```<code>int main () {
    AClass<ADerived> aClass;
    return 0;
}
</code>```

But now when you do something against the contraint:

```<code>class AnotherClass {

};
int main () {
    AClass<AnotherClass> aClass;
    return 0;
}
</code>```

AnotherClass is not derived from ABase, therefore my compiler (GCC) gives roughly the following error:

In function 'int main()': note: constraints not satisfied
note: the expression 'std::is_base_of::value
[with U = ABase; T = AnotherClass]' evaluated to 'false'
9 | concept Derived = std::is_base_of::value;

As you can imagine this feature is very useful and can do much more than constraining a class to have a specific base.

OwnerDisplayName: Jorge Ferreira

Title: Template Constraints C++

Body:
In C# we can define a generic type that imposes constraints on the types that can be used as the generic parameter. The following example illustrates the usage of generic constraints:

interface IFoo
{
}

class Foo<T> where T : IFoo
{
}

class Bar : IFoo
{
}

class Simpson
{
}

class Program
{
    static void Main(string[] args)
    {
        Foo<Bar> a = new Foo<Bar>();
        Foo<Simpson> b = new Foo<Simpson>(); // error CS0309
    }
}

Is there a way we can impose constraints for template parameters in C++.

C++0x has native support for this but I am talking about current standard C++.

LastEditorDisplayName: Leon Timmermans

Body:
Using C++20, yes there is: Constraints and concepts

Perhaps you want to guarantee a template is derived from a specific class:

#include <concepts>

template<class T, class U>
concept Derived = std::is_base_of<U, T>::value;

class ABase { };
class ADerived : ABase { };

template<Derived<ABase> T>
class AClass {
    T aMemberDerivedFromABase;
};

The following then compiles like normal:

int main () {
    AClass<ADerived> aClass;
    return 0;
}

But now when you do something against the contraint:

class AnotherClass {

};
int main () {
    AClass<AnotherClass> aClass;
    return 0;
}

AnotherClass is not derived from ABase, therefore my compiler (GCC) gives roughly the following error:

In function 'int main()': note: constraints not satisfied
note: the expression 'std::is_base_of<U, T>::value
[with U = ABase; T = AnotherClass]' evaluated to 'false'
9 | concept Derived = std::is_base_of<U, T>::value;

As you can imagine this feature is very useful and can do much more than constraining a class to have a specific base.