问:
React Modal component is not working in Nextjs
It randomly started doing this and I am not sure why tho. I have two modals (these are named differently) that are exactly the same but only one is working. The modal I am using is the React-Modal library. The first one works just fine on the home page but the second doesn't at all on an edit details page.

What I did notice is that there is a div placed with an Id of __Next on the home page that is working that places the content of the modal inside but that same exact div does not show up on the other page for the same modal to work.

Below are the two components I am working with and its parent component that houses both

Parent:

import styles from './homeheader.module.css';
import { useRouter } from 'next/router';

import { useState } from 'react';
import NewInvoice from '../invoice/modal/NewInvoice';
import Link from 'next/link';

import { getDatabase, ref, remove } from "firebase/database";
import { database } from '../firebase/firebase';
import EditInvoice from '../invoice/modal/EditInvoice';

export default function HomeHeader(props) {
    const [newInvoiceModalIsOpen, setNewInvoiceOpen] = useState(false);
    const [editInvoiceModalIsOpen, setEditInvoiceOpen] = useState(false);
    const router = useRouter();
    const pathName = router.pathname;
    const { data, count, id, detail } = props;

    function openNewInvoiceModalHandler() {
        setNewInvoiceOpen(true)
    }

    function closeNewInvoiceModalHandler() {
        setNewInvoiceOpen(false)
    }
    function openEditInvoiceModalHandler() {
        setEditInvoiceOpen(true)
    }

    function closeEditInvoiceModalHandler() {
        console.log(data)
        setEditInvoiceOpen(false)
    }

    function deleteInvoiceHandler() {
        console.log('delete')
        console.log(id)
        const db = database;
        remove(ref(db, 'invoices/' + id))
    }

    function markAsPaidInvoiceHandler() {
        console.log('paid')
    }

    if (pathName === '/detail/[id]') {
        return (
            <>

                    <Link href="/">
                        Go back
                    </Link>
                    {/*
{detail.data.status}
 */}

                        <button onClick={openEditInvoiceModalHandler}>Edit</button>
                        <button onClick={deleteInvoiceHandler}>Delete</button>
                        <button onClick={markAsPaidInvoiceHandler}>Mark as Paid</button>

                <EditInvoice isOpen={editInvoiceModalIsOpen} closeModal={closeEditInvoiceModalHandler} details={detail}/>
            </>
            )
    }

    return (

Invoices

There are {count} total invoices

                <select className={styles.filter} id="filter" placeholder="Filter by status">
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                </select>
                <button className={styles.button} onClick={openNewInvoiceModalHandler}>New Invoice</button>

            <NewInvoice isOpen={newInvoiceModalIsOpen} closeModal={closeNewInvoiceModalHandler} count={count}/>

    )
}```
</div>
</div>
</p>
<p>Child modal component that IS WORKING:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { useForm } from 'react-hook-form';
import ReactModal from 'react-modal';
import { database } from '../../firebase/firebase';
import { ref, set } from "firebase/database";

import styles from './newinvoice.module.css'

// ReactModal.setAppElement("#__next")

export default function NewInvoice (props) {
    const { register, handleSubmit, watch, formState: { errors } } = useForm();

    function onSubmit(data) {
        const randGen = Math.floor(Math.random() * 9999999);
        data.id = randGen;
        const db = database;
        set(ref(db, '/invoices/' + randGen), {
            data: data
        })

        setTimeout(() => {
            window.location.reload(true)
        }, 500)

        props.closeModal();
    }

    return (
        <>

            <ReactModal isOpen={props.isOpen}>
            <h1>New Invoice</h1>
                <form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
                    <label>Street Address</label>
                    <input {...register("senderAddress.street")} />
                    <label>City</label>
                    <input {...register("senderAddress.city")} />
                    <label>Postal Code</label>
                    <input {...register("senderAddress.postCode")} />
                    <label>Country</label>
                    <input {...register("senderAddress.country")} />
                    <label>Client"s Name</label>
                    <input {...register("clientName")} />
                    <label>Client"s Email</label>
                    <input {...register("clientEmail")} />
                    <label>Street Address</label>
                    <input {...register("clientAddress.street")} />
                    <label>City</label>
                    <input {...register("clientAddress.city")} />
                    <label>Postal Code</label>
                    <input {...register("clientAddress.postCode")} />
                    <label>Country</label>
                    <input {...register("clientAddress.country")} />
                    <label>Invoice Date</label>
                    <input {...register("createdAt")} />
                    <label>Payment Terms</label>
                    <input {...register("paymentTerms")} />
                    <label>Project Description</label>
                    <input {...register("description")} />
                    {/* //Item list goes here */}
                    <input {...register("items")} />

                    <input type="submit" placeholder="Submit"/>
                </form>
                <button onClick={props.closeModal}>Close</button>
            </ReactModal>

        </>
    )
}</code>```

Child component that is NOT WORKING:

import { useForm } from 'react-hook-form';
import ReactModal from 'react-modal';
import { database } from '../../firebase/firebase';
import { ref, set } from "firebase/database";
import { useRouter } from 'next/router';

import styles from './newinvoice.module.css'
import { useEffect, useState } from 'react';

ReactModal.setAppElement("#react-modals")

