问:
Trying to make Gridview builder scroll
so i have a Gridview builder kept in an expanded widget. the reason i kept it is because i have other widgets built above this Grid view so the idea was to have the Gridview builder take the remaining available space in the device. if i just kept the grid view builder alone, a renderflex error would occur and i dont want to put the gridview in a container because i want it to take the remaining available space in the device. the problem is that now the grid view refuses to scroll. how do i solve this.</p>
```<code> Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(18.0),
            child: SizedBox(
              child: Row(
                children: [
                  Text(results.length.toString(),
                    style: GoogleFonts.tenorSans(
                        fontSize: 20,
                        fontWeight: FontWeight.w500
                    ),
                  ),
                  const SizedBox(
                    width: 6,
                  ),
                  Text('Dresses',
                    style: GoogleFonts.tenorSans(
                        fontSize: 20,
                        fontWeight: FontWeight.w500
                    ),
                  ),
                  const SizedBox(
                    width: 90,
                  ),
                  Container(
                    height: 30,
                    width: 100,
                    child: DropdownButtonHideUnderline(
                      child: DropdownButton2(
                            iconOnClick: SvgPicture.asset('assets/iconImages/Back.svg'),
                            //dropdownOverButton: true,
                          buttonPadding: EdgeInsets.symmetric(horizontal: 13),
                          buttonDecoration: BoxDecoration(
                            color: Colors.grey.shade200,
                            borderRadius: BorderRadius.circular(20)
                          ),
                            alignment: AlignmentDirectional.topStart,
                            dropdownElevation: 0,
                            isDense: true,
                            style: GoogleFonts.tenorSans(
                                fontSize: 15,
                                color: Colors.black
                            ),
                            //menuMaxHeight: MediaQuery.of(context).size.height,
                            isExpanded: true,
                            value: _newItem,
                            icon: SvgPicture.asset('assets/iconImages/Forward.svg'),
                            items: nnew.map<DropdownMenuItem>((value){
                              return DropdownMenuItem(
                                value: value,
                                child: Text(value),

                              );
                            }).toList() ,
                            onChanged: (newValue){

                              if(newValue != _newItem){
                                switch(newValue){
                                  case 'Tops': Navigator.push(context, MaterialPageRoute(builder: (context){
                                    return const WomenTop();
                                  }));
                                  break;
                                  case 'Shoes': Navigator.push(context, MaterialPageRoute(builder: (context){
                                    return const WomenShoes();
                                  }));
                                }
                              }
                              setState(() {
                                _newItem = newValue;
                              });
                            }
                        ),
                    ),
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Container(
                   padding: EdgeInsets.all(6),
                    decoration: BoxDecoration(
                      color: Colors.grey.shade200,
                      borderRadius: BorderRadius.circular(15)
                    ),
                      child: SvgPicture.asset('assets/iconImages/Listview.svg')
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Container(
                      padding: EdgeInsets.all(6),
                      decoration: BoxDecoration(
                          color: Colors.grey.shade200,
                          borderRadius: BorderRadius.circular(15)
                      ),
                      child: SvgPicture.asset('assets/iconImages/Filter.svg')
                  )
                ],
              ),
            ),
          ),
          const SizedBox(
            height: 6,
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Row(
              children: [
                Container(
                  height: 40,
                  width: 120,
                  decoration: BoxDecoration(
                    border: Border(
                      top: BorderSide(
                        color: Colors.grey.shade400
                      ),
                      bottom: BorderSide(
                          color: Colors.grey.shade400
                      ),
                      left: BorderSide(
                          color: Colors.grey.shade400
                      ),
                      right: BorderSide(
                          color: Colors.grey.shade400
                      ),
                    ),
                    borderRadius: BorderRadius.circular(25)
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('Women',
                        style: GoogleFonts.tenorSans(
                          fontSize: 20,
                          fontWeight: FontWeight.w300
                        ),
                      ),
                      IconButton(
                          onPressed: (){},
                          icon: Icon(Icons.close)
                      )
                    ],
                  ),
                ),
                const SizedBox(
                  width: 10,
                ),
                Container(
                  height: 40,
                  width: 120,
                  decoration: BoxDecoration(
                      border: Border(
                        top: BorderSide(
                            color: Colors.grey.shade400
                        ),
                        bottom: BorderSide(
                            color: Colors.grey.shade400
                        ),
                        left: BorderSide(
                            color: Colors.grey.shade400
                        ),
                        right: BorderSide(
                            color: Colors.grey.shade400
                        ),
                      ),
                      borderRadius: BorderRadius.circular(25)
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('Dresses',
                        style: GoogleFonts.tenorSans(
                            fontSize: 20,
                            fontWeight: FontWeight.w300
                        ),
                      ),
                      IconButton(
                          onPressed: (){},
                          icon: Icon(Icons.close)
                      )
                    ],
                  ),
                )
              ],
            ),
          ),
    Expanded(
      child: Padding(
           padding: const EdgeInsets.all(10.0),
              child: StaggeredGridView.countBuilder(
                scrollDirection: Axis.vertical,
              crossAxisCount: 2,

              itemCount: results.length,

              itemBuilder: (BuildContext ctx, index){
              return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
              children: [
              Container(
              width: 250,
              height: 250,

              decoration: BoxDecoration(
              image: DecorationImage(
              fit: BoxFit.cover,
              image: NetworkImage(results[index]['image'])
              )
              ),
              ),
                const SizedBox(
                  height: 10,
                ),

                Text('WM',
                  style: GoogleFonts.tenorSans(
                      fontWeight: FontWeight.w500,
                      fontSize: 15
                  ),
                ),

              const SizedBox(
                height: 10,
              ),

              Text(results[index]['name'],
              style: GoogleFonts.tenorSans(
              fontWeight: FontWeight.w500,
              fontSize: 15
              ),
              ),

              const SizedBox(
              height: 5,
              ),
              Text('\$${results[index]['price'].toString()}',
              style: GoogleFonts.tenorSans(
              fontWeight: FontWeight.w500,
              fontSize: 17,
              color: Colors.orange
              ),
              )
              ],
              ),
              );
              },
              staggeredTileBuilder: (context) => const StaggeredTile.fit(1)
              ),
              ),
    )
                ],
              )
</code>```

Title: Trying to make Gridview builder scroll

Body:
so i have a Gridview builder kept in an expanded widget. the reason i kept it is because i have other widgets built above this Grid view so the idea was to have the Gridview builder take the remaining available space in the device. if i just kept the grid view builder alone, a renderflex error would occur and i dont want to put the gridview in a container because i want it to take the remaining available space in the device. the problem is that now the grid view refuses to scroll. how do i solve this.

 Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(18.0),
            child: SizedBox(
              child: Row(
                children: [
                  Text(results.length.toString(),
                    style: GoogleFonts.tenorSans(
                        fontSize: 20,
                        fontWeight: FontWeight.w500
                    ),
                  ),
                  const SizedBox(
                    width: 6,
                  ),
                  Text('Dresses',
                    style: GoogleFonts.tenorSans(
                        fontSize: 20,
                        fontWeight: FontWeight.w500
                    ),
                  ),
                  const SizedBox(
                    width: 90,
                  ),
                  Container(
                    height: 30,
                    width: 100,
                    child: DropdownButtonHideUnderline(
                      child: DropdownButton2(
                            iconOnClick: SvgPicture.asset('assets/iconImages/Back.svg'),
                            //dropdownOverButton: true,
                          buttonPadding: EdgeInsets.symmetric(horizontal: 13),
                          buttonDecoration: BoxDecoration(
                            color: Colors.grey.shade200,
                            borderRadius: BorderRadius.circular(20)
                          ),
                            alignment: AlignmentDirectional.topStart,
                            dropdownElevation: 0,
                            isDense: true,
                            style: GoogleFonts.tenorSans(
                                fontSize: 15,
                                color: Colors.black
                            ),
                            //menuMaxHeight: MediaQuery.of(context).size.height,
                            isExpanded: true,
                            value: _newItem,
                            icon: SvgPicture.asset('assets/iconImages/Forward.svg'),
                            items: nnew.map<DropdownMenuItem>((value){
                              return DropdownMenuItem(
                                value: value,
                                child: Text(value),

                              );
                            }).toList() ,
                            onChanged: (newValue){

                              if(newValue != _newItem){
                                switch(newValue){
                                  case 'Tops': Navigator.push(context, MaterialPageRoute(builder: (context){
                                    return const WomenTop();
                                  }));
                                  break;
                                  case 'Shoes': Navigator.push(context, MaterialPageRoute(builder: (context){
                                    return const WomenShoes();
                                  }));
                                }
                              }
                              setState(() {
                                _newItem = newValue;
                              });
                            }
                        ),
                    ),
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Container(
                   padding: EdgeInsets.all(6),
                    decoration: BoxDecoration(
                      color: Colors.grey.shade200,
                      borderRadius: BorderRadius.circular(15)
                    ),
                      child: SvgPicture.asset('assets/iconImages/Listview.svg')
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Container(
                      padding: EdgeInsets.all(6),
                      decoration: BoxDecoration(
                          color: Colors.grey.shade200,
                          borderRadius: BorderRadius.circular(15)
                      ),
                      child: SvgPicture.asset('assets/iconImages/Filter.svg')
                  )
                ],
              ),
            ),
          ),
          const SizedBox(
            height: 6,
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Row(
              children: [
                Container(
                  height: 40,
                  width: 120,
                  decoration: BoxDecoration(
                    border: Border(
                      top: BorderSide(
                        color: Colors.grey.shade400
                      ),
                      bottom: BorderSide(
                          color: Colors.grey.shade400
                      ),
                      left: BorderSide(
                          color: Colors.grey.shade400
                      ),
                      right: BorderSide(
                          color: Colors.grey.shade400
                      ),
                    ),
                    borderRadius: BorderRadius.circular(25)
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('Women',
                        style: GoogleFonts.tenorSans(
                          fontSize: 20,
                          fontWeight: FontWeight.w300
                        ),
                      ),
                      IconButton(
                          onPressed: (){},
                          icon: Icon(Icons.close)
                      )
                    ],
                  ),
                ),
                const SizedBox(
                  width: 10,
                ),
                Container(
                  height: 40,
                  width: 120,
                  decoration: BoxDecoration(
                      border: Border(
                        top: BorderSide(
                            color: Colors.grey.shade400
                        ),
                        bottom: BorderSide(
                            color: Colors.grey.shade400
                        ),
                        left: BorderSide(
                            color: Colors.grey.shade400
                        ),
                        right: BorderSide(
                            color: Colors.grey.shade400
                        ),
                      ),
                      borderRadius: BorderRadius.circular(25)
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('Dresses',
                        style: GoogleFonts.tenorSans(
                            fontSize: 20,
                            fontWeight: FontWeight.w300
                        ),
                      ),
                      IconButton(
                          onPressed: (){},
                          icon: Icon(Icons.close)
                      )
                    ],
                  ),
                )
              ],
            ),
          ),
    Expanded(
      child: Padding(
           padding: const EdgeInsets.all(10.0),
              child: StaggeredGridView.countBuilder(
                scrollDirection: Axis.vertical,
              crossAxisCount: 2,

              itemCount: results.length,

              itemBuilder: (BuildContext ctx, index){
              return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
              children: [
              Container(
              width: 250,
              height: 250,

              decoration: BoxDecoration(
              image: DecorationImage(
              fit: BoxFit.cover,
              image: NetworkImage(results[index]['image'])
              )
              ),
              ),
                const SizedBox(
                  height: 10,
                ),

                Text('WM',
                  style: GoogleFonts.tenorSans(
                      fontWeight: FontWeight.w500,
                      fontSize: 15
                  ),
                ),

              const SizedBox(
                height: 10,
              ),

              Text(results[index]['name'],
              style: GoogleFonts.tenorSans(
              fontWeight: FontWeight.w500,
              fontSize: 15
              ),
              ),

              const SizedBox(
              height: 5,
              ),
              Text('\$${results[index]['price'].toString()}',
              style: GoogleFonts.tenorSans(
              fontWeight: FontWeight.w500,
              fontSize: 17,
              color: Colors.orange
              ),
              )
              ],
              ),
              );
              },
              staggeredTileBuilder: (context) => const StaggeredTile.fit(1)
              ),
              ),
    )
                ],
              )


