问:
Make a new form through php after checking some values provided from the user
I have a project to do that is entirely in PHP. All the code must be in a single file. I must create a form that accepts the user's name or names, the days of the week checkbox, and an activity as a dropdown list. There is a submit button at the bottom that, when clicked, will take all of the data that the user provided, check it, and then send it to a new form. If the data is incorrect, I'll explain what to look for later, the user will see a message in the first form. All the fields are sticky. I will start with the fact that the user should put some data:

print_text_input, print_text_input, print_activity, printValues(), are functions that take the user's data and do some stuff with it. I will explain them later.

```<code>print("<form action='' method='post'>\n");
print_text_input('text', 'name', 'Όνοματεπώνυμο');
print_day('checkbox', 'days', 'Ημέρα της εβδομάδας');
print_activity('select', 'activity', 'Δραστηριότητα');
print("<button onclick='printValues()'>Υποβολή</button>\n");
print("</form>\n");
</code>```

Here is the first function that takes the name, last name, middle name, etc. and just checks if the pattern letter, space, or letter occurs. I used a regular expression to check that. Also, the user must not put a space before the first word or after the last. Also, this must be sticky.

```<code>function print_text_input($name)
{
    if (isset($_POST['name']) && !empty($_POST['name']))
    {
        $_SESSION[$name] = $_POST['name'];
    }

    print("<p>Ονοματεπώνυμο<input type='text' name='name'");

    if (isset($_SESSION[$name])) {
        print(" value='" . $_SESSION[$name] . "'");
    }

    print(">");

    if(isset($_POST['name']) && !empty($_POST['name']))
    {
        if(preg_match('/^[a-zA-Z]+( [a-zA-Z]+)*$/', $_POST['name']))
        {
            $correct1 = true;
            return $name;
        }
        else
        {
            print("<p>Please enter a valid name with the pattern 'letter, space, letter' and no leading or trailing spaces or double spaces.</p>");
        }
    }
    print("</p>\n");
}
</code>```

Later there is this function, which requires that the user choose at least two days, with one of them being Saturday or Sunday. Also, this is a sticky checkbox.

```<code>function print_day($days)
{
    $strings = array();

    print("<p><b>Ημέρες</b></p>");
    $days = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');

  foreach($days as $day)
  {
    if(isset($_POST['days']) && in_array($day, $_POST['days']))
    {
      $checked = "checked";
    }
    else
    {
      $checked = "";
    }

    print("<input type='checkbox' name='days[]' value='$day' $checked>" . $day . "<br>");
    }

    if(isset($_POST['days']) && count($_POST['days']) >= 2 && (in_array('Saturday', $_POST['days']) || in_array('Sunday', $_POST['days'])))
    {
        $strings[] = $day;
    }
    else
    {
        print("<p>Please select at least two days, including Saturday or Sunday.</p>");
    }
    return $strings;

    print("</p>\n");
}
</code>```

Here's a function that takes an array of activities (in Greek), displays them in a drop-down list, and the user simply selects one of them. Also, this is sticky.

```<code>function print_activity($activity)
{
    $activity = array('Τρέξιμο', 'Κολύμπι', 'Ποδηλασία', 'Ορειβασία', 'Σκι');

    if (isset($_POST['activity']) && !empty($_POST['activity']))
    {
        $_SESSION['activity'] = $_POST['activity'];
    }

    print("<p><label for='activity'>Παρακαλώ επιλέξτε μία δραστηριότητα από τις παρακάτω:</label></p>\n");

    print("<select name='activity' id='activity'>");
    foreach($activity as $option)
    {
        print("<option value='$option'");
        if (isset($_SESSION['activity']) && $_SESSION['activity'] == $option)
        {
            print(" selected");
        }
        print(">$option</option>");
    }
    print("</select>\n");

    if(isset($_POST['activity']) && !empty($_POST['activity']))
    {
        if(in_array($_POST['activity'], $activity))
        {
            return $activity;
        }
        else
        {
            print("<p>Please select a valid activity from the list.</p>");
        }
    }
}
</code>```

At last, there is this method that is used when the user clicks the submit button. It should take the values of the functions above, if the values are correct after the checks in each function occur, and present them as a new form in the same window. What I am trying to say is that the original form with name, days, and activity should "disappear" when the user clicks the submit button and when all the data provided are correct, have a new form with only: Name: "name" , Day: "name of days", Activity: "activity".

```<code>function print_values()
{
    print("<form method='POST'>\n");

    $name1 = print_text_input('name');
    $day1 = print_day('day');
    $activity1 = print_activity('$activity');

    if(isset($_POST['name1']) && isset($_POST['activity1']) && isset($_POST['day1']))
    {
        print("<label>Name: <input type='text' name='name1'></label>\n");
        foreach ($day as $day1)
        {
            print("<li>$day</li>\n");
        }
        print("<label>Activity: <input type='text' name='activity1'></label>\n");
    }
    print("</form>\n");
}
</code>```

-First, I need that the checkbox have a title of Activities inside the checkbox, but it cannot be chosen. That will be an enhansement, so if you are not in the mood to respond to that, that is fine.

-Secondly, the problem is that when I click the submit button, the functions check the inputs and make them sticky, but the submit, as in taking me to a new form, does not work.

Note: All of the code must be in a single file. The new form included.

Thank you in advance for bothering to look in my code.

Body:
I have a project to do that is entirely in PHP. All the code must be in a single file. I must create a form that accepts the user's name or names, the days of the week checkbox, and an activity as a dropdown list. There is a submit button at the bottom that, when clicked, will take all of the data that the user provided, check it, and then send it to a new form. If the data is incorrect, I'll explain what to look for later, the user will see a message in the first form. All the fields are sticky. I will start with the fact that the user should put some data:

print_text_input, print_text_input, print_activity, printValues(), are functions that take the user's data and do some stuff with it. I will explain them later.

print("<form action='' method='post'>\n");
print_text_input('text', 'name', 'Όνοματεπώνυμο');
print_day('checkbox', 'days', 'Ημέρα της εβδομάδας');
print_activity('select', 'activity', 'Δραστηριότητα');
print("<button onclick='printValues()'>Υποβολή</button>\n");
print("</form>\n");

Here is the first function that takes the name, last name, middle name, etc. and just checks if the pattern letter, space, or letter occurs. I used a regular expression to check that. Also, the user must not put a space before the first word or after the last. Also, this must be sticky.