export default function EditInvoice(props) {
    const { register, handleSubmit, watch, formState: { errors } } = useForm();
    const [formData, setFormData] = useState();
    const { isOpen, closeModal, detail } = props;
    const router = useRouter();
    const id = router.query.id;
    const dbLink = `https://invoice-app-3fa85-default-rtdb.firebaseio.com/invoices/${id}.json`;

    function onSubmit(data) {
        const db = database;
        set(ref(db, '/invoices/' + id), {
            data: data
        })

        setTimeout(() => {
            window.location.reload(true)
        }, 500)

        props.closeModal();
    }

    // function onSubmit(data) {
    //     console.log(data)
    // }

    useEffect(() => {
        // fectchData();
        console.log(formData)
    })

    const fectchData = async () => {
        try {
            const res = await fetch(dbLink);
            const json = await res.json();

            setFormData(json)
        } catch (error) {
            console.log(error)
        }
    }

    if (!formData) {
        console.log('not working')
        return
Loading....

    }

    return (
        <>
            <ReactModal isOpen={true} portalClassName="editInvoiceModal" parentSelector={() => document.querySelector('#react-modals')}>

Edit Invoice

                <form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
                    Street Address
                    <input {...register("senderAddress.street")} defaultValue={detail.senderAddress.street}/>
                 {/*    City
                    <input {...register("senderAddress.city")} defaultValue={formData.senderAddress.city}/>
                    Postal Code
                    <input {...register("senderAddress.postCode")} defaultValue={formData.senderAddress.postCode}/>
                    Country
                    <input {...register("senderAddress.country")} defaultValue={formData.senderAddress.country}/>
                    Client"s Name
                    <input {...register("clientName")} defaultValue={formData.clientName}/>
                    Client"s Email
                    <input {...register("clientEmail")} defaultValue={formData.clientEmail}/>
                    Street Address
                    <input {...register("clientAddress.street")} defaultValue={formData.clientAddress.street}/>
                    City
                    <input {...register("clientAddress.city")} defaultValue={formData.clientAddress.city}/>
                    Postal Code
                    <input {...register("clientAddress.postCode")} defaultValue={formData.clientAddress.postCode}/>
                    Country
                    <input {...register("clientAddress.country")} defaultValue={formData.clientAddress.country}/>
                    Invoice Date
                    <input {...register("createdAt")} defaultValue={formData.createdAt}/>
                    Payment Terms
                    <input {...register("paymentTerms")} defaultValue={formData.paymentTerms}/>
                    Project Description
                    <input {...register("description")} defaultValue={formData.description}/>
                    {/* //Item list goes here */}

                    <input type="submit" placeholder="Submit"/>
                 </form>
                <button onClick={closeModal}>Close</button>
            </ReactModal>

        </>
    )
}```

It may be sloppy code as of now and was working to clean it up a lot more until I noticed this issue.

答:
In your parent, try adding a placeholder.

```<code><div id="react-modals" />
</code>```

Your react modal seems to be looking for a div with the #react-modals id.

Body:
It randomly started doing this and I am not sure why tho. I have two modals (these are named differently) that are exactly the same but only one is working. The modal I am using is the React-Modal library. The first one works just fine on the home page but the second doesn't at all on an edit details page.

What I did notice is that there is a div placed with an Id of __Next on the home page that is working that places the content of the modal inside but that same exact div does not show up on the other page for the same modal to work.

Below are the two components I am working with and its parent component that houses both

Parent:

import styles from './homeheader.module.css';
import { useRouter } from 'next/router';

import { useState } from 'react';
import NewInvoice from '../invoice/modal/NewInvoice';
import Link from 'next/link';

import { getDatabase, ref, remove } from "firebase/database";
import { database } from '../firebase/firebase';
import EditInvoice from '../invoice/modal/EditInvoice';

export default function HomeHeader(props) {
    const [newInvoiceModalIsOpen, setNewInvoiceOpen] = useState(false);
    const [editInvoiceModalIsOpen, setEditInvoiceOpen] = useState(false);
    const router = useRouter();
    const pathName = router.pathname;
    const { data, count, id, detail } = props;

    function openNewInvoiceModalHandler() {
        setNewInvoiceOpen(true)
    }

    function closeNewInvoiceModalHandler() {
        setNewInvoiceOpen(false)
    }
    function openEditInvoiceModalHandler() {
        setEditInvoiceOpen(true)
    }

    function closeEditInvoiceModalHandler() {
        console.log(data)
        setEditInvoiceOpen(false)
    }

    function deleteInvoiceHandler() {
        console.log('delete')
        console.log(id)
        const db = database;
        remove(ref(db, 'invoices/' + id))
    }

    function markAsPaidInvoiceHandler() {
        console.log('paid')
    }

    if (pathName === '/detail/[id]') {
        return (
            <>

                    <Link href="/">
                        Go back
                    </Link>
                    {/*
{detail.data.status}
 */}

                        <button onClick={openEditInvoiceModalHandler}>Edit</button>
                        <button onClick={deleteInvoiceHandler}>Delete</button>
                        <button onClick={markAsPaidInvoiceHandler}>Mark as Paid</button>

                <EditInvoice isOpen={editInvoiceModalIsOpen} closeModal={closeEditInvoiceModalHandler} details={detail}/>
            </>
            )
    }

    return (

Invoices

There are {count} total invoices

                <select className={styles.filter} id="filter" placeholder="Filter by status">
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                </select>
                <button className={styles.button} onClick={openNewInvoiceModalHandler}>New Invoice</button>

            <NewInvoice isOpen={newInvoiceModalIsOpen} closeModal={closeNewInvoiceModalHandler} count={count}/>

    )
}

Child modal component that IS WORKING:

import { useForm } from 'react-hook-form';
import ReactModal from 'react-modal';
import { database } from '../../firebase/firebase';
import { ref, set } from "firebase/database";

import styles from './newinvoice.module.css'

// ReactModal.setAppElement("#__next")

export default function NewInvoice (props) {
    const { register, handleSubmit, watch, formState: { errors } } = useForm();

    function onSubmit(data) {
        const randGen = Math.floor(Math.random() * 9999999);
        data.id = randGen;
        const db = database;
        set(ref(db, '/invoices/' + randGen), {
            data: data
        })

        setTimeout(() => {
            window.location.reload(true)
        }, 500)

        props.closeModal();
    }

    return (
        <>

            <ReactModal isOpen={props.isOpen}>

New Invoice

                <form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
                    Street Address
                    <input {...register("senderAddress.street")} />
                    City
                    <input {...register("senderAddress.city")} />
                    Postal Code
                    <input {...register("senderAddress.postCode")} />
                    Country
                    <input {...register("senderAddress.country")} />
                    Client"s Name
                    <input {...register("clientName")} />
                    Client"s Email
                    <input {...register("clientEmail")} />
                    Street Address
                    <input {...register("clientAddress.street")} />
                    City
                    <input {...register("clientAddress.city")} />
                    Postal Code
                    <input {...register("clientAddress.postCode")} />
                    Country
                    <input {...register("clientAddress.country")} />
                    Invoice Date
                    <input {...register("createdAt")} />
                    Payment Terms
                    <input {...register("paymentTerms")} />
                    Project Description
                    <input {...register("description")} />
                    {/* //Item list goes here */}
                    <input {...register("items")} />

                    <input type="submit" placeholder="Submit"/>
                </form>
                <button onClick={props.closeModal}>Close</button>
            </ReactModal>

        </>
    )
}

Child component that is NOT WORKING:

import { useForm } from 'react-hook-form';
import ReactModal from 'react-modal';
import { database } from '../../firebase/firebase';
import { ref, set } from "firebase/database";
import { useRouter } from 'next/router';

import styles from './newinvoice.module.css'
import { useEffect, useState } from 'react';

ReactModal.setAppElement("#react-modals")

export default function EditInvoice(props) {
    const { register, handleSubmit, watch, formState: { errors } } = useForm();
    const [formData, setFormData] = useState();
    const { isOpen, closeModal, detail } = props;
    const router = useRouter();
    const id = router.query.id;
    const dbLink = `https://invoice-app-3fa85-default-rtdb.firebaseio.com/invoices/${id}.json`;

    function onSubmit(data) {
        const db = database;
        set(ref(db, '/invoices/' + id), {
            data: data
        })

        setTimeout(() => {
            window.location.reload(true)
        }, 500)

        props.closeModal();
    }

    // function onSubmit(data) {
    //     console.log(data)
    // }

    useEffect(() => {
        // fectchData();
        console.log(formData)
    })

    const fectchData = async () => {
        try {
            const res = await fetch(dbLink);
            const json = await res.json();

            setFormData(json)
        } catch (error) {
            console.log(error)
        }
    }

    if (!formData) {
        console.log('not working')
        return
Loading....

    }

    return (
        <>
            <ReactModal isOpen={true} portalClassName="editInvoiceModal" parentSelector={() => document.querySelector('#react-modals')}>

Edit Invoice

                <form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
                    Street Address
                    <input {...register("senderAddress.street")} defaultValue={detail.senderAddress.street}/>
                 {/*    City
                    <input {...register("senderAddress.city")} defaultValue={formData.senderAddress.city}/>
                    Postal Code
                    <input {...register("senderAddress.postCode")} defaultValue={formData.senderAddress.postCode}/>
                    Country
                    <input {...register("senderAddress.country")} defaultValue={formData.senderAddress.country}/>
                    Client"s Name
                    <input {...register("clientName")} defaultValue={formData.clientName}/>
                    Client"s Email
                    <input {...register("clientEmail")} defaultValue={formData.clientEmail}/>
                    Street Address
                    <input {...register("clientAddress.street")} defaultValue={formData.clientAddress.street}/>
                    City
                    <input {...register("clientAddress.city")} defaultValue={formData.clientAddress.city}/>
                    Postal Code
                    <input {...register("clientAddress.postCode")} defaultValue={formData.clientAddress.postCode}/>
                    Country
                    <input {...register("clientAddress.country")} defaultValue={formData.clientAddress.country}/>
                    Invoice Date
                    <input {...register("createdAt")} defaultValue={formData.createdAt}/>
                    Payment Terms
                    <input {...register("paymentTerms")} defaultValue={formData.paymentTerms}/>
                    Project Description
                    <input {...register("description")} defaultValue={formData.description}/>
                    {/* //Item list goes here */}

                    <input type="submit" placeholder="Submit"/>
                 </form>
                <button onClick={closeModal}>Close</button>
            </ReactModal>

        </>
    )
}

It may be sloppy code as of now and was working to clean it up a lot more until I noticed this issue.

Body:
In your parent, try adding a placeholder.

<div id="react-modals" />

Your react modal seems to be looking for a div with the #react-modals id.


来源: stackexchange

问:
Android Studio SDL2 Invalid conversion between vector type '__m64' (vector of 1 'long long' value) and integer type 'int' of different size
I am having problems compiling SDL2 for android. I have gotten to a point where the NDK is throwing an error about a header included by SDL.h.

mmintrin.h is the header included with the ndk that is problematic.

Invalid conversion between vector type '__m64' (vector of 1 'long long' value) and integer type 'int' of different size

SDL.h

```<code>#include "SDL_cpuinfo.h"
</code>```

SDL_cpuinfo.h

```<code>#if !defined(_MSC_VER) || __has_feature(modules) || defined(__MMX__)
#include <mmintrin.h>
#endif
</code>```

mmintirin.h

```<code>static __inline__ __m64 __DEFAULT_FN_ATTRS
_mm_cvtsi32_si64(int __i)
{
    return (__m64)__builtin_ia32_vec_init_v2si(__i, 0);
}
</code>```

This is all stock code from the SDL project and a fresh install of android studio.

```<code>    In file included from /home/nick/development/extenal_git/SDL/include/SDL.h:38:
In file included from /home/nick/development/extenal_git/SDL/include/SDL_cpuinfo.h:102:
In file included from /home/nick/Android/Sdk/ndk/16.1.4479499/toolchains/llvm/prebuilt/linux-x86_64/lib64/clang/5.0.300080/include/immintrin.h:28:
/home/nick/Android/Sdk/ndk/16.1.4479499/toolchains/llvm/prebuilt/linux-x86_64/lib64/clang/5.0.300080/include/mmintrin.h:64:12: error: invalid conversion between vector type '__m64' (vector of 1 'long long' value) and integer type 'int' of different size
</code>```

答: I started from scratch and did not encounter this issue again. May have been misconfiguration of the .mk files.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am having problems compiling SDL2 for android. I have gotten to a point where the NDK is throwing an error about a header included by SDL.h.

mmintrin.h is the header included with the ndk that is problematic.

Invalid conversion between vector type '__m64' (vector of 1 'long long' value) and integer type 'int' of different size

SDL.h

#include "SDL_cpuinfo.h"

SDL_cpuinfo.h

#if !defined(_MSC_VER) || __has_feature(modules) || defined(__MMX__)
#include <mmintrin.h>
#endif

mmintirin.h

static __inline__ __m64 __DEFAULT_FN_ATTRS
_mm_cvtsi32_si64(int __i)
{
    return (__m64)__builtin_ia32_vec_init_v2si(__i, 0);
}

This is all stock code from the SDL project and a fresh install of android studio.

    In file included from /home/nick/development/extenal_git/SDL/include/SDL.h:38:
In file included from /home/nick/development/extenal_git/SDL/include/SDL_cpuinfo.h:102:
In file included from /home/nick/Android/Sdk/ndk/16.1.4479499/toolchains/llvm/prebuilt/linux-x86_64/lib64/clang/5.0.300080/include/immintrin.h:28:
/home/nick/Android/Sdk/ndk/16.1.4479499/toolchains/llvm/prebuilt/linux-x86_64/lib64/clang/5.0.300080/include/mmintrin.h:64:12: error: invalid conversion between vector type '__m64' (vector of 1 'long long' value) and integer type 'int' of different size


问:
Finding the last occurrence of x in the array
I want to find the last occurrence of x(13) in the array which is 6, but my code only finds the first occurrences which is 4, is there a way I can solve this?</p>
```<code>/* Application Program */
int[] arr = {9, 12, 2, 8, 13, -8, 13, 9};
int index = lastIndexOf(arr, 13);

if(index != -1)
    System.out.println(index);
else
    System.out.println("not found");

/* Method */
public static int lastIndexOf(int[] arr, int x){
    for(int i = 0; i<arr.length; i++){
        if(arr[i] == x){
            return i;
        }
    }
    return -1;
}
</code>```

答:
Iterate the array backwards. Like,</p>
```<code>public static int lastIndexOf(int[] arr, int x) {
    for (int i = arr.length - 1; i >= 0; i--) {
        if (arr[i] == x) {
            return i;
        }
    }
    return -1;
}
</code>```

Body:
I want to find the last occurrence of x(13) in the array which is 6, but my code only finds the first occurrences which is 4, is there a way I can solve this?

/* Application Program */
int[] arr = {9, 12, 2, 8, 13, -8, 13, 9};
int index = lastIndexOf(arr, 13);

if(index != -1)
    System.out.println(index);
else
    System.out.println("not found");

/* Method */
public static int lastIndexOf(int[] arr, int x){
    for(int i = 0; i<arr.length; i++){
        if(arr[i] == x){
            return i;
        }
    }
    return -1;
}

Body:
Iterate the array backwards. Like,

public static int lastIndexOf(int[] arr, int x) {
    for (int i = arr.length - 1; i >= 0; i--) {
        if (arr[i] == x) {
            return i;
        }
    }
    return -1;
}