来源: stackexchange

问:
Typescript object property bracket notation
Apologies about the elementary question. I am wondering about this specific bracket notation I found in a function in Typescript:

```<code>const results = await getAllUsers();
  const totalUsers = await getUserCount();
  const firstUser = await getFirstUser();

  return {
    props: {
      meta: defaultMetaProps,
      results,
      totalUsers,
      user: firstUser
    },
    revalidate: 10
  };
</code>```

From what I can tell online, the main way to use brackets in Typescript is to specify properties of objects, like:

```<code>props = {
  a: 'a',
  b: 'b'
}

</code>```

However, I am confused because this set of lines does not seem to follow that convention:

```<code>props: {
      meta: defaultMetaProps,
      results,
      totalUsers,
      user: firstUser
    }
</code>```

Specifically, results and totalUsers don't have corresponding property names. Am I misinterpreting something?

ContentLicense: CC BY-SA 4.0

Body:
Apologies about the elementary question. I am wondering about this specific bracket notation I found in a function in Typescript:

const results = await getAllUsers();
  const totalUsers = await getUserCount();
  const firstUser = await getFirstUser();

  return {
    props: {
      meta: defaultMetaProps,
      results,
      totalUsers,
      user: firstUser
    },
    revalidate: 10
  };

From what I can tell online, the main way to use brackets in Typescript is to specify properties of objects, like:

props = {
  a: 'a',
  b: 'b'
}

However, I am confused because this set of lines does not seem to follow that convention:

props: {
      meta: defaultMetaProps,
      results,
      totalUsers,
      user: firstUser
    }

Specifically, results and totalUsers don't have corresponding property names. Am I misinterpreting something?


问:
Getting error in my resume field in django in admin panel when made even made it optional
I have to input a resume field in a interview form website using django which is optional in the form and the form is getting submitted well on the front end but when I am opening the admin panel it is showing errors in the registation in the admin panel if the resume is not uploaded.

` admin.py:

```<code>class RegAdmin(ImportExportModelAdmin, admin.ModelAdmin):
    list_display = ('name', 'email', 'branch', 'phone_number',
                    'terms_confirmed')
    search_fields = ('name', 'email', 'branch', 'phone_number')

    def resume_url(self, instance):
        resume = instance.resume.url
        if resume:
            return mark_safe('<a target="_blank" href="%s">Resume Link</a>' %
                             (resume))
        else:
            return '-'

</code>```

`

forms.py

```<code>resume = models.FileField(
        upload_to='resumes/',
        validators=[
            file_size,
            FileExtensionValidator(allowed_extensions=["pdf", "docx"])
        ],
        blank=True,
        null=True)

</code>```

Body:
I have to input a resume field in a interview form website using django which is optional in the form and the form is getting submitted well on the front end but when I am opening the admin panel it is showing errors in the registation in the admin panel if the resume is not uploaded.

` admin.py:

class RegAdmin(ImportExportModelAdmin, admin.ModelAdmin):
    list_display = ('name', 'email', 'branch', 'phone_number',
                    'terms_confirmed')
    search_fields = ('name', 'email', 'branch', 'phone_number')

    def resume_url(self, instance):
        resume = instance.resume.url
        if resume:
            return mark_safe('Resume Link' %
                             (resume))
        else:
            return '-'

`

forms.py

resume = models.FileField(
        upload_to='resumes/',
        validators=[
            file_size,
            FileExtensionValidator(allowed_extensions=["pdf", "docx"])
        ],
        blank=True,
        null=True)


问:
Understanding standard error of the spread
I'm doing a HarvardX course on Data Science, and in it they are talking about "standard error of the spread".
Now, no matter how hard I try to imagine what a standard error of spread would mean or look like, it seems to be either very difficult or just called differently from what it should be called?
I was trying to find some articles or videos related to it, but the only ones that the search returns take me back only to HarvardX materials.
The formula that is provided is:

2 * SE_bar

SE_bar = sqrt((X_bar*(1-X_bar)/N)) # standard error of the estimate

I would like to understand what it is, where can I read more about it? Maybe it is called differently somewhere?


问:
Upload File to Google Cloud
Iam trying to upload a file to the Google Cloud via JavaScript.
But but right now i'm failing miserably.

This is my Code so far:

```<code> function uploadFile(){

    const file = document.querySelector('input[type=file]').files[0];
    const reader = new FileReader();
    let blob;
    reader.onload = function(e) {
        console.log(file)
        blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });

        fetch('https://storage.googleapis.com/upload/storage/v1/b/"my_bucket_here"/o', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer "Token here"'
            },
            body: blob,
        })
            .then(response => console.log('Success'))
            .catch(error => console.log(error));
    };
    reader.readAsArrayBuffer(file);

}
</code>```

At first I try to get the Token from my input tag in my html File

```<code>const file = document.querySelector('input[type=file]').files[0];
</code>```

Html:

```<code>    <input type="file" id="upload" name="upload" class="box">
</code>```

Then I have the reader.onload function where I store the File into a Blob

the logging of the File shows me the selectet File so the Code where i get my File should work....

After that Iam trying to Post my Blob via fetch Api to my bucket

I think this is the point where the Code fails, because I get an 400 Http Error.

POST https://storage.googleapis.com/upload/storage/v1/b/yaec_example/o 400
reader.onload @ upload.js:11
load (async)
uploadFile @ upload.js:7
onclick @ index.html?_ijt=v0tmlt6ecn7lbgsgmve0d34dra:49

It would be great if someone experienced in Google Cloud Upload could help me...

Thanks!

Title: Upload File to Google Cloud

Body:
Iam trying to upload a file to the Google Cloud via JavaScript.
But but right now i'm failing miserably.

This is my Code so far:

 function uploadFile(){

    const file = document.querySelector('input[type=file]').files[0];
    const reader = new FileReader();
    let blob;
    reader.onload = function(e) {
        console.log(file)
        blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });

        fetch('https://storage.googleapis.com/upload/storage/v1/b/"my_bucket_here"/o', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer "Token here"'
            },
            body: blob,
        })
            .then(response => console.log('Success'))
            .catch(error => console.log(error));
    };
    reader.readAsArrayBuffer(file);

}

At first I try to get the Token from my input tag in my html File

const file = document.querySelector('input[type=file]').files[0];

Html:

    <input type="file" id="upload" name="upload" class="box">

Then I have the reader.onload function where I store the File into a Blob

the logging of the File shows me the selectet File so the Code where i get my File should work....

After that Iam trying to Post my Blob via fetch Api to my bucket

I think this is the point where the Code fails, because I get an 400 Http Error.

POST https://storage.googleapis.com/upload/storage/v1/b/yaec_example/o 400
reader.onload @ upload.js:11
load (async)
uploadFile @ upload.js:7
onclick @ index.html?_ijt=v0tmlt6ecn7lbgsgmve0d34dra:49

It would be great if someone experienced in Google Cloud Upload could help me...

Thanks!


问:
React Native - Bottom Sheet Modal: Dynamic height on state change doesn't work every time

Situation:

I am using the Bottom Sheet Modal by Gorham to load a modal that shows a stopwatch interface. One element of this interface is a textInput field which is used to label the time that is taken.
I added onFocus and onBlur to this textInput field to trigger a useState (true/false) to hide/show two elements from the interface, with the goal, to reduce the interface when the user types, and to show more of screen behind the modal.

Problem:

The useState effect works fine. The elements get hidden/shown in perfect speed .
But, the height of the modal doesnt re-render/re-calculate every time. Sometimes the height stays the old height, even though 2/3 of the modal became free thanks to the useState implementation.
With the current code, it works correctly only 60% of the time.

If I click the inputField a bit longer, it works +90% of the time. But my users wont know that this helps, nor should they have to find out.

Correct
Wrong

 const slimModeHandler = () => {
    setTimeout(() => {
      setSlimMode((prevState) => {
        return true;
      });
    }, 500);
  };