function print_text_input($name)
{
    if (isset($_POST['name']) && !empty($_POST['name']))
    {
        $_SESSION[$name] = $_POST['name'];
    }

    print("
Ονοματεπώνυμο<input type='text' name='name'");

    if (isset($_SESSION[$name])) {
        print(" value='" . $_SESSION[$name] . "'");
    }

    print(">");

    if(isset($_POST['name']) && !empty($_POST['name']))
    {
        if(preg_match('/^[a-zA-Z]+( [a-zA-Z]+)*$/', $_POST['name']))
        {
            $correct1 = true;
            return $name;
        }
        else
        {
            print("
Please enter a valid name with the pattern 'letter, space, letter' and no leading or trailing spaces or double spaces.
");
        }
    }
    print("
\n");
}

Later there is this function, which requires that the user choose at least two days, with one of them being Saturday or Sunday. Also, this is a sticky checkbox.

function print_day($days)
{
    $strings = array();

    print("
Ημέρες
");
    $days = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');

  foreach($days as $day)
  {
    if(isset($_POST['days']) && in_array($day, $_POST['days']))
    {
      $checked = "checked";
    }
    else
    {
      $checked = "";
    }

    print("<input type='checkbox' name='days[]' value='$day' $checked>" . $day . "
");
    }

    if(isset($_POST['days']) && count($_POST['days']) >= 2 && (in_array('Saturday', $_POST['days']) || in_array('Sunday', $_POST['days'])))
    {
        $strings[] = $day;
    }
    else
    {
        print("
Please select at least two days, including Saturday or Sunday.
");
    }
    return $strings;

    print("
\n");
}

Here's a function that takes an array of activities (in Greek), displays them in a drop-down list, and the user simply selects one of them. Also, this is sticky.

function print_activity($activity)
{
    $activity = array('Τρέξιμο', 'Κολύμπι', 'Ποδηλασία', 'Ορειβασία', 'Σκι');

    if (isset($_POST['activity']) && !empty($_POST['activity']))
    {
        $_SESSION['activity'] = $_POST['activity'];
    }

    print("
Παρακαλώ επιλέξτε μία δραστηριότητα από τις παρακάτω:
\n");

    print("<select name='activity' id='activity'>");
    foreach($activity as $option)
    {
        print("<option value='$option'");
        if (isset($_SESSION['activity']) && $_SESSION['activity'] == $option)
        {
            print(" selected");
        }
        print(">$option</option>");
    }
    print("</select>\n");

    if(isset($_POST['activity']) && !empty($_POST['activity']))
    {
        if(in_array($_POST['activity'], $activity))
        {
            return $activity;
        }
        else
        {
            print("
Please select a valid activity from the list.
");
        }
    }
}

At last, there is this method that is used when the user clicks the submit button. It should take the values of the functions above, if the values are correct after the checks in each function occur, and present them as a new form in the same window. What I am trying to say is that the original form with name, days, and activity should "disappear" when the user clicks the submit button and when all the data provided are correct, have a new form with only: Name: "name" , Day: "name of days", Activity: "activity".

function print_values()
{
    print("<form method='POST'>\n");

    $name1 = print_text_input('name');
    $day1 = print_day('day');
    $activity1 = print_activity('$activity');

    if(isset($_POST['name1']) && isset($_POST['activity1']) && isset($_POST['day1']))
    {
        print("Name: <input type='text' name='name1'>\n");
        foreach ($day as $day1)
        {
            print("
$day
\n");
        }
        print("Activity: <input type='text' name='activity1'>\n");
    }
    print("</form>\n");
}

-First, I need that the checkbox have a title of Activities inside the checkbox, but it cannot be chosen. That will be an enhansement, so if you are not in the mood to respond to that, that is fine.

-Secondly, the problem is that when I click the submit button, the functions check the inputs and make them sticky, but the submit, as in taking me to a new form, does not work.

Note: All of the code must be in a single file. The new form included.

Thank you in advance for bothering to look in my code.


来源: stackexchange

问:
Android permission denied when saving file from a non-UI thread
I having trouble with the download of an image from a new thread and saving it into a file.

on some devices it works flawelsly

on others, such as the HTC INCERDIBLE, I am getting an exception

I managed to figure out it is in this line:

```<code>InputStream is=new URL(url).openStream();
</code>```

this is the complete stack dump

```<code>import java.io.InputStream;

Bitmap bitmap=null;
InputStream is=new URL(url).openStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
</code>```

```<code>D/dalvikvm( 1930): GC_EXPLICIT freed 26K, 47% free 3642K/6855K, external 0K/0K, paused 90ms
W/System.err( 2669): java.io.FileNotFoundException: /mnt/sdcard/com.example.testing1/remote-image-cache/74110ca30e217cfdcc78a98f814de093c217bc07.hdr (Permission denied)
W/System.err( 2669):    at org.apache.harmony.luni.platform.OSFileSystem.open(Native Method)
W/System.err( 2669):    at dalvik.system.BlockGuard$WrappedFileSystem.open(BlockGuard.java:232)
W/System.err( 2669):    at java.io.FileOutputStream.<init>(FileOutputStream.java:94)
W/System.err( 2669):    at java.io.FileOutputStream.<init>(FileOutputStream.java:66)
W/System.err( 2669):    at java.io.FileWriter.<init>(FileWriter.java:42)
W/System.err( 2669):    at org.appcelerator.titanium.util.TiResponseCache.put(TiResponseCache.java:359)
W/System.err( 2669):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.maybeCache(HttpURLConnectionImpl.java:331)
W/System.err( 2669):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1043)
W/System.err( 2669):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:512)
W/System.err( 2669):    at java.net.URL.openStream(URL.java:645)
W/System.err( 2669):    at ti.testing.ImageLoader.getBitmap(ImageLoader.java:163)
W/System.err( 2669):    at ti.testing.ImageLoader.access$100(ImageLoader.java:29)
W/System.err( 2669):    at ti.testing.ImageLoader$PhotosLoader.run(ImageLoader.java:256)
</code>```

My manifest.xml file includes many permissions:

```<code></application>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
</code>```

this is how I am getting the file path

```<code>   if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
    else
        cacheDir=context.getCacheDir();
</code>```

I don't understand it... Ideas ?

EDIT

I tried changing:

```<code>cacheDir=new File("/mnt/","emmc");
</code>```

but now I get:

```<code>W/System.err( 404): java.io.FileNotFoundException: /mnt/emmc/cp_1216407347.jpeg
(No such file or directory)
</code>```

I tried changing cacheDir=new File("/mnt/","emmc"); but now I get W/System.err( 404): java.io.FileNotFoundException: /mnt/emmc/cp_1216407347.jpeg (No such file or directory)

ContentLicense: CC BY-SA 3.0

Body:
I having trouble with the download of an image from a new thread and saving it into a file.

on some devices it works flawelsly

on others, such as the HTC INCERDIBLE, I am getting an exception

I managed to figure out it is in this line:

InputStream is=new URL(url).openStream();

this is the complete stack dump

import java.io.InputStream;

Bitmap bitmap=null;
InputStream is=new URL(url).openStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();

D/dalvikvm( 1930): GC_EXPLICIT freed 26K, 47% free 3642K/6855K, external 0K/0K, paused 90ms
W/System.err( 2669): java.io.FileNotFoundException: /mnt/sdcard/com.example.testing1/remote-image-cache/74110ca30e217cfdcc78a98f814de093c217bc07.hdr (Permission denied)
W/System.err( 2669):    at org.apache.harmony.luni.platform.OSFileSystem.open(Native Method)
W/System.err( 2669):    at dalvik.system.BlockGuard$WrappedFileSystem.open(BlockGuard.java:232)
W/System.err( 2669):    at java.io.FileOutputStream.<init>(FileOutputStream.java:94)
W/System.err( 2669):    at java.io.FileOutputStream.<init>(FileOutputStream.java:66)
W/System.err( 2669):    at java.io.FileWriter.<init>(FileWriter.java:42)
W/System.err( 2669):    at org.appcelerator.titanium.util.TiResponseCache.put(TiResponseCache.java:359)
W/System.err( 2669):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.maybeCache(HttpURLConnectionImpl.java:331)
W/System.err( 2669):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1043)
W/System.err( 2669):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:512)
W/System.err( 2669):    at java.net.URL.openStream(URL.java:645)
W/System.err( 2669):    at ti.testing.ImageLoader.getBitmap(ImageLoader.java:163)
W/System.err( 2669):    at ti.testing.ImageLoader.access$100(ImageLoader.java:29)
W/System.err( 2669):    at ti.testing.ImageLoader$PhotosLoader.run(ImageLoader.java:256)

My manifest.xml file includes many permissions:

</application>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>

this is how I am getting the file path

   if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
    else
        cacheDir=context.getCacheDir();

I don't understand it... Ideas ?

EDIT

I tried changing:

cacheDir=new File("/mnt/","emmc");

but now I get:

W/System.err( 404): java.io.FileNotFoundException: /mnt/emmc/cp_1216407347.jpeg
(No such file or directory)

I tried changing cacheDir=new File("/mnt/","emmc"); but now I get W/System.err( 404): java.io.FileNotFoundException: /mnt/emmc/cp_1216407347.jpeg (No such file or directory)


问:
get Websphere installed application mapped shared lIbrary using jython script
I want to list the  current mapped Shared libraries for specific application name

this is how i use for Shared lib mapping

AdminApp.edit(''+eval("app_Name")+'', '[ -MapSharedLibForMod [[ "'+eval("app_Name")+'" META-INF/application.xml "'+"shared_lib_name+'"]]]' )

ContentLicense: CC BY-SA 4.0


问:
Wrong picture size when loading .docx file
I am using xceedsoftware/DocX library to load docx file and get picture size in it. When I open this file in MS Word in shows image size 93.7x77.8 millimeters. But when I open file with docx library it shows picture size 265x220. How to get right size in millimeters? I noticed that coefficient between word size and library size is always around 0.353 (93.7/265 = 0.353) or  2.82 (265/93.7=2.82) but I can't find which unit of measurement corresponds to that.</p>


问:
"Cannot read properties of undefined (reading 'commit')" in nuxt
i dont know why am i getting this error

Here is my code in component:

```<code>export default{

 methods: {
    updateHighPrice($event) {
      this.$store.commit('setHighPrice', $event.target.value)
    },
}
</code>```

and her is my code in store.js

```<code>const store = createStore({
  state () {
    return {
        cart:[],
        cartItems:0,
        checkoutStatus: null,
        highprice: 1500,
        sale: false
    }
  },
   mutations:{
    setHighPrice(state, event) {
        state.highprice = event
      },
}
})
</code>```

I tried to change 'commit' to 'dispatch' but it still not working

Body:
i dont know why am i getting this error

Here is my code in component:

export default{

 methods: {
    updateHighPrice($event) {
      this.$store.commit('setHighPrice', $event.target.value)
    },
}

and her is my code in store.js

const store = createStore({
  state () {
    return {
        cart:[],
        cartItems:0,
        checkoutStatus: null,
        highprice: 1500,
        sale: false
    }
  },
   mutations:{
    setHighPrice(state, event) {
        state.highprice = event
      },
}
})

I tried to change 'commit' to 'dispatch' but it still not working


问:
use ArrayKey inside NodeJs Script on Ubuntu Bash Container
i developped on WIndows , a NodeJs Script with many console Menu.
The user can navigate throught the menu with arrayKey and select the commands option. ( console ).

It works fine on VsCode Terminal, Windows Termina and CMD....

I tryed to use Docker and created an Ubuntu Container to lauchan the script.... but i cannot use the  arrayKey to navigate on the menu :
This is the result when i use the keyboard Arrays.

Any Idea how to fix it ?


问:
NodeJS SpeechRecorder pipe to child process ffmpeg encoder - dest.on is not a function
Trying to make a utility to help me with recording words for something.  Unfortunately getting stuck on the basics.

The error I get when I hit s key and talk enough to fill the buffer is

```<code>terminate called after throwing an instance of 'Napi::Error'
  what():  dest.on is not a function
[1]    2298218 IOT instruction (core dumped)  node record.js
</code>```

Code is below. I can write the wav file and then encode that but I'd rather not have to have an intermediate file unless there is no way around it, and I can't imagine that is the case.

```<code>const { spawn } = require('child_process');
const { writeFileSync } = require('fs');
const readline = require('readline');
const { SpeechRecorder } = require('speech-recorder');
const { WaveFile } = require('wavefile');

let paused = true;

const ffmpeg = spawn('ffmpeg', [
 // '-f', 's16', // input format
  //'-sample_rate', '16000',
  '-i', '-', // input source
  '-c:a', 'libvorbis', // audio codec
  'output.ogg', // output file
  '-y'
]);

let buffer = [];
const recorder = new SpeechRecorder({
  onAudio: ({ audio, speech }) => {
    //if(speech) {

      for (let i = 0; i < audio.length; i++) {
        buffer.push(audio[i]);
      }

      if(buffer.length >= 16000 * 5) {
        console.log('piping to ffmpeg for output');
        let wav = new WaveFile()
        wav.fromScratch(1,16000,"16",buffer);
        //writeFileSync('output.wav',wav.toBuffer());
        ffmpeg.stdin.pipe(buffer, {end: false});
      }
    //}
  }
});

// listen for keypress events
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);

process.stdin.on('keypress', (str, key) => {
  if (key.name === 's') {
    // pause or resume recording
    paused = !paused;
    if(paused) { recorder.stop(); } else { recorder.start(); }

  } else if (key.ctrl && key.name === 'c') {
    // exit program
    ffmpeg.kill('SIGINT');
    process.exit();
  }
});
</code>```

Body:
Trying to make a utility to help me with recording words for something.  Unfortunately getting stuck on the basics.

The error I get when I hit s key and talk enough to fill the buffer is

terminate called after throwing an instance of 'Napi::Error'
  what():  dest.on is not a function
[1]    2298218 IOT instruction (core dumped)  node record.js

Code is below. I can write the wav file and then encode that but I'd rather not have to have an intermediate file unless there is no way around it, and I can't imagine that is the case.

const { spawn } = require('child_process');
const { writeFileSync } = require('fs');
const readline = require('readline');
const { SpeechRecorder } = require('speech-recorder');
const { WaveFile } = require('wavefile');

let paused = true;

const ffmpeg = spawn('ffmpeg', [
 // '-f', 's16', // input format
  //'-sample_rate', '16000',
  '-i', '-', // input source
  '-c:a', 'libvorbis', // audio codec
  'output.ogg', // output file
  '-y'
]);

let buffer = [];
const recorder = new SpeechRecorder({
  onAudio: ({ audio, speech }) => {
    //if(speech) {

      for (let i = 0; i < audio.length; i++) {
        buffer.push(audio[i]);
      }

      if(buffer.length >= 16000 * 5) {
        console.log('piping to ffmpeg for output');
        let wav = new WaveFile()
        wav.fromScratch(1,16000,"16",buffer);
        //writeFileSync('output.wav',wav.toBuffer());
        ffmpeg.stdin.pipe(buffer, {end: false});
      }
    //}
  }
});

// listen for keypress events
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);

process.stdin.on('keypress', (str, key) => {
  if (key.name === 's') {
    // pause or resume recording
    paused = !paused;
    if(paused) { recorder.stop(); } else { recorder.start(); }

  } else if (key.ctrl && key.name === 'c') {
    // exit program
    ffmpeg.kill('SIGINT');
    process.exit();
  }
});


问:
How to detect protrusions in a straight line which arent necessarily horizontal/vertical?
So i have images similar to this
And I need to count how many protrusions there are coming out of the main thick line. I have no idea how to tackle this so I need ideas.
First thing i did was extract the whoe line from the photo so its a black and white photo with the white pixels being only the grey line. With some noise but it'll do for now. But the biggest problem is detection if theres a protrusion in it. Thought about detecting horizontal lines but it wont work as the protrusions arent always horizontal like in the example shown. They are horizontal in some cases but not all.


问:
Binary XML file line #9 in com.client:layout/stripe_card_form_view
I have been following this guide for Stripe API:

https://github.com/material-components/material-components-android/blob/master/docs/getting-started.md#4-change-your-app-theme-to-inherit-from-a-material-components-theme

I am trying to implement Stripe in react native and I would like to use the CardForm from this library but there is additional setup for this case which is included from above.

But for some reason, I am getting this error:

android/app/build.gradle:

```<code>dependencies {
   implementation 'androidx.appcompat:appcompat:1.4.1'
   implementation 'com.google.android.material:material:1.6.0'
}
</code>```

package.json

```<code>"dependencies": {
    "@stripe/stripe-react-native": "^0.22.0"
}
</code>```

Component:

```<code>import { StyleSheet, Text, View, Modal } from 'react-native';
import React from 'react';
import {
  StripeProvider,
  usePaymentSheet,
  CardField,
  CardForm,
  useStripe,
} from '@stripe/stripe-react-native';

const PaymentModal = () => {

  function PaymentScreen() {
    return (
      <View>
        <CardForm
          postalCodeEnabled={true}
          cardStyle={{
            backgroundColor: '#FFFFFF',
            textColor: '#000000',
            borderWidth: 1,
          }}
          style={{
            width: '100%',
            height: 50,
            marginVertical: 30,
          }}
          onCardChange={cardDetails => {
            setCard(cardDetails);
          }}
          onFocus={focusedField => {
            console.log('focusField', focusedField);
          }}
        />
      </View>
    );
  }

  return (
    <Modal
      visible={true}
      transparent={true}
      animationType="slide"
      onRequestClose={() => null}>
      <View
        style={{
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          flex: 1,
          alignItems: "center",
          justifyContent: "flex-end"
        }}>
        <View style={{
          width: "100%",
          height: "60%",
          backgroundColor: "white"
        }}>
          <StripeProvider publishableKey="pk_test_51MBYAwFjaRQnIgRgw0j5Qo40oXqM5UijDDo5L6ynKB68VZJ3KLJN0b90b9HNpJ90c4CJqe7BHR2kvKSQOW45Z2yb00A0I2UpnH">
            <PaymentScreen />
            {/* <Button title='Buy' onPress={buy} /> */}
          </StripeProvider>
        </View>
      </View>
    </Modal>
  );
}

export default PaymentModal

const styles = StyleSheet.create({})
</code>```

Body:
I have been following this guide for Stripe API:

https://github.com/material-components/material-components-android/blob/master/docs/getting-started.md#4-change-your-app-theme-to-inherit-from-a-material-components-theme

I am trying to implement Stripe in react native and I would like to use the CardForm from this library but there is additional setup for this case which is included from above.

But for some reason, I am getting this error:

android/app/build.gradle:

dependencies {
   implementation 'androidx.appcompat:appcompat:1.4.1'
   implementation 'com.google.android.material:material:1.6.0'
}

package.json

"dependencies": {
    "@stripe/stripe-react-native": "^0.22.0"
}

Component:

import { StyleSheet, Text, View, Modal } from 'react-native';
import React from 'react';
import {
  StripeProvider,
  usePaymentSheet,
  CardField,
  CardForm,
  useStripe,
} from '@stripe/stripe-react-native';

const PaymentModal = () => {

  function PaymentScreen() {
    return (
      <View>
        <CardForm
          postalCodeEnabled={true}
          cardStyle={{
            backgroundColor: '#FFFFFF',
            textColor: '#000000',
            borderWidth: 1,
          }}
          style={{
            width: '100%',
            height: 50,
            marginVertical: 30,
          }}
          onCardChange={cardDetails => {
            setCard(cardDetails);
          }}
          onFocus={focusedField => {
            console.log('focusField', focusedField);
          }}
        />
      </View>
    );
  }

  return (
    <Modal
      visible={true}
      transparent={true}
      animationType="slide"
      onRequestClose={() => null}>
      <View
        style={{
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          flex: 1,
          alignItems: "center",
          justifyContent: "flex-end"
        }}>
        <View style={{
          width: "100%",
          height: "60%",
          backgroundColor: "white"
        }}>
          <StripeProvider publishableKey="pk_test_51MBYAwFjaRQnIgRgw0j5Qo40oXqM5UijDDo5L6ynKB68VZJ3KLJN0b90b9HNpJ90c4CJqe7BHR2kvKSQOW45Z2yb00A0I2UpnH">
            <PaymentScreen />
            {/* <Button title='Buy' onPress={buy} /> */}
          </StripeProvider>
        </View>
      </View>
    </Modal>
  );
}

export default PaymentModal

const styles = StyleSheet.create({})


问:
Left or right swipe through a page of ItemsDetailsView within destination of NavigationLink
Using the code below, I'm displaying a list of filtered items that when clicked leads to a detailed items page ItemDetailView(item: item) for that specific row. I am trying to make it so that the user, once on the details page can then swipe left or right to go either up or down the list of filtered items and view the detailed page of those without having to navigate back to the list view.

So for instance, if they click on item 2 in a list of 5 items it takes them to the details of item 2 through NavigationLink. Once on the details page, I want to be able to swipe left to see the details page for item 1. Likewise, if I swipe right, I want to be able to see the details for item 3.

```<code>if let filteredItems = itemModel.items.filter { $0.isBetween(dateSelected.date!.startOfDay) } { ForEach(foundItems) { item in
NavigationLink ( destination: ItemDetailView(item: item) ) { ListViewRow(item:item)} }
</code>```

I've tried using TabView with the code below, but once in the details view, I end up with a vertically scrollable details view of each item. Any suggestions on how I can accomplish the result I'm looking for? Any hints pointing me in the right direction would be appreciated.

```<code>if let filteredItems = itemModel.items.filter { $0.isBetween(dateSelected.date!.startOfDay) } { ForEach(foundItems) { item in
NavigationLink(
destination: TabView(){
List(itemModel.items) {item in ItemDetailView(item: item) }
}.tabViewStyle(.page)
) { ListViewRow(item:item) }
} }
</code>```

Diagram:

Body:
Using the code below, I'm displaying a list of filtered items that when clicked leads to a detailed items page ItemDetailView(item: item) for that specific row. I am trying to make it so that the user, once on the details page can then swipe left or right to go either up or down the list of filtered items and view the detailed page of those without having to navigate back to the list view.

So for instance, if they click on item 2 in a list of 5 items it takes them to the details of item 2 through NavigationLink. Once on the details page, I want to be able to swipe left to see the details page for item 1. Likewise, if I swipe right, I want to be able to see the details for item 3.

if let filteredItems = itemModel.items.filter { $0.isBetween(dateSelected.date!.startOfDay) } { ForEach(foundItems) { item in
NavigationLink ( destination: ItemDetailView(item: item) ) { ListViewRow(item:item)} }

I've tried using TabView with the code below, but once in the details view, I end up with a vertically scrollable details view of each item. Any suggestions on how I can accomplish the result I'm looking for? Any hints pointing me in the right direction would be appreciated.

if let filteredItems = itemModel.items.filter { $0.isBetween(dateSelected.date!.startOfDay) } { ForEach(foundItems) { item in
NavigationLink(
destination: TabView(){
List(itemModel.items) {item in ItemDetailView(item: item) }
}.tabViewStyle(.page)
) { ListViewRow(item:item) }
} }

Diagram:


问:
elastic beanstalk error when use sh ./platform/hooks/prebuild : no such file or directory
I'm trying to deploy simple front-end web by elastic beanstalk.

When I deploy my app by eb deploy or eb create --elb-type application --instance-type t3.micro, There are an error when executing an sh that I add to prevent Out Of Memory.

```<code>2022/12/10 08:20:43.618277 [INFO] Executing instruction: StageApplication
2022/12/10 08:20:43.620012 [INFO] extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/
2022/12/10 08:20:43.620027 [INFO] Running command /bin/sh -c /usr/bin/unzip -q -o /opt/elasticbeanstalk/deployment/app_source_bundle -d /var/app/staging/
2022/12/10 08:20:43.646596 [INFO] finished extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/ successfully
2022/12/10 08:20:43.647365 [INFO] Executing instruction: RunAppDeployPreBuildHooks
2022/12/10 08:20:43.647379 [INFO] Executing platform hooks in .platform/hooks/prebuild/
2022/12/10 08:20:43.647409 [INFO] Following scripts will be executed in order: [00_test.sh 01_configure_swap_space.sh]
2022/12/10 08:20:43.647413 [INFO] Try add execution permission
2022/12/10 08:20:43.647418 [INFO] Adding execute mode to file, original mode is 420
2022/12/10 08:20:43.647428 [INFO] Running script: .platform/hooks/prebuild/00_test.sh
2022/12/10 08:20:43.647663 [ERROR] An error occurred during execution of command [app-deploy] - [RunAppDeployPreBuildHooks]. Stop running the command. Error: Command .platform/hooks/prebuild/00_test.sh failed with error fork/exec .platform/hooks/prebuild/00_test.sh: no such file or directory

2022/12/10 08:20:43.647668 [INFO] Executing cleanup logic
2022/12/10 08:20:43.647752 [INFO] CommandService Response: {"status":"FAILURE","api_version":"1.0","results":[{"status":"FAILURE","msg":"Engine execution has encountered an error.","returncode":1,"events":[{"msg":"Instance deployment failed. For details, see 'eb-engine.log'.","timestamp":1670660443647,"severity":"ERROR"}]}]}

2022/12/10 08:20:43.648454 [INFO] Platform Engine finished execution on command: app-deploy
</code>```

I created an 00_test.sh echoing simple statement in exactly same location and chomd 777 to them. But it still doesn't work.

Some post(/.platform/hooks/': No such file or directory when deploying Django App to AWS Elastic Beanstalk) said it depends on OS, so I also tried to this all process with in vscode.

If someone who experienced same situation, want to know why this happened and solution.

Body:
I'm trying to deploy simple front-end web by elastic beanstalk.

When I deploy my app by eb deploy or eb create --elb-type application --instance-type t3.micro, There are an error when executing an sh that I add to prevent Out Of Memory.

2022/12/10 08:20:43.618277 [INFO] Executing instruction: StageApplication
2022/12/10 08:20:43.620012 [INFO] extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/
2022/12/10 08:20:43.620027 [INFO] Running command /bin/sh -c /usr/bin/unzip -q -o /opt/elasticbeanstalk/deployment/app_source_bundle -d /var/app/staging/
2022/12/10 08:20:43.646596 [INFO] finished extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/ successfully
2022/12/10 08:20:43.647365 [INFO] Executing instruction: RunAppDeployPreBuildHooks
2022/12/10 08:20:43.647379 [INFO] Executing platform hooks in .platform/hooks/prebuild/
2022/12/10 08:20:43.647409 [INFO] Following scripts will be executed in order: [00_test.sh 01_configure_swap_space.sh]
2022/12/10 08:20:43.647413 [INFO] Try add execution permission
2022/12/10 08:20:43.647418 [INFO] Adding execute mode to file, original mode is 420
2022/12/10 08:20:43.647428 [INFO] Running script: .platform/hooks/prebuild/00_test.sh
2022/12/10 08:20:43.647663 [ERROR] An error occurred during execution of command [app-deploy] - [RunAppDeployPreBuildHooks]. Stop running the command. Error: Command .platform/hooks/prebuild/00_test.sh failed with error fork/exec .platform/hooks/prebuild/00_test.sh: no such file or directory

2022/12/10 08:20:43.647668 [INFO] Executing cleanup logic
2022/12/10 08:20:43.647752 [INFO] CommandService Response: {"status":"FAILURE","api_version":"1.0","results":[{"status":"FAILURE","msg":"Engine execution has encountered an error.","returncode":1,"events":[{"msg":"Instance deployment failed. For details, see 'eb-engine.log'.","timestamp":1670660443647,"severity":"ERROR"}]}]}

2022/12/10 08:20:43.648454 [INFO] Platform Engine finished execution on command: app-deploy

I created an 00_test.sh echoing simple statement in exactly same location and chomd 777 to them. But it still doesn't work.

Some post(/.platform/hooks/': No such file or directory when deploying Django App to AWS Elastic Beanstalk) said it depends on OS, so I also tried to this all process with in vscode.

If someone who experienced same situation, want to know why this happened and solution.


问:
How to parse gunzip response body data coming from Twitter's /oauth2/token route in NodeJs using node-fetch?
I am trying to get access_token from Twitter for every user that authenticates through Twitter to my app. I've got code from Twitter but I have to send POST request to https://twitter.com/i/oauth2/token to get access_token. I am using node-fetch library  to make requests. I am even getting OK, 200 status from server. But I am unable to parse response body to get access_token. Is there a way to parse this? My code:

```<code>            const response = await fetch('https://twitter.com/i/oauth2/token', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    Authorization: `Basic ${Buffer.from(process.env.TWITTER_CLIENT_ID + ':' + process.env.TWITTER_CLIENT_SECRET).toString('base64')}`,
                },
                body: new URLSearchParams({
                    code: req.query['code'] as string,
                    grant_type: 'authorization_code',
                    code_verifier: 'challenge',
                }),
            });

            console.log(response)
</code>```

And I am getting this response:

```<code>Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: Gunzip {
      _writeState: [Uint32Array],
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      bytesWritten: 0,
      _handle: [Zlib],
      _outBuffer: <Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0a 3c 68 74 6d 6c 20 64 69 72 3d 22 6c 74 72 22 20 6c 61 6e 67 3d 22 65 6e 22 3e 0a 3c 68 65 61 64 3e 0a ... 16334 more bytes>,
      _outOffset: 0,
      _chunkSize: 16384,
      _defaultFlushFlag: 2,
      _finishFlushFlag: 2,
      _defaultFullFlushFlag: 3,
      _info: undefined,
      _maxOutputLength: 4294967296,
      _level: -1,
      _strategy: 0,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null,
      [Symbol(kError)]: null
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'https://twitter.com/i/oauth2/token',
    status: 200,
    statusText: 'OK',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}
</code>```

I tried to use response.json(). But it gave me an error:

```<code>FetchError: invalid json response body at https://twitter.com/i/oauth2/token reason: Unexpected token < in JSON at position 0
    at D:\Fireart\digest\package\backend\node_modules\node-fetch\lib\index.js:273:32
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async AuthController.twitterAuth (D:\Fireart\digest\package\backend\src\controllers\auth.controller.ts:249:25) {
  type: 'invalid-json'
}
[GET] /auth/twitter/callback >> StatusCode:: 500, Error:: INTERNAL_ERROR, Message:: invalid json response body at https://twitter.com/i/oauth2/token reason: Unexpected token < in JSON at position 0
</code>```

I also tried to use response.text(). But it gave me HTML code that does not have access_token. The tried to access response.body. I got this:

```<code><ref *1> Gunzip {
  _writeState: Uint32Array(2) [ 0, 0 ],
  _readableState: ReadableState {
    objectMode: false,
    highWaterMark: 16384,
    buffer: BufferList { head: null, tail: null, length: 0 },
    length: 0,
    pipes: [],
    flowing: null,
    ended: false,
    endEmitted: false,
    reading: false,
    constructed: true,
    sync: false,
    needReadable: false,
    emittedReadable: false,
    readableListening: false,
    resumeScheduled: false,
    errorEmitted: false,
    emitClose: true,
    autoDestroy: true,
    destroyed: false,
    errored: null,
    closed: false,
    closeEmitted: false,
    defaultEncoding: 'utf8',
    awaitDrainWriters: null,
    multiAwaitDrain: false,
    readingMore: false,
    dataEmitted: false,
    decoder: null,
    encoding: null,
    [Symbol(kPaused)]: null
  },
  _events: [Object: null prototype] {
    prefinish: [Function: prefinish],
    unpipe: [Function: onunpipe],
    error: [ [Function: onerror], [Function (anonymous)] ],
    close: [Function: bound onceWrapper] { listener: [Function: onclose] },
    finish: [Function: bound onceWrapper] { listener: [Function: onfinish] }
  },
  _eventsCount: 5,
  _maxListeners: undefined,
  _writableState: WritableState {
    objectMode: false,
    highWaterMark: 16384,
    finalCalled: false,
    needDrain: false,
    ending: false,
    ended: false,
    finished: false,
    destroyed: false,
    decodeStrings: true,
    defaultEncoding: 'utf8',
    length: 493,
    writing: true,
    corked: 0,
    sync: false,
    bufferProcessing: false,
    onwrite: [Function: bound onwrite],
    writecb: [Function: nop],
    writelen: 159,
    afterWriteTickInfo: null,
    buffered: [
      [Object], [Object],
      [Object], [Object],
      [Object], [Object],
      [Object]
    ],
    bufferedIndex: 0,
    allBuffers: true,
    allNoop: true,
    pendingcb: 8,
    constructed: true,
    prefinished: false,
    errorEmitted: false,
    emitClose: true,
    autoDestroy: true,
    errored: null,
    closed: false,
    closeEmitted: false,
    [Symbol(kOnFinished)]: []
  },
  allowHalfOpen: true,
  bytesWritten: 0,
  _handle: Zlib {
    onerror: [Function: zlibOnError],
    buffer: <Buffer 1f 8b 08 00 00 00 00 00 00 00 3c 8d b1 0e c2 30 0c 44 77 be 22 78 6e 04 6c 0c 35 0b 30 c3 c0 c2 68 12 97 5a 4a 52 94 ba 2d 9f 4f 5a a9 4c a7 a7 77 ba ... 109 more bytes>,
    cb: [Function (anonymous)],
    availOutBefore: 16384,
    availInBefore: 159,
    inOff: 0,
    flushFlag: 2,
    [Symbol(owner_symbol)]: [Circular *1]
  },
  _outBuffer: <Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0a 3c 68 74 6d 6c 20 64 69 72 3d 22 6c 74 72 22 20 6c 61 6e 67 3d 22 65 6e 22 3e 0a 3c 68 65 61 64 3e 0a ... 16334 more bytes>,
  _outOffset: 0,
  _chunkSize: 16384,
  _defaultFlushFlag: 2,
  _finishFlushFlag: 2,
  _defaultFullFlushFlag: 3,
  _info: undefined,
  _maxOutputLength: 4294967296,
  _level: -1,
  _strategy: 0,
  [Symbol(kCapture)]: false,
  [Symbol(kCallback)]: null,
  [Symbol(kError)]: null
}
</code>```

Please help. Is there a way to get access token?

Body:
I am trying to get access_token from Twitter for every user that authenticates through Twitter to my app. I've got code from Twitter but I have to send POST request to https://twitter.com/i/oauth2/token to get access_token. I am using node-fetch library  to make requests. I am even getting OK, 200 status from server. But I am unable to parse response body to get access_token. Is there a way to parse this? My code:

            const response = await fetch('https://twitter.com/i/oauth2/token', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    Authorization: `Basic ${Buffer.from(process.env.TWITTER_CLIENT_ID + ':' + process.env.TWITTER_CLIENT_SECRET).toString('base64')}`,
                },
                body: new URLSearchParams({
                    code: req.query['code'] as string,
                    grant_type: 'authorization_code',
                    code_verifier: 'challenge',
                }),
            });

            console.log(response)

And I am getting this response:

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: Gunzip {
      _writeState: [Uint32Array],
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      bytesWritten: 0,
      _handle: [Zlib],
      _outBuffer: <Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0a 3c 68 74 6d 6c 20 64 69 72 3d 22 6c 74 72 22 20 6c 61 6e 67 3d 22 65 6e 22 3e 0a 3c 68 65 61 64 3e 0a ... 16334 more bytes>,
      _outOffset: 0,
      _chunkSize: 16384,
      _defaultFlushFlag: 2,
      _finishFlushFlag: 2,
      _defaultFullFlushFlag: 3,
      _info: undefined,
      _maxOutputLength: 4294967296,
      _level: -1,
      _strategy: 0,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null,
      [Symbol(kError)]: null
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'https://twitter.com/i/oauth2/token',
    status: 200,
    statusText: 'OK',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}

I tried to use response.json(). But it gave me an error:

FetchError: invalid json response body at https://twitter.com/i/oauth2/token reason: Unexpected token < in JSON at position 0
    at D:\Fireart\digest\package\backend\node_modules\node-fetch\lib\index.js:273:32
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async AuthController.twitterAuth (D:\Fireart\digest\package\backend\src\controllers\auth.controller.ts:249:25) {
  type: 'invalid-json'
}
[GET] /auth/twitter/callback >> StatusCode:: 500, Error:: INTERNAL_ERROR, Message:: invalid json response body at https://twitter.com/i/oauth2/token reason: Unexpected token < in JSON at position 0

I also tried to use response.text(). But it gave me HTML code that does not have access_token. The tried to access response.body. I got this:

<ref *1> Gunzip {
  _writeState: Uint32Array(2) [ 0, 0 ],
  _readableState: ReadableState {
    objectMode: false,
    highWaterMark: 16384,
    buffer: BufferList { head: null, tail: null, length: 0 },
    length: 0,
    pipes: [],
    flowing: null,
    ended: false,
    endEmitted: false,
    reading: false,
    constructed: true,
    sync: false,
    needReadable: false,
    emittedReadable: false,
    readableListening: false,
    resumeScheduled: false,
    errorEmitted: false,
    emitClose: true,
    autoDestroy: true,
    destroyed: false,
    errored: null,
    closed: false,
    closeEmitted: false,
    defaultEncoding: 'utf8',
    awaitDrainWriters: null,
    multiAwaitDrain: false,
    readingMore: false,
    dataEmitted: false,
    decoder: null,
    encoding: null,
    [Symbol(kPaused)]: null
  },
  _events: [Object: null prototype] {
    prefinish: [Function: prefinish],
    unpipe: [Function: onunpipe],
    error: [ [Function: onerror], [Function (anonymous)] ],
    close: [Function: bound onceWrapper] { listener: [Function: onclose] },
    finish: [Function: bound onceWrapper] { listener: [Function: onfinish] }
  },
  _eventsCount: 5,
  _maxListeners: undefined,
  _writableState: WritableState {
    objectMode: false,
    highWaterMark: 16384,
    finalCalled: false,
    needDrain: false,
    ending: false,
    ended: false,
    finished: false,
    destroyed: false,
    decodeStrings: true,
    defaultEncoding: 'utf8',
    length: 493,
    writing: true,
    corked: 0,
    sync: false,
    bufferProcessing: false,
    onwrite: [Function: bound onwrite],
    writecb: [Function: nop],
    writelen: 159,
    afterWriteTickInfo: null,
    buffered: [
      [Object], [Object],
      [Object], [Object],
      [Object], [Object],
      [Object]
    ],
    bufferedIndex: 0,
    allBuffers: true,
    allNoop: true,
    pendingcb: 8,
    constructed: true,
    prefinished: false,
    errorEmitted: false,
    emitClose: true,
    autoDestroy: true,
    errored: null,
    closed: false,
    closeEmitted: false,
    [Symbol(kOnFinished)]: []
  },
  allowHalfOpen: true,
  bytesWritten: 0,
  _handle: Zlib {
    onerror: [Function: zlibOnError],
    buffer: <Buffer 1f 8b 08 00 00 00 00 00 00 00 3c 8d b1 0e c2 30 0c 44 77 be 22 78 6e 04 6c 0c 35 0b 30 c3 c0 c2 68 12 97 5a 4a 52 94 ba 2d 9f 4f 5a a9 4c a7 a7 77 ba ... 109 more bytes>,
    cb: [Function (anonymous)],
    availOutBefore: 16384,
    availInBefore: 159,
    inOff: 0,
    flushFlag: 2,
    [Symbol(owner_symbol)]: [Circular *1]
  },
  _outBuffer: <Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0a 3c 68 74 6d 6c 20 64 69 72 3d 22 6c 74 72 22 20 6c 61 6e 67 3d 22 65 6e 22 3e 0a 3c 68 65 61 64 3e 0a ... 16334 more bytes>,
  _outOffset: 0,
  _chunkSize: 16384,
  _defaultFlushFlag: 2,
  _finishFlushFlag: 2,
  _defaultFullFlushFlag: 3,
  _info: undefined,
  _maxOutputLength: 4294967296,
  _level: -1,
  _strategy: 0,
  [Symbol(kCapture)]: false,
  [Symbol(kCallback)]: null,
  [Symbol(kError)]: null
}

Please help. Is there a way to get access token?


问:
Shoppinglist program, structs, malloc() and functions
I started with an assignment which should include a program that can add remove print, edit, save list.

I am stuck on the first function that should add an item to my grocery list. As you can see, this function (and all other functions) receives a pointer to a shopping list. This is a pointer to the shopping list defined in main(), and my functions should make changes directly to the shopping list that the argument list is pointing to.

The function should ask the user for a name, amount and unit of an item. It should then place it last in the shopping list. The “length” field should always be containing the index to the last position of the array, so this is where the item should be placed. For instance, length is zero when the list is empty, so the first time this function is called, the item should be placed at index zero in list->itemArray.

This function is also responsible for increasing the length of the list. Since we just added one item, the list is now one item longer. Just remember that it should not be possible to add more than 5 items to the list.

If the user enters a non-positive number for amount, the program should tell the user that the input is invalid and repeat the question until a correct answer has been given.

How should I limit the size list to just 5 products?

```<code>#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include "ShoppingList.h"

int main(void)
{
    struct ShoppingList shoppingList;
    shoppingList.length = 0; // The shopping list is empty at the start

    int option;

    do
    {
        printf("\n\nWelcome to the shopping list manager!\n");
        printf("=====================================\n\n");

        printf("1. Add an item\n");
        printf("2. Display the shopping list\n");
        printf("3. Remove an item\n");
        printf("4. Change an item\n");
        printf("5. Save list\n");
        printf("6. Load list\n");
        printf("7. Exit\n");

        printf("What do you want to do? ");
        scanf("%d", &option);

        switch (option)
        {
        case 1: addItem(&shoppingList); break;
        case 2: printList(&shoppingList); break;
        case 3: removeItem(&shoppingList); break;
        case 4: editItem(&shoppingList); break;
        case 5: saveList(&shoppingList); break;
        case 6: loadList(&shoppingList); break;
        case 7: break;
        default:
            printf("Please enter a number between 1 and 7");
        }
    } while (option != 7);

    return 0;
}
</code>```
```<code>#define _CRT_SECURE_NO_WARNINGS
#include"ShoppingList.h"
#include<stdio.h>
#include<stdlib.h> // For malloc() and free()

void addItem(struct ShoppingList* list)
{

    list = (struct ShoppingList*)malloc(sizeof(struct ShoppingList) * 5);

        printf("Name for product: ");
        scanf("%s", list->itemList[list->length].productName);

        do
        {
            printf("Enter the amount: ");
            scanf("%f", &list->itemList[list->length].amount);

            if (list->itemList[list->length].amount <= 0.0)
            {
                printf("Input is invalid.\n");
            }

        } while (list->itemList[list->length].amount <= 0.0);

        printf("Enter unit of item: ");
        scanf("%s", list->itemList[list->length].unit);

        list->length++;

}

void printList(struct ShoppingList *list)
{
    int i;

    printf("\nName:\tAmount:\tUnit:\n\n");

    for (i = 0; i < list->length; i++) {
        printf("%s\t%d\t%s\n", list->itemList[i].productName, list->itemList[i].amount, list->itemList[i].unit);
    }

    printf("\n\n");
}

void editItem(struct ShoppingList *list)
{

}

void removeItem(struct ShoppingList *list)
{

}

void saveList(struct ShoppingList *list)
{

}

void loadList(struct ShoppingList* list)
{

}

</code>```
```<code>#ifndef SHOPPING_LIST_H
#define SHOPPING_LIST_H

// Struct definitions

struct GroceryItem
{
    char productName[20];
    float amount;
    char unit[10];
};

struct ShoppingList
{
    int length;
    struct GroceryItem itemList[5];
};

// Function declarations

void addItem(struct ShoppingList *list);
void printList(struct ShoppingList *list);
void editItem(struct ShoppingList *list);
void removeItem(struct ShoppingList *list);
void saveList(struct ShoppingList *list);
void loadList(struct ShoppingList* list);

#endif

</code>```

Body:
I started with an assignment which should include a program that can add remove print, edit, save list.

I am stuck on the first function that should add an item to my grocery list. As you can see, this function (and all other functions) receives a pointer to a shopping list. This is a pointer to the shopping list defined in main(), and my functions should make changes directly to the shopping list that the argument list is pointing to.

The function should ask the user for a name, amount and unit of an item. It should then place it last in the shopping list. The “length” field should always be containing the index to the last position of the array, so this is where the item should be placed. For instance, length is zero when the list is empty, so the first time this function is called, the item should be placed at index zero in list->itemArray.

This function is also responsible for increasing the length of the list. Since we just added one item, the list is now one item longer. Just remember that it should not be possible to add more than 5 items to the list.

If the user enters a non-positive number for amount, the program should tell the user that the input is invalid and repeat the question until a correct answer has been given.

How should I limit the size list to just 5 products?

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include "ShoppingList.h"

int main(void)
{
    struct ShoppingList shoppingList;
    shoppingList.length = 0; // The shopping list is empty at the start

    int option;

    do
    {
        printf("\n\nWelcome to the shopping list manager!\n");
        printf("=====================================\n\n");

        printf("1. Add an item\n");
        printf("2. Display the shopping list\n");
        printf("3. Remove an item\n");
        printf("4. Change an item\n");
        printf("5. Save list\n");
        printf("6. Load list\n");
        printf("7. Exit\n");

        printf("What do you want to do? ");
        scanf("%d", &option);

        switch (option)
        {
        case 1: addItem(&shoppingList); break;
        case 2: printList(&shoppingList); break;
        case 3: removeItem(&shoppingList); break;
        case 4: editItem(&shoppingList); break;
        case 5: saveList(&shoppingList); break;
        case 6: loadList(&shoppingList); break;
        case 7: break;
        default:
            printf("Please enter a number between 1 and 7");
        }
    } while (option != 7);

    return 0;
}

#define _CRT_SECURE_NO_WARNINGS
#include"ShoppingList.h"
#include<stdio.h>
#include<stdlib.h> // For malloc() and free()

void addItem(struct ShoppingList* list)
{

    list = (struct ShoppingList*)malloc(sizeof(struct ShoppingList) * 5);

        printf("Name for product: ");
        scanf("%s", list->itemList[list->length].productName);

        do
        {
            printf("Enter the amount: ");
            scanf("%f", &list->itemList[list->length].amount);

            if (list->itemList[list->length].amount <= 0.0)
            {
                printf("Input is invalid.\n");
            }

        } while (list->itemList[list->length].amount <= 0.0);

        printf("Enter unit of item: ");
        scanf("%s", list->itemList[list->length].unit);

        list->length++;

}

void printList(struct ShoppingList *list)
{
    int i;

    printf("\nName:\tAmount:\tUnit:\n\n");

    for (i = 0; i < list->length; i++) {
        printf("%s\t%d\t%s\n", list->itemList[i].productName, list->itemList[i].amount, list->itemList[i].unit);
    }

    printf("\n\n");
}

void editItem(struct ShoppingList *list)
{

}

void removeItem(struct ShoppingList *list)
{

}

void saveList(struct ShoppingList *list)
{

}

void loadList(struct ShoppingList* list)
{

}

#ifndef SHOPPING_LIST_H
#define SHOPPING_LIST_H

// Struct definitions

struct GroceryItem
{
    char productName[20];
    float amount;
    char unit[10];
};

struct ShoppingList
{
    int length;
    struct GroceryItem itemList[5];
};

// Function declarations

void addItem(struct ShoppingList *list);
void printList(struct ShoppingList *list);
void editItem(struct ShoppingList *list);
void removeItem(struct ShoppingList *list);
void saveList(struct ShoppingList *list);
void loadList(struct ShoppingList* list);

#endif


问:
How to process two GET requests, at the same time and collect the data in javascript
Hello I have a question and a doubt, I am in a view, when I give a button I do the following code

function pagar_recibo(id) {
    $.ajax ({
        delay: 250,
        type: 'GET',
        url: '/general/recibo/add',
        data: {
            'id': id,
            'action_al': 'add_alumnos',
        },
    });
};```
</div>
</div>
</p>
<p>This button is a href that goes to another url, that is to say it makes another request to the server with GET then in the new view in the get_context_data I have the following</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['arg'] = json.dumps(self.alum())
        # context['arg'] = self.alum()
        return context</code>```

and the function is as follows

def alum(self, **kwargs):
        data = []
        try:
            action = self.request.GET.get('action_al', False)
            print(action)
            if action == False:
                return
            elif action == 'add_alumnos':
                data = []
                id = int(self.request.GET['id'])
                Alumnos = Alumno.objects.filter(pk=id)
                for i in Alumnos:
                    item = i.toJSON()
                    item['text'] = i.get_full_name()
                    data.append(item)
                print(data)
        except Exception as e:
            data['error'] = str(e)
        return data```
</div>
</div>
</p>
<p>This is how I pick it up in the template</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>window.data = {{ arg|safe }};</code>```

The problem is that one GET request is empty, the url change and the other is the ajax request with the given key and value, but I always get empty windows data, how could I fix that?
It could be done with a POST request? then how do I collect the value in the js file?
Please I would need help. Regards

Body:
Hello I have a question and a doubt, I am in a view, when I give a button I do the following code

function pagar_recibo(id) {
    $.ajax ({
        delay: 250,
        type: 'GET',
        url: '/general/recibo/add',
        data: {
            'id': id,
            'action_al': 'add_alumnos',
        },
    });
};

This button is a href that goes to another url, that is to say it makes another request to the server with GET then in the new view in the get_context_data I have the following

def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['arg'] = json.dumps(self.alum())
        # context['arg'] = self.alum()
        return context

and the function is as follows

def alum(self, **kwargs):
        data = []
        try:
            action = self.request.GET.get('action_al', False)
            print(action)
            if action == False:
                return
            elif action == 'add_alumnos':
                data = []
                id = int(self.request.GET['id'])
                Alumnos = Alumno.objects.filter(pk=id)
                for i in Alumnos:
                    item = i.toJSON()
                    item['text'] = i.get_full_name()
                    data.append(item)
                print(data)
        except Exception as e:
            data['error'] = str(e)
        return data

This is how I pick it up in the template

window.data = {{ arg|safe }};

The problem is that one GET request is empty, the url change and the other is the ajax request with the given key and value, but I always get empty windows data, how could I fix that?
It could be done with a POST request? then how do I collect the value in the js file?
Please I would need help. Regards


问:
LINQ Group list and count how many values exist for each distinct group
I have a list of people

var data = new Person[]{
    new Person{
        Gender = "male",
        Age = 7,
    },
    new Person{
        Gender = "female",
        Age = 14,
    },
    new Person{
        Gender = "male",
        Age = 12,
    },
    new Person{
        Gender = "male",
        Age = 8,
    },
    new Person{
        Gender = "male",
        Age = 18,
    },
    new Person{
        Gender = "female",
        Age = 18,
    },
    new Person{
        Gender = "male",
        Age = 7,
    }
};

```
<p>I want to group it into age-range so that each range shows the count of male and female under it.</p>
<p>I have tried this:</p>
<pre class="lang-cs prettyprint-override"><code>var grouped = data.GroupBy(d => new { age = 5 * (d.Age / 5), d.Gender }).Select(d => new
{
    range = $"{d.Key.age}-{d.Key.age + 4}",
    male = d.Count(x => x.Gender == "male"),
    female =  d.Count(x => x.Gender == "female")

}).Dump("grouped");

</code>```

and I get this

range
male
female

5-9
3
0

10-14
0
1

10-14
1
0

15-19
1
0

15-19
0
1

but I want this

range
male
female

5-9
30
0

10-14
1
1

15-19
1
1

How do I go about it please?

Body:
I have a list of people

var data = new Person[]{
    new Person{
        Gender = "male",
        Age = 7,
    },
    new Person{
        Gender = "female",
        Age = 14,
    },
    new Person{
        Gender = "male",
        Age = 12,
    },
    new Person{
        Gender = "male",
        Age = 8,
    },
    new Person{
        Gender = "male",
        Age = 18,
    },
    new Person{
        Gender = "female",
        Age = 18,
    },
    new Person{
        Gender = "male",
        Age = 7,
    }
};

I want to group it into age-range so that each range shows the count of male and female under it.

I have tried this:

var grouped = data.GroupBy(d => new { age = 5 * (d.Age / 5), d.Gender }).Select(d => new
{
    range = $"{d.Key.age}-{d.Key.age + 4}",
    male = d.Count(x => x.Gender == "male"),
    female =  d.Count(x => x.Gender == "female")

}).Dump("grouped");

and I get this

range
male
female

5-9
3
0

10-14
0
1

10-14
1
0

15-19
1
0

15-19
0
1

but I want this

range
male
female

5-9
30
0

10-14
1
1

15-19
1
1

How do I go about it please?


问:
how to get current running code line and directory name in go
i`m looking for a way to get current working directory plus the very line which is running, in a string variable to be stored or printed like :

```<code>./dir/working_file.go:29
</code>```

i have used os.Getwd( ) but it just gets the file name. line is missing.
thanks in advance.

Body:
i`m looking for a way to get current working directory plus the very line which is running, in a string variable to be stored or printed like :

./dir/working_file.go:29

i have used os.Getwd( ) but it just gets the file name. line is missing.
thanks in advance.


问:
Email extraction from social networks using either R or Python
For research purposes, we need to extract large sums of email addresses from social networks such as Twitter, Facebook and TikTok. We have tried Selenium but social network accounts we use to extract the social network. We would like to know if there are statistical packages we can use to achieve our purpose.</p>


问:
Add new form item to antd dynamic form list outside of the form
Based on this code snippet, I would like to reach and trigger the add property outside of the form. Any idea how can I do it?

```<code><Form form={form} initialValues={initialValues} onFinish={onSubmit}>
  <Form.List>
    {(fields, { add, remove }) => (
      <div>
        {fields.map(field => (
          <Form.Item {...field}>
            <Input />
          </Form.Item>
        ))}
      </div>
    )}
  </Form.List>
  // I don't want use this button here, inside the form list.
  // I want invoke the add function from outside.
  <Button type="link" onClick={() => add()}>
    Add
  </Button>
</Form>
// Or maybe from here
<Button type="link" onClick={() => add()}>
  Add
</Button>
</code>```

Body:
Based on this code snippet, I would like to reach and trigger the add property outside of the form. Any idea how can I do it?

<Form form={form} initialValues={initialValues} onFinish={onSubmit}>
  <Form.List>
    {(fields, { add, remove }) => (

        {fields.map(field => (
          <Form.Item {...field}>
            <Input />
          </Form.Item>
        ))}

    )}
  </Form.List>
  // I don't want use this button here, inside the form list.
  // I want invoke the add function from outside.
  <Button type="link" onClick={() => add()}>
    Add
  </Button>
</Form>
// Or maybe from here
<Button type="link" onClick={() => add()}>
  Add
</Button>


问:
Oauth2.0, Is it safe to authorize using post request without redirect?
So I'm trying to implement my own authorization server using spring. I have my front-end app which is implemented using ReactJs. One thing that I don't understand is that, why do I have to redirect to the login page on the authorization server side. I want to have nice and clean login page on the client side using ReactJs without redirecting to the other site. I mean, I trust my client (ReactJs app) anyway can I just use post request to make an authentication like this.

```<code>const login = () =>
// start loggin in
axios.post('/oauth/login_api_without_redirect',
           { username: 'usr',
             password: 'pwd',
             client_id: 'react_app',
             ... scope, state, etc...
             code_challenge: sha_256('yyyy'),
             code_challenge_method: 'sha_256' })
      .then(r => {
          axios.post('/oauth/token',
                     { ... etc params ...
                       auth_code: r.data.authorizationCode,
                       code_verifier: 'yyyy' })
      })

</code>```

and on the authorization server side I would have this API.

```<code>@PostMapping("/oauth/login_api_without_redirect")
public String authorize(AuthenticationDTO authen) {
    // include client_secret and other stuff..
    return authorizationCode
}
</code>```

Is that safe to do so.

Body:
So I'm trying to implement my own authorization server using spring. I have my front-end app which is implemented using ReactJs. One thing that I don't understand is that, why do I have to redirect to the login page on the authorization server side. I want to have nice and clean login page on the client side using ReactJs without redirecting to the other site. I mean, I trust my client (ReactJs app) anyway can I just use post request to make an authentication like this.

const login = () =>
// start loggin in
axios.post('/oauth/login_api_without_redirect',
           { username: 'usr',
             password: 'pwd',
             client_id: 'react_app',
             ... scope, state, etc...
             code_challenge: sha_256('yyyy'),
             code_challenge_method: 'sha_256' })
      .then(r => {
          axios.post('/oauth/token',
                     { ... etc params ...
                       auth_code: r.data.authorizationCode,
                       code_verifier: 'yyyy' })
      })

and on the authorization server side I would have this API.

@PostMapping("/oauth/login_api_without_redirect")
public String authorize(AuthenticationDTO authen) {
    // include client_secret and other stuff..
    return authorizationCode
}

Is that safe to do so.


问:
why mobile menu toggle button is not working?
My website’s menu is working on desktops and large screens. when I resize my browser to a small size or open my site on mobile then menu toggle button does not work and the menu dropdown does not show up.
My website running the latest Version: 3.2.4.

I also tried deactivating the plugins and clearing the cache but nothing works.

Before the update, I was facing the same issue but when updated to the latest issue goes away. now it’s back again.
To review the issue please check on the website.
Please help me.


问:
pytorch error: The size of tensor a (56) must match the size of tensor b (28) at non-singleton dimension 3
Using count_ops to calculate FLOPS for a neural network model gives me the error mentioned in the title. I have changed a pretrained model (resnet18) by using assignments. My goal is to calculate the FLOPS for each edited model (to make sure the model is passing inputs).

```<code>  net = resnet18()
  phi = math.pow(math.sqrt(2), 7)
  # net.conv1 = nn.Conv2d(math.ceil(phi*3), math.ceil(phi*64), kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
  net.conv1 = nn.Conv2d(math.ceil(3), math.ceil(phi*64), kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
  net.bn1 = nn.BatchNorm2d(math.ceil(phi*64), eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  net.relu = nn.ReLU(inplace=True)
  net.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)

  net.layer1[0].conv1 = nn.Conv2d(math.ceil(phi*64), math.ceil(phi*64), kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
.
.

  net.layer2[0].conv1 = nn.Conv2d(math.ceil(phi*64), math.ceil(phi*128), kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
.
.
  net.layer3[0].conv1 = nn.Conv2d(math.ceil(phi*128), math.ceil(phi*256), kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
.
.
  net.layer4[0].conv1 = nn.Conv2d(math.ceil(phi*256), math.ceil(phi*512), kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
.
.
# net.avgpool = Identity()
  net.avgpool = nn.AdaptiveAvgPool2d(output_size=(1, 1))
  nn.fc = nn.Linear(in_features=math.ceil(phi*512), out_features=1000, bias=True)
</code>```

The edited model works when I use model.named_parameters(). I am thinking that I messed up by directly assigning layers with new values (I am not sure of the order of parameters for the layers, printing my model seems to be fine, but for the love of god not a single input passes throught the model). Want to know where I messed up in the syntax, because of which my inputs are not passing through the model.

```<code>ip = torch.rand(1,3,224,224).to(dev)
count_ops(net, ip) # Count the number of FLOPs
</code>```

Body:
Using count_ops to calculate FLOPS for a neural network model gives me the error mentioned in the title. I have changed a pretrained model (resnet18) by using assignments. My goal is to calculate the FLOPS for each edited model (to make sure the model is passing inputs).

  net = resnet18()
  phi = math.pow(math.sqrt(2), 7)
  # net.conv1 = nn.Conv2d(math.ceil(phi*3), math.ceil(phi*64), kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
  net.conv1 = nn.Conv2d(math.ceil(3), math.ceil(phi*64), kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
  net.bn1 = nn.BatchNorm2d(math.ceil(phi*64), eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  net.relu = nn.ReLU(inplace=True)
  net.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)

  net.layer1[0].conv1 = nn.Conv2d(math.ceil(phi*64), math.ceil(phi*64), kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
.
.

  net.layer2[0].conv1 = nn.Conv2d(math.ceil(phi*64), math.ceil(phi*128), kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
.
.
  net.layer3[0].conv1 = nn.Conv2d(math.ceil(phi*128), math.ceil(phi*256), kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
.
.
  net.layer4[0].conv1 = nn.Conv2d(math.ceil(phi*256), math.ceil(phi*512), kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
.
.
# net.avgpool = Identity()
  net.avgpool = nn.AdaptiveAvgPool2d(output_size=(1, 1))
  nn.fc = nn.Linear(in_features=math.ceil(phi*512), out_features=1000, bias=True)

The edited model works when I use model.named_parameters(). I am thinking that I messed up by directly assigning layers with new values (I am not sure of the order of parameters for the layers, printing my model seems to be fine, but for the love of god not a single input passes throught the model). Want to know where I messed up in the syntax, because of which my inputs are not passing through the model.

ip = torch.rand(1,3,224,224).to(dev)
count_ops(net, ip) # Count the number of FLOPs


问:
How to immediately see the changes by removing an element from the list without refreshing the page in Flutter?
I am getting data from the network. I display a list with data. I have the ability to remove one element from a list using the removeInfo method. When deleting, the element does not disappear from the list, but it is deleted. How can I make sure that when one element is removed from the list, the entire page is not updated for me, but just the element is deleted? If I chose to delete - so that the element disappears and there is no need to refresh the page to see the changes.

body

```<code>BlocBuilder<InfoCubit, InfoState>(
    builder: (context, state) {
      final InfoCubit infoCubit =
          BlocProvider.of<InfoCubit>(context);

      if (state is InfoLoaded) {

        return SizedBox(
          height: MediaQuery.of(context).size.height,
          child: Padding(
            padding: const EdgeInsets.only(top: 40, left: 14, right: 14),
            child: MediaQuery.removePadding(
              context: context,
              removeTop: true,
              child: ListView.builder(
                physics: const BouncingScrollPhysics(),
                itemCount: state.info.length + 1,
                itemBuilder: (context, index) {
                      return Padding(
                          padding: const EdgeInsets.only(bottom: 16),
                          child: GestureDetector(
                            onTap: () {},
                            child: Container(
                              height: 112,
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 14, vertical: 10),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(25),
                                color: constants.Colors.greyMiddle,
                              ),
                              child: Row(
                                children: [
                                  IconButton(
                                    onPressed: () {
                                      if (state.info[index].status ==
                                          true) {
                                        showDialog(
                                          context: context,
                                          builder: (BuildContext context) {
                                            return const PendingDialog();
                                          },
                                        );
                                      } else if (state.info[index].status ==
                                              null &&
                                          !state.info[index].blocked) {
                                        ShowCustomDialog()
                                            .showBorderDialog(
                                          barrierDismissible: false,
                                          context: context,
                                          child:
                                              const DeleteInfoDialog(),
                                        )
                                            .then((value) async {
                                          if (value) {
                                            await infoCubit
                                                .removeInfo(
                                              infoId:
                                                  state.info[index].id,
                                              userId: widget.userId,
                                            )
                                                .then((value) {
                                              if (value) {
                                                deleteNotification(
                                                    context);
                                              }
                                            });
                                          }
                                        });
                                      } else {
                                        try {
                                          setState(() {
                                            state.info[index].selected =
                                                !state.info[index]
                                                    .selected;
                                          });
                                        } catch (_) {}
                                      }
                                    },
                                    icon: state.info[index].selected
                                        ? SvgPicture.asset(
                                            constants.Assets.remove2)
                                        : state.info[index].status ==
                                                true
                                            ? SvgPicture.asset(
                                                constants.Assets.pending,
                                              )
                                            : state.info[index]
                                                        .status ==
                                                    false
                                                ? !state.info[index]
                                                        .blocked
                                                    ? SvgPicture.asset(
                                                        constants
                                                            .Assets.remove,
                                                        color: constants
                                                            .Colors
                                                            .greyLight,
                                                      )
                                                    : SvgPicture.asset(
                                                        constants.Assets
                                                            .threeDot,
                                                      )
                                                : SvgPicture.asset(
                                                    constants
                                                        .Assets.threeDot,
                                                  ),
                                    padding: EdgeInsets.zero,
                                    constraints: const BoxConstraints(),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        );
              ),
            ),
          ),
        );
        // }
      }
      return const Center(
        child: CircularProgressIndicator(
          color: constants.Colors.purpleMain,
        ),
      );
    },
  ),
</code>```

state

```<code>@immutable
abstract class InfoState {}

class InfoInitial extends InfoState {}

class InfoLoading extends InfoState {}

class InfoLoaded extends InfoState {
  final List<InfoModel> info;
  InfoLoaded(this.info);
}

class InfoDeletedSuccess extends InfoState {
  final int infoId;

  InfoDeletedSuccess(this.infoId);
}

class InfoError extends InfoState {}
</code>```

cubit

```<code>class InfoCubit extends Cubit<InfoState> {
  final InfoRepository _repository;
  InfoCubit(this._repository) : super(InfoInitial());

  Future loadPage(int userId) async {
    try {
      emit(InfoLoading());

      List<InfoModel> info=
          await _repository.getInfo(userId: userId);

      emit(InfoLoaded(info));
    } catch (_) {
      emit(InfoError());
    }
  }

  Future<bool> removeChargingStation(
      {required int infoId, int? userId}) async {
    try {
      await _repository.removeInfo(
          infoId: infoId);
      if (userId != null) {
        loadPage(userId);
      }
      // emit(InfoDeletedSuccess(chargingStationId));
      return true;
    } catch (_) {
      return false;
    }
  }

  void reload() => emit(StationSwitcherInitial());

}
</code>```

Body:
I am getting data from the network. I display a list with data. I have the ability to remove one element from a list using the removeInfo method. When deleting, the element does not disappear from the list, but it is deleted. How can I make sure that when one element is removed from the list, the entire page is not updated for me, but just the element is deleted? If I chose to delete - so that the element disappears and there is no need to refresh the page to see the changes.

body

BlocBuilder<InfoCubit, InfoState>(
    builder: (context, state) {
      final InfoCubit infoCubit =
          BlocProvider.of<InfoCubit>(context);

      if (state is InfoLoaded) {

        return SizedBox(
          height: MediaQuery.of(context).size.height,
          child: Padding(
            padding: const EdgeInsets.only(top: 40, left: 14, right: 14),
            child: MediaQuery.removePadding(
              context: context,
              removeTop: true,
              child: ListView.builder(
                physics: const BouncingScrollPhysics(),
                itemCount: state.info.length + 1,
                itemBuilder: (context, index) {
                      return Padding(
                          padding: const EdgeInsets.only(bottom: 16),
                          child: GestureDetector(
                            onTap: () {},
                            child: Container(
                              height: 112,
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 14, vertical: 10),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(25),
                                color: constants.Colors.greyMiddle,
                              ),
                              child: Row(
                                children: [
                                  IconButton(
                                    onPressed: () {
                                      if (state.info[index].status ==
                                          true) {
                                        showDialog(
                                          context: context,
                                          builder: (BuildContext context) {
                                            return const PendingDialog();
                                          },
                                        );
                                      } else if (state.info[index].status ==
                                              null &&
                                          !state.info[index].blocked) {
                                        ShowCustomDialog()
                                            .showBorderDialog(
                                          barrierDismissible: false,
                                          context: context,
                                          child:
                                              const DeleteInfoDialog(),
                                        )
                                            .then((value) async {
                                          if (value) {
                                            await infoCubit
                                                .removeInfo(
                                              infoId:
                                                  state.info[index].id,
                                              userId: widget.userId,
                                            )
                                                .then((value) {
                                              if (value) {
                                                deleteNotification(
                                                    context);
                                              }
                                            });
                                          }
                                        });
                                      } else {
                                        try {
                                          setState(() {
                                            state.info[index].selected =
                                                !state.info[index]
                                                    .selected;
                                          });
                                        } catch (_) {}
                                      }
                                    },
                                    icon: state.info[index].selected
                                        ? SvgPicture.asset(
                                            constants.Assets.remove2)
                                        : state.info[index].status ==
                                                true
                                            ? SvgPicture.asset(
                                                constants.Assets.pending,
                                              )
                                            : state.info[index]
                                                        .status ==
                                                    false
                                                ? !state.info[index]
                                                        .blocked
                                                    ? SvgPicture.asset(
                                                        constants
                                                            .Assets.remove,
                                                        color: constants
                                                            .Colors
                                                            .greyLight,
                                                      )
                                                    : SvgPicture.asset(
                                                        constants.Assets
                                                            .threeDot,
                                                      )
                                                : SvgPicture.asset(
                                                    constants
                                                        .Assets.threeDot,
                                                  ),
                                    padding: EdgeInsets.zero,
                                    constraints: const BoxConstraints(),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        );
              ),
            ),
          ),
        );
        // }
      }
      return const Center(
        child: CircularProgressIndicator(
          color: constants.Colors.purpleMain,
        ),
      );
    },
  ),

state

@immutable
abstract class InfoState {}

class InfoInitial extends InfoState {}

class InfoLoading extends InfoState {}

class InfoLoaded extends InfoState {
  final List<InfoModel> info;
  InfoLoaded(this.info);
}

class InfoDeletedSuccess extends InfoState {
  final int infoId;

  InfoDeletedSuccess(this.infoId);
}

class InfoError extends InfoState {}

cubit

class InfoCubit extends Cubit<InfoState> {
  final InfoRepository _repository;
  InfoCubit(this._repository) : super(InfoInitial());

  Future loadPage(int userId) async {
    try {
      emit(InfoLoading());

      List<InfoModel> info=
          await _repository.getInfo(userId: userId);

      emit(InfoLoaded(info));
    } catch (_) {
      emit(InfoError());
    }
  }

  Future<bool> removeChargingStation(
      {required int infoId, int? userId}) async {
    try {
      await _repository.removeInfo(
          infoId: infoId);
      if (userId != null) {
        loadPage(userId);
      }
      // emit(InfoDeletedSuccess(chargingStationId));
      return true;
    } catch (_) {
      return false;
    }
  }

  void reload() => emit(StationSwitcherInitial());

}


问:
html accessibility - screen reader not reading updated content?
I have sort of a basic accessibility question.

So I have the following:

```<code><fieldset>
    <legend id="legend">content to read</legend>
    <div>
        <input type="text">
    </div>
</fieldset>
</code>```

When I tab onto input, my screen reader (MacOS VoiceOver) reads the legend's "content to read".

But if I change that text to something else using JavaScript, the screen reader still reads the original "content to read" every time instead of "updated text" as below. I also added aria-live="polite" but to no avail.

```<code><fieldset>
    <legend aria-live="polite" id="legend">updated text</legend>
    <div>
        <input type="text">
    </div>
</fieldset>

<script>
    // example js that updated content above
    document.getElementById("legend").textContent = "updated text"
</script>
</code>```

I am quite new to html accessibility, and thought it would be reasonable to expect the updated content to be read...otherwise how can I make it happen?

Thanks for your input,

EDIT(Dec 11, 2022):
Per recent comment, I decided to include the full code in the codesandbox below.

codesandbox link

To reproduce the issue:

Tab onto radio 1 to hear content to read being read.

Tab onto button Click me to change text to change the legend text from content to read to updated text

Tab onto radio button again to hear content to read still being read, when updated text is expected.

Body:
I have sort of a basic accessibility question.

So I have the following:

<fieldset>
    <legend id="legend">content to read</legend>

        <input type="text">

</fieldset>

When I tab onto input, my screen reader (MacOS VoiceOver) reads the legend's "content to read".

But if I change that text to something else using JavaScript, the screen reader still reads the original "content to read" every time instead of "updated text" as below. I also added aria-live="polite" but to no avail.

<fieldset>
    <legend aria-live="polite" id="legend">updated text</legend>

        <input type="text">

</fieldset>

I am quite new to html accessibility, and thought it would be reasonable to expect the updated content to be read...otherwise how can I make it happen?

Thanks for your input,

EDIT(Dec 11, 2022):
Per recent comment, I decided to include the full code in the codesandbox below.

codesandbox link

To reproduce the issue:

Tab onto radio 1 to hear content to read being read.

Tab onto button Click me to change text to change the legend text from content to read to updated text

Tab onto radio button again to hear content to read still being read, when updated text is expected.


问:
A div between text element characters
I have a text element that is built when the user clicks a button. In the middle of that text, I want to add an input element but I could not find a way.
I actually made a lot of things but here are the important ones So, First I made an input element and a button when the user enter input and click the button what he wrote will be displayed in a h1 element with a random missing word I want to make an input element and I want it to be in the same place that the missing word should've been in.

```<code>function myFunction() {
  var x = document.getElementById("input").value;
  var y = document.getElementById("inputed");
  x = x.substr(0, c) + x.substr(d, x.length);

  const z = x.length;

  //I want an input element to be between the charAt(c) and charAt(d)
  y.innerHTML = `${x.slice(
        0,
        c
    )}<input type="text" style="color: gray;border:2px solid;border-radius: 10px;outline: none;font-size: x-large;height:40px;width: 100px;" >${x.slice(
        d,
        z
    )} `;
  console.log(z);
}
</code>```

The problem is when I enter this code it doesn't display all the text after the input element it misses about 7 characters
That is all!I will be extremly happy if someone helps me.

Title: A div between text element characters

Body:
I have a text element that is built when the user clicks a button. In the middle of that text, I want to add an input element but I could not find a way.
I actually made a lot of things but here are the important ones So, First I made an input element and a button when the user enter input and click the button what he wrote will be displayed in a h1 element with a random missing word I want to make an input element and I want it to be in the same place that the missing word should've been in.

function myFunction() {
  var x = document.getElementById("input").value;
  var y = document.getElementById("inputed");
  x = x.substr(0, c) + x.substr(d, x.length);

  const z = x.length;

  //I want an input element to be between the charAt(c) and charAt(d)
  y.innerHTML = `${x.slice(
        0,
        c
    )}<input type="text" style="color: gray;border:2px solid;border-radius: 10px;outline: none;font-size: x-large;height:40px;width: 100px;" >${x.slice(
        d,
        z
    )} `;
  console.log(z);
}

The problem is when I enter this code it doesn't display all the text after the input element it misses about 7 characters
That is all!I will be extremly happy if someone helps me.


问:
How do track user engagement duration in Firebase ABTest
I want to create one AB Test using Firebase, I can not found the metrics for tracking user engagement durations, is there have one suggestion or solution to solve this problem?

I try to use screen_view event to measure the duration, but this event be track as event count only, I expect using the event property value for measure the metrics.

Thanks!


问:
why when I type echo <?php ?> in inspect element auto command becomes <---?php ?--->?
I want to make a php tag but through echo, and why does the input I get instead become an automatic command?

which was originally :

```<code><?php

public function section(string $name)
  {
    $this->nameSection = $name;
    echo '<?php echo ' . $this->nameSection;
  }

  public function endSection()
  {
    echo "?>";
  }
</code>```

Becomes :

```<code><!--?php ---?>
</code>```

oh yes I call them like this :

```<code><?php $kurumi->section("content") ?>

<?php $kurumi->endSection() ?>
</code>```

my intention want to fill variable with html tag

and I want to get <?php ?> output in inspect element

Body:
I want to make a php tag but through echo, and why does the input I get instead become an automatic command?

which was originally :

<?php

public function section(string $name)
  {
    $this->nameSection = $name;
    echo '<?php echo ' . $this->nameSection;
  }

  public function endSection()
  {
    echo "?>";
  }

Becomes :