问:
Target another styled component when input:invalid
I have a case like this

image1

image2

image3

how to handle when input:invalid then ErrorMessage will change display: block

I tried like this but it doesn't work
image4

答:
I would personally use conditional rendering with the useState hook: set a boolean to true when the input is invalid and only display the error message if the boolean is true.

If you prefer using CSS and styled components, you need to declare your ErrorMessage component before your Input component so the Input can target the ErrorMessage. Try this:

export const ErrorMessage = styled.p`
    color: red;
    ...
    display: none;
`
export const Input = styled.input`
    ...
    font-weight: 400;
    margin-bottom: 4px;
    &:invalid ~ ${ErrorMessage} {
        display: block;
    }
`
```


问:
Mathematica - Force Logarithmic Scale on Plots & Grouped Axes Labels
I have a ListPointPlot3D plot and all three axes contain a logarithmic distribution of data points.

Like this:

```<code>..... .  .    .        .                .                                .
</code>```

How do I force Mathematica to make the axes' scales logarithmic so that I get a linear distribution of data points across them?

Thanks

答:
AFAIK there isn't a LogLogLogPlot, so the next best thing would be to take the logs of your data and plot those. You then have to come up with Ticks of your own.

A rough version:

```<code>tks = {1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000};
list = 10^RandomReal[{0, 4}, {100, 3}]

ListPointPlot3D[Log[10, list]},
   Ticks ->
    {
      {Log[10, tks], tks}\[Transpose],
      {Log[10, tks], tks}\[Transpose],
      {Log[10, tks], tks}\[Transpose]
    },
    BoxRatios -> 1, PlotStyle -> PointSize -> 0.02
]
</code>```

Ticks has many more possibilities to beautify your scale. I trust you'll find your way to its location in the manual.

ContentLicense: CC BY-SA 3.0

Body:
I have a ListPointPlot3D plot and all three axes contain a logarithmic distribution of data points.

Like this:

..... .  .    .        .                .                                .

How do I force Mathematica to make the axes' scales logarithmic so that I get a linear distribution of data points across them?

Thanks

Body:
AFAIK there isn't a LogLogLogPlot, so the next best thing would be to take the logs of your data and plot those. You then have to come up with Ticks of your own.

A rough version:

tks = {1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000};
list = 10^RandomReal[{0, 4}, {100, 3}]

ListPointPlot3D[Log[10, list]},
   Ticks ->
    {
      {Log[10, tks], tks}\[Transpose],
      {Log[10, tks], tks}\[Transpose],
      {Log[10, tks], tks}\[Transpose]
    },
    BoxRatios -> 1, PlotStyle -> PointSize -> 0.02
]

Ticks has many more possibilities to beautify your scale. I trust you'll find your way to its location in the manual.


问:
Algorithm to find minimum number of days to color boxes by one or more robots
I have n boxes which should be colored. Each day robot can color one box or generate another robot, who works exactly as his parent starting next day.

i.e., if on Sunday I have one robot and 10 balls, on Monday:

There is one robot, 1 colored boxes and 9 uncolored boxes, or

There are 2 robots and 10 uncolored boxes.

I need to find the minimum number of days to color all boxes.

I thought to solve that using dynamic programming:

```<code>T(n,1) = min(T(n-1,1) + 1, T(n,2))
</code>```

But I am not sure how to create a DP matrix and if DP is correct approach at all.

答:
As Peter de Rivaz notes, an optimal solution is to have all robots replicate until the job can be finished in one day, taking 1 + ceil(log_2(n)) days total.

You could write a dynamic programming solution, and it would work, but here you can show that this strategy is guaranteed to minimize the number of days.

Suppose that there is an optimal strategy where robot r paints a box on day d. Then, after day d+2, robot r's output from the previous three days will be at most '3 boxes painted, 2 total robots (counting r itself)' or '1 box painted, 4 total robots.'

If instead the robot had replicated before painting, its output after day d+2 from the previous three days would be '4 boxes painted, 4 total robots', which is strictly better than the alternatives and thus also optimal. So you can conclude that unless you will be done after day d or day d+1, it is always optimal to replicate on day d.

Now, what if you're done after day d+1? It's still optimal to replicate on day d rather than painting both days-- you get two boxes painted in two days either way, meaning that our strategy is at least as good as any other strategy.

Body:
I have n boxes which should be colored. Each day robot can color one box or generate another robot, who works exactly as his parent starting next day.

i.e., if on Sunday I have one robot and 10 balls, on Monday:

There is one robot, 1 colored boxes and 9 uncolored boxes, or

There are 2 robots and 10 uncolored boxes.

I need to find the minimum number of days to color all boxes.

I thought to solve that using dynamic programming:

T(n,1) = min(T(n-1,1) + 1, T(n,2))

But I am not sure how to create a DP matrix and if DP is correct approach at all.


问:
How can I get the transaction hash from a contract call (AssemblyScript)?
I want to be able to return the transaction hash in some of my contract methods using near-sdk-as. I thought I could use context.blockIndex, but I assume this is something other than the transaction hash?

答:
You can't return tx hash from the contract method because the transaction is not finished at that point, you're still in it

the contract call itself, the one you make from any client, receives the transaction hash as part id the response value

see here for an example
https://github.com/Learn-NEAR/starter--near-api-js/blob/ffe12359f94aa8b558824a3f3ec1f4ba82c0e86a/contract-advanced.html#L54


问:
HTML Emails Rendering Text Centered in IE
I'm sending a HTML email from Outlook to my mail.live.com account. When I view the results in mail.live.com using Firefox the email looks ok, but when I use IE all the content is centered.

I have added lots of align=left  and inline CSS style='text-align:left' to control it but it doesn't make any difference.

When I load the HTML file directly into IE it's ok; only when viewing from my Live/Hotmail account it is skewed.

Has anyone had this issue?

```<code> <html>
 <body style='background:#333;font-family:arial;text-align:left;'>

        <style>

            #BlueStripe {

                color:#000000;
                background:#113399;
                width:800px;
                height:35px;

            }

            #Content {
                width:800px;

            }
            #LeftContentPanel {
                border:none;

                padding:20px;
                padding-top:5px;
            }

            #LeftContentPanel h1, h2, h3 {
                color:#113399;
                font-family:Arial,Verdana;
                font-weight:normal;
                margin-bottom:5px;

            }
            #LeftContentPanel p {
                margin-top:5px;
            }

            h1, h2 {
                font-weight:normal;
                font-size:22px;
                padding-bottom:0px;

            }
            #RightContentPanel {

                width:220px;
                padding:10px;

                margin-top:10px;
                margin-right:30px;

                color:#fff;

                font-weight:normal;

            }
            #RightContentPanel h1, h2 {
                font-weight:normal;
                font-size:20px;
                margin-top:5px;
                margin-bottom:-5px;

            }

            #RightContentPanel p {
                font-weight:normal;
                font-size:14px;

            }

            .edition {
                text-align:left;
                font-family:Arial,Verdana;
                font-weight:normal;
                font-size:16px;
                color:#113399;
                margin-left:10px;
                margin-top:15px;

            }

            #FooterText {
                color:#113399;
                font-size:12px;
            }

            p {
                text-align:left;

            }

    </style>

        <table border='0' Id='PageWidth' Style='border:0px;width:800px;background:#fff;text-align:left;' cellpadding=0 cellspacing=0 align='center'>
            <tr>
                <td>
                    <table border='0'  Style='border:0px;width:800px;' cellpadding=0 cellspacing=0 align='left'>

                        <tr Id='BlueStripe' Width='800'>
                            <td ColSpan='3'></td>
                        </tr>

                        <!-- Header -->
                        <tr id='LogoTitle' align='Left'>
                            <!--  Col 1/2 -->   <td align='left'>
                                                    <img src='logo.jpg' alt='club logo' />
                                                </td> <!-- Col 1 -->
                            <!--  Col 2/2 -->   <td class='Panel2' ColSpan='2'>
                                                    <br />
                                                    <img src='title.jpg' alt='club news' />
                                                    <br />
                                                    <br />
                                                    <p class='edition' align='left'>Edition 9 – September 2011</p></td> <!-- Col 2 -->
                        </tr>
                        <!-- Banner Image - Dumb Bells -->
                        <tr Id='BannerImage'  Style='width:800px;'>
                            <!--  Col 1/1 -->
                            <td ColSpan='3' Width='800px' Style='width:800px;text-align:left;' CellSpacing='0' CellPadding='0'  align='Left'>
                                <img src='banner.jpg' alt='Dumb Bells' Width='800px' />

                            </td> <!-- Col 1 -->
                        </tr>
                        <tr Id='Content' align='Left'>
                            <!--  Col 1/1 -->
                            <td ColSpan='3'>
                                <br />
                                <table id='ContentPanel' Style='margin-top:10px'>
                                    <tr  align='Left'>
                                        <td align='Left'>
                                            <table id='' Style='border:0;text-align:left' align='left'>
                                                <tr>
                                                    <td Id='LeftContentPanel' Width='460'>
                                                        <h1>Insert heading here</h1>
                                                        <p>
                                                            Vellant enes mo volupition eati amenima ximpor andis es mil mi,
                                                            optate cum in niatqui dellabo. Turiti quos debis demolen dustis
                                                            que peditat iorione quidignimin non con eaquatia nullore perit,
                                                            totat incimol orrum, coriassequo quia aut eos unt quia dolent
                                                            estemquodio odionseque esed que dolupta sperror sit quia que
                                                            pa dipsape llore, nitiis audi de nonse nisqui quia velit estem rem
                                                            quam rerum autem voluptiae atur?
                                                        </p>
                                                        <h1>Insert heading here</h1>
                                                        <p>
                                                            Feremos quisinte siment. Cium volorpo ressit re, omnisci as
                                                            autent as moluptas nonsece atquaessit eum dolut aut quis
                                                            nobisto quat aborem quis antempore, id moluptatur, sa que et
                                                            ea ium apis delignisi te si aut poribus ullaudae od quia conem
                                                            se verepud itatemporum ulparum re, volut velis eatis es accum
                                                            aut ratur, vende ius si doloriorum ent qui que velesciat que nam,
                                                            alitem ati a non remperorest restrum volentintem voluptatur am
                                                            rem eumqui quat et ea quiame quat.
                                                        </p>
                                                        <p>
                                                            Occatem poreium in rehentio eat el earia iur am, et laborio.
                                                            Itatur? Quiae estiorecese conseque niet estem as etusciur mos
                                                            ipsapid que videbit audit quid ut volupta sperias sequate ctotat
                                                            et et voluptis dellest, simus, secus aute quis iliquis si quia simus.
                                                        </p>

                                                        <div id='FooterText'>
                                                            more text here
                                                        </div>

                                                    </td>
                                                </tr>
                                            </table>

                                        </td>
                                        <td Width=5></td>
                                        <td valign='top' align='left' style='padding:15px;text-align:left'>
                                            <table  Id='RightContentPanel' Style='text-align:left;' >
                                                <tr style='padding:15px;text-align:left'>

                                                    <td style='margin-top:0px;padding:5px;padding:15px;text-align:left;padding-top:5px;   background-color:#113399;'>
                                                            <h1>Insert header here</h1>
                                                            <p align='left' style='text-align:left'>
                                                                Vellant enes mo volupition eati
                                                                amenima ximpor andis es mil
                                                                mi, optate cum in niatqui de
                                                                llabo. Turiti quos debis demo
                                                                len dustis que peditat iorione
                                                                quidignimin non con eaquatia
                                                                nullore perit, totat incimol or
                                                                rum, coriassequo quia aut eos
                                                                unt quia dolent estemquodio.
                                                            </p>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td height='35'>
                                                    </td>
                                                </tr>
                                                <tr>

                                                    <td Style='margin-top:30px;padding-top:5px;padding:5px;padding:15px;text-align:left;background-color:#ff3333;'>
                                                            <h1>Insert header here</h1>
                                                            <p>
                                                                Vellant enes mo volupition eati
                                                                amenima ximpor andis es mil
                                                                mi, optate cum in niatqui de
                                                                llabo. Turiti quos debis demo
                                                                len dustis que peditat iorione
                                                                quidignimin non con eaquatia
                                                                nullore perit, totat incimol or
                                                                rum, coriassequo quia aut eos
                                                                unt quia dolent estemquodio.
                                                            </p>

                                                    </td>
                                                </tr>
                                            </table>

                                        </td>
                                    </tr>
                                </table>

                            </td> <!-- End Col 1 -->

                        </tr>
                        <tr>
                            <td Id='BlueStripe' ColSpan='3'></td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