```
<pre class="lang-js prettyprint-override"><code><View style={styles.textInputWrapper}>
        <View style={styles.textInputCol}>
          <BottomSheetTextInput
            style={styles.textInputField}
            placeholder="Name this lap"
            placeholderTextColor={GlobalStyles.colors.font500}
            clearButtonMode="always"
            maxLength={20}
            onChangeText={inputHandlerLapNameState}
            value={modalMemory.modalMemoryLapNameState}
            /* keyboardBehavior="interactive" */
            /* onPressIn={() => {
              setSlimMode((prevState) => {
                return true;
              });
            }} */
            onFocus={slimModeHandler}
            onBlur={() => {
              setSlimMode((prevState) => {
                return false;
              });
            }}
          />
        </View>
</code>```

  const dynamicContainerHeight = useMemo(() => {
    console.log("pre rerendering of dynamicContainerHeight", slimMode);
    //add 500 ms delay to slimMode

    /*  setTimeout(() => { */
    console.log("slimMode during timeOut", slimMode);
    return {
      ...styles.modalContainer,
      paddingBottom: 16,
      /*       height: 120, */
    };
    /*     }, 500); */
  }, [slimMode]);
```
<pre class="lang-js prettyprint-override"><code>    <BottomSheetView
      style={dynamicContainerHeight}
      onLayout={handleContentLayout}
    >
</code>```

{!slimMode ? (
        <TimerModalCreateStopwatch
          stopwatch={stopwatch}
          handleLeftButtonPress={handleLeftButtonPress}
          handleLeftButtonLongPress={handleLeftButtonLongPress}
          handleLeftButtonLongPressOut={handleLeftButtonLongPressOut}
          handleRightButtonPress={handleRightButtonPress}
          modalMemory={modalMemory}
        />
      ) : null}
```

Unfortunately, everything works 100% of the time on the iOS emulator on my Mac, so I can't learn anything from there. I assume this is because the emulator is less performant than my actual iPhone. (old mac)
Also, when I activate Remote Debugging on my iPhone, it also works 100% of the time on my phone. I assume because everything renders slower on my phone when debugging mode is on?

Ergo, my suspicion is that I have to add some delay somewhere.?

What more have I already tried?

I tried onPressIn instead of onFocus. This works almost +80% of the time I click on textInput, but (!) now the slimMode (state) changes a tick too early, which makes the keyboard push the textInput up a little too harsh. The animation sequence feels off/wrong.

I added console.log to check if the "dynamicContainerHeight" gets re-rendered correctly with onFocus and onBlur. Yes, it does.

I tried putting the dynamicContainerHeight value in state as well.

I tried useCallback instead of useMemo, and I tried to call it from onFocus.

I removed "dynamicContainerHeight" as suggested by the package author to "risk" the additional re-render. But this additional re-render did not help.

I played with "keyboardBehavior" which is one of the custom hooks for textInput by the package author.

I added delay to dynamicContainerHeight and useState.

I played with an if (slimMode) statement inside of  "dynamicContainerHeight" to serve a static (instead of dynamics) height when state changes ...

Added keyboardAvoidingView ...

Trued collapse method provided by the package author ...

I am not sure what to try next. 3-4 days working on this ...

Body:
Situation:

I am using the Bottom Sheet Modal by Gorham to load a modal that shows a stopwatch interface. One element of this interface is a textInput field which is used to label the time that is taken.
I added onFocus and onBlur to this textInput field to trigger a useState (true/false) to hide/show two elements from the interface, with the goal, to reduce the interface when the user types, and to show more of screen behind the modal.

Problem:

The useState effect works fine. The elements get hidden/shown in perfect speed .
But, the height of the modal doesnt re-render/re-calculate every time. Sometimes the height stays the old height, even though 2/3 of the modal became free thanks to the useState implementation.
With the current code, it works correctly only 60% of the time.

If I click the inputField a bit longer, it works +90% of the time. But my users wont know that this helps, nor should they have to find out.

Correct
Wrong

 const slimModeHandler = () => {
    setTimeout(() => {
      setSlimMode((prevState) => {
        return true;
      });
    }, 500);
  };

<View style={styles.textInputWrapper}>
        <View style={styles.textInputCol}>
          <BottomSheetTextInput
            style={styles.textInputField}
            placeholder="Name this lap"
            placeholderTextColor={GlobalStyles.colors.font500}
            clearButtonMode="always"
            maxLength={20}
            onChangeText={inputHandlerLapNameState}
            value={modalMemory.modalMemoryLapNameState}
            /* keyboardBehavior="interactive" */
            /* onPressIn={() => {
              setSlimMode((prevState) => {
                return true;
              });
            }} */
            onFocus={slimModeHandler}
            onBlur={() => {
              setSlimMode((prevState) => {
                return false;
              });
            }}
          />
        </View>

  const dynamicContainerHeight = useMemo(() => {
    console.log("pre rerendering of dynamicContainerHeight", slimMode);
    //add 500 ms delay to slimMode

    /*  setTimeout(() => { */
    console.log("slimMode during timeOut", slimMode);
    return {
      ...styles.modalContainer,
      paddingBottom: 16,
      /*       height: 120, */
    };
    /*     }, 500); */
  }, [slimMode]);

    <BottomSheetView
      style={dynamicContainerHeight}
      onLayout={handleContentLayout}
    >

{!slimMode ? (
        <TimerModalCreateStopwatch
          stopwatch={stopwatch}
          handleLeftButtonPress={handleLeftButtonPress}
          handleLeftButtonLongPress={handleLeftButtonLongPress}
          handleLeftButtonLongPressOut={handleLeftButtonLongPressOut}
          handleRightButtonPress={handleRightButtonPress}
          modalMemory={modalMemory}
        />
      ) : null}

Unfortunately, everything works 100% of the time on the iOS emulator on my Mac, so I can't learn anything from there. I assume this is because the emulator is less performant than my actual iPhone. (old mac)
Also, when I activate Remote Debugging on my iPhone, it also works 100% of the time on my phone. I assume because everything renders slower on my phone when debugging mode is on?

Ergo, my suspicion is that I have to add some delay somewhere.?

What more have I already tried?

I tried onPressIn instead of onFocus. This works almost +80% of the time I click on textInput, but (!) now the slimMode (state) changes a tick too early, which makes the keyboard push the textInput up a little too harsh. The animation sequence feels off/wrong.

I added console.log to check if the "dynamicContainerHeight" gets re-rendered correctly with onFocus and onBlur. Yes, it does.

I tried putting the dynamicContainerHeight value in state as well.

I tried useCallback instead of useMemo, and I tried to call it from onFocus.

I removed "dynamicContainerHeight" as suggested by the package author to "risk" the additional re-render. But this additional re-render did not help.

I played with "keyboardBehavior" which is one of the custom hooks for textInput by the package author.

I added delay to dynamicContainerHeight and useState.

I played with an if (slimMode) statement inside of  "dynamicContainerHeight" to serve a static (instead of dynamics) height when state changes ...

Added keyboardAvoidingView ...

Trued collapse method provided by the package author ...

I am not sure what to try next. 3-4 days working on this ...


问:
Facing issue with if statement
facing problem in setting the range in an if statement

if n>=6 & n<=20:
    print("Weird")
```

When I check the output for n=6 and n=20 if a not getting weird as output. I included 6 and 20 in the statement, but it doesn't work

Title: Facing issue with if statement

Body:
facing problem in setting the range in an if statement

if n>=6 & n<=20:
    print("Weird")

When I check the output for n=6 and n=20 if a not getting weird as output. I included 6 and 20 in the statement, but it doesn't work


问:
Mutating independent elements of a mutable array
I am trying to loop over an array that contains mutable elements. For each element, except the first, I wish to mutate it based on the state of the previous element. Take this, for a toy example:

#[derive(Copy, Clone, Debug)]
struct Foo(u32);

impl Foo {
    fn new() -> Self {
        Foo(1)
    }

    fn frobnicate(&mut self, other: &mut Self){
        self.0 += other.0;
        other.0 += 1;
    }
}

fn main() {
    let mut array = [Foo::new(); 3];   // FIXME

    for i in 1..3 {
        let mut this = array[i];       // FIXME
        let last = &mut array[i - 1];  // FIXME

        this.frobnicate(last);
    }

    println!("{:?}", array);
}
```
<p>The <code>FIXME</code> lines allow the above to compile, but it doesn't give the correct result. I would expect the following state:</p>
```         | Start  | i = 1  | i = 2  |
-------- | ------ | ------ | ------ |
array[0] | Foo(1) | Foo(2) | Foo(2) |
array[1] | Foo(1) | Foo(2) | Foo(3) |
array[2] | Foo(1) | Foo(1) | Foo(3) |
```
<p>The final output I get is <code>[Foo(2), Foo(2), Foo(1)]</code>. I <em>think</em> this is happening because <code>this</code> is a mutable copy of <code>array[i]</code>, rather than a mutable reference, which is just discarded at the end of each loop iteration. If I change to:</p>
<pre class="lang-rust prettyprint-override"><code>let this = &mut array[i];
</code>```

Then I get a borrow error on the assignment of last. The compiler suggests .split_at_mut(position), but this is getting into the weeds of my understanding; moreover, this method (and .split_array_mut) are marked as experimental.

How can I independently mutate elements from the same array?

Body:
I am trying to loop over an array that contains mutable elements. For each element, except the first, I wish to mutate it based on the state of the previous element. Take this, for a toy example:

#[derive(Copy, Clone, Debug)]
struct Foo(u32);

impl Foo {
    fn new() -> Self {
        Foo(1)
    }

    fn frobnicate(&mut self, other: &mut Self){
        self.0 += other.0;
        other.0 += 1;
    }
}

fn main() {
    let mut array = [Foo::new(); 3];   // FIXME

    for i in 1..3 {
        let mut this = array[i];       // FIXME
        let last = &mut array[i - 1];  // FIXME

        this.frobnicate(last);
    }

    println!("{:?}", array);
}

The FIXME lines allow the above to compile, but it doesn't give the correct result. I would expect the following state:

         | Start  | i = 1  | i = 2  |
-------- | ------ | ------ | ------ |
array[0] | Foo(1) | Foo(2) | Foo(2) |
array[1] | Foo(1) | Foo(2) | Foo(3) |
array[2] | Foo(1) | Foo(1) | Foo(3) |

The final output I get is [Foo(2), Foo(2), Foo(1)]. I think this is happening because this is a mutable copy of array[i], rather than a mutable reference, which is just discarded at the end of each loop iteration. If I change to:

let this = &mut array[i];

Then I get a borrow error on the assignment of last. The compiler suggests .split_at_mut(position), but this is getting into the weeds of my understanding; moreover, this method (and .split_array_mut) are marked as experimental.

How can I independently mutate elements from the same array?


问:
SwiftUI - AVPlayer show controls when video didn't started yet
I have multiple videos inside LazyVStack and there are no controls before the videos is clicked, which makes it look like it's not a video but image.

When a playing video is clicked then it pauses and the controls are visible, why no also before the video plays?

I tried:

```<code>player = AVPlayer(url: URL(string: vidUrl)!)
player!.pause()
</code>```

Body:
I have multiple videos inside LazyVStack and there are no controls before the videos is clicked, which makes it look like it's not a video but image.

When a playing video is clicked then it pauses and the controls are visible, why no also before the video plays?

I tried:

player = AVPlayer(url: URL(string: vidUrl)!)
player!.pause()


问:
How does this implementation of iterator_traits makes it SFINAE firendly?
I saw EA implementation of the standard library and I noticed that they use a default iterator that somehow makes iterator_traits SFINAE friendly.

Based on my understanding of what SFINAE means, it basically means overloading a template function so they don't produce hard errors when template deduction fails. How does this apply to this context?

```<code>template <typename _Iterator, class = void>
    struct default_iterator_traits {};

    template <typename _Iterator>
    struct default_iterator_traits<
        _Iterator,
        void_t<
            typename _Iterator::iterator_category,
            typename _Iterator::value_type,
            typename _Iterator::difference_type,
            typename _Iterator::pointer,
            typename _Iterator::reference
        >
    >
    {
        typedef typename _Iterator::iterator_category iterator_category;
        typedef typename _Iterator::value_type        value_type;
        typedef typename _Iterator::difference_type   difference_type;
        typedef typename _Iterator::pointer           pointer;
        typedef typename _Iterator::reference         reference;
    };

    template<class _Iterator>
    struct iterator_traits : public default_iterator_traits<_Iterator> {};

    // ... rest of the implementation ..
</code>```

Full implementation is here: EASTL/iterator

Body:
I saw EA implementation of the standard library and I noticed that they use a default iterator that somehow makes iterator_traits SFINAE friendly.

Based on my understanding of what SFINAE means, it basically means overloading a template function so they don't produce hard errors when template deduction fails. How does this apply to this context?

template <typename _Iterator, class = void>
    struct default_iterator_traits {};

    template <typename _Iterator>
    struct default_iterator_traits<
        _Iterator,
        void_t<
            typename _Iterator::iterator_category,
            typename _Iterator::value_type,
            typename _Iterator::difference_type,
            typename _Iterator::pointer,
            typename _Iterator::reference
        >
    >
    {
        typedef typename _Iterator::iterator_category iterator_category;
        typedef typename _Iterator::value_type        value_type;
        typedef typename _Iterator::difference_type   difference_type;
        typedef typename _Iterator::pointer           pointer;
        typedef typename _Iterator::reference         reference;
    };

    template<class _Iterator>
    struct iterator_traits : public default_iterator_traits<_Iterator> {};

    // ... rest of the implementation ..

Full implementation is here: EASTL/iterator


问:
How to show the url of an image with python discord bot?
I am creating a small bot in python, but I have a small problem and I want it to show me the image as a link and I don't know how to do it

This is the code I am currently using:

```<code>with io.BytesIO() as image_binary:
                img1.save(image_binary, 'PNG')
                image_binary.seek(0)
                embed=discord.Embed(title="Skin Minecraft", url="https://twitter.com/", description=f"", color=discord.Colour.random())

                embed.set_image(url=f"attachment://Skin-{usuariominecraft}.png")

                await ctx.send(embed=embed, file=discord.File(fp=image_binary, filename=f"Skin-{usuariominecraft}.png"))
</code>```

Thank you very much in advance!

Body:
I am creating a small bot in python, but I have a small problem and I want it to show me the image as a link and I don't know how to do it

This is the code I am currently using:

with io.BytesIO() as image_binary:
                img1.save(image_binary, 'PNG')
                image_binary.seek(0)
                embed=discord.Embed(title="Skin Minecraft", url="https://twitter.com/", description=f"", color=discord.Colour.random())

                embed.set_image(url=f"attachment://Skin-{usuariominecraft}.png")

                await ctx.send(embed=embed, file=discord.File(fp=image_binary, filename=f"Skin-{usuariominecraft}.png"))

Thank you very much in advance!


问:
Auth0 Composer issues
Busy setting up Auth0 on my PHP app and running into problems installing various libraries required

When I run composer require guzzlehttp/guzzle guzzlehttp/psr7 http-interop/http-factory-guzzle I receive a couple errors and at this stage I am not sure what the next step is

```<code>Info from https://repo.packagist.org: #StandWithUkraine
Using version ^7.5 for guzzlehttp/guzzle
Using version ^2.4 for guzzlehttp/psr7
Using version ^1.2 for http-interop/http-factory-guzzle
./composer.json has been updated
Running composer update guzzlehttp/guzzle guzzlehttp/psr7 http-interop/http-factory-guzzle
Loading composer repositories with package information
Info from https://repo.packagist.org: #StandWithUkraine
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - google/apiclient is locked to version v2.8.2 and an update of this package was not requested.
    - google/apiclient v2.8.2 requires guzzlehttp/psr7 ^1.2 -> found guzzlehttp/psr7[1.2.0, ..., 1.9.0] but it conflicts with your root composer.json require (^2.4).
  Problem 2
    - Root composer.json requires guzzlehttp/guzzle ^7.5 -> satisfiable by guzzlehttp/guzzle[7.5.0].
    - guzzlehttp/guzzle 7.5.0 requires guzzlehttp/promises ^1.5 -> found guzzlehttp/promises[1.5.0, 1.5.1, 1.5.2] but the package is fixed to 1.4.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.
</code>```

The same happens when trying to add the Auth0 library composer require auth0/auth0-php

```<code>Info from https://repo.packagist.org: #StandWithUkraine
Using version ^8.3 for auth0/auth0-php
./composer.json has been updated
Running composer update auth0/auth0-php
Loading composer repositories with package information
Info from https://repo.packagist.org: #StandWithUkraine
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - auth0/auth0-php[8.3.0, ..., 8.3.1] require psr/http-factory-implementation ^1.0 -> could not be found in any version, but the following packages provide it:
      - guzzlehttp/psr7 PSR-7 message implementation that also provides common utility methods
      - nyholm/psr7 A fast PHP7 implementation of PSR-7
      - http-interop/http-factory-guzzle An HTTP Factory using Guzzle PSR7
      - laminas/laminas-diactoros PSR HTTP Message implementations
      - zendframework/zend-diactoros PSR HTTP Message implementations
      - slim/psr7 Strict PSR-7 implementation
      - typo3/cms-core TYPO3 CMS Core
      - tuupola/http-factory Lightweight autodiscovering PSR-17 HTTP factories
      - nimbly/capsule Capsule is a simple PSR-7 HTTP message and PSR-17 HTTP factory implementation.
      - httpsoft/http-message Strict and fast implementation of PSR-7 and PSR-17
      - yiisoft/psr-dummy-provider PSR Dummy Provider
      - mileschou/psr The support library for PSR
      - oro/platform Business Application Platform (BAP)
      - typo3/cms TYPO3 CMS is a free open source Content Management Framework initially created by Kasper Skaarhoj an
      - php-extended/php-http-message-factory-psr17 An implementation of the psr-17 based on the php-http-message-psr7 library
      - windwalker/uri Windwalker Uri package
      - sunrise/http-factory HTTP factory for PHP 7.1+ based on PSR-17
      - http-interop/http-factory-diactoros An HTTP Factory using Zend Diactoros
      - bittyphp/http PSR-7 and PSR-17 HTTP implementation.
      - windwalker/http Windwalker Http package
      ... and 49 more.
      Consider requiring one of these to satisfy the psr/http-factory-implementation requirement.
    - auth0/auth0-php[8.3.2, ..., 8.3.8] require php ^8.0 -> your php version (7.4.30) does not satisfy that requirement.
    - Root composer.json requires auth0/auth0-php ^8.3 -> satisfiable by auth0/auth0-php[8.3.0, ..., 8.3.8].

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details.
 - It's a private package and you forgot to add a custom repository to find it

Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.
</code>```

This is on the production server so I am very reluctant to just go at as usual to try resolve this and instead need the definitive fix here

Title: Auth0 Composer issues

Body:
Busy setting up Auth0 on my PHP app and running into problems installing various libraries required

When I run composer require guzzlehttp/guzzle guzzlehttp/psr7 http-interop/http-factory-guzzle I receive a couple errors and at this stage I am not sure what the next step is

Info from https://repo.packagist.org: #StandWithUkraine
Using version ^7.5 for guzzlehttp/guzzle
Using version ^2.4 for guzzlehttp/psr7
Using version ^1.2 for http-interop/http-factory-guzzle
./composer.json has been updated
Running composer update guzzlehttp/guzzle guzzlehttp/psr7 http-interop/http-factory-guzzle
Loading composer repositories with package information
Info from https://repo.packagist.org: #StandWithUkraine
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - google/apiclient is locked to version v2.8.2 and an update of this package was not requested.
    - google/apiclient v2.8.2 requires guzzlehttp/psr7 ^1.2 -> found guzzlehttp/psr7[1.2.0, ..., 1.9.0] but it conflicts with your root composer.json require (^2.4).
  Problem 2
    - Root composer.json requires guzzlehttp/guzzle ^7.5 -> satisfiable by guzzlehttp/guzzle[7.5.0].
    - guzzlehttp/guzzle 7.5.0 requires guzzlehttp/promises ^1.5 -> found guzzlehttp/promises[1.5.0, 1.5.1, 1.5.2] but the package is fixed to 1.4.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