</body>
</code>```

Additional information from another user:

None of the answers so far seem to help. I had my top level stacked tables centered and all the nested tables aligned left with text-align:left; on all possible elements and it didn't change anything.

Then I removed all instances of centered text and tables throughout the code and it STILL renders with centered text in all web email clients in IE 9. Interestingly, if I send the email from Gmail or Yahoo in IE 9, it renders properly (without having to add all the extra align/text-align lefts). However, this email must originate from Outlook, so that isn't a feasible workaround in this case.

答:
There is probably a conflicting id/class in your html though that should have resulted in the same effect in all browsers.

It is impossible to tell you what is going on in your browser. Try inspecting the elements with the browsers debugging tools, this should tell you what styles are being applied to them and they should reveal where the text-align is coming from.

In Internet Explorer the shortcut for the debugging tool is F12, use the arrow in the left top of that window to be able to focus on certain elements.

Body:
I'm sending a HTML email from Outlook to my mail.live.com account. When I view the results in mail.live.com using Firefox the email looks ok, but when I use IE all the content is centered.

I have added lots of align=left  and inline CSS style='text-align:left' to control it but it doesn't make any difference.

When I load the HTML file directly into IE it's ok; only when viewing from my Live/Hotmail account it is skewed.

Has anyone had this issue?

Edition 9 – September 2011

Insert heading here

                                                            Vellant enes mo volupition eati amenima ximpor andis es mil mi,
                                                            optate cum in niatqui dellabo. Turiti quos debis demolen dustis
                                                            que peditat iorione quidignimin non con eaquatia nullore perit,
                                                            totat incimol orrum, coriassequo quia aut eos unt quia dolent
                                                            estemquodio odionseque esed que dolupta sperror sit quia que
                                                            pa dipsape llore, nitiis audi de nonse nisqui quia velit estem rem
                                                            quam rerum autem voluptiae atur?

Insert heading here

                                                            Feremos quisinte siment. Cium volorpo ressit re, omnisci as
                                                            autent as moluptas nonsece atquaessit eum dolut aut quis
                                                            nobisto quat aborem quis antempore, id moluptatur, sa que et
                                                            ea ium apis delignisi te si aut poribus ullaudae od quia conem
                                                            se verepud itatemporum ulparum re, volut velis eatis es accum
                                                            aut ratur, vende ius si doloriorum ent qui que velesciat que nam,
                                                            alitem ati a non remperorest restrum volentintem voluptatur am
                                                            rem eumqui quat et ea quiame quat.

                                                            Occatem poreium in rehentio eat el earia iur am, et laborio.
                                                            Itatur? Quiae estiorecese conseque niet estem as etusciur mos
                                                            ipsapid que videbit audit quid ut volupta sperias sequate ctotat
                                                            et et voluptis dellest, simus, secus aute quis iliquis si quia simus.

                                                            more text here

Insert header here

                                                                Vellant enes mo volupition eati
                                                                amenima ximpor andis es mil
                                                                mi, optate cum in niatqui de
                                                                llabo. Turiti quos debis demo
                                                                len dustis que peditat iorione
                                                                quidignimin non con eaquatia
                                                                nullore perit, totat incimol or
                                                                rum, coriassequo quia aut eos
                                                                unt quia dolent estemquodio.

Insert header here

                                                                Vellant enes mo volupition eati
                                                                amenima ximpor andis es mil
                                                                mi, optate cum in niatqui de
                                                                llabo. Turiti quos debis demo
                                                                len dustis que peditat iorione
                                                                quidignimin non con eaquatia
                                                                nullore perit, totat incimol or
                                                                rum, coriassequo quia aut eos
                                                                unt quia dolent estemquodio.

Additional information from another user:

None of the answers so far seem to help. I had my top level stacked tables centered and all the nested tables aligned left with text-align:left; on all possible elements and it didn't change anything.

Then I removed all instances of centered text and tables throughout the code and it STILL renders with centered text in all web email clients in IE 9. Interestingly, if I send the email from Gmail or Yahoo in IE 9, it renders properly (without having to add all the extra align/text-align lefts). However, this email must originate from Outlook, so that isn't a feasible workaround in this case.


问:
Android Studio Bumblebee: Gradle sync failed
After upgrading to Bumblebee, some of my projects now show this:

```<code>The specified Gradle installation directory '/Applications/Android Studio.app/Contents/gradle/gradle-2.14.1' does not exist.
</code>```

How can I solved this issue? I have tried some old solutions (eg Android Studio - Gradle sync error on gradle-diagnostics-X.X.X.jar) and does not seem to work. Also tried clear cache and restart.

答:
Go to Android Studio Preferences → Build, Execute, Deployment → Build Tools → Gradle.

Change the "Use Gradle from:" option from "Specified location" to your properties file.

(Screenshot provided by Mike)

Then, click "Try Again".

Body:
After upgrading to Bumblebee, some of my projects now show this:

The specified Gradle installation directory '/Applications/Android Studio.app/Contents/gradle/gradle-2.14.1' does not exist.

How can I solved this issue? I have tried some old solutions (eg Android Studio - Gradle sync error on gradle-diagnostics-X.X.X.jar) and does not seem to work. Also tried clear cache and restart.


答:
Method-1

If you are scanning from the first element to the last element, you should store the result in a variable.

public static int lastIndexOf(int[] arr, int x)
{
    int resultIndex = -1;

    for(int i = 0; i < arr.length; i++)
        if(arr[i] == x)
            resultIndex = i;

    return resultIndex;
}
```
<h5>Method-2</h5>
<p>If you're scanning from the last element to the first element, you can return the result directly from the method.</p>
<pre class="lang-java prettyprint-override"><code>public static int lastIndexOf(int[] arr, int x)
{
    for(int i = arr.length - 1 ; i >= 0; --i)
        if(arr[i] == x)
            return i;

    return -1;
}
</code>```

Title: Finding the last occurrence of x in the array

Body:
Method-1

If you are scanning from the first element to the last element, you should store the result in a variable.

public static int lastIndexOf(int[] arr, int x)
{
    int resultIndex = -1;

    for(int i = 0; i < arr.length; i++)
        if(arr[i] == x)
            resultIndex = i;

    return resultIndex;
}

Method-2

If you're scanning from the last element to the first element, you can return the result directly from the method.

public static int lastIndexOf(int[] arr, int x)
{
    for(int i = arr.length - 1 ; i >= 0; --i)
        if(arr[i] == x)
            return i;

    return -1;
}


问:
How to hide button when another button is clicked in React?
I have 2 buttons displayed on the page Display and Hide. When the Hide button is clicked I want to hide the Display button.

I am using useState. To some extent, I am able to hide Display more text present on the button, but not the whole button

Initial state- https://ibb.co/jMdH3tq

When the Hide button is clicked, Display text disappear but the button stays- https://ibb.co/Jm5FPNy

```<code>const [show, setShow] = useState(false);

const hideButton = () => {
  setShow(true);
};
</code>```

Hide button code:

```<code><div>
  <button
    style={{ marginLeft: '190px' }}
    className="button button1"
    onClick={() => {
      clearBooks();
      hideButton();
    }}
  >
    Hide
  </button>
</div>;
</code>```

Show button code:

```<code><button
  className="button button1"
  style={{ marginLeft: '190px', width: '124px', height: '50px' }}
  onClick={fetchBooks}
>
  {!show && 'Display more'}