The same happens when trying to add the Auth0 library composer require auth0/auth0-php

Info from https://repo.packagist.org: #StandWithUkraine
Using version ^8.3 for auth0/auth0-php
./composer.json has been updated
Running composer update auth0/auth0-php
Loading composer repositories with package information
Info from https://repo.packagist.org: #StandWithUkraine
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - auth0/auth0-php[8.3.0, ..., 8.3.1] require psr/http-factory-implementation ^1.0 -> could not be found in any version, but the following packages provide it:
      - guzzlehttp/psr7 PSR-7 message implementation that also provides common utility methods
      - nyholm/psr7 A fast PHP7 implementation of PSR-7
      - http-interop/http-factory-guzzle An HTTP Factory using Guzzle PSR7
      - laminas/laminas-diactoros PSR HTTP Message implementations
      - zendframework/zend-diactoros PSR HTTP Message implementations
      - slim/psr7 Strict PSR-7 implementation
      - typo3/cms-core TYPO3 CMS Core
      - tuupola/http-factory Lightweight autodiscovering PSR-17 HTTP factories
      - nimbly/capsule Capsule is a simple PSR-7 HTTP message and PSR-17 HTTP factory implementation.
      - httpsoft/http-message Strict and fast implementation of PSR-7 and PSR-17
      - yiisoft/psr-dummy-provider PSR Dummy Provider
      - mileschou/psr The support library for PSR
      - oro/platform Business Application Platform (BAP)
      - typo3/cms TYPO3 CMS is a free open source Content Management Framework initially created by Kasper Skaarhoj an
      - php-extended/php-http-message-factory-psr17 An implementation of the psr-17 based on the php-http-message-psr7 library
      - windwalker/uri Windwalker Uri package
      - sunrise/http-factory HTTP factory for PHP 7.1+ based on PSR-17
      - http-interop/http-factory-diactoros An HTTP Factory using Zend Diactoros
      - bittyphp/http PSR-7 and PSR-17 HTTP implementation.
      - windwalker/http Windwalker Http package
      ... and 49 more.
      Consider requiring one of these to satisfy the psr/http-factory-implementation requirement.
    - auth0/auth0-php[8.3.2, ..., 8.3.8] require php ^8.0 -> your php version (7.4.30) does not satisfy that requirement.
    - Root composer.json requires auth0/auth0-php ^8.3 -> satisfiable by auth0/auth0-php[8.3.0, ..., 8.3.8].

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details.
 - It's a private package and you forgot to add a custom repository to find it

Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

This is on the production server so I am very reluctant to just go at as usual to try resolve this and instead need the definitive fix here


问:
How to avoid accessor to throw error in Laravel 9
When I create instance of a model but don't fill all the fields, my accessor throws an error:

Attempt to read property "img" on null

Eg.

```<code>class Books extends Model {

    protected function getAuthorImgTag:attribute {
        return attribute::make(
            function() {
                return "<img src='" . $this->author->img . "'/>";
            }
        )
    }
}
</code>```

And I create following instance (without author associated with it):

```<code>$book = new Book;
return view('allbooks', compact('book'));
</code>```

How can I avoid the error? Should I wrap the accessor with try/catch? Or should I simply return null when $this->author is not set?

Body:
When I create instance of a model but don't fill all the fields, my accessor throws an error:

Attempt to read property "img" on null

Eg.

class Books extends Model {

    protected function getAuthorImgTag:attribute {
        return attribute::make(
            function() {
                return "author->img . "'/>";
            }
        )
    }
}

And I create following instance (without author associated with it):

$book = new Book;
return view('allbooks', compact('book'));

How can I avoid the error? Should I wrap the accessor with try/catch? Or should I simply return null when $this->author is not set?


问:
How to exit out of VSCode's Live Preview extension devtools pane windowed mode
Whenever I click the vertical triple dot button in the live preview devtools, there is no longer an option to exit out of windowed mode. I want the devtools pane to be intergrated within the VSCode window, which I could do before, but now it seems like they removed that option? My live preview version is v0.4.4 and I tried reinstalling it but it didn't work.

Live preview devtools:

Chrome devtools:


问:
Changing the color of the navigation bar depending on the background
I need to smoothly change the color of the logo and menu depending on the background color.

It would be best if I could choose the colors myself, e.g. in the second section let the color change to red and in the third to green

I am using locomotive-scroll for horizontal scrolling, I am also sending the code:

```<code>        <nav class=" fixed w-full z-50 ">
                <div class=" container mx-auto flex my-7 ">
                    <div class=" w-1/2 "><img src="/logo.svg" alt="logo" /></div>
                    <ul class=" flex w-1/2 gap-7 justify-end items-center text-white font-spacegrotesk ">
                        <li>Work</li>
                        <li>About</li>
                        <li>Contact</li>
                    </ul>
                </div>
            </nav>
            <div class=" scroll-container relative w-full flex ">
                <div data-scroll-section class=" min-w-full min-h-screen h-screen  bg-[#EDE1D1] ">
                    <h1 class="text-white">section 1</h1>
                </div>
                <div data-scroll-section class=" min-w-full min-h-screen h-screen  bg-[#BD7E36] ">
                    <h1 class="text-green-700">section 2</h1>
                </div>
                <div data-scroll-section class=" min-w-full min-h-screen h-screen  bg-[#6F311A] ">
                    <h1 class="text-black">section 3</h1>
                </div>
            </div>

    <script>
            //Horizontal Scroll
            var locoScroll = new LocomotiveScroll({
                el: document.querySelector('.scroll-container'),
                smooth: true,
                direction: 'horizontal',
                class: true,
                multiplier: 1,
                lerp: 0.04,
                scrollbarContainer: false,
                getDirection: true,
                getSpeed: true,
                getDirection: true,
                scrollFromAnywhere: true,
            });
        </script>
</code>```

Body:
I need to smoothly change the color of the logo and menu depending on the background color.

It would be best if I could choose the colors myself, e.g. in the second section let the color change to red and in the third to green

I am using locomotive-scroll for horizontal scrolling, I am also sending the code:

Work

About

Contact

section 1

section 2

section 3


问:
Caught Toggle undefined while making navbar in js
i wrote a code for switching the navbar to menu in css media query. but i caught this error. I am a newbie in Website designing can someone help. why the toggle is undefined while we never make a toggle=x-y variable?

I tried to make a hamburger menu but toggle is undefined. in HTML this is code:

```<code>  <div class="toggleMenu" onclick="toggleMenu();"></div>
</code>```

in Js this is code:

```<code>function toggleMenu(){
    const togglemenu = document.querySelector(".toggleMenu");
    const navigation = document.querySelector(".navigation");
.toggleMenu.classsList.toggle("active");
.navigation.classsList.toggle("active");
}
</code>```

in css it is

```<code>@media screen and (max-width:800px){
  .toggleMenu{
    position: absolute;
    right: 5%;
    /* background-color: var(--cl-3--); */
    background-image: url(/Graphics/Instagram.svg);
    background-position: center;
    background-repeat: no-repeat;
    background-size: 30px;
    width: 30px;
    height: 30px;
    padding: 2em;
    z-index: 1000;
    transition: background-size 0.3s ease-in-out;
  }
  .toggleMenu.active{
    position: fixed;
    background-image: url(/Graphics/Twitter.svg);
    background-size: 25px;
  }
  .navigation{
    justify-content: center;
    align-items: center;
    flex-direction: column;
    max-height: 0;
    opacity: 0;
    transform-origin: top;
    transform: scale(0);
  }
  .navigation.active{
    position: fixed;
    inset: 0;
    margin: auto;
    max-height: 100%;
    opacity: 1;
    background-color: var(--cl-6--);
    transform: scale(1);
    z-index: 999;
  }
}
</code>```

Body:
i wrote a code for switching the navbar to menu in css media query. but i caught this error. I am a newbie in Website designing can someone help. why the toggle is undefined while we never make a toggle=x-y variable?

I tried to make a hamburger menu but toggle is undefined. in HTML this is code:

in Js this is code:

function toggleMenu(){
    const togglemenu = document.querySelector(".toggleMenu");
    const navigation = document.querySelector(".navigation");
.toggleMenu.classsList.toggle("active");
.navigation.classsList.toggle("active");
}

in css it is

@media screen and (max-width:800px){
  .toggleMenu{
    position: absolute;
    right: 5%;
    /* background-color: var(--cl-3--); */
    background-image: url(/Graphics/Instagram.svg);
    background-position: center;
    background-repeat: no-repeat;
    background-size: 30px;
    width: 30px;
    height: 30px;
    padding: 2em;
    z-index: 1000;
    transition: background-size 0.3s ease-in-out;
  }
  .toggleMenu.active{
    position: fixed;
    background-image: url(/Graphics/Twitter.svg);
    background-size: 25px;
  }
  .navigation{
    justify-content: center;
    align-items: center;
    flex-direction: column;
    max-height: 0;
    opacity: 0;
    transform-origin: top;
    transform: scale(0);
  }
  .navigation.active{
    position: fixed;
    inset: 0;
    margin: auto;
    max-height: 100%;
    opacity: 1;
    background-color: var(--cl-6--);
    transform: scale(1);
    z-index: 999;
  }
}


问:
Calculate retention rate for the users per time window in Kusto
I'm trying to calculate the user retention for the users per time window without comparing the previous time windows.

For example,

Table:

```<code>let T = datatable(UserId:string, Timestamp:datetime)
[
    // May
    'A', datetime(2022-05-01),
    'D', datetime(2022-05-06),
    'C', datetime(2022-05-10),
    'B', datetime(2022-05-15),
    'E', datetime(2022-05-20),
    // June
    'C', datetime(2022-06-02),
    'T', datetime(2022-06-02),
    'J', datetime(2022-06-02),
    'H', datetime(2022-06-13),
    'T', datetime(2022-06-13),
    'G', datetime(2022-06-15),
    'B', datetime(2022-06-15),
    'S', datetime(2022-06-18),
    'M', datetime(2022-06-18),
    'L', datetime(2022-06-20),
    'Z', datetime(2022-06-25),
    // July
    'C', datetime(2022-07-04),
    'T', datetime(2022-07-04),
    'M', datetime(2022-07-04),
    'G', datetime(2022-07-10),
    'L', datetime(2022-07-10)
];
</code>```

For

```<code>start = datetime(2022-05-01)\
end = datetime(2022-08-01)\
time window = 28d
</code>```

Result Expected:

From
To
Retained
RetentionRate

2022-05-01T00:00:00Z
2022-05-01T00:00:00Z
5
1

2022-05-01T00:00:00Z
2022-05-29T00:00:00Z
2
0.4

2022-05-01T00:00:00Z
2022-06-26T00:00:00Z
1
0.2

2022-05-01T00:00:00Z
2022-07-24T00:00:00Z
0
0

2022-05-29T00:00:00Z
2022-05-29T00:00:00Z
10
1

2022-05-29T00:00:00Z
2022-06-26T00:00:00Z
5
0.5

2022-05-29T00:00:00Z
2022-07-24T00:00:00Z
0
0

2022-06-26T00:00:00Z
2022-06-26T00:00:00Z
5
1

2022-06-26T00:00:00Z
2022-07-24T00:00:00Z
0
0

2022-07-24T00:00:00Z
2022-07-24T00:00:00Z
0
NaN

The user journey starts from the current window and checks if the user was retained in the next window. May 1 started with 5 users and only 2 were retained in the next time window and only 1 was retained in the next. May 29 started with 10 users (including 1 user already seen in May) and in the next window 5 were retained.

Kusto has new_activity_metrics plugin but it takes into account the previous time window.

In the above case, From June to June window will filter the users who were already seen in May.

One solution I can think of is to use new_activity_metrics and call set each month as the start value.

```<code>T
| evaluate new_activity_metrics(UserId, Timestamp, datetime(2022-05-01), datetime(2022-08-01), 28d )
| where from_Timestamp == datetime(2022-05-01)
| union (
    T
    | evaluate new_activity_metrics(UserId, Timestamp, datetime(2022-05-29), datetime(2022-08-01), 28d )
    | where from_Timestamp == datetime(2022-05-29)
)
| union (
    T
    | evaluate new_activity_metrics(UserId, Timestamp, datetime(2022-06-26), datetime(2022-08-01), 28d )
    | where from_Timestamp == datetime(2022-06-26)
)
| union (
    T
    | evaluate new_activity_metrics(UserId, Timestamp, datetime(2022-07-24), datetime(2022-08-01), 28d )
    | where from_Timestamp == datetime(2022-07-24)
)
| project from_Timestamp, to_Timestamp, dcount_retained_values, retention_rate
</code>```

Not sure how to make this dynamic ( work for any given start and end time )

Probably there is a better plugin to use that I'm missing.

Any idea how to solve this?

Body:
I'm trying to calculate the user retention for the users per time window without comparing the previous time windows.

For example,

Table:

let T = datatable(UserId:string, Timestamp:datetime)
[
    // May
    'A', datetime(2022-05-01),
    'D', datetime(2022-05-06),
    'C', datetime(2022-05-10),
    'B', datetime(2022-05-15),
    'E', datetime(2022-05-20),
    // June
    'C', datetime(2022-06-02),
    'T', datetime(2022-06-02),
    'J', datetime(2022-06-02),
    'H', datetime(2022-06-13),
    'T', datetime(2022-06-13),
    'G', datetime(2022-06-15),
    'B', datetime(2022-06-15),
    'S', datetime(2022-06-18),
    'M', datetime(2022-06-18),
    'L', datetime(2022-06-20),
    'Z', datetime(2022-06-25),
    // July
    'C', datetime(2022-07-04),
    'T', datetime(2022-07-04),
    'M', datetime(2022-07-04),
    'G', datetime(2022-07-10),
    'L', datetime(2022-07-10)
];

For

start = datetime(2022-05-01)\
end = datetime(2022-08-01)\
time window = 28d

Result Expected:

From
To
Retained
RetentionRate

2022-05-01T00:00:00Z
2022-05-01T00:00:00Z
5
1

2022-05-01T00:00:00Z
2022-05-29T00:00:00Z
2
0.4

2022-05-01T00:00:00Z
2022-06-26T00:00:00Z
1
0.2

2022-05-01T00:00:00Z
2022-07-24T00:00:00Z
0
0

2022-05-29T00:00:00Z
2022-05-29T00:00:00Z
10
1

2022-05-29T00:00:00Z
2022-06-26T00:00:00Z
5
0.5

2022-05-29T00:00:00Z
2022-07-24T00:00:00Z
0
0

2022-06-26T00:00:00Z
2022-06-26T00:00:00Z
5
1

2022-06-26T00:00:00Z
2022-07-24T00:00:00Z
0
0

2022-07-24T00:00:00Z
2022-07-24T00:00:00Z
0
NaN

The user journey starts from the current window and checks if the user was retained in the next window. May 1 started with 5 users and only 2 were retained in the next time window and only 1 was retained in the next. May 29 started with 10 users (including 1 user already seen in May) and in the next window 5 were retained.

Kusto has new_activity_metrics plugin but it takes into account the previous time window.

In the above case, From June to June window will filter the users who were already seen in May.

One solution I can think of is to use new_activity_metrics and call set each month as the start value.

T
| evaluate new_activity_metrics(UserId, Timestamp, datetime(2022-05-01), datetime(2022-08-01), 28d )
| where from_Timestamp == datetime(2022-05-01)
| union (
    T
    | evaluate new_activity_metrics(UserId, Timestamp, datetime(2022-05-29), datetime(2022-08-01), 28d )
    | where from_Timestamp == datetime(2022-05-29)
)
| union (
    T
    | evaluate new_activity_metrics(UserId, Timestamp, datetime(2022-06-26), datetime(2022-08-01), 28d )
    | where from_Timestamp == datetime(2022-06-26)
)
| union (
    T
    | evaluate new_activity_metrics(UserId, Timestamp, datetime(2022-07-24), datetime(2022-08-01), 28d )
    | where from_Timestamp == datetime(2022-07-24)
)
| project from_Timestamp, to_Timestamp, dcount_retained_values, retention_rate

Not sure how to make this dynamic ( work for any given start and end time )

Probably there is a better plugin to use that I'm missing.

Any idea how to solve this?


问:
Can't Display/Show Single Channel Image using PIL in python. The Image is extracted from Tensorflow Data Set
Can't Display/Show Single Channel Image using PIL in python. The Image is extracted from Tensorflow Data Set.

first = train.take(1)
images, labels = list(first)[0]
first_image = images[0]
first_image[:3,:3,0]
```
<p>Output:</p>
```<tf.Tensor: shape=(3, 3), dtype=float32, numpy=
array([[176.     , 169.125  , 161.25   ],
       [186.     , 173.26562, 161.17188],
       [191.625  , 178.42188, 164.78125]], dtype=float32)>
```
<pre class="lang-py prettyprint-override"><code>Image.fromarray(first_image.numpy().astype("uint8"))
</code>```

Output:

```<code>KeyError                                  Traceback (most recent call last)
D:\ProgramFiles\Anaconda\lib\site-packages\PIL\Image.py in fromarray(obj, mode)
   2952         try:
-> 2953             mode, rawmode = _fromarray_typemap[typekey]
   2954         except KeyError as e:

KeyError: ((1, 1, 1), '|u1')

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_20488\2928708011.py in <module>
----> 1 Image.fromarray(first_image.numpy().astype("uint8"))

D:\ProgramFiles\Anaconda\lib\site-packages\PIL\Image.py in fromarray(obj, mode)
   2953             mode, rawmode = _fromarray_typemap[typekey]
   2954         except KeyError as e:
-> 2955             raise TypeError("Cannot handle this data type: %s, %s" % typekey) from e
   2956     else:
   2957         rawmode = mode

TypeError: Cannot handle this data type: (1, 1, 1), |u1
</code>```

Body:
Can't Display/Show Single Channel Image using PIL in python. The Image is extracted from Tensorflow Data Set.

first = train.take(1)
images, labels = list(first)[0]
first_image = images[0]
first_image[:3,:3,0]

Output:

<tf.Tensor: shape=(3, 3), dtype=float32, numpy=
array([[176.     , 169.125  , 161.25   ],
       [186.     , 173.26562, 161.17188],
       [191.625  , 178.42188, 164.78125]], dtype=float32)>

Image.fromarray(first_image.numpy().astype("uint8"))

Output:

KeyError                                  Traceback (most recent call last)
D:\ProgramFiles\Anaconda\lib\site-packages\PIL\Image.py in fromarray(obj, mode)
   2952         try:
-> 2953             mode, rawmode = _fromarray_typemap[typekey]
   2954         except KeyError as e:

KeyError: ((1, 1, 1), '|u1')

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_20488\2928708011.py in <module>
----> 1 Image.fromarray(first_image.numpy().astype("uint8"))

D:\ProgramFiles\Anaconda\lib\site-packages\PIL\Image.py in fromarray(obj, mode)
   2953             mode, rawmode = _fromarray_typemap[typekey]
   2954         except KeyError as e:
-> 2955             raise TypeError("Cannot handle this data type: %s, %s" % typekey) from e
   2956     else:
   2957         rawmode = mode

TypeError: Cannot handle this data type: (1, 1, 1), |u1


问:
Jacobian of Bundle Adjustment
I'm new to the computer vision world. I'm trying to implement the Levenberg-Marquardt algorithm but I'm stuck at the computation of the jacobian. I'm trying to compute the jacobian of the 3d points from 2 views. I found this picture to help me implement it: jacobians
What I do is for every point I concatenate this 2x4 matrix to form a "row". Then I append this rows toghether for every view. Now, I have a total of 2008 points and I get a matrix of 4x8032. When I try to compute the delta to update my 3d reconstruction I get a matrix of 8032 x 4016. Do you have any suggestions on what I am doing wrong?

I tried implementing the Jacobian in a different way, but at that point I can't get the multiplication between the Jacobian and the residuals.

Title: Jacobian of Bundle Adjustment