</button>;
</code>```

答:
If you are trying to hide the button do the following: I noticed the show state is set to false initially and you are setting it to true on click. Do you want the opposite, true as initial state hide when selecting the button?

Based on that, adjust show accordingly either show or !show

```<code>{show &&
<button
    className="button button1"
    style={{ marginLeft: "190px", width: "124px", height: "50px" }}
    onClick={fetchBooks}
  >
  </button>
}
</code>```

Body:
I have 2 buttons displayed on the page Display and Hide. When the Hide button is clicked I want to hide the Display button.

I am using useState. To some extent, I am able to hide Display more text present on the button, but not the whole button

Initial state- https://ibb.co/jMdH3tq

When the Hide button is clicked, Display text disappear but the button stays- https://ibb.co/Jm5FPNy

const [show, setShow] = useState(false);

const hideButton = () => {
  setShow(true);
};

Hide button code:

  <button
    style={{ marginLeft: '190px' }}
    className="button button1"
    onClick={() => {
      clearBooks();
      hideButton();
    }}
  >
    Hide
  </button>

;

Show button code:

<button
  className="button button1"
  style={{ marginLeft: '190px', width: '124px', height: '50px' }}
  onClick={fetchBooks}
>
  {!show && 'Display more'}
</button>;

Body:
If you are trying to hide the button do the following: I noticed the show state is set to false initially and you are setting it to true on click. Do you want the opposite, true as initial state hide when selecting the button?

Based on that, adjust show accordingly either show or !show

{show &&
<button
    className="button button1"
    style={{ marginLeft: "190px", width: "124px", height: "50px" }}
    onClick={fetchBooks}
  >
  </button>
}


问:
How to send json request to rails using jquery
I would like to send JSON post request to rails 3 server. I have following ajax request:

$.ajax({
                 type: 'POST',

                 contentType: "application/json",

                 url: url,
                 data: {email: "example@test.com", password: "password"},

                 success: onSuccess,

                 error: onError,

                 dataType: "json"

                 });

However the rails server receive the data as following:

{"_json"=>["object Object"]}

Where I want it to receive it as:

{"email"=>"exmaple@test.com", "password"=>"[FILTERED]"}

I think this is happening because the jquery wraps the data with _json object if the content type is json.

Does anybody know how I should do this?

答:
This turns out to be because of bugs in old version of jquery. I now user jquery version 1.5 and send post request as follow:

```<code>$.post(url, { email: emailVal, password: passwordVal }, callback, "json").error(errorHandler);
</code>```

It now works perfectly fine.

Body:
This turns out to be because of bugs in old version of jquery. I now user jquery version 1.5 and send post request as follow:

$.post(url, { email: emailVal, password: passwordVal }, callback, "json").error(errorHandler);

It now works perfectly fine.


问:
How to record a canvas + audio with no new drawing on the canvas
I want to record a video from some script running on an HTML canvas and simultaneously record the audio from the microphone. I am using canvas.captureStream() to create a video stream from the canvas. Then I create an audio stream from getUserMedia() and mix both streams in a single one which is passed to a new MediaRecorder.

The problem is that, by default, no frame is captured in the canvas stream if nothing is painted to the canvas. So the video and audio are desynchronized in the parts where the canvas is inactive.

The code I am using looks like this:

let recording = false;
let mediaRecorder;
let chunks = [];

let newStream, canvasStream

let constrains = {
  audio: {
    channelCount: { ideal: 2, min: 1 },
    sampleRate: 48000,
    sampleSize: 16,
    volume: 1,
    echoCancellation: true,
    noiseSuppression: true,
    autoGainControl: true,
  },
  video: false
};

recButton.addEventListener("click", () => {
  recording = !recording;
  if (recording) {
    recButton.textContent = "Click to Stop";
    recButton.style.color = "red";
    canvasStream = canvas.captureStream(40); // ---> captureStream()

    navigator.mediaDevices.getUserMedia(constrains) // ---> audioStream
      .then(audioStream => {

        canvasStream.addTrack(audioStream.getTracks()[0]);   // --> joint the two streams

        mediaRecorder = new MediaRecorder(canvasStream, {
          mimeType: 'video/webm; codecs=vp9',
          // ignoreMutedMedia: false
        });

        mediaRecorder.ondataavailable = e => {
          if (e.data.size > 0) {
            chunks.push(e.data);  // chunks = [];   already defined above....
          }
        };
        mediaRecorder.start();
      })
      .catch(err => {
        console.log(err.name, err.message);
      });
  } else {
    recButton.textContent = "Record";
    recButton.style.color = "black";
    mediaRecorder.stop()

    stopTracks(canvasStream);  // function stop defined below
    console.log(mediaRecorder.state)
    setTimeout(() => {                // why this is necessary?
      const blob = new Blob(chunks, {
        type: "video/mp4"
      });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "recording.mp4";
      a.click();
      URL.revokeObjectURL(url);
    }, 200);
  }
});

let stopTracks = stream => stream.getTracks().forEach(track => track.stop());
```

答:
That's a bit of a Chrome bug since even if the video track should indeed have produced no data in this case, the audio track has and the MediaRecorder should have captured it.

The only way to workaround this is to perform a new drawing on the canvas at least in the same painting frame as your call to canvas.captureStream().

With a 2D context, the less intrusive way to do that is to draw a transparent 1x1 rectangle.

let recording = false;
let mediaRecorder;
const chunks = [];

let newStream, canvasStream

const constrains = {
  audio: {
    channelCount: { ideal: 2, min: 1 },
    sampleRate: 48000,
    sampleSize: 16,
    volume: 1,
    echoCancellation: true,
    noiseSuppression: true,
    autoGainControl: true,
  },
  video: false
};

recButton.addEventListener("click", () => {
  recording = !recording;
  if (recording) {
    recButton.textContent = "Click to Stop";
    recButton.style.color = "red";
    canvasStream = canvas.captureStream(40);
    // force activate the Canvas track
    forceEmptyDrawing(canvas);
    navigator.mediaDevices.getUserMedia(constrains) // ---> audioStream
      .then(audioStream => {

        canvasStream.addTrack(audioStream.getTracks()[0]); // --> joint the two streams
        mediaRecorder = new MediaRecorder(canvasStream, {
          // don't forget the audio codec
          mimeType: "video/webm; codecs=vp9,opus",
          // ignoreMutedMedia: false
        });

        mediaRecorder.ondataavailable = e => {
          if (e.data.size > 0) {
            chunks.push(e.data);
          }
        };
        mediaRecorder.start(10);
      })
      .catch(err => {
        console.log(err.name, err.message);
      });
  } else {
    recButton.textContent = "Record";
    recButton.style.color = "black";
    mediaRecorder.stop()
    // wait for the stop event
    // don't rely on some magic timeout
    mediaRecorder.onstop = () => {
      // only when the recorder is completely stopped
      // you can stop the tracks
      stopTracks(canvasStream);
      const blob = new Blob(chunks, {
        type: "video/webm" // you asked for webm, not mp4
      });
      // just to verify we did record something
      console.log(`recorded a ${ blob.size }b file`);
    };
  }
});

const stopTracks = stream => stream.getTracks().forEach(track => track.stop());

// draws a 1x1 transparent rectangle
function forceEmptyDrawing(canvas) {
  const ctx = canvas.getContext("2d");
  const alpha = ctx.globalAlpha;
  ctx.globalAlpha = 0;
  ctx.fillRect(0, 0, 1, 1);
  ctx.globalAlpha = alpha;
}
```

As a fiddle since StackSnippets can't use gUM (for Chrome only, Firefox and Safari don't support the provided mimeType).

Body:
That's a bit of a Chrome bug since even if the video track should indeed have produced no data in this case, the audio track has and the MediaRecorder should have captured it.

The only way to workaround this is to perform a new drawing on the canvas at least in the same painting frame as your call to canvas.captureStream().

With a 2D context, the less intrusive way to do that is to draw a transparent 1x1 rectangle.

let recording = false;
let mediaRecorder;
const chunks = [];

let newStream, canvasStream

const constrains = {
  audio: {
    channelCount: { ideal: 2, min: 1 },
    sampleRate: 48000,
    sampleSize: 16,
    volume: 1,
    echoCancellation: true,
    noiseSuppression: true,
    autoGainControl: true,
  },
  video: false
};

recButton.addEventListener("click", () => {
  recording = !recording;
  if (recording) {
    recButton.textContent = "Click to Stop";
    recButton.style.color = "red";
    canvasStream = canvas.captureStream(40);
    // force activate the Canvas track
    forceEmptyDrawing(canvas);
    navigator.mediaDevices.getUserMedia(constrains) // ---> audioStream
      .then(audioStream => {

        canvasStream.addTrack(audioStream.getTracks()[0]); // --> joint the two streams
        mediaRecorder = new MediaRecorder(canvasStream, {
          // don't forget the audio codec
          mimeType: "video/webm; codecs=vp9,opus",
          // ignoreMutedMedia: false
        });

        mediaRecorder.ondataavailable = e => {
          if (e.data.size > 0) {
            chunks.push(e.data);
          }
        };
        mediaRecorder.start(10);
      })
      .catch(err => {
        console.log(err.name, err.message);
      });
  } else {
    recButton.textContent = "Record";
    recButton.style.color = "black";
    mediaRecorder.stop()
    // wait for the stop event
    // don't rely on some magic timeout
    mediaRecorder.onstop = () => {
      // only when the recorder is completely stopped
      // you can stop the tracks
      stopTracks(canvasStream);
      const blob = new Blob(chunks, {
        type: "video/webm" // you asked for webm, not mp4
      });
      // just to verify we did record something
      console.log(`recorded a ${ blob.size }b file`);
    };
  }
});

const stopTracks = stream => stream.getTracks().forEach(track => track.stop());

// draws a 1x1 transparent rectangle
function forceEmptyDrawing(canvas) {
  const ctx = canvas.getContext("2d");
  const alpha = ctx.globalAlpha;
  ctx.globalAlpha = 0;
  ctx.fillRect(0, 0, 1, 1);
  ctx.globalAlpha = alpha;
}

As a fiddle since StackSnippets can't use gUM (for Chrome only, Firefox and Safari don't support the provided mimeType).


问:
Multer give undefined for req.file
I'm make api to upload files using node js.

i using multer for handle multipart/form-data
but when i console.log(req.file) it appears undefined

Route

```<code>const uploadController = require('../controller/upload.server.controller');
const multer = require('multer');

const upload = multer({ dest: 'uploads/' });

/**
 * Routes
 */