问:
import machine ModuleNotFoundError: No module named 'machine'
```<code>import machine
import time

LED=machine.Pin(25,machine.Pin.OUT)

while True:
     r=input('led ta che zamani cheshmak bezanad?')
     b=input('ta che zamani roshan bemanad?')
     a=input('ta che zamani khamoosh bemanad?')

if r==5:
        LED.value(r)

if b==5:
        time.sleep(b)

if a==5:
        time.sleep(a)

</code>```

te erorr is from (imprt machine ) but i couldnt find it............................................................................................................................................................................

Body:
import machine
import time

LED=machine.Pin(25,machine.Pin.OUT)

while True:
     r=input('led ta che zamani cheshmak bezanad?')
     b=input('ta che zamani roshan bemanad?')
     a=input('ta che zamani khamoosh bemanad?')

if r==5:
        LED.value(r)

if b==5:
        time.sleep(b)

if a==5:
        time.sleep(a)

te erorr is from (imprt machine ) but i couldnt find it............................................................................................................................................................................


问:
Error when following dgl library tutorial "CSVDataset"
I'm quite new to the library dgl so I was following tutorial on how to use their class dgl.data.CSVDataset() for reading your own datasets. My example -graph classification section chapter and I'm even using the same data for this example that was mentioned in docs.

After creating the same folder schema with the same .csv files and the same data, after running dgl.data.CSVDataset(), receiving the error in edges.csv:

```<code>KeyError: '0,0,1,"0.3219496197945605,0.3439899477636117,0.7051530741717352"'
</code>```

Details of the error logs show the following:

```<code>DGLError(f"Duplicate edge type[{e_data.type}] for same graph[{graph_id}], please place the same edge_type for same graph into single EdgeData.")
</code>```

And that is quite strange due to the fact that I'm using the same data from example and this graph obviously should be able to handle self-loops/reversed edges. Sorry if I'm asking something trivial, spent already couple of hours trying to find the reason of this in web but without success. Any suggestions to solve it will be really appreciated! Thanks.

Body:
I'm quite new to the library dgl so I was following tutorial on how to use their class dgl.data.CSVDataset() for reading your own datasets. My example -graph classification section chapter and I'm even using the same data for this example that was mentioned in docs.

After creating the same folder schema with the same .csv files and the same data, after running dgl.data.CSVDataset(), receiving the error in edges.csv:

KeyError: '0,0,1,"0.3219496197945605,0.3439899477636117,0.7051530741717352"'

Details of the error logs show the following:

DGLError(f"Duplicate edge type[{e_data.type}] for same graph[{graph_id}], please place the same edge_type for same graph into single EdgeData.")

And that is quite strange due to the fact that I'm using the same data from example and this graph obviously should be able to handle self-loops/reversed edges. Sorry if I'm asking something trivial, spent already couple of hours trying to find the reason of this in web but without success. Any suggestions to solve it will be really appreciated! Thanks.


问:
How to access generic parameter's companion object in Kotlin
Say that I have interfaces IEntity and IEntityFactory and a class Person. Imagine that I also have additional implementations of IEntity with their own unique properties, similar to Person.

I require that Person implements the properties of IEntity and the "static" methods of IEntityFactory on its companion object. I wish there were a way to enforce this, but there does not seem to be.

interface IEntityFactory<T : IData> {
    // a string like "entity.person" used for identifying object types across the wire
    val objectType: String
    // a function to get the class instance from a Map
    fun fromMap(map: Map<String, @Contextual Any?>): T
    // a function that checks if the given string meets the requirements to be of this object type
    fun isOfType(objectType: String?): Boolean
}
```
<pre class="lang-kotlin prettyprint-override"><code>interface IEntity {
    val objectType: String
    val name: String
}
</code>```

@Serializable
data class Person(
    override val objectType: String,
    override val name: String,
) : IEntity {

    companion object : IEntityFactory<Person> {
        override val objectType: String = "entity.person"
        override fun fromMap(map: Map<String, Any?>) = // do work
        override fun isOfType(objectType: String?) = // do work
    }
}
```
<p>Now, say that I want to easily convert a <code>Map<String, Any></code> to any of the <code>IEntities</code> given above. One way may be to create an extension function:</p>
<pre class="lang-kotlin prettyprint-override"><code>fun <T : IEntity> Map<String, String>.toData(): T? {
    val objectType = this["objectType"]!!.lowercase()
    if(T.isOfType(objectType)) return T.fromMap(this)
}
</code>```

Obviously, the above code does not work: How is the compiler supposed to know that all implementations of IEntity implement their own IEntityFactory<IEntity>> (and consequently, their own implementations of IEntity.fromMap()?

What is a good (Kotlin-esque) way around this, since interfaces cannot enforce the implementation of the companion object?

EDIT:
In reference to @aSemy's proposal:

inline fun <reified T : IData> Map<String, String>.toData(): T? {
    return try {
        val jsonMap = Json.encodeToString(this)
        Json.decodeFromString(jsonMap)
    } catch (_: Exception) {
        null
    }
}
```

Body:
Say that I have interfaces IEntity and IEntityFactory and a class Person. Imagine that I also have additional implementations of IEntity with their own unique properties, similar to Person.

I require that Person implements the properties of IEntity and the "static" methods of IEntityFactory on its companion object. I wish there were a way to enforce this, but there does not seem to be.

interface IEntityFactory<T : IData> {
    // a string like "entity.person" used for identifying object types across the wire
    val objectType: String
    // a function to get the class instance from a Map
    fun fromMap(map: Map<String, @Contextual Any?>): T
    // a function that checks if the given string meets the requirements to be of this object type
    fun isOfType(objectType: String?): Boolean
}

interface IEntity {
    val objectType: String
    val name: String
}

@Serializable
data class Person(
    override val objectType: String,
    override val name: String,
) : IEntity {

    companion object : IEntityFactory<Person> {
        override val objectType: String = "entity.person"
        override fun fromMap(map: Map<String, Any?>) = // do work
        override fun isOfType(objectType: String?) = // do work
    }
}

Now, say that I want to easily convert a Map<String, Any> to any of the IEntities given above. One way may be to create an extension function:

fun <T : IEntity> Map<String, String>.toData(): T? {
    val objectType = this["objectType"]!!.lowercase()
    if(T.isOfType(objectType)) return T.fromMap(this)
}

Obviously, the above code does not work: How is the compiler supposed to know that all implementations of IEntity implement their own IEntityFactory<IEntity>> (and consequently, their own implementations of IEntity.fromMap()?

What is a good (Kotlin-esque) way around this, since interfaces cannot enforce the implementation of the companion object?

EDIT:
In reference to @aSemy's proposal:

inline fun <reified T : IData> Map<String, String>.toData(): T? {
    return try {
        val jsonMap = Json.encodeToString(this)
        Json.decodeFromString(jsonMap)
    } catch (_: Exception) {
        null
    }
}


问:
Is there a python code that accepts the result of psychometric survey and feeds it as variable into customer risk analysis model(e.g for bank loan)?
I have a python code for mbti and another code for customer risk analysis regarding bank loan.
I am looking for a way to feed the mbti result into my customer risk analysis code.
How can i build a python code that runs a psychometric test and then feeds result into another python code that is a customer financial risk model?

mbti code can be found at https://github.com/CaptainBKola/funTimeWithPython/blob/main/projects/myersbriggs.py
customer financial risk analysis model code can be found at
https://github.com/vishnukanduri/Credit-Risk-Modeling-in-Python/blob/master/Credit%20Risk%20Modeling.ipynb

P.S - I have approached the originator of the afore mentioned python credit risk model(github), asking the question above.
My github entry is below;
https://github.com/vishnukanduri/Credit-Risk-Modeling-in-Python/issues/1#issue-1488813324

Thanks.
Any help to signpost me in right direction is appreciated

I have run the python mbti code above and it ran well.
The credit risk modelling python code did not run because I did not have a pre-existing csv file containing original bank customer's data and variables. I noticed the credit risk modelling python code took a long time to load on jupyter.


问:
Python Cython compatibility between different python versions?
First sorry if the question doesn't fit. English is not my native language. So i'll try to explain.

Let's presume i have python 3.9 installed on my PC

So, with setup.py i build .so files. These .so files will work on others PC with python 3.9 installed only, but it will not work on PC with python 3.8 or python 3.11 installed.

My code is compatible across python 3.8-3.11.

How you solve this? Or better question is, is it possible to solve this?

Build command:
python3 setup.py build_ext --inplace

I suppose if i want to work on other python version i need to build with:

```<code>python3.8 setup.py build_ext --inplace
python3.9 setup.py build_ext --inplace
python3.10 setup.py build_ext --inplace
and so on...
...
</code>```

But this is unacceptable for me. Because i need to install a lot python versions on build computer and ship separately each package.

If is not possible another question is; is there some alternative?

What's the point here?

The point is i need to convert python code to machine code, which need to work no matter what minor python version is on target computer (3.8, 3.9, 3.10 or 3.11).

Cython is great, and i would like to continue with cython, but this 'issue' is no go for me.

Body:
First sorry if the question doesn't fit. English is not my native language. So i'll try to explain.

Let's presume i have python 3.9 installed on my PC

So, with setup.py i build .so files. These .so files will work on others PC with python 3.9 installed only, but it will not work on PC with python 3.8 or python 3.11 installed.

My code is compatible across python 3.8-3.11.

How you solve this? Or better question is, is it possible to solve this?

Build command:
python3 setup.py build_ext --inplace

I suppose if i want to work on other python version i need to build with:

python3.8 setup.py build_ext --inplace
python3.9 setup.py build_ext --inplace
python3.10 setup.py build_ext --inplace
and so on...
...

But this is unacceptable for me. Because i need to install a lot python versions on build computer and ship separately each package.

If is not possible another question is; is there some alternative?

What's the point here?

The point is i need to convert python code to machine code, which need to work no matter what minor python version is on target computer (3.8, 3.9, 3.10 or 3.11).

Cython is great, and i would like to continue with cython, but this 'issue' is no go for me.


问:
I lost the code to my firebase website, is there any way for me to retrieve it?
I deployed my code on firebase for my website, I lost the code is there any way for me to get my code back?

I looked at a other question like the one im asking im pretty sure its outdated so the solutions does not work anymore.


问:
Artefacts when implementing expandable items in RecyclerView
I'm trying to make a simple RecyclerView with expandable items using Kotlin. Basically a list of bins which expand out to show descriptions of what should go in them. I tried to follow the Android Studio Recycler View example as closely as possible. The problem is when I expand each item, some artefacts would show.

Unexpanded view

Expanded view

Note: The expanded view is the result of pressing on "Recycling Bin", the artefact is made up of the bin's description text and also "Garden Waste Bin" somehow being duplicated.

Below is my implementation

Adapter class

```<code>class BinAdapter(private val dataSet: List<Bin>) : RecyclerView.Adapter<BinViewHolder>() {

    var expandedPosition = -1
    var previousExpandedPosition = -1

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BinViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.bin_row_item, parent, false)

        return BinViewHolder(view)
    }

    override fun onBindViewHolder(viewHolder: BinViewHolder, position: Int) {
        viewHolder.itemView.isActivated
        viewHolder.titleView.text = dataSet[position].name
        viewHolder.descriptionView.text = dataSet[position].description
        val isExpanded = position == expandedPosition
        viewHolder.descriptionView.visibility = if (isExpanded) View.VISIBLE else View.GONE
        viewHolder.itemView.isActivated = isExpanded

        if (isExpanded) {
            previousExpandedPosition = position
        }

        viewHolder.itemView.setOnClickListener {
            expandedPosition = if (isExpanded) -1 else position
            notifyItemChanged(previousExpandedPosition)
            notifyItemChanged(position)
        }
    }

    override fun getItemCount() = dataSet.size
</code>```

Fragment class

```<code>class BinLookupFragment : Fragment() {
    private var _binding: FragmentBinLookupBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentBinLookupBinding.inflate(inflater, container, false)

        binding.binRecyclerView.adapter = BinAdapter(BinList(resources))

        return binding.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
</code>```

ViewHolder class

```<code>class BinViewHolder(itemView: View) : ViewHolder(itemView) {
    val titleView: TextView
    val descriptionView: TextView

    init {

        titleView = itemView.findViewById(R.id.titleView)
        descriptionView = itemView.findViewById(R.id.descriptionView)
    }
}
</code>```

Row item layout

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/titleView"
        android:layout_width="@dimen/bin_list_width"
        android:layout_height="@dimen/bin_list_item_title_height"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />

    <TextView
        android:id="@+id/descriptionView"
        android:layout_width="@dimen/bin_list_width"
        android:layout_height="@dimen/bin_list_item_description_height"
        app:layout_constraintTop_toBottomOf="@id/titleView"
        app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

fragment layout

```<code>    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/bin_recycler_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="200dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
    </androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Has anyone come across this before or have some debugging tips?

Body:
I'm trying to make a simple RecyclerView with expandable items using Kotlin. Basically a list of bins which expand out to show descriptions of what should go in them. I tried to follow the Android Studio Recycler View example as closely as possible. The problem is when I expand each item, some artefacts would show.

Unexpanded view

Expanded view

Note: The expanded view is the result of pressing on "Recycling Bin", the artefact is made up of the bin's description text and also "Garden Waste Bin" somehow being duplicated.

Below is my implementation

Adapter class

class BinAdapter(private val dataSet: List<Bin>) : RecyclerView.Adapter<BinViewHolder>() {

    var expandedPosition = -1
    var previousExpandedPosition = -1

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BinViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.bin_row_item, parent, false)

        return BinViewHolder(view)
    }

    override fun onBindViewHolder(viewHolder: BinViewHolder, position: Int) {
        viewHolder.itemView.isActivated
        viewHolder.titleView.text = dataSet[position].name
        viewHolder.descriptionView.text = dataSet[position].description
        val isExpanded = position == expandedPosition
        viewHolder.descriptionView.visibility = if (isExpanded) View.VISIBLE else View.GONE
        viewHolder.itemView.isActivated = isExpanded

        if (isExpanded) {
            previousExpandedPosition = position
        }

        viewHolder.itemView.setOnClickListener {
            expandedPosition = if (isExpanded) -1 else position
            notifyItemChanged(previousExpandedPosition)
            notifyItemChanged(position)
        }
    }

    override fun getItemCount() = dataSet.size

Fragment class

class BinLookupFragment : Fragment() {
    private var _binding: FragmentBinLookupBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentBinLookupBinding.inflate(inflater, container, false)

        binding.binRecyclerView.adapter = BinAdapter(BinList(resources))

        return binding.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

ViewHolder class

class BinViewHolder(itemView: View) : ViewHolder(itemView) {
    val titleView: TextView
    val descriptionView: TextView

    init {

        titleView = itemView.findViewById(R.id.titleView)
        descriptionView = itemView.findViewById(R.id.descriptionView)
    }
}

Row item layout

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/titleView"
        android:layout_width="@dimen/bin_list_width"
        android:layout_height="@dimen/bin_list_item_title_height"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />

    <TextView
        android:id="@+id/descriptionView"
        android:layout_width="@dimen/bin_list_width"
        android:layout_height="@dimen/bin_list_item_description_height"
        app:layout_constraintTop_toBottomOf="@id/titleView"
        app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

fragment layout

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/bin_recycler_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="200dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
    </androidx.constraintlayout.widget.ConstraintLayout>

Has anyone come across this before or have some debugging tips?


问:
How to make a webpage give string input to main.exe running on windows and download word document output?
Hello stack overflow world!

I'm a self-thought programing  enthusiast, with not much experience.

I have made a python script and turned it into .exe that more or less does the following:

Based on user input, opens some webpages and saves them as HTML files,

Runs an excel macro that refreshes power queries connected to those saved files,

Runs a macro in a word document linked to that excel, that smooths out the text and saves output as a word document containing sales a purches agreemnent for a real estate, filled with information scraped online.

I was trying to host this whole operation to a sever, to be able to run it from anywhere. Any ideas how I might be able to do it? I ran out of ides what to type in google in order to procdeed with my little project.

I have looked up Common Gateway Interface (CGI) but I'm not sure if this is the right approach.


问:
INVALID_ARGUMENT: logits and labels must be broadcastable: logits_size=[32,10] labels_size=[32,25]
I'm trying building very basic CNN model for architect style classification using TensorFlow, Keras on M1 Pro(Ventura, on conda virtual-environment)

And this is my code:

*Dataset directory structure

testdataset
_label1
-image1
-image2
_label2
-image3
-image4
...

Data Pipeline building
enter image description here

CNN Model Building
enter image description here

model.summary()
enter image description here

*result
enter image description here

I'm actual noob for this ML area, so I'm in desperate needs for you masters' help.
I've checked if it caused by GPU recognition issue but it recognize my gpu appropriately.

I'd really appreciate for all of your guys effort for my problem and I'd really thankful for just pointing out the trouble point. Also huge love for the resolutions.
Thank you guys. Hope you had a great day so far :P)

I'm actual noob for this ML area, so I'm in desperate needs for you masters' help.
I've checked if it caused by GPU recognition issue but it recognize my gpu appropriately.

I'd really appreciate for all of your guys effort for my problem and I'd really thankful for just pointing out the trouble point. Also huge love for the resolutions.
Thank you guys. Hope you had a great day so far :P)


问:
Babel/Node: how to mix import/export syntax with top-level await
I am starting a Node.js project that uses react-pdf. This means that I need Babel to transpile the TSX syntax into JS code. I am having big trouble to make it work properly. If I want to use import/export syntax, my package.json must say that "type": "commonjs". But, as far as I'm aware, if I want to use top-level await type property must be set to "module". I don't really know what is the difference between both.

So, I set "type": "commonjs", I receive the following error:

```<code>const token = await getAuthToken();
              ^^^^^

SyntaxError: await is only valid in async functions and the top level bodies of modules
</code>```

And now, when "type": "module":

```<code>var _react = _interopRequireDefault(require("react"));
         ^

ReferenceError: require is not defined in ES module scope, you can use import instead
</code>```

I can see that the transpiled files use require() syntax, which is not allowed when type is set to "module". So, isn't there any way to make Babel transpile to import/export syntax, so I can both use this syntax AND top-level await feature?

[EDIT]: As asked, there goes my .babelrc configuration file:

```<code>{
  "presets": [
    [
      "@babel/env",
      { "targets": { "node": 18 } }
    ],
    [
      "@babel/preset-react",
      { "targets": { "node": 18 } }
    ],
    [
      "@babel/preset-typescript",
      { "targets": { "node": 18 } }
    ]
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-object-rest-spread"
  ]
}
</code>```

If it's important, my package.json script line is:

```<code>"run": "babel --extensions .ts,.tsx src -d output && node output/document.js"
</code>```

Body:
I am starting a Node.js project that uses react-pdf. This means that I need Babel to transpile the TSX syntax into JS code. I am having big trouble to make it work properly. If I want to use import/export syntax, my package.json must say that "type": "commonjs". But, as far as I'm aware, if I want to use top-level await type property must be set to "module". I don't really know what is the difference between both.

So, I set "type": "commonjs", I receive the following error:

const token = await getAuthToken();
              ^^^^^

SyntaxError: await is only valid in async functions and the top level bodies of modules

And now, when "type": "module":

var _react = _interopRequireDefault(require("react"));
         ^

ReferenceError: require is not defined in ES module scope, you can use import instead

I can see that the transpiled files use require() syntax, which is not allowed when type is set to "module". So, isn't there any way to make Babel transpile to import/export syntax, so I can both use this syntax AND top-level await feature?

[EDIT]: As asked, there goes my .babelrc configuration file:

{
  "presets": [
    [
      "@babel/env",
      { "targets": { "node": 18 } }
    ],
    [
      "@babel/preset-react",
      { "targets": { "node": 18 } }
    ],
    [
      "@babel/preset-typescript",
      { "targets": { "node": 18 } }
    ]
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-object-rest-spread"
  ]
}

If it's important, my package.json script line is:

"run": "babel --extensions .ts,.tsx src -d output && node output/document.js"