module.exports = function (app) {
  app
    .route('/api/upload')
    .post(upload.single('image'), uploadController.upload);
};
</code>```

Controller

```<code>exports.upload = async function (req, res) {
    console.log(req.file);
};
</code>```

my request with postman

答:
Try this:</p>
```<code>app.post('/api/upload', upload.single('image'), function (req, res, next) {
  console.log(req.file);
})
</code>```

Title: Multer give undefined for req.file

Body:
I'm make api to upload files using node js.

i using multer for handle multipart/form-data
but when i console.log(req.file) it appears undefined

Route

const uploadController = require('../controller/upload.server.controller');
const multer = require('multer');

const upload = multer({ dest: 'uploads/' });

/**
 * Routes
 */
module.exports = function (app) {
  app
    .route('/api/upload')
    .post(upload.single('image'), uploadController.upload);
};

Controller

exports.upload = async function (req, res) {
    console.log(req.file);
};

my request with postman

Body:
Try this:

app.post('/api/upload', upload.single('image'), function (req, res, next) {
  console.log(req.file);
})


问:
WSAStartup link error
I am using EVC++ and I want to compile the program which uses the sockets.
I've included

#include <winsock2.h>

And I have included in project properties a path to Ws2.lib
But still get the error at link step:

error LNK2019: unresolved external symbol WSAStartup referenced in function ...

How to resolve this problem?

答:
In my case, that problem was solved by adding
#pragma comment(lib, "ws2_32.lib")

ContentLicense: CC BY-SA 2.5

Title: WSAStartup link error


问:
Accessing Firebase value
I am struggling with a simple JSON from Firebase and I am trying to access the value inside it. But can't seems to wrap my head around, I am trying to access the apiHash and apiId. Any help will be great! Thanks

This is the json retuned by Firebase.

```<code>Mv9ALVaVEwa0nGyYWeo:{
apiHash: '6962d35961356a5',
apiId: 9506201
}
</code>```

The code to get the json above

```<code>async function queryData(_mobileNo){
  const ref  = admin.database().ref("users/");
  const snapshot = await ref.orderByChild("mobileNo").equalTo(_mobileNo).once('value');
  return snapshot.val();
}
</code>```

The Firebase realtime data structure

答:
You can try using Object.values() as shown below:

// data = snapshot.val()
const data = {
  randomKey: {
    apiHash: "value"
  }
};

console.log(Object.values(data)[0]);```

Title: Accessing Firebase value

Body:
I am struggling with a simple JSON from Firebase and I am trying to access the value inside it. But can't seems to wrap my head around, I am trying to access the apiHash and apiId. Any help will be great! Thanks

This is the json retuned by Firebase.

Mv9ALVaVEwa0nGyYWeo:{
apiHash: '6962d35961356a5',
apiId: 9506201
}

The code to get the json above

async function queryData(_mobileNo){
  const ref  = admin.database().ref("users/");
  const snapshot = await ref.orderByChild("mobileNo").equalTo(_mobileNo).once('value');
  return snapshot.val();
}

The Firebase realtime data structure


问:
Creating a JSON object from Google Sheets
I am trying to learn AppScript and I am using Google Sheets as an example. I want to create a simple JSON object using some data populated in the Sheet.

Table Example

```
Name    ID   Price   Qty
ABC     123  100      1
DEF     342   56      2
HIJ     233   90      3
IJK     213   68      5
```

I want the JSON out to be something like

```<code>[
  {
    "Name": "ABC",
    "ID": "123",
    "Price": 100,
    "Qty": 1
  },
  {
    "Name": "DEF",
    "ID": "342",
    "Price": 56,
    "Qty": 2
  },
  {
    "Name": "HIJ",
    "ID": "233",
    "Price": 90,
    "Qty": 3
  },
  {
    "Name": "IJK",
    "ID": "213",
    "Price": 68,
    "Qty": 5
  }
]
</code>```

I started by following this Youtube tutorial : https://www.youtube.com/watch?v=TQzPIVJf6-w. However that video talks about creating each column header as a the object. Where as i want the Column name to be the key and the Row value to be the value.

Here is my current AppScript Code

```<code>function doGet() {
  var result={};
  var rewards = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1')
  .getDataRange()
  .getValues();

  result.rewardObj = makeObject(rewards);
  //Logger.log(result.rewardObj);
  return ContentService.createTextOutput(JSON.stringify(result))
  .setMimeType(ContentService.MimeType.JSON)

}

function makeObject(multiArray)
{
  var obj = {};
  var colNames = multiArray.shift();
  var rowNames = multiArray.slice(0,1);
  var rowCount = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getLastRow();
  var colCount = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getLastColumn();

  for(var j=0;j<4;j++)
  {
    for(var i=0;i<4;i++)
      {
        //obj[colNames] = rowNames.map(function(item){return item[i];});
        obj[colNames[j][i]] = multiArray[j][i];
      }
  }
  Logger.log(rowCount)
  Logger.log(colCount)
  Logger.log(multiArray[57][12]);
  return obj;
}
</code>```

The output is a single object

```<code>{"rewardObj":{"Name":"ABC","ID":"123","Price":"100","Qty":"1"}}
</code>```

PS: I am not a programmer, I am just learning some scripting in a hackey way. Apologies for not knowing the basics :)

答:
edit 2022 : for headers of columns and headers of rows as follows

yourJsonName
col1
col2
col3
col4

row1
1
2
3

row2
4

6
4

row3
7
8
9
8

try

```<code>function myJson() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('YourSheetName');
  var [headers, ...rows] = sheet.getDataRange().getValues();
  var jsonString = `var ${sheet.getRange(1,1).getValue()} = ${JSON.stringify(data2json(headers, rows))}`
  Logger.log (jsonString)
}
function data2json(headers, rows) {
  var obj = {},items = {};
  for (var i in rows) {
    obj = {};
    for (var col = 1; col < headers.length; col++) {
      if(rows[i][col]!='') obj[headers[col]] = rows[i][col];
    }
    items[rows[i][0]] = obj
  }
  return items;
}
</code>```

var [headers, ...rows] = [['yourJsonName', 'col1', 'col2', 'col3', 'col4'], ['row1', 1.0, 2.0, 3.0, ], ['row2', 4.0, , 6.0, 4.0], ['row3', 7.0, 8.0, 9.0, 8.0]]
console.log (`var ${headers[0]} = ${JSON.stringify(data2json(headers, rows))}`)
function data2json(headers, rows) {
  var obj = {},items = {};
  for (var i in rows) {
    obj = {};
    for (var col = 1; col < headers.length; col++) {
      if(rows[i][col]!='') obj[headers[col]] = rows[i][col];
    }
    items[rows[i][0]] = obj
  }
  return items;
}```
</div>
</div>
</p>
<p>with saving in drive ... adapt names as necessary (YourSheetName, YourFolderName, YourFileName)</p>
```function myJson() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('YourSheetName');
  var [headers, ...rows] = sheet.getDataRange().getValues();
  var jsonString = `var ${sheet.getRange(1,1).getValue()} = ${JSON.stringify(data2json(headers, rows))}`
  var folders = DriveApp.getFoldersByName('YourFolderName');
  if (folders.hasNext()) {
    var folder = folders.next();
    saveData(folder, 'YourFileName.json',jsonString);
  }
}
function data2json(headers, rows) {
  var obj = {},items = {};
  for (var i in rows) {
    obj = {};
    for (var col = 1; col < headers.length; col++) {
      if(rows[i][col]!='') obj[headers[col]] = rows[i][col];
    }
    items[rows[i][0]] = obj
  }
  return items;
}
function saveData(folder, fileName, content) {
  var children = folder.getFilesByName(fileName);
  var file = null;
  if (children.hasNext()) {
    file = children.next();
    file.setContent(content);
  } else {
    file = folder.createFile(fileName, content);
  }
  Logger.log(file.getUrl())
}
```

Body:
I am trying to learn AppScript and I am using Google Sheets as an example. I want to create a simple JSON object using some data populated in the Sheet.

Table Example

Name    ID   Price   Qty
ABC     123  100      1
DEF     342   56      2
HIJ     233   90      3
IJK     213   68      5

I want the JSON out to be something like

[
  {
    "Name": "ABC",
    "ID": "123",
    "Price": 100,
    "Qty": 1
  },
  {
    "Name": "DEF",
    "ID": "342",
    "Price": 56,
    "Qty": 2
  },
  {
    "Name": "HIJ",
    "ID": "233",
    "Price": 90,
    "Qty": 3
  },
  {
    "Name": "IJK",
    "ID": "213",
    "Price": 68,
    "Qty": 5
  }
]

I started by following this Youtube tutorial : https://www.youtube.com/watch?v=TQzPIVJf6-w. However that video talks about creating each column header as a the object. Where as i want the Column name to be the key and the Row value to be the value.

Here is my current AppScript Code

function doGet() {
  var result={};
  var rewards = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1')
  .getDataRange()
  .getValues();

  result.rewardObj = makeObject(rewards);
  //Logger.log(result.rewardObj);
  return ContentService.createTextOutput(JSON.stringify(result))
  .setMimeType(ContentService.MimeType.JSON)

}

function makeObject(multiArray)
{
  var obj = {};
  var colNames = multiArray.shift();
  var rowNames = multiArray.slice(0,1);
  var rowCount = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getLastRow();
  var colCount = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getLastColumn();

  for(var j=0;j<4;j++)
  {
    for(var i=0;i<4;i++)
      {
        //obj[colNames] = rowNames.map(function(item){return item[i];});
        obj[colNames[j][i]] = multiArray[j][i];
      }
  }
  Logger.log(rowCount)
  Logger.log(colCount)
  Logger.log(multiArray[57][12]);
  return obj;
}

The output is a single object

{"rewardObj":{"Name":"ABC","ID":"123","Price":"100","Qty":"1"}}

PS: I am not a programmer, I am just learning some scripting in a hackey way. Apologies for not knowing the basics :)

Body:
edit 2022 : for headers of columns and headers of rows as follows

yourJsonName
col1
col2
col3
col4

row1
1
2
3

row2
4

6
4

row3
7
8
9
8

try

function myJson() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('YourSheetName');
  var [headers, ...rows] = sheet.getDataRange().getValues();
  var jsonString = `var ${sheet.getRange(1,1).getValue()} = ${JSON.stringify(data2json(headers, rows))}`
  Logger.log (jsonString)
}
function data2json(headers, rows) {
  var obj = {},items = {};
  for (var i in rows) {
    obj = {};
    for (var col = 1; col < headers.length; col++) {
      if(rows[i][col]!='') obj[headers[col]] = rows[i][col];
    }
    items[rows[i][0]] = obj
  }
  return items;
}

var [headers, ...rows] = [['yourJsonName', 'col1', 'col2', 'col3', 'col4'], ['row1', 1.0, 2.0, 3.0, ], ['row2', 4.0, , 6.0, 4.0], ['row3', 7.0, 8.0, 9.0, 8.0]]
console.log (`var ${headers[0]} = ${JSON.stringify(data2json(headers, rows))}`)
function data2json(headers, rows) {
  var obj = {},items = {};
  for (var i in rows) {
    obj = {};
    for (var col = 1; col < headers.length; col++) {
      if(rows[i][col]!='') obj[headers[col]] = rows[i][col];
    }
    items[rows[i][0]] = obj
  }
  return items;
}

with saving in drive ... adapt names as necessary (YourSheetName, YourFolderName, YourFileName)

function myJson() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('YourSheetName');
  var [headers, ...rows] = sheet.getDataRange().getValues();
  var jsonString = `var ${sheet.getRange(1,1).getValue()} = ${JSON.stringify(data2json(headers, rows))}`
  var folders = DriveApp.getFoldersByName('YourFolderName');
  if (folders.hasNext()) {
    var folder = folders.next();
    saveData(folder, 'YourFileName.json',jsonString);
  }
}
function data2json(headers, rows) {
  var obj = {},items = {};
  for (var i in rows) {
    obj = {};
    for (var col = 1; col < headers.length; col++) {
      if(rows[i][col]!='') obj[headers[col]] = rows[i][col];
    }
    items[rows[i][0]] = obj
  }
  return items;
}
function saveData(folder, fileName, content) {
  var children = folder.getFilesByName(fileName);
  var file = null;
  if (children.hasNext()) {
    file = children.next();
    file.setContent(content);
  } else {
    file = folder.createFile(fileName, content);
  }
  Logger.log(file.getUrl())
}


问:
how to play background music in Asterisk AGI while some process is Going on in background to remove the silence during execution
I am using python 2 in asterisk 2 there is a section where code listen to callers audio and process the audio. During the process there is a silence of 15 sec before the audio is played. I want to add a music during the processing of audio. Is there a way to do this.
the extension.config is like this

```<code>[autoattendant2]
exten => 5555,1,same=>n,Answer()
same=> n, AGI(/root/code_base/Queue/code2.py)
same=>n,hangup()

</code>```

Below is the python code

```<code>#!/usr/bin/env python2
import sys
import re
import time
import random
import subprocess
import requests
import json
from datetime import datetime

    env = {}
    tests = 0;
    while 1:
       line = sys.stdin.readline().strip()
       if line == '':
          break
       key,data = line.split(':')
       if key[:4] <> 'agi_':
          #skip input that doesn't begin with agi_
          sys.stderr.write("Did not work!\n");
          sys.stderr.flush()
          continue
       key = key.strip()
       data = data.strip()
       if key <> '':
          env[key] = data

    sys.stderr.write("AGI Environment Dump:\n");
    sys.stderr.flush()
    for key in env.keys():
       sys.stderr.write(" -- %s = %s\n" % (key, env[key]))
       sys.stderr.flush()

    def checkresult (params):
       params = params.rstrip()
       if re.search('^200',params):
          result = re.search('result=(\d+)',params)
          if (not result):
             sys.stderr.write("FAIL ('%s')\n" % params)
             sys.stderr.flush()
             return -1
          else:
             result = result.group(1)
             #debug("Result:%s Params:%s" % (result, params))
             sys.stderr.write("PASS (%s)\n" % result)
             sys.stderr.flush()
             return result
       else:
          sys.stderr.write("FAIL (unexpected result '%s')\n" % params)
          sys.stderr.flush()
          return -2

    def change_file(path, cid):
    # one of the process example
       filename = 'complain{0}'.format(cid)
       #filename =
       input_file = path + '/' + filename + '.gsm'
       output_file = path + '/' + filename + '.wav'
       #command = "sox {} -r 8000 -c 1 {}".format(input_file, output_file)
       command = "sox {} -b 16 -r 44100 -c 1  {} trim 0 7 vol 2".format(input_file, output_file)
       subprocess.call(command, shell=True)
       pbcheck = requests.get("http://127.0.0.1:8000/STT_complaint/", params = {"address" : output_file, "lang" : language, "cid":cid, "phone":callerid, "start_time":now})
       res = pbcheck.content
       res2 = res.replace('"', "")

       return res2
    def run_cmd(cmd):
    #This runs the general command
       sys.stderr.write(cmd)
       sys.stderr.flush()
       sys.stdout.write(cmd)
       sys.stdout.flush()
       result = sys.stdin.readline().strip()
       checkresult(result)

    #language = "ben"
# asking problem recorded audio
    cmd_streaming = "STREAM FILE /root/code_base/recorded_voices/{0}/plz_tell_problem \"\"\n".format(language, language)
    run_cmd(cmd_streaming)
# listening to caller / recording caller voice
    cmd_record = "RECORD FILE {0}/complain{1} gsm 1234 {2} s=3 \"\"\n".format(fixed_path, cid, 15)
    run_cmd(cmd_record)
  #processing audio
    processed_output = change_file(path , cid) # while this is executing ad giving output i want to play wait_music and then stop to run
    # while processing play this
    cmd_streaming = "STREAM FILE /root/code_base/recorded_voices/wait_music  \"\"\n".format(language, language)
    run_cmd(cmd_streaming)
    # once output received (processed_output) play next audio

    cmd_streaming = "STREAM FILE /root/code_base/recorded_voices/next_instruction  \"\"\n")
    run_cmd(cmd_streaming)
</code>```

答:
For that asterisk AGI have the special command "SET MUSIC ON"

https://wiki.asterisk.org/wiki/display/AST/Asterisk+18+AGICommand_set+music

Set waiting tone for asterisk agi function processing

Body:
I am using python 2 in asterisk 2 there is a section where code listen to callers audio and process the audio. During the process there is a silence of 15 sec before the audio is played. I want to add a music during the processing of audio. Is there a way to do this.
the extension.config is like this

[autoattendant2]
exten => 5555,1,same=>n,Answer()
same=> n, AGI(/root/code_base/Queue/code2.py)
same=>n,hangup()

Below is the python code

#!/usr/bin/env python2
import sys
import re
import time
import random
import subprocess
import requests
import json
from datetime import datetime

    env = {}
    tests = 0;
    while 1:
       line = sys.stdin.readline().strip()
       if line == '':
          break
       key,data = line.split(':')
       if key[:4] <> 'agi_':
          #skip input that doesn't begin with agi_
          sys.stderr.write("Did not work!\n");
          sys.stderr.flush()
          continue
       key = key.strip()
       data = data.strip()
       if key <> '':
          env[key] = data

    sys.stderr.write("AGI Environment Dump:\n");
    sys.stderr.flush()
    for key in env.keys():
       sys.stderr.write(" -- %s = %s\n" % (key, env[key]))
       sys.stderr.flush()

    def checkresult (params):
       params = params.rstrip()
       if re.search('^200',params):
          result = re.search('result=(\d+)',params)
          if (not result):
             sys.stderr.write("FAIL ('%s')\n" % params)
             sys.stderr.flush()
             return -1
          else:
             result = result.group(1)
             #debug("Result:%s Params:%s" % (result, params))
             sys.stderr.write("PASS (%s)\n" % result)
             sys.stderr.flush()
             return result
       else:
          sys.stderr.write("FAIL (unexpected result '%s')\n" % params)
          sys.stderr.flush()
          return -2

    def change_file(path, cid):
    # one of the process example
       filename = 'complain{0}'.format(cid)
       #filename =
       input_file = path + '/' + filename + '.gsm'
       output_file = path + '/' + filename + '.wav'
       #command = "sox {} -r 8000 -c 1 {}".format(input_file, output_file)
       command = "sox {} -b 16 -r 44100 -c 1  {} trim 0 7 vol 2".format(input_file, output_file)
       subprocess.call(command, shell=True)
       pbcheck = requests.get("http://127.0.0.1:8000/STT_complaint/", params = {"address" : output_file, "lang" : language, "cid":cid, "phone":callerid, "start_time":now})
       res = pbcheck.content
       res2 = res.replace('"', "")

       return res2
    def run_cmd(cmd):
    #This runs the general command
       sys.stderr.write(cmd)
       sys.stderr.flush()
       sys.stdout.write(cmd)
       sys.stdout.flush()
       result = sys.stdin.readline().strip()
       checkresult(result)

    #language = "ben"
# asking problem recorded audio
    cmd_streaming = "STREAM FILE /root/code_base/recorded_voices/{0}/plz_tell_problem \"\"\n".format(language, language)
    run_cmd(cmd_streaming)
# listening to caller / recording caller voice
    cmd_record = "RECORD FILE {0}/complain{1} gsm 1234 {2} s=3 \"\"\n".format(fixed_path, cid, 15)
    run_cmd(cmd_record)
  #processing audio
    processed_output = change_file(path , cid) # while this is executing ad giving output i want to play wait_music and then stop to run
    # while processing play this
    cmd_streaming = "STREAM FILE /root/code_base/recorded_voices/wait_music  \"\"\n".format(language, language)
    run_cmd(cmd_streaming)
    # once output received (processed_output) play next audio

    cmd_streaming = "STREAM FILE /root/code_base/recorded_voices/next_instruction  \"\"\n")
    run_cmd(cmd_streaming)


答: Try using req.file as per the docs source: multer

Title: Multer give undefined for req.file


问:
Non-nullable instance field '_controller' must be initialized

The method 'TapBar' isn't defined for the type '_HomescreenState'.

Non-nullable instance field '_controller' must be initialized.

I'm getting above errors in my code.. how to correct those. appreciate your help on this..

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

class Homescreen extends StatefulWidget {
  Homescreen({ Key? key }) : super(key: key);

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

class _HomescreenState extends State<Homescreen> with SingleTickerProviderStateMixin{

   TabController _controller;   //error

@override
void initState(){
  super.initState();
  _controller =TabController(length: 4, vsync:this, initialIndex: 0);
}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Whatsapp Clone"),
        actions: [
          IconButton(icon: Icon(Icons.search), onPressed: () {}),
          IconButton(icon: Icon(Icons.more_vert), onPressed: () {}),
    ],
        bottom: TapBar(                //error
          _controller:_controller,
        ),
    ),
    );
  }
}
</code>```

答:
Because of null safety your variable must be initialzied when created, to fix this you can use late to tell it that it will be initialized after being created but before being used:</p>
```<code>late final TabController _controller;
</code>```

Body:
The method 'TapBar' isn't defined for the type '_HomescreenState'.

Non-nullable instance field '_controller' must be initialized.

I'm getting above errors in my code.. how to correct those. appreciate your help on this..

import 'package:flutter/material.dart';

class Homescreen extends StatefulWidget {
  Homescreen({ Key? key }) : super(key: key);

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

class _HomescreenState extends State<Homescreen> with SingleTickerProviderStateMixin{

   TabController _controller;   //error

@override
void initState(){
  super.initState();
  _controller =TabController(length: 4, vsync:this, initialIndex: 0);
}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Whatsapp Clone"),
        actions: [
          IconButton(icon: Icon(Icons.search), onPressed: () {}),
          IconButton(icon: Icon(Icons.more_vert), onPressed: () {}),
    ],
        bottom: TapBar(                //error
          _controller:_controller,
        ),
    ),
    );
  }
}

Body:
Because of null safety your variable must be initialzied when created, to fix this you can use late to tell it that it will be initialized after being created but before being used:

late final TabController _controller;


答:
Call Like this :

```<code>late final TabController _controller;

void initState(){

  _controller =TabController(length: 4, vsync:this, initialIndex: 0);
 super.initState();
}
</code>```

Call the super.initState(); after _controller initialization

Title: Non-nullable instance field '_controller' must be initialized

Body:
Call Like this :

late final TabController _controller;

void initState(){

  _controller =TabController(length: 4, vsync:this, initialIndex: 0);
 super.initState();
}

Call the super.initState(); after _controller initialization


问:
XYZ - is an object, interface or union type field. Leaf selections on objects, interfaces, and unions without subfields are disallowed
Running this Mutation GraphQL query:

```<code>mutation {
    addProduct (input: { name: "Salad Roll", description : "Tasty Salad Roll" })
}
</code>```

I'm getting this error:

"errors": [         {           "message": "addProduct is an object, interface
or union type field. Leaf selections on objects, interfaces, and
unions without subfields are disallowed.",

How do I fix it?

答:
The solution is to return a value:</p>
```<code>mutation {
    addProduct (input: { name: "Salad Roll", description : "Tasty Salad Roll" })
    {
        product
        {
        id
        }
    }
}
</code>```

Body:
Running this Mutation GraphQL query:

mutation {
    addProduct (input: { name: "Salad Roll", description : "Tasty Salad Roll" })
}

I'm getting this error:

"errors": [         {           "message": "addProduct is an object, interface
or union type field. Leaf selections on objects, interfaces, and
unions without subfields are disallowed.",

How do I fix it?

Body:
The solution is to return a value:

mutation {
    addProduct (input: { name: "Salad Roll", description : "Tasty Salad Roll" })
    {
        product
        {
        id
        }
    }
}


问:
How to indent custom uilabel in a UITableViewCell when editing
I have a custom uitableviewcell that i would like to indent when I turn on this:

[self.boatsDisplay setEditing:YES animated:YES];

Could anyone provide me a hint or some guidance?

Thanks

答:
In your UITableViewDelegate you can use the tableView:indentationLevelForRowAtIndexPath: method:

```<code>- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
  if(tableView.editing == YES){
    return 1; // or higher integer
  } else {
    return 0;
  }
}
</code>```

if you want to check for your custom cell only you can add &&[[tableView cellForRowAtIndexPath:indexPath] isKindOfClass:yourTableViewCell] in the if condition.

Body:
In your UITableViewDelegate you can use the tableView:indentationLevelForRowAtIndexPath: method:

- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
  if(tableView.editing == YES){
    return 1; // or higher integer
  } else {
    return 0;
  }
}

if you want to check for your custom cell only you can add &&[[tableView cellForRowAtIndexPath:indexPath] isKindOfClass:yourTableViewCell] in the if condition.


问:
UTF-8, UTF-16, and UTF-32
What are the differences between UTF-8, UTF-16, and UTF-32?

I understand that they will all store Unicode, and that each uses a different number of bytes to represent a character. Is there an advantage to choosing one over the other?

答:
After reading through the answers, UTF-32 needs some loving.

C#:

```<code>Data1 = RandomNumberGenerator.GetBytes(500_000_000);

sw = Stopwatch.StartNew();
int l = Encoding.UTF8.GetString(Data1).Length;
sw.Stop();
Console.WriteLine($"UTF-8: Elapsed - {sw.ElapsedMilliseconds * .001:0.000s}   Size - {l:###,###,###}");

sw = Stopwatch.StartNew();
l = Encoding.Unicode.GetString(Data1).Length;
sw.Stop();
Console.WriteLine($"Unicode: Elapsed - {sw.ElapsedMilliseconds * .001:0.000s}   Size - {l:###,###,###}");

sw = Stopwatch.StartNew();
l = Encoding.UTF32.GetString(Data1).Length;
sw.Stop();
Console.WriteLine($"UTF-32: Elapsed - {sw.ElapsedMilliseconds * .001:0.000s}   Size - {l:###,###,###}");

sw = Stopwatch.StartNew();
l = Encoding.ASCII.GetString(Data1).Length;
sw.Stop();
Console.WriteLine($"ASCII: Elapsed - {sw.ElapsedMilliseconds * .001:0.000s}   Size - {l:###,###,###}");
</code>```

UTF-8 -- Elapsed 9.939s - Size 473,752,800

Unicode -- Elapsed 0.853s - Size 250,000,000

UTF-32 -- Elapsed 3.143s - Size 125,030,570

ASCII -- Elapsed 2.362s - Size 500,000,000

UTF-32 -- MIC DROP

LastEditorDisplayName: Joe K

Title: UTF-8, UTF-16, and UTF-32

Body:
After reading through the answers, UTF-32 needs some loving.

C#:

Data1 = RandomNumberGenerator.GetBytes(500_000_000);

sw = Stopwatch.StartNew();
int l = Encoding.UTF8.GetString(Data1).Length;
sw.Stop();
Console.WriteLine($"UTF-8: Elapsed - {sw.ElapsedMilliseconds * .001:0.000s}   Size - {l:###,###,###}");

sw = Stopwatch.StartNew();
l = Encoding.Unicode.GetString(Data1).Length;
sw.Stop();
Console.WriteLine($"Unicode: Elapsed - {sw.ElapsedMilliseconds * .001:0.000s}   Size - {l:###,###,###}");

sw = Stopwatch.StartNew();
l = Encoding.UTF32.GetString(Data1).Length;
sw.Stop();
Console.WriteLine($"UTF-32: Elapsed - {sw.ElapsedMilliseconds * .001:0.000s}   Size - {l:###,###,###}");

sw = Stopwatch.StartNew();
l = Encoding.ASCII.GetString(Data1).Length;
sw.Stop();
Console.WriteLine($"ASCII: Elapsed - {sw.ElapsedMilliseconds * .001:0.000s}   Size - {l:###,###,###}");

UTF-8 -- Elapsed 9.939s - Size 473,752,800

Unicode -- Elapsed 0.853s - Size 250,000,000

UTF-32 -- Elapsed 3.143s - Size 125,030,570

ASCII -- Elapsed 2.362s - Size 500,000,000

UTF-32 -- MIC DROP


问:
Sum two columns to a third one of DataGridView. How?
How can I sum the values of two dataGridView columns and store the result in a third column for each row ? </p>

答:
```<code><yourDataTable>.Columns.Add("yourNewSumColumnName");
<yourDataTable.Columns["yourSumColumnName"].Expression = "<yourExistingCol1> +  <yourExistingCol2>"
</code>```


问:
How to simulate high order AR(p) process?
I need to simulate high order AR(p) series. I have no coefficients, only p is known. I I tried to use arima.sim, but i need to provide specific coefficients to make simulation, and unfortunetley it's imposible to randomly select valid coefficients which will keep stationarity condition. Any ideas? I need ANY AR(p) samples (lot of them). Thanks.</p>

答:
A stationary AR(p) process will have characteristic equation with p roots outside the unit circle. Because the characteristic equation has real coefficients, these roots will be in conjugate pairs, and if p is odd, there will be one real root. So an efficient way to generate the coefficients is to first generate the roots, and then construct the characteristic polynomial, from which the coefficients are easily extracted.

Here is some code to do it.

It is simpler to generate inverse roots within the unit circle, and then invert them.

library(polynom)

# Order of AR polynomial
p <- 50
n_real_roots <- p %% 2
inv_real_roots <- runif(n_real_roots, -1, 1)
# Generate inverse complex roots in conjugate pairs
n_complex_roots <- (p - n_real_roots) / 2
r <- runif(n_complex_roots, -1, 1)
angle <- runif(n_complex_roots, -pi, pi)
inv_complex_roots <- c(complex(argument = angle, modulus = r),
                       complex(argument = -angle, modulus = r))
# Find polynomial with these as roots
poly <- suppressWarnings(polynom::poly.calc(1/c(inv_real_roots, inv_complex_roots)))
# Scale to have constant 1
poly <- poly / poly[1]
phi <- -as.numeric(poly)[-1]

y <- arima.sim(n = 100, model=list(ar = phi))
plot(y)
```

Created on 2022-02-06 by the reprex package (v2.0.1)

Body:
A stationary AR(p) process will have characteristic equation with p roots outside the unit circle. Because the characteristic equation has real coefficients, these roots will be in conjugate pairs, and if p is odd, there will be one real root. So an efficient way to generate the coefficients is to first generate the roots, and then construct the characteristic polynomial, from which the coefficients are easily extracted.

Here is some code to do it.

It is simpler to generate inverse roots within the unit circle, and then invert them.

library(polynom)

# Order of AR polynomial
p <- 50
n_real_roots <- p %% 2
inv_real_roots <- runif(n_real_roots, -1, 1)
# Generate inverse complex roots in conjugate pairs
n_complex_roots <- (p - n_real_roots) / 2
r <- runif(n_complex_roots, -1, 1)
angle <- runif(n_complex_roots, -pi, pi)
inv_complex_roots <- c(complex(argument = angle, modulus = r),
                       complex(argument = -angle, modulus = r))
# Find polynomial with these as roots
poly <- suppressWarnings(polynom::poly.calc(1/c(inv_real_roots, inv_complex_roots)))
# Scale to have constant 1
poly <- poly / poly[1]
phi <- -as.numeric(poly)[-1]

y <- arima.sim(n = 100, model=list(ar = phi))
plot(y)

Created on 2022-02-06 by the reprex package (v2.0.1)