问:
TextField don't resize my alertdialog - Flutter
I leave the entire code fragment, the main idea is to have a textfield that, by using the keyboard, shows me a series of elements, in the description variable, I have that element to select, this works well, the only issue is, how to keep my alertdialog with all the correct notes.

```<code> return await Get.generalDialog(
    barrierLabel: "Barrier",
    barrierDismissible: false,
    transitionBuilder: (context, a1, a2, widget) {
      return StatefulBuilder(builder: (context, setState) {
        return Transform.scale(
            scale: a1.value,
            child: Opacity(
              opacity: a1.value,
              child: Dialog(
                insetAnimationCurve: Curves.bounceOut,
                insetPadding: EdgeInsets.only(right: 20, left: 20),
                //backgroundColor: colorFour(),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12.0),
                ),
                child: SingleChildScrollView(
                  child: Container(
                    height: 340,
                    child: Column(
                      children: <Widget>[
                        Container(
                          alignment: Alignment.topCenter,
                          height: 50,
                          decoration: BoxDecoration(
                            color: Colors.red,
                            borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(12),
                              topRight: Radius.circular(12),
                            ),
                          ),
                          padding: EdgeInsets.all(5),
                          child: Center(
                            child: Text(
                              title,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 18,
                                  fontWeight: FontWeight.w600),
                              maxLines: 2,
                              textAlign: TextAlign.center,
                            ),
                          ),
                        ),
                        SingleChildScrollView(
                            padding: EdgeInsets.only(left: 10, right: 10),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment:
                                  CrossAxisAlignment.stretch,
                              children: [
                                Container(
                                  margin: EdgeInsets.only(top: 10),
                                  child: TextFormField(
                                    controller: controller,
                                    decoration: InputDecoration(
                                        border: OutlineInputBorder(
                                            gapPadding: 5.0)),
                                    keyboardType: TextInputType.text,
                                    maxLines: 1,
                                    onChanged: (String cadena) async {
                                      listado = pivote
                                          .where((x) => x.descripcion
                                              .split("/")[value]
                                              .toLowerCase()
                                              .contains(
                                                  cadena.toLowerCase()))
                                          .toList();
                                      setState(() {});
                                    },
                                  ),
                                ),
                                Container(
                                  height: 200,
                                  margin: EdgeInsets.only(
                                      top: 10, bottom: 10.0),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(5)),
                                      border: Border.all(
                                          color: Colors.grey, width: 1)),
                                  child: ListView.builder(
                                      padding: const EdgeInsets.all(0.0),
                                      physics: BouncingScrollPhysics(),
                                      itemCount: listado.length,
                                      shrinkWrap: true,
                                      scrollDirection: Axis.vertical,
                                      itemBuilder: (context, index) {
                                        return Container(
                                          height: 34,
                                          child: InkWell(
                                              child: SizedBox.expand(
                                                child: Align(
                                                  alignment:
                                                      Alignment.centerLeft,
                                                  child: Padding(
                                                    padding:
                                                        EdgeInsets.only(
                                                            right: 5,
                                                            left: 5),
                                                    child: Text(
                                                        listado[index]
                                                            .descripcion
                                                            .split(
                                                                "/")[value],
                                                        textAlign:
                                                            TextAlign.left),
                                                  ),
                                                ),
                                              ),
                                              onTap: () {
                                                Get.back(result: {
                                                  "item": listado[index],
                                                });
                                              }),
                                        );
                                      }),
                                ),
                              ],
                            )),
                      ],
                    ),
                  ),
                ),
              ),
            ));
      });
    },
    pageBuilder: (context, animation1, animation2) {
      return Container();
    });
</code>```

I need to overlay my alertdialog, that is to say that the size does not break my design, this happens after focusing on the textfield

答:
Show us some code to help you out.
In any case, it might make sense to wrap the layout in a SingleChildScrollView.
Here is a very good explanation.

https://api.flutter.dev/flutter/widgets/SingleChildScrollView-class.html

```<code>yourAlertDialog(
  context: context,
  builder: (BuildContext context) {
    return SingleChildScrollView(child: yourchild);
  },
);
</code>```

Your layout should be wrapped in Scrollview , I didn't replicate or run this code but it should be like this:

```<code>AlertDialog(
      title: Text("title", style: TextStyle(color: ThemeColors.colorPrimary),),
      content: Container(
        width: double.maxFinite,
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: StatefulBuilder(builder: (BuildContext context1, StateSetter setState) {
            this.setState = setState;
            return Container(
                    height: 340,
                    child: Column(
                      children: <Widget>[
                        //your container
                      ],
                    ),
                  ),

          }),

      )),

    );
</code>```

Body:
I leave the entire code fragment, the main idea is to have a textfield that, by using the keyboard, shows me a series of elements, in the description variable, I have that element to select, this works well, the only issue is, how to keep my alertdialog with all the correct notes.

 return await Get.generalDialog(
    barrierLabel: "Barrier",
    barrierDismissible: false,
    transitionBuilder: (context, a1, a2, widget) {
      return StatefulBuilder(builder: (context, setState) {
        return Transform.scale(
            scale: a1.value,
            child: Opacity(
              opacity: a1.value,
              child: Dialog(
                insetAnimationCurve: Curves.bounceOut,
                insetPadding: EdgeInsets.only(right: 20, left: 20),
                //backgroundColor: colorFour(),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12.0),
                ),
                child: SingleChildScrollView(
                  child: Container(
                    height: 340,
                    child: Column(
                      children: <Widget>[
                        Container(
                          alignment: Alignment.topCenter,
                          height: 50,
                          decoration: BoxDecoration(
                            color: Colors.red,
                            borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(12),
                              topRight: Radius.circular(12),
                            ),
                          ),
                          padding: EdgeInsets.all(5),
                          child: Center(
                            child: Text(
                              title,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 18,
                                  fontWeight: FontWeight.w600),
                              maxLines: 2,
                              textAlign: TextAlign.center,
                            ),
                          ),
                        ),
                        SingleChildScrollView(
                            padding: EdgeInsets.only(left: 10, right: 10),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment:
                                  CrossAxisAlignment.stretch,
                              children: [
                                Container(
                                  margin: EdgeInsets.only(top: 10),
                                  child: TextFormField(
                                    controller: controller,
                                    decoration: InputDecoration(
                                        border: OutlineInputBorder(
                                            gapPadding: 5.0)),
                                    keyboardType: TextInputType.text,
                                    maxLines: 1,
                                    onChanged: (String cadena) async {
                                      listado = pivote
                                          .where((x) => x.descripcion
                                              .split("/")[value]
                                              .toLowerCase()
                                              .contains(
                                                  cadena.toLowerCase()))
                                          .toList();
                                      setState(() {});
                                    },
                                  ),
                                ),
                                Container(
                                  height: 200,
                                  margin: EdgeInsets.only(
                                      top: 10, bottom: 10.0),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(5)),
                                      border: Border.all(
                                          color: Colors.grey, width: 1)),
                                  child: ListView.builder(
                                      padding: const EdgeInsets.all(0.0),
                                      physics: BouncingScrollPhysics(),
                                      itemCount: listado.length,
                                      shrinkWrap: true,
                                      scrollDirection: Axis.vertical,
                                      itemBuilder: (context, index) {
                                        return Container(
                                          height: 34,
                                          child: InkWell(
                                              child: SizedBox.expand(
                                                child: Align(
                                                  alignment:
                                                      Alignment.centerLeft,
                                                  child: Padding(
                                                    padding:
                                                        EdgeInsets.only(
                                                            right: 5,
                                                            left: 5),
                                                    child: Text(
                                                        listado[index]
                                                            .descripcion
                                                            .split(
                                                                "/")[value],
                                                        textAlign:
                                                            TextAlign.left),
                                                  ),
                                                ),
                                              ),
                                              onTap: () {
                                                Get.back(result: {
                                                  "item": listado[index],
                                                });
                                              }),
                                        );
                                      }),
                                ),
                              ],
                            )),
                      ],
                    ),
                  ),
                ),
              ),
            ));
      });
    },
    pageBuilder: (context, animation1, animation2) {
      return Container();
    });

I need to overlay my alertdialog, that is to say that the size does not break my design, this happens after focusing on the textfield

Body:
Show us some code to help you out.
In any case, it might make sense to wrap the layout in a SingleChildScrollView.
Here is a very good explanation.

https://api.flutter.dev/flutter/widgets/SingleChildScrollView-class.html

yourAlertDialog(
  context: context,
  builder: (BuildContext context) {
    return SingleChildScrollView(child: yourchild);
  },
);

Your layout should be wrapped in Scrollview , I didn't replicate or run this code but it should be like this:

AlertDialog(
      title: Text("title", style: TextStyle(color: ThemeColors.colorPrimary),),
      content: Container(
        width: double.maxFinite,
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: StatefulBuilder(builder: (BuildContext context1, StateSetter setState) {
            this.setState = setState;
            return Container(
                    height: 340,
                    child: Column(
                      children: <Widget>[
                        //your container
                      ],
                    ),
                  ),

          }),

      )),

    );


来源: stackexchange

问:
How to change font size in Material Design TabLayout android?
I have been trying to explore online to set my font size for TabLayout TabItems
But none of them seems to be working for me. This is what I tried referring last link

below are the things which I have implemented so far,
Not sure why it's not picking textSize from style.

in xml:

```<code><com.google.android.material.tabs.TabLayout
                android:id="@+id/tabLayoutForgot"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/header_height"
                app:layout_constraintTop_toBottomOf="@+id/imageViewLogo"
                app:tabIndicatorColor="@color/text_color"
                app:tabSelectedTextColor="@color/text_color"
                app:tabGravity="fill"
                app:tabTextAppearance="@style/MyCustomTabLayout"
                app:tabMode="fixed"
                app:tabIndicatorFullWidth="false"
                app:tabTextColor="@color/text_color" />
</code>```

in themes.xml:

```<code><style name="MyCustomTabLayout" parent="@android:style/TextAppearance.Widget.TabWidget">
        <item name="textAllCaps">false</item>
        <item name="android:textSize">20sp</item>
        <item name="android:fontFamily">@font/roboto_medium</item>
        <item name="android:textColor">@color/text_color</item>
    </style>
</code>```

this does everything else like textAllCaps and fontFamily but doesn't seems to take textSize.

Appreciate any help.

答:
Try style to com.google.android.material.tabs.TabLayout

Add parent of main style as @style/Widget.MaterialComponents.TabLayout

Add parent of tabTextAppearance style as @style/Widget.AppCompat.TextView

```<code><style name="MyCustomTabLayout" parent="@style/Widget.MaterialComponents.TabLayout">
    <item name="tabSelectedTextColor">@color/black</item>
    <item name="tabTextColor">@color/purple_700</item>
    <item name="tabIndicatorColor">@color/black</item>
    <item name="tabTextAppearance">@style/TabText</item>
</style>

<style name="TabText" parent="@style/Widget.AppCompat.TextView">
    <item name="textAllCaps">false</item>
    <item name="android:textSize">20sp</item>
</style>
</code>```

In Xml:

```<code><com.google.android.material.tabs.TabLayout
      android:id="@+id/tabLayoutForgot"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="10dp"
      app:tabGravity="fill"
      style="@style/MyCustomTabLayout"
      app:tabMode="fixed"
      app:tabIndicatorFullWidth="false"/>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have been trying to explore online to set my font size for TabLayout TabItems
But none of them seems to be working for me. This is what I tried referring last link

below are the things which I have implemented so far,
Not sure why it's not picking textSize from style.

in xml:

<com.google.android.material.tabs.TabLayout
                android:id="@+id/tabLayoutForgot"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/header_height"
                app:layout_constraintTop_toBottomOf="@+id/imageViewLogo"
                app:tabIndicatorColor="@color/text_color"
                app:tabSelectedTextColor="@color/text_color"
                app:tabGravity="fill"
                app:tabTextAppearance="@style/MyCustomTabLayout"
                app:tabMode="fixed"
                app:tabIndicatorFullWidth="false"
                app:tabTextColor="@color/text_color" />

in themes.xml:

this does everything else like textAllCaps and fontFamily but doesn't seems to take textSize.

Appreciate any help.

Body:
Try style to com.google.android.material.tabs.TabLayout

Add parent of main style as @style/Widget.MaterialComponents.TabLayout

Add parent of tabTextAppearance style as @style/Widget.AppCompat.TextView

<style name="MyCustomTabLayout" parent="@style/Widget.MaterialComponents.TabLayout">
    <item name="tabSelectedTextColor">@color/black</item>
    <item name="tabTextColor">@color/purple_700</item>
    <item name="tabIndicatorColor">@color/black</item>
    <item name="tabTextAppearance">@style/TabText</item>
</style>

<style name="TabText" parent="@style/Widget.AppCompat.TextView">
    <item name="textAllCaps">false</item>
    <item name="android:textSize">20sp</item>
</style>

In Xml:

<com.google.android.material.tabs.TabLayout
      android:id="@+id/tabLayoutForgot"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="10dp"
      app:tabGravity="fill"
      style="@style/MyCustomTabLayout"
      app:tabMode="fixed"
      app:tabIndicatorFullWidth="false"/>


问:
How can I solve USDZConvert Pxr Import Error?
I'm running into this issue after installing USDZ tools from Apple's website. I'm a bit rusty at Python and tried installing all the underlying packages.

I set my PYTHONPATH already using export PYTHONPATH="/Users/gt/usdpython/USD/lib/python:$PYTHONPATH"

```<code>USD git:(master) ✗ usdzconvert
Traceback (most recent call last):
  File "/Users/gt/usdpython/usdzconvert/usdzconvert", line 17, in <module>
    usdUtils.printError("failed to import pxr module. Please add path to USD Python bindings to your PYTHONPATH.")
NameError: name 'usdUtils' is not defined
</code>```

答:
Run Rosetta Terminal fixes it.
https://developer.apple.com/forums/thread/671459</p>

Body:
I'm running into this issue after installing USDZ tools from Apple's website. I'm a bit rusty at Python and tried installing all the underlying packages.

I set my PYTHONPATH already using export PYTHONPATH="/Users/gt/usdpython/USD/lib/python:$PYTHONPATH"

USD git:(master) ✗ usdzconvert
Traceback (most recent call last):
  File "/Users/gt/usdpython/usdzconvert/usdzconvert", line 17, in <module>
    usdUtils.printError("failed to import pxr module. Please add path to USD Python bindings to your PYTHONPATH.")
NameError: name 'usdUtils' is not defined


问:
Why does scrollTop has a fractional part?
Trying to scroll down a div with a lot of data when I press play on a video.

I get this weird issue where my scrollTop is 211.25 but my scrollHeight is 711 and clientHeight is 500px

I had to put a Math.floor on scrollTop to get it to an even number.

Where is this .25px coming from?

HTML:

```<code><video id="v0" tabindex="0" autobuffer="autobuffer" preload="preload" controls>
  <source src="http://res.cloudinary.com/david-wash-blog/video/upload/sample-video.mp4" type="video/mp4"></source>
  <p>Sorry, your browser does not support the <video> element.</p>
</video>
<div id="data-scroll">
   SOME DATA
   SOME DATA
   SOME DATA
   SOME DATA
   SOME DATA
   SOME DATA

</div>
</code>```

CSS:

```<code>#v0 {
  width: 100%;
  height: 200px;
}

#data-scroll {
  width: 500px;
  height: 500px;
  overflow-y: scroll;
  border: solid red 10px;
}
#footer {
  height: 400px;
}
</code>```

JAVASCRIPT:

```<code>(function(){
  var vid = document.getElementById('v0');
  var dataScroll = document.getElementById('data-scroll');
  var controls = document.getElementById('controls');

  function playScroll(){
      console.log(`clientHeight:${dataScroll.clientHeight}`);
      console.log(`scrollHeight: ${dataScroll.scrollHeight}`);
      console.log(`scrolling dataScroll @ ${dataScroll.scrollTop}`);
      script.scrollTop += 100;
      if(dataScroll.scrollHeight - Math.floor(dataScroll.scrollTop) === script.clientHeight){
        console.log(`stop scrolling dataScroll @ ${dataScroll.scrollTop}`);
        window.cancelAnimationFrame(playScroll);
      }
      window.requestAnimationFrame(playScroll);
    }

  vid.addEventListener('play', function(){
    window.requestAnimationFrame(playScroll);
  });
}());
</code>```

答:
Why does scrollTop has a fractional part?

Because web spec authors felt like it for some odd random reason, literally.

Most likely what you're looking for is this:

```<code>// It reached the bottom.
Math.round(scrollTop) >= scrollHeight - clientHeight
</code>```

So far that has been working for me. I don't know of anything better yet, but if I find out, I'll update it.

EDIT: The previous one doesn't always work. Sometimes scrollTop will be slightly more or less than scrollHeight - clientHeight after rounding, especially in cases when content is scaled (f.e. zoom or CSS transforms).

This is what I'm using now, working well, with Math.abs to handle the more-or-less case:

function isScrolledToBottom(el) {
    // NOTE: scrollTop is fractional, while scrollHeight and clientHeight are
    // not, so without this Math.abs() trick then sometimes the result won't
    // work because scrollTop may not be exactly equal to el.scrollHeight -
    // el.clientHeight when scrolled to the bottom.
    return Math.abs(el.scrollHeight - el.clientHeight - el.scrollTop) < 1
}
```
<p>Note, I'm not using <code>window</code> APIs, only element APIs because this works in every scroll case, including for the top level scroll of the page.</p>
<p>For top level scroll, we can use it like this:</p>
<pre class="lang-js prettyprint-override"><code>isScrolledToBottom(document.documentElement)
</code>```

but we can also use it for scroll within any element nested anywhere in the page.

Body:
Trying to scroll down a div with a lot of data when I press play on a video.

I get this weird issue where my scrollTop is 211.25 but my scrollHeight is 711 and clientHeight is 500px

I had to put a Math.floor on scrollTop to get it to an even number.

Where is this .25px coming from?

HTML:

<video id="v0" tabindex="0" autobuffer="autobuffer" preload="preload" controls>
  <source src="http://res.cloudinary.com/david-wash-blog/video/upload/sample-video.mp4" type="video/mp4"></source>

Sorry, your browser does not support the <video> element.

</video>

   SOME DATA
   SOME DATA
   SOME DATA
   SOME DATA
   SOME DATA
   SOME DATA

CSS:

#v0 {
  width: 100%;
  height: 200px;
}

#data-scroll {
  width: 500px;
  height: 500px;
  overflow-y: scroll;
  border: solid red 10px;
}
#footer {
  height: 400px;
}

JAVASCRIPT:

(function(){
  var vid = document.getElementById('v0');
  var dataScroll = document.getElementById('data-scroll');
  var controls = document.getElementById('controls');

  function playScroll(){
      console.log(`clientHeight:${dataScroll.clientHeight}`);
      console.log(`scrollHeight: ${dataScroll.scrollHeight}`);
      console.log(`scrolling dataScroll @ ${dataScroll.scrollTop}`);
      script.scrollTop += 100;
      if(dataScroll.scrollHeight - Math.floor(dataScroll.scrollTop) === script.clientHeight){
        console.log(`stop scrolling dataScroll @ ${dataScroll.scrollTop}`);
        window.cancelAnimationFrame(playScroll);
      }
      window.requestAnimationFrame(playScroll);
    }

  vid.addEventListener('play', function(){
    window.requestAnimationFrame(playScroll);
  });
}());

Body:
Why does scrollTop has a fractional part?

Because web spec authors felt like it for some odd random reason, literally.

Most likely what you're looking for is this:

// It reached the bottom.
Math.round(scrollTop) >= scrollHeight - clientHeight

So far that has been working for me. I don't know of anything better yet, but if I find out, I'll update it.

EDIT: The previous one doesn't always work. Sometimes scrollTop will be slightly more or less than scrollHeight - clientHeight after rounding, especially in cases when content is scaled (f.e. zoom or CSS transforms).

This is what I'm using now, working well, with Math.abs to handle the more-or-less case:

function isScrolledToBottom(el) {
    // NOTE: scrollTop is fractional, while scrollHeight and clientHeight are
    // not, so without this Math.abs() trick then sometimes the result won't
    // work because scrollTop may not be exactly equal to el.scrollHeight -
    // el.clientHeight when scrolled to the bottom.
    return Math.abs(el.scrollHeight - el.clientHeight - el.scrollTop) < 1
}

Note, I'm not using window APIs, only element APIs because this works in every scroll case, including for the top level scroll of the page.

For top level scroll, we can use it like this:

isScrolledToBottom(document.documentElement)

but we can also use it for scroll within any element nested anywhere in the page.


问:
Can't prevent client side submission php
I've created a register page using php, and the the form successfully sends data to the database.

I'm trying to prevent client side submission, but I can't get the form to stop submitting, even with nothing in the input fields.

It also submits every time and I refresh the page, and I'm not sure why.

I tried to temporarily removing the php, but I'm still having the same issue.

Before I do any further form validation, I need to the form to stop submitting.

Register page with html and php

```<code><?php
require_once "connection.php";

session_start();  //intiate session for current user on site

if (isset($_SESSION["email"]) && isset($_SESSION["password"])) {
    header("location: index.php");
}

$email = filter_input(INPUT_POST, "email", FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, "password");

$hashed_password = password_hash($password, PASSWORD_DEFAULT);

//database entry
$create_account = $pdo->prepare("INSERT INTO users (email,password) VALUES (:email, :password)");
$create_account->bindParam(':email', $email);
$create_account->bindParam(':password', $hashed_password);
$create_account->execute();
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Food Roulette</title>
    <link rel="stylesheet" href="style.css">

</head>

<body class="colorThis">

    <div class="oneForm">
        <form action="register.php" id="signupForm" method="POST">
            <h1 class="register"> Register now </h1><br>
            <label class="emailOne" for="email"> Email Address </label><br>
            <input type="email" id="email" name="email"><br>

            <label class="passwordOne" for="password"> Password </label><br>
            <input type="password" id="password" name="password"><br>
            <button onsubmit="validateRegistrationForm()" class="registerBtn" name="register_button">Login</button>
        </form>
    </div>

    <script src="app.js"></script>
</body>

</html>
</code>```

App.js with form validation

```<code>function validateRegistrationForm() {
    const email = document.getElementById(email);
    const password = document.getElementById(password);

    form.addEventListener("submit", (e) => {
        e.preventDefault();

    })

}
</code>```

答:
You are registering event listener after the form has been submitted through onsubmit="validateRegistrationForm()". You should add event listener outside the validateRegistrationForm function.
Like this:

```<code>    var form  = document.getElementById('signupForm');
    form.addEventListener("submit", (e) =>{
        const email = document.getElementById(email);
        const password = document.getElementById(password);
        e.preventDefault();
    })
</code>```

and remove onsubmit from button:

```<code>   <button  class="registerBtn" name="register_button"> Login </button>
</code>```

Body:
I've created a register page using php, and the the form successfully sends data to the database.

I'm trying to prevent client side submission, but I can't get the form to stop submitting, even with nothing in the input fields.

It also submits every time and I refresh the page, and I'm not sure why.

I tried to temporarily removing the php, but I'm still having the same issue.

Before I do any further form validation, I need to the form to stop submitting.

Register page with html and php

<?php
require_once "connection.php";

session_start();  //intiate session for current user on site

if (isset($_SESSION["email"]) && isset($_SESSION["password"])) {
    header("location: index.php");
}

$email = filter_input(INPUT_POST, "email", FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, "password");

$hashed_password = password_hash($password, PASSWORD_DEFAULT);

//database entry
$create_account = $pdo->prepare("INSERT INTO users (email,password) VALUES (:email, :password)");
$create_account->bindParam(':email', $email);
$create_account->bindParam(':password', $hashed_password);
$create_account->execute();
?>

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Food Roulette</title>
    <link rel="stylesheet" href="style.css">

        <form action="register.php" id="signupForm" method="POST">

 Register now

             Email Address

            <input type="email" id="email" name="email">

             Password

            <input type="password" id="password" name="password">

            <button onsubmit="validateRegistrationForm()" class="registerBtn" name="register_button">Login</button>
        </form>

App.js with form validation

function validateRegistrationForm() {
    const email = document.getElementById(email);
    const password = document.getElementById(password);

    form.addEventListener("submit", (e) => {
        e.preventDefault();

    })

}

Body:
You are registering event listener after the form has been submitted through onsubmit="validateRegistrationForm()". You should add event listener outside the validateRegistrationForm function.
Like this:

    var form  = document.getElementById('signupForm');
    form.addEventListener("submit", (e) =>{
        const email = document.getElementById(email);
        const password = document.getElementById(password);
        e.preventDefault();
    })

and remove onsubmit from button:

   <button  class="registerBtn" name="register_button"> Login </button>


问:
Don't change the reference to a collection with cascade="all-delete-orphan"
I am getting an error:

Don't change the reference to a collection with cascade="all-delete-orphan"

while trying the following operation:

```<code>beginTx();
Parent parent = new Parent();
Child child = new Child();
parent.addChild(child);
getSession().save(parent);
commitTx();
closeSession();

beginTx();
//id is the primary key
child.setID(null);
getSession().update(child);
commitTx();
closeSession();
</code>```

Parent and child are related by one-to-many with cascade = 'all-delete-orphan'.

```<code>class Parent {
Set child;
}

<set name="child" table="Child" cascade="all-delete-orphan" inverse="true">
    <key column="FK"></key>
    <one-to-many class="Child"/>
</set>
</code>```

Any idea why this exception is being thrown?
Why is setting null on the primary key causing this exception even though the entity is in detached state ?

答:
Another reason you can get this is because EntityManager.detach an object in the entity graph followed by EntityManager.flush (which may occur eventually) in which case since it's detached from the entity graph it will try to create a new one again, but it is in a weird state and if you modify it you would get the  following error

Don't change the reference to a collection ...

ContentLicense: CC BY-SA 3.0

Body:
I am getting an error:

Don't change the reference to a collection with cascade="all-delete-orphan"

while trying the following operation:

beginTx();
Parent parent = new Parent();
Child child = new Child();
parent.addChild(child);
getSession().save(parent);
commitTx();
closeSession();

beginTx();
//id is the primary key
child.setID(null);
getSession().update(child);
commitTx();
closeSession();

Parent and child are related by one-to-many with cascade = 'all-delete-orphan'.

class Parent {
Set child;
}

<set name="child" table="Child" cascade="all-delete-orphan" inverse="true">
    <key column="FK"></key>
    <one-to-many class="Child"/>
</set>

Any idea why this exception is being thrown?
Why is setting null on the primary key causing this exception even though the entity is in detached state ?


答: Use required fieids so that form will not be submitted empty.</p>

Title: Can't prevent client side submission php


问:
Stored procedure only runs once
I have a SQL Server stored procedure:

```<code>CREATE PROCEDURE dbo.GetNextNumber
    @NextNumber int OUT
AS
    UPDATE SystemSettings
    SET REGISTRY_NUMBER = REGISTRY_NUMBER + 1
    WHERE ID = 1;

    SELECT @NextRegistryNumber = REGISTRY_NUMBER
    FROM SystemSettings
    WHERE ID = 1;

    SELECT 'NextNumber' = @NextRegistryNumber;
</code>```

I call this from a C# API method:

```<code>public int GetNextRegistryNumberFC()
{
    string procedure = "GetNextNumber";

    // Create ADO.NET objects.
    // SqlConnection con = new SqlConnection(connectionString);
    // SqlCommand cmd = new SqlCommand(procedure, con);

    using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings[<ConnectionString>].ConnectionString))
    using (var cmd = new SqlCommand(procedure, con))

    try
    {
        // Configure command and add input parameters.
        cmd.CommandType = CommandType.StoredProcedure;

        // Add the output parameter.
        cmd.Parameters.Add("@NextNumber", SqlDbType.Int).Direction = ParameterDirection.Output;

        // Execute the command.
        con.Open();
        cmd.ExecuteNonQuery();

        NextRegistryNumber = Convert.ToInt32(cmd.Parameters["@NextNumber"].Value);
    }
    catch (Exception ex)
    {
        throw;
    }
    finally
    {
        cmd.Dispose();
        con.Close();
        con.Dispose();
    }

    return NextRegistryNumber;
}
</code>```

This works the first time I run it. After that it just return the same number each time instead of incrementing it. I am not sure what I happening. If I run the stored procedure by it self it works each time. Does anyone know what is going wrong here?

答:
Is this a typo?

```<code>SELECT 'NextNumber' = @NextRegistryNumber;
</code>```

This would output a table with a column called 'NextNumber' with the value in @NextRegistryNumber ie: you've done a column alias.

It should be:

```<code>SELECT @NextNumber = @NextRegistryNumber;
</code>```

OR

```<code>SET @NextNumber = @NextRegistryNumber;
</code>```

Title: Stored procedure only runs once

Body:
I have a SQL Server stored procedure:

CREATE PROCEDURE dbo.GetNextNumber
    @NextNumber int OUT
AS
    UPDATE SystemSettings
    SET REGISTRY_NUMBER = REGISTRY_NUMBER + 1
    WHERE ID = 1;

    SELECT @NextRegistryNumber = REGISTRY_NUMBER
    FROM SystemSettings
    WHERE ID = 1;

    SELECT 'NextNumber' = @NextRegistryNumber;

I call this from a C# API method:

public int GetNextRegistryNumberFC()
{
    string procedure = "GetNextNumber";

    // Create ADO.NET objects.
    // SqlConnection con = new SqlConnection(connectionString);
    // SqlCommand cmd = new SqlCommand(procedure, con);

    using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings[<ConnectionString>].ConnectionString))
    using (var cmd = new SqlCommand(procedure, con))

    try
    {
        // Configure command and add input parameters.
        cmd.CommandType = CommandType.StoredProcedure;

        // Add the output parameter.
        cmd.Parameters.Add("@NextNumber", SqlDbType.Int).Direction = ParameterDirection.Output;

        // Execute the command.
        con.Open();
        cmd.ExecuteNonQuery();

        NextRegistryNumber = Convert.ToInt32(cmd.Parameters["@NextNumber"].Value);
    }
    catch (Exception ex)
    {
        throw;
    }
    finally
    {
        cmd.Dispose();
        con.Close();
        con.Dispose();
    }

    return NextRegistryNumber;
}

This works the first time I run it. After that it just return the same number each time instead of incrementing it. I am not sure what I happening. If I run the stored procedure by it self it works each time. Does anyone know what is going wrong here?

Body:
Is this a typo?

SELECT 'NextNumber' = @NextRegistryNumber;

This would output a table with a column called 'NextNumber' with the value in @NextRegistryNumber ie: you've done a column alias.

It should be:

SELECT @NextNumber = @NextRegistryNumber;

OR

SET @NextNumber = @NextRegistryNumber;


问:
Running into Nektos/Act error permission denied when running actions locally
Pretty new to Nektos/act and in general running workflows locally and cant seem to find a solution to a permissions denied error when installing Node version 16. Here is the error I am running into when I run the following:

Command:

```<code>act -j release
</code>```

Error:

```<code>docker exec cmd=[mkdir -p /var/run/act/actions/actions-setup-node@v1/] user= workdir=
mkdir: cannot create directory '/var/run/act/actions': Permission denied
</code>```

Yaml (Example)

```<code>name: Release Example
on:
  push:
    branches: [ master ]
jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
        with:
          token: ${{secrets.PRIVATE_SECRET}}

      - name: Use version 16 of Node.js
        uses: actions/setup-node@v1
        with:
          node-version: '16'

      - name: Pre Install
        run: echo "//npm.pkg.github.com/:_authToken=${{secrets.GITHUB_TOKEN}}"> ~/.npmrc

      - name: Install
        run: npm ci
        env:
          PRIVATE_SECRET: ${{secrets.PRIVATE_SECRET}}

      - name: Release
        env:
          GITHUB_TOKEN: ${{secrets.PRIVATE_SECRET}}
          PRIVATE_SECRET: ${{secrets.PRIVATE_SECRET}}
          REGISTRY_TOKEN: ${{secrets.PRIVATE_SECRET}}
        run: npx semantic-release
</code>```

What I have tried:

I have tried setting the user to root on the container for example

```<code>container:
  image: ghcr.io/catthehacker/ubuntu:full-20.04
  options: --user root
</code>```

I have tried setting sudo in steps

```<code> - run: sudo chown runner:docker /var/run/docker.sockenter
</code>```

I have tried passing the secrets via acts flags

I have tried setting the working directory and setting env auth override to true

I have checked issues related to this topic on the repo and it seems like others are facing the same issue but I have not been able to figure out a solution.

NOTE: This is all working on GitHub, but fails locally with the error mentioned above. Trying hard to test locally to not muddy up my repo with broken commits. Any help is greatly appreciated.

答:
Appears to be a bug with the recent release. I confirm that downgrading to 0.2.24 fixed this issue.

https://github.com/nektos/act/issues/935#issuecomment-1035261208

```<code>brew remove act
cd $(brew --repository)/Library/Taps/homebrew/homebrew-core/Formula
git checkout 3ab2604b1e630d4eccab40d0e78f29bd912a72b8 -- act.rb
brew install act
brew pin act
git checkout HEAD -- act.rb
act --version # make sure it's 0.2.24
</code>```

Body:
Pretty new to Nektos/act and in general running workflows locally and cant seem to find a solution to a permissions denied error when installing Node version 16. Here is the error I am running into when I run the following:

Command:

act -j release

Error:

docker exec cmd=[mkdir -p /var/run/act/actions/actions-setup-node@v1/] user= workdir=
mkdir: cannot create directory '/var/run/act/actions': Permission denied

Yaml (Example)

name: Release Example
on:
  push:
    branches: [ master ]
jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
        with:
          token: ${{secrets.PRIVATE_SECRET}}

      - name: Use version 16 of Node.js
        uses: actions/setup-node@v1
        with:
          node-version: '16'

      - name: Pre Install
        run: echo "//npm.pkg.github.com/:_authToken=${{secrets.GITHUB_TOKEN}}"> ~/.npmrc

      - name: Install
        run: npm ci
        env:
          PRIVATE_SECRET: ${{secrets.PRIVATE_SECRET}}

      - name: Release
        env:
          GITHUB_TOKEN: ${{secrets.PRIVATE_SECRET}}
          PRIVATE_SECRET: ${{secrets.PRIVATE_SECRET}}
          REGISTRY_TOKEN: ${{secrets.PRIVATE_SECRET}}
        run: npx semantic-release

What I have tried:

I have tried setting the user to root on the container for example

container:
  image: ghcr.io/catthehacker/ubuntu:full-20.04
  options: --user root

I have tried setting sudo in steps

 - run: sudo chown runner:docker /var/run/docker.sockenter

I have tried passing the secrets via acts flags

I have tried setting the working directory and setting env auth override to true

I have checked issues related to this topic on the repo and it seems like others are facing the same issue but I have not been able to figure out a solution.

NOTE: This is all working on GitHub, but fails locally with the error mentioned above. Trying hard to test locally to not muddy up my repo with broken commits. Any help is greatly appreciated.

Body:
Appears to be a bug with the recent release. I confirm that downgrading to 0.2.24 fixed this issue.

https://github.com/nektos/act/issues/935#issuecomment-1035261208

brew remove act
cd $(brew --repository)/Library/Taps/homebrew/homebrew-core/Formula
git checkout 3ab2604b1e630d4eccab40d0e78f29bd912a72b8 -- act.rb
brew install act
brew pin act
git checkout HEAD -- act.rb
act --version # make sure it's 0.2.24


问:
Message queue in android
can anybody tell me,
how can get data(message) from message queue ?
or how can send message from main thread to other thread ?.

Thanks

答:
not any other Thread.. you can sen it main Thread or Ui thread, using Handler..

create handler and send a runnable object as anarguement..

Title: Message queue in android


问:
NEARprotocol: Why is AssemblyScript smart contract development only for non financial use cases?
In the NEAR protocol smart contract development documentation for AssemblyScript it says:

Why?

答:
big fan of your work

the Rust-to-Wasm toolchain is the most mature in the industry and Rust offers safety guarantees that no other language can

AssemblyScript is a young language maintained by a small community of developers so the compiler hasn't had anywhere near as much attention as the Rust compiler has

if someone is building a contract that manages a lot of value, they should be using the best possible technology to solve the problem.  in this case, that's Rust.

AssemblyScript makes it easy for web developers to learn to write smart contracts in a matter of hours.  Rust takes a little longer, maybe some weeks of practice sparring with the borrow checker in the dojo ;)

below is a slide from our Intro to NEAR for Senior Developers


问:
Send POST request with JSON data Spring boot
I trying to send a post request with json data in a particular format using Spring boot. I am not getting data in expected format. Please help e resolve it. Thanks in advance.

```<code>class UserService{
public void sendRequest(User data){
  HttpHeaders header = new HttpHeaders();
  mapHeaders.set("Content-Type","application/json");
  Map<String,User> m= new HashMap<String,User>();
  m.put("request",data);
  //print m i.e. payload being sent
  HttpEntity entity = new HttpEntity<Object>(m, header);
  String url = some url here
  ResponseEntity<Object> response = restTemplate.exchange(url, httpMethod, entity,
   Object.class);
   }
}

class User{
private String firstName;
private String lastName;

}

</code>```

While printing payload it displays payload as:

```<code>{request=User(firstName=Raj,lastName=Kumar)}
</code>```

I want the data as

```<code>{request={firstName=Raj,lastName=Kumar}}
</code>```

答:
You can use JSONObject :

```<code>Map<String, JSONObject> m = new HashMap<>();
m.put("request", new JSONObject(data));
</code>```

Result :

```<code>{request={"firstName":"Raj","lastName":"Kumar"}}
</code>```

Maven dependency :

```<code>    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20210307</version>
    </dependency>
</code>```

Body:
I trying to send a post request with json data in a particular format using Spring boot. I am not getting data in expected format. Please help e resolve it. Thanks in advance.

class UserService{
public void sendRequest(User data){
  HttpHeaders header = new HttpHeaders();
  mapHeaders.set("Content-Type","application/json");
  Map<String,User> m= new HashMap<String,User>();
  m.put("request",data);
  //print m i.e. payload being sent
  HttpEntity entity = new HttpEntity<Object>(m, header);
  String url = some url here
  ResponseEntity<Object> response = restTemplate.exchange(url, httpMethod, entity,
   Object.class);
   }
}

class User{
private String firstName;
private String lastName;

}

While printing payload it displays payload as:

{request=User(firstName=Raj,lastName=Kumar)}

I want the data as

{request={firstName=Raj,lastName=Kumar}}

Body:
You can use JSONObject :

Map<String, JSONObject> m = new HashMap<>();
m.put("request", new JSONObject(data));

Result :

{request={"firstName":"Raj","lastName":"Kumar"}}

Maven dependency :

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20210307</version>
    </dependency>


问:
Binary to decimal in java using only recursion (no loops)
I can not seem to get my method to convert the binary number to a decimal correctly. I believe i am really close and in fact i want to use a string to hold the binary number to hold it and then re-write my method to just use a .length to get the size but i do not know how to actually do that. Could someone help me figure out how i'd rewrite the code using a string to hold the binary value and then obtain the decimal value using only recursion and no loops?

This is my full code right now and i won't get get rid of asking for the size of the binary and use a string to figure it out myself. Please help :)

```<code>package hw_1;
import java.util.Scanner;

public class Hw_1 {

    public static void main(String[] args) {

        int input;
        int size;
        Scanner scan = new Scanner(System.in);

        System.out.print("Enter decimal integer: ");
        input = scan.nextInt();
        convert(input);
        System.out.println();
        System.out.print("Enter binary integer and size : ");
        input = scan.nextInt();
        size = scan.nextInt();
        System.out.println(binaryToDecimal(input, size));

    }

    public static void convert(int num) {
        if (num > 0) {
            convert(num / 2);
            System.out.print(num % 2 + " ");
        }
    }

    public static int binaryToDecimal(int binary, int size) {
        if (binary == 0) {
            return 0;
        }
        return binary % 10
                * (int) Math.pow(2, size) + binaryToDecimal((int) binary / 10, size - 1);

    }
}
</code>```

答:
Just did the necessary changes in your code.
In this way, you would not require the size input from the user.
And,both the conversions of decimal to binary and binary to decimal would be succesfully done.

```<code>package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {

    int input;
    int size;
    Scanner scan = new Scanner(System.in);

    System.out.print("Enter decimal integer: ");
    input = scan.nextInt();
    convert(input);
    System.out.println();
    System.out.print("Enter binary integer : ");
    input = scan.nextInt();
    System.out.println(binaryToDecimal(input));

}

public static void convert(int num) {
    if (num > 0) {
        convert(num / 2);
        System.out.print(num % 2 + " ");
    }
    return -1;
}
public static int binaryToDecimal(int binary) {
    if(binary==0)
    {
        return 0;
    }
    else
    {
        String n=Integer.toString(binary);
        int size=(n.length())-1;
        int k=(binary%10)*(int)(Math.pow(2,size));
        return k + binaryToDecimal(((int)binary/10));
    }

}
</code>```

}

Body:
I can not seem to get my method to convert the binary number to a decimal correctly. I believe i am really close and in fact i want to use a string to hold the binary number to hold it and then re-write my method to just use a .length to get the size but i do not know how to actually do that. Could someone help me figure out how i'd rewrite the code using a string to hold the binary value and then obtain the decimal value using only recursion and no loops?

This is my full code right now and i won't get get rid of asking for the size of the binary and use a string to figure it out myself. Please help :)

package hw_1;
import java.util.Scanner;

public class Hw_1 {

    public static void main(String[] args) {

        int input;
        int size;
        Scanner scan = new Scanner(System.in);

        System.out.print("Enter decimal integer: ");
        input = scan.nextInt();
        convert(input);
        System.out.println();
        System.out.print("Enter binary integer and size : ");
        input = scan.nextInt();
        size = scan.nextInt();
        System.out.println(binaryToDecimal(input, size));

    }

    public static void convert(int num) {
        if (num > 0) {
            convert(num / 2);
            System.out.print(num % 2 + " ");
        }
    }

    public static int binaryToDecimal(int binary, int size) {
        if (binary == 0) {
            return 0;
        }
        return binary % 10
                * (int) Math.pow(2, size) + binaryToDecimal((int) binary / 10, size - 1);

    }
}

Body:
Just did the necessary changes in your code.
In this way, you would not require the size input from the user.
And,both the conversions of decimal to binary and binary to decimal would be succesfully done.

package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {

    int input;
    int size;
    Scanner scan = new Scanner(System.in);

    System.out.print("Enter decimal integer: ");
    input = scan.nextInt();
    convert(input);
    System.out.println();
    System.out.print("Enter binary integer : ");
    input = scan.nextInt();
    System.out.println(binaryToDecimal(input));

}

public static void convert(int num) {
    if (num > 0) {
        convert(num / 2);
        System.out.print(num % 2 + " ");
    }
    return -1;
}
public static int binaryToDecimal(int binary) {
    if(binary==0)
    {
        return 0;
    }
    else
    {
        String n=Integer.toString(binary);
        int size=(n.length())-1;
        int k=(binary%10)*(int)(Math.pow(2,size));
        return k + binaryToDecimal(((int)binary/10));
    }

}

}


问:
Laravel Sail Set MySQL Data Configuration Setting
I'm using Laravel Sail with MySQL.  We have triggers on our database and I need to be able to set log_bin_trust_function_creators = 1 in the configuration.  For the life of me, I can't figure out set this automatically when the container is created.

答: You could use a volume in docker-compose to replace the config. Then it will use your new config. To copy the current config from the container to your host OS you can use docker cp <container>:<file> <destination>.


问:
What is the most efficient way of updating multiple records in Oracle with same value
We have a batch job that needs to update millions of rows (not all rows) of a table with a particular value.

We have the following implementation :

We process say e.g. 10K records at a time and fire the Update query with hardcoded values in the IN clause like so :

```<code>@Query("UPDATE Order or SET or.status= 'PROCESSED' WHERE or.orderId IN (:orderIds)")
@Modifying
void updateProcessedOrders(@Param("orderIds") List<String> orderIds);
</code>```

The first limitation is that the Update with IN clause can update only 1000 records at a time. Hence we have to split the list of Ids in a batch of 1000s and then create an Update query for each of them. So instead of one query for 10k orderIds we have to fire 10 update queries.

The job works in a reasonable amount of time for 10 to 15 million records however for one of the clients the amount of data is to the tune of 200 million. For 200 million the job takes 2 days to complete which is unacceptable.

So my question is :
Is there a more efficient way of updating millions of records with the same value?

答:
One option to remove the 1000 elements in IN list restriction is to create another table, e.g.

```<code>create table order_ids (orderId number constraint pk_oid primary key);
</code>```

and insert all ID values you're working with. It means not 1000 by 1000, but as many as needed (millions, possibly) at once.

Then

```<code>update order a set a.status = 'PROCESSED'
where exists (select null
              from order_ids b
              where b.orderId = a.orderId);
</code>```

(table's primary key means that Oracle will implicitly index that column; if you allow duplicates, then remove primary key and create index on that column).

Body:
We have a batch job that needs to update millions of rows (not all rows) of a table with a particular value.

We have the following implementation :

We process say e.g. 10K records at a time and fire the Update query with hardcoded values in the IN clause like so :

@Query("UPDATE Order or SET or.status= 'PROCESSED' WHERE or.orderId IN (:orderIds)")
@Modifying
void updateProcessedOrders(@Param("orderIds") List<String> orderIds);

The first limitation is that the Update with IN clause can update only 1000 records at a time. Hence we have to split the list of Ids in a batch of 1000s and then create an Update query for each of them. So instead of one query for 10k orderIds we have to fire 10 update queries.

The job works in a reasonable amount of time for 10 to 15 million records however for one of the clients the amount of data is to the tune of 200 million. For 200 million the job takes 2 days to complete which is unacceptable.

So my question is :
Is there a more efficient way of updating millions of records with the same value?

Body:
One option to remove the 1000 elements in IN list restriction is to create another table, e.g.

create table order_ids (orderId number constraint pk_oid primary key);

and insert all ID values you're working with. It means not 1000 by 1000, but as many as needed (millions, possibly) at once.

Then

update order a set a.status = 'PROCESSED'
where exists (select null
              from order_ids b
              where b.orderId = a.orderId);

(table's primary key means that Oracle will implicitly index that column; if you allow duplicates, then remove primary key and create index on that column).


问:
Flex wrap and overflow on both column and row
I am trying to create a resizable flex box that can only accommodate as much detail as it could. I want the inner items to be stacked horizontally.

Flex items should grow horizontally until width and wrap itself:

When reducing the width, it will wrap to the next line:

But when I resize so that the height is not sufficient, I want the items to over flow completely. Unlike in this image here, it's partially inside.

I have written the below for wrapping it for width, how do I do it for height as well?

```<code> display: flex;

  flex-direction: row;

  flex-wrap: wrap;

  background-color: green;

  overflow: hidden;
</code>```

答:
If you have a resizable container using the resize property then it will not be able to overflow like you want to because it's not compatible with overflow: visible;

The resize property does not apply to inline elements or to block elements where overflow="visible". So, make sure that overflow is set to "scroll", "auto", or "hidden".

.container {
  background: #008000;
  border: 5px solid black;
  display: flex;
  flex-wrap: wrap;
  padding: 5px;
  height: 120px;
  width: 160px;
  resize: both;
  gap: 5px;
  overflow: hidden;
}

.container>div {
  height: 50px;
  width: 50px;
  background: #fff;
  display: grid;
  place-items: center;
  font-size: 25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="container">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
  </div>
</body></code>```

Here's a workaround, but some tradeoffs that might not be exactly what you are looking for. Check the snippets:

.container {
  background: #008000;
  border: 5px solid black;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  padding: 5px;
  height: 120px;
  max-width: 160px;
  resize: vertical;
  gap: 5px;
  overflow: hidden;
}

.container>div {
  height: 50px;
  width: 50px;
  background: #fff;
  display: grid;
  place-items: center;
  font-size: 25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="container">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
  </div>
</body></code>```

Body:
I am trying to create a resizable flex box that can only accommodate as much detail as it could. I want the inner items to be stacked horizontally.

Flex items should grow horizontally until width and wrap itself:

When reducing the width, it will wrap to the next line:

But when I resize so that the height is not sufficient, I want the items to over flow completely. Unlike in this image here, it's partially inside.

I have written the below for wrapping it for width, how do I do it for height as well?

 display: flex;

  flex-direction: row;

  flex-wrap: wrap;

  background-color: green;

  overflow: hidden;

Body:
If you have a resizable container using the resize property then it will not be able to overflow like you want to because it's not compatible with overflow: visible;

The resize property does not apply to inline elements or to block elements where overflow="visible". So, make sure that overflow is set to "scroll", "auto", or "hidden".

.container {
  background: #008000;
  border: 5px solid black;
  display: flex;
  flex-wrap: wrap;
  padding: 5px;
  height: 120px;
  width: 160px;
  resize: both;
  gap: 5px;
  overflow: hidden;
}

.container>div {
  height: 50px;
  width: 50px;
  background: #fff;
  display: grid;
  place-items: center;
  font-size: 25px;
}

<body>
  <div class="container">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
  </div>
</body>

Here's a workaround, but some tradeoffs that might not be exactly what you are looking for. Check the snippets:

.container {
  background: #008000;
  border: 5px solid black;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  padding: 5px;
  height: 120px;
  max-width: 160px;
  resize: vertical;
  gap: 5px;
  overflow: hidden;
}

.container>div {
  height: 50px;
  width: 50px;
  background: #fff;
  display: grid;
  place-items: center;
  font-size: 25px;
}

<body>
  <div class="container">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
  </div>
</body>


问:
JavaScript files that are concatenated fail
I have been looking at combining my JavaScript files into one file, to gain some performance. Mostly it worked like a charm, but not for the jquery.templates, knockout.js and knockout.mapping.js libraries.

I have tried something as simple as manually copy/pasting the content of the three files into one file. As soon as I reference that new file instead of the three original files it fails - with undefined is not a function, but the error is not as important as why there is any difference at all.

Any idea why this happens?

答: Check strict mode tags in all files. If the first has it but later ones don't strict mode will be enabled for everything, or the other way round.


问:
Unknown custom element - did you register the component correctly?
I'm currently using webpack with vuejs 2. I have a very basic component [Main.vue] that is rendered by vue-router and inside this component, I want to have another one [Information.vue]. For some reason, I can't render it properly.

components/test/Information.vue

```<code><template>
    <div>
    TEST
    </div>
</template>

<script>
export default {
  name: 'information',
  props: {
    bleh: {
      type: Object,
      required: true
    }
  }
}
</script>
</code>```

components/test/injex.js

```<code>export { default as Main } from './Main'
export { default as Information } from './Information'
</code>```

components/test/Main.vue

```<code><template>
    <information :bleh="{}" />
</template>

<script>
import { Information } from 'components/test'
export default {
  name: 'main',
  components: { Information  }
}
</script>
</code>```

Any idea why I get the following error ?

```<code>[Vue warn]: Unknown custom element: <information> - did you register
the component correctly? For recursive components, make sure to
provide the "name" option
</code>```

答:
Try register component directly. I fixed my one by this.</p>
```<code>Vue.component('Information', Information)
</code>```

Body:
I'm currently using webpack with vuejs 2. I have a very basic component [Main.vue] that is rendered by vue-router and inside this component, I want to have another one [Information.vue]. For some reason, I can't render it properly.

components/test/Information.vue

<template>

    TEST

</template>

components/test/injex.js

export { default as Main } from './Main'
export { default as Information } from './Information'

components/test/Main.vue

<template>
    <information :bleh="{}" />
</template>

Any idea why I get the following error ?

[Vue warn]: Unknown custom element: <information> - did you register
the component correctly? For recursive components, make sure to
provide the "name" option

Body:
Try register component directly. I fixed my one by this.

Vue.component('Information', Information)


问:
Is there a way to handle files within google cloud storage?
There are many compressed files inside google cloud storage.

I want to unzip the zipped file, rename it and save it back to another bucket.

I've seen a lot of posts, but I couldn't find a way other than how to download it with gsutil and handle it.

Do you have any other way?

答:
You can start using cloudFunctions for it. CloudFunction will get triggered when the object is created/finalized and it will do the job automatically.

You can also use the same function to iterate over all the zip files, do the tasks and move same files to another bucket. One thing to make sure it may not be able to move all files in a single go, but for the files which already exists on the bucket, you can use local machine to run the program.

Here is the list of libraries to connect to CloudStorage


问:
How to paste an Excel chart into PowerPoint placeholder using Python?
I have an excel file with a series of formatted charts on a tab called Charts.  I have named the charts, Figure1, Figure2, Figure3, etc.

I have an existing PowerPoint template. The template has 2 placeholders per slide (so that it can accommodate 2 charts per slide).

I would like to paste Figure1 in the left placeholder of slide 3, and Figure2 in the right placeholder of slide 3.  I want to do this in python as the data analysis is done in python and excel is used to share stored results with colleagues.

Attempt 1:

Attempt 1 uses win32com.client.  I am following this example: How to copy chart from excel and paste it as chart into powerpoint (not image) using python

but I cannot get the syntax right to insert the chart into the placeholder.  When I follow the syntax in the solution, nothing happens and I get a message

<bound method Paste of <COMObject >>

Current code:

xlApp = win32.Dispatch('Excel.Application')
wb = xlApp.Workbooks.Open(outputPath+'Chart Pack.xlsb')

pptApp = win32.Dispatch('PowerPoint.Application')
ppt = pptApp.Presentations.Open(template)

# attempt 1
wb.sheets('Charts').ChartObjects('Figure1').Copy
ppt.slides[2].Shapes.Paste

# attempt 2
wb.sheets('Charts').ChartObjects('Figure1').Copy
ppt.slides[2].placeholders[1].Paste
```
<p><strong>Attempt 2:</strong></p>
<p>Attempt 2 uses <code>python-pptx</code>.  I looked at the documentation here:
https://python-pptx.readthedocs.io/en/latest/user/placeholders-using.html</p>
<p>but the example involves creating an excel chart from scratch in PowerPoint (I am not sure why you would ever do that), and I can't figure out the syntax to insert an existing chart from excel.</p>
<p>Current code:</p>
<pre class="lang-python prettyprint-override"><code>from pptx import Presentation

xlApp = win32.Dispatch('Excel.Application')
wb = xlApp.Workbooks.Open(outputPath+'Chart Pack.xlsb')

prs = Presentation(template)
slide = prs.slides[3]

for shape in slide.placeholders:
    print('%d %s' % (shape.placeholder_format.idx, shape.name))

placeholder = prs.slides[3].placeholders[1]
placeholder.name
placeholder.placeholder_format.type
placeholder.insert_chart(wb.sheets('Charts').ChartObjects('Figure1').Copy)
</code>```

Requirements:

I would like to paste the excel chart as an excel object (rather than as a picture) as my colleague likes to be able to click on data series to get the underlying values etc.

I would like to paste the chart inside a placeholder (rather than on top of it).

I don't want to generate a new chart in PowerPoint as most examples do.  A colleague has prepared an excel dashboard and formatted a number of charts as desired, and doing it all from scratch would be laborious.

I don't want to do this in VBA.  I would like to do it in python as it is part of a broader program.

I don't want to use something like plotnine, seaborn, matplotlib etc.  As per 1, my colleague likes excel objects that he can click on to show underlying values.  This can't be done in these programs.

Python should be able to do this.  Any ideas?

答:
You're very close! Copy and Paste are methods, so to call them you need to add brackets after them, e.g. Copy().

To get slide 2, you need to use the Item method of the Slides class: ppt.Slides.Item(2)

import win32com.client as win32

xlApp = win32.Dispatch('Excel.Application')
wb = xlApp.Workbooks.Open(outputPath+'Chart Pack.xlsb')

pptApp = win32.Dispatch('PowerPoint.Application')
ppt = pptApp.Presentations.Open(template)

slide_num = 3
LEFT_PLACEHOLDER = 3
RIGHT_PLACEHOLDER = 2

# Figure1
window.View.GotoSlide(slide_num)
wb.sheets('Charts').ChartObjects('Figure1').Copy()
ppt.Slides.Item(slide_num).Shapes.Paste().Select()
window.Selection.Cut()
ppt.Slides.Item(slide_num).Shapes(LEFT_PLACEHOLDER).Select()
window.View.Paste()

# Figure2
window.View.GotoSlide(slide_num)
wb.sheets('Charts').ChartObjects('Figure2').Copy()
ppt.Slides.Item(slide_num).Shapes.Paste().Select()
window.Selection.Cut()
ppt.Slides.Item(slide_num).Shapes(RIGHT_PLACEHOLDER).Select()
window.View.Paste()
```

EDIT: I was able to paste the chart directly into the placeholder after fiddling around a bit trying to implement the solution in this answer. It a bit hacky, but it works.

Body:
I have an excel file with a series of formatted charts on a tab called Charts.  I have named the charts, Figure1, Figure2, Figure3, etc.

I have an existing PowerPoint template. The template has 2 placeholders per slide (so that it can accommodate 2 charts per slide).

I would like to paste Figure1 in the left placeholder of slide 3, and Figure2 in the right placeholder of slide 3.  I want to do this in python as the data analysis is done in python and excel is used to share stored results with colleagues.

Attempt 1:

Attempt 1 uses win32com.client.  I am following this example: How to copy chart from excel and paste it as chart into powerpoint (not image) using python

but I cannot get the syntax right to insert the chart into the placeholder.  When I follow the syntax in the solution, nothing happens and I get a message

<bound method Paste of <COMObject >>

Current code:

xlApp = win32.Dispatch('Excel.Application')
wb = xlApp.Workbooks.Open(outputPath+'Chart Pack.xlsb')

pptApp = win32.Dispatch('PowerPoint.Application')
ppt = pptApp.Presentations.Open(template)

# attempt 1
wb.sheets('Charts').ChartObjects('Figure1').Copy
ppt.slides[2].Shapes.Paste

# attempt 2
wb.sheets('Charts').ChartObjects('Figure1').Copy
ppt.slides[2].placeholders[1].Paste

Attempt 2:

Attempt 2 uses python-pptx.  I looked at the documentation here:
https://python-pptx.readthedocs.io/en/latest/user/placeholders-using.html

but the example involves creating an excel chart from scratch in PowerPoint (I am not sure why you would ever do that), and I can't figure out the syntax to insert an existing chart from excel.

Current code:

from pptx import Presentation

xlApp = win32.Dispatch('Excel.Application')
wb = xlApp.Workbooks.Open(outputPath+'Chart Pack.xlsb')

prs = Presentation(template)
slide = prs.slides[3]

for shape in slide.placeholders:
    print('%d %s' % (shape.placeholder_format.idx, shape.name))

placeholder = prs.slides[3].placeholders[1]
placeholder.name
placeholder.placeholder_format.type
placeholder.insert_chart(wb.sheets('Charts').ChartObjects('Figure1').Copy)

Requirements:

I would like to paste the excel chart as an excel object (rather than as a picture) as my colleague likes to be able to click on data series to get the underlying values etc.

I would like to paste the chart inside a placeholder (rather than on top of it).

I don't want to generate a new chart in PowerPoint as most examples do.  A colleague has prepared an excel dashboard and formatted a number of charts as desired, and doing it all from scratch would be laborious.

I don't want to do this in VBA.  I would like to do it in python as it is part of a broader program.

I don't want to use something like plotnine, seaborn, matplotlib etc.  As per 1, my colleague likes excel objects that he can click on to show underlying values.  This can't be done in these programs.

Python should be able to do this.  Any ideas?

Body:
You're very close! Copy and Paste are methods, so to call them you need to add brackets after them, e.g. Copy().

To get slide 2, you need to use the Item method of the Slides class: ppt.Slides.Item(2)

import win32com.client as win32

xlApp = win32.Dispatch('Excel.Application')
wb = xlApp.Workbooks.Open(outputPath+'Chart Pack.xlsb')

pptApp = win32.Dispatch('PowerPoint.Application')
ppt = pptApp.Presentations.Open(template)

slide_num = 3
LEFT_PLACEHOLDER = 3
RIGHT_PLACEHOLDER = 2

# Figure1
window.View.GotoSlide(slide_num)
wb.sheets('Charts').ChartObjects('Figure1').Copy()
ppt.Slides.Item(slide_num).Shapes.Paste().Select()
window.Selection.Cut()
ppt.Slides.Item(slide_num).Shapes(LEFT_PLACEHOLDER).Select()
window.View.Paste()

# Figure2
window.View.GotoSlide(slide_num)
wb.sheets('Charts').ChartObjects('Figure2').Copy()
ppt.Slides.Item(slide_num).Shapes.Paste().Select()
window.Selection.Cut()
ppt.Slides.Item(slide_num).Shapes(RIGHT_PLACEHOLDER).Select()
window.View.Paste()

EDIT: I was able to paste the chart directly into the placeholder after fiddling around a bit trying to implement the solution in this answer. It a bit hacky, but it works.


问:
How to clear/reset results of the Python line profiler?
I'm trying to start and stop the line profiling of a Python function multiple times during runtime. Therefore I'd like to reset the already collected stats when starting a new profiling. Is there a way to do that?

In lack of an obvious solution I also tried replacing the line profiler lp with a fresh instance:

```<code>#!/usr/bin/env python3
from line_profiler import LineProfiler

lp = LineProfiler()

@lp
def count():
    return sum(range(1_000_000))

count()
lp.print_stats()

# reset line profiler
new_lp = LineProfiler()
for f in lp.functions:
    new_lp(f)
lp = new_lp

count()
lp.print_stats()
</code>```

But somehow the new stats are empty, possibly because the function count() can't be wrapped twice?

答:
I came up with the following solution based of a new profiler class. Every time a profiling is started, it creates a new instance of LineProfiler. The key is to store wrapped functions next to the originals, so that they can be reset when stopping the profiler.

from typing import Optional
from line_profiler import LineProfiler
from functools import wraps

class MyLineProfiler:

    def __init__(self):
        self.functions: list[list] = []
        self.line_profiler: Optional[LineProfiler] = None

    def __call__(self, func):
        index = len(self.functions)

        @wraps(func)
        def wrap(*args, **kw):
            return self.functions[index][1](*args, **kw)

        self.functions.append([func, func])
        return wrap

    def start(self):
        self.line_profiler = LineProfiler()
        for f in self.functions:
            f[1] = self.line_profiler(f[0])

    def stop(self, *, print: bool = True):
        for f in self.functions:
            f[1] = f[0]
        if self.line_profiler and print:
            self.line_profiler.print_stats()

    def reset(self):
        self.stop(print=False)
        self.start()
```
<p>The wrapped functions call whatever is currently stored at <code>functions[index][1]</code>, either the original <code>func</code> (when no profiling is stopped) or the decorated one (when <code>start()</code> was called).</p>
<p>It can be used as follows:</p>
<pre class="lang-py prettyprint-override"><code>profile = MyLineProfiler()

@profile
def count():
    return sum(range(1_000_000))

count()

profile.start()
count()
count()
profile.stop()

profile.start()
count()
profile.stop()
</code>```

Body:
I'm trying to start and stop the line profiling of a Python function multiple times during runtime. Therefore I'd like to reset the already collected stats when starting a new profiling. Is there a way to do that?

In lack of an obvious solution I also tried replacing the line profiler lp with a fresh instance:

#!/usr/bin/env python3
from line_profiler import LineProfiler

lp = LineProfiler()

@lp
def count():
    return sum(range(1_000_000))

count()
lp.print_stats()

# reset line profiler
new_lp = LineProfiler()
for f in lp.functions:
    new_lp(f)
lp = new_lp

count()
lp.print_stats()

But somehow the new stats are empty, possibly because the function count() can't be wrapped twice?

Body:
I came up with the following solution based of a new profiler class. Every time a profiling is started, it creates a new instance of LineProfiler. The key is to store wrapped functions next to the originals, so that they can be reset when stopping the profiler.

from typing import Optional
from line_profiler import LineProfiler
from functools import wraps

class MyLineProfiler:

    def __init__(self):
        self.functions: list[list] = []
        self.line_profiler: Optional[LineProfiler] = None

    def __call__(self, func):
        index = len(self.functions)

        @wraps(func)
        def wrap(*args, **kw):
            return self.functions[index][1](*args, **kw)

        self.functions.append([func, func])
        return wrap

    def start(self):
        self.line_profiler = LineProfiler()
        for f in self.functions:
            f[1] = self.line_profiler(f[0])

    def stop(self, *, print: bool = True):
        for f in self.functions:
            f[1] = f[0]
        if self.line_profiler and print:
            self.line_profiler.print_stats()

    def reset(self):
        self.stop(print=False)
        self.start()

The wrapped functions call whatever is currently stored at functions[index][1], either the original func (when no profiling is stopped) or the decorated one (when start() was called).

It can be used as follows:

profile = MyLineProfiler()

@profile
def count():
    return sum(range(1_000_000))

count()

profile.start()
count()
count()
profile.stop()

profile.start()
count()
profile.stop()


问:
How to find longest subsequence based on conditions in Impala SQL
I have a SQL table on Impala that contains ID, dt (monthly basis with no skipped month), and status of each person ID. I want to check how long that each ID is in each status (my expected answer is shown on expected column)

I tried to solve this problem on the value column by using

```<code>count(status) over (partition by ID, status order by dt)
</code>```

but it doesn't reset the value when the status is changed.

```<code>+------+------------+--------+-------+----------+
|  ID  |     dt     | status | value | expected |
+------+------------+--------+-------+----------+
| 0001 | 01/01/2020 |      0 |     1 |        1 |
| 0001 | 01/02/2020 |      0 |     2 |        2 |
| 0001 | 01/03/2020 |      1 |     1 |        1 |
| 0001 | 01/04/2020 |      1 |     2 |        2 |
| 0001 | 01/05/2020 |      1 |     3 |        3 |
| 0001 | 01/06/2020 |      0 |     3 |        1 |
| 0001 | 01/07/2020 |      1 |     4 |        1 |
| 0001 | 01/08/2020 |      1 |     5 |        2 |
+------+------------+--------+-------+----------+
</code>```

Is there anyway to reset the counter when the status is changed?

答:
When you partition by ID and status, two groups are formed for the values 0 and 1 in status field. So, the months 1, 2, 6 go into first group with 0 status and the months 3, 4, 5, 7, 8 go into the second group with 1 status. Then, the count function counts the number of statuses individually in those groups. Thus the first group has counts from 1 to 3 and the second group has counts from 1 to 5. This query so far doesn't account for the change in statuses rather just simply divide the record set as per different status values.

One approach would be to divide the records into different blocks where each status change starts a new block. The below query follows this approach and gives the expected result:

```<code>SELECT ID,dt,status,
    COUNT(status) OVER(PARTITION BY ID,block_number ORDER BY dt) as value
FROM (
    SELECT ID,dt,status,
        SUM(change_in_status) OVER(PARTITION BY ID ORDER BY dt) as block_number
    FROM(
        SELECT ID,dt,status,
            CASE WHEN
                    status<>LAG(status) OVER(PARTITION BY ID ORDER BY dt)
                    OR LAG(status) OVER(PARTITION BY ID ORDER BY dt) IS NULL
                THEN 1
                ELSE 0
            END as change_in_status
        FROM statuses
    ) derive_status_changes
) derive_blocks;
</code>```

Here is a working example in DB Fiddle.

Body:
I have a SQL table on Impala that contains ID, dt (monthly basis with no skipped month), and status of each person ID. I want to check how long that each ID is in each status (my expected answer is shown on expected column)

I tried to solve this problem on the value column by using

count(status) over (partition by ID, status order by dt)

but it doesn't reset the value when the status is changed.

+------+------------+--------+-------+----------+
|  ID  |     dt     | status | value | expected |
+------+------------+--------+-------+----------+
| 0001 | 01/01/2020 |      0 |     1 |        1 |
| 0001 | 01/02/2020 |      0 |     2 |        2 |
| 0001 | 01/03/2020 |      1 |     1 |        1 |
| 0001 | 01/04/2020 |      1 |     2 |        2 |
| 0001 | 01/05/2020 |      1 |     3 |        3 |
| 0001 | 01/06/2020 |      0 |     3 |        1 |
| 0001 | 01/07/2020 |      1 |     4 |        1 |
| 0001 | 01/08/2020 |      1 |     5 |        2 |
+------+------------+--------+-------+----------+

Is there anyway to reset the counter when the status is changed?

Body:
When you partition by ID and status, two groups are formed for the values 0 and 1 in status field. So, the months 1, 2, 6 go into first group with 0 status and the months 3, 4, 5, 7, 8 go into the second group with 1 status. Then, the count function counts the number of statuses individually in those groups. Thus the first group has counts from 1 to 3 and the second group has counts from 1 to 5. This query so far doesn't account for the change in statuses rather just simply divide the record set as per different status values.

One approach would be to divide the records into different blocks where each status change starts a new block. The below query follows this approach and gives the expected result:

SELECT ID,dt,status,
    COUNT(status) OVER(PARTITION BY ID,block_number ORDER BY dt) as value
FROM (
    SELECT ID,dt,status,
        SUM(change_in_status) OVER(PARTITION BY ID ORDER BY dt) as block_number
    FROM(
        SELECT ID,dt,status,
            CASE WHEN
                    status<>LAG(status) OVER(PARTITION BY ID ORDER BY dt)
                    OR LAG(status) OVER(PARTITION BY ID ORDER BY dt) IS NULL
                THEN 1
                ELSE 0
            END as change_in_status
        FROM statuses
    ) derive_status_changes
) derive_blocks;

Here is a working example in DB Fiddle.


问:
Two way data binding in angular 12 reactive forms
I've been using angular for a while. I want to implement two way binding but I'm stuck with the following code.

Since [(ngModel)] is no no longer used in angular 12 within the formGroup I'm unable to find a solution

```<code>socials = [
{ name: 'Facebook', icon: 'facebook.webp', selected: false, link:'' },
{ name: 'Instagram', icon: 'instagram.webp', selected: false, link:'' },
{ name: 'Twitter', icon: 'linkdin.webp', selected: false, link:'' },
{ name: 'Whatsapp', icon: 'whatsapp.webp', selected: false, link:'' }
</code>```

];

here I want to change the value of link that will be entered in the following input (6th last line)

```<code><div class="row">
        <div class="col-6 col-lg-3 my-2" *ngFor="let control of socialsArray.controls; let i = index;">
          <input class="form-check-input" type="checkbox" (change)="getSelectedSocialsCards()" [formControl]="control" id="checkbox{{i}}">
          <label for="checkbox{{i}}" class="w-100">
            <div class="card cursorIn" [ngStyle] = "{'background-color' : socials[i].selected == true ? '#ededed' : '#fff'}">
              <div class="d-flex justify-content-end pt-2 pr-2 h-25">
                <fa-icon [icon]="faCheckCircle" [ngClass]="socials[i].selected === true ? 'iconColor' : 'iconColor1'"></fa-icon>
              </div>
              <div class="card-body d-flex p-0 px-4 mt-0">
                <div class="col-3 align-self-center font-weight-bold text-center cardIcon p-0">
                  <img src="/assets/images/social_media/{{socials[i].icon}}" width="40px" height="40px"
                    class="rounded-circle">
                </div>
                <div class="col-9 d-flex flex-column justify-content-start align-items-start cardRight">
                  <div>
                    {{socials[i].name}}
                  </div>
                </div>
              </div>
            </div>
            <div class="col-12 mt-2" [ngStyle] = "{'display' : socials[i].selected == true ? 'block' : 'none' }">
              <div class="form-group">
                <label>
                  {{socials[i].name}} link
                </label>
                <input type="text" class="form-control" (change)="getSelectedSocialsCards()" formControlName="socialLink">
              </div>
            </div>
          </label>
        </div>
      </div>
</code>```

I've declared socialLink inside formGroup

```<code>socialLink:new FormControl(null, [Validators.required])
</code>```

this is my component.ts code for the same

```<code>getSelectedSocialsCards() {
this.selectedSocialsCards = [];
this.socialsArray.controls.forEach((control, i) => {
  this.socials[i].selected = false;
  if (control.value) {
    this.socials[i].selected = true;
    this.socials[i].link = this.addForm.get('socialLink').value;
   let linksValue = {'socialName': this.socials[i].name, 'socialLink': this.socials[i].link}
    this.selectedSocialsCards.push(linksValue);
  }
});
console.log(this.selectedSocialsCards);
this.socialError =  this.selectedSocialsCards.length > 0 ? false : true;
this.addForm.patchValue({socialsCheck: this.selectedSocialsCards});
</code>```

}

So far I'm able to get the last value inserted intot he input field and that is the value of all the links.

I've tried to resolve the issue but couldn't find any solution. I'll be obliged if anyone can help me with this.
Thank you

答:
You can use [(ngModel)] in within the formGroup mention 'name' in tag.
for example <input class="form-check-input" type="checkbox" (change)="getSelectedSocialsCards()" [formControl]="control" [(ngModel)]="testcontrol" name="testcontrol" id="checkbox{{i}}"> like that</p>

Body:
I've been using angular for a while. I want to implement two way binding but I'm stuck with the following code.

Since [(ngModel)] is no no longer used in angular 12 within the formGroup I'm unable to find a solution

socials = [
{ name: 'Facebook', icon: 'facebook.webp', selected: false, link:'' },
{ name: 'Instagram', icon: 'instagram.webp', selected: false, link:'' },
{ name: 'Twitter', icon: 'linkdin.webp', selected: false, link:'' },
{ name: 'Whatsapp', icon: 'whatsapp.webp', selected: false, link:'' }

];

here I want to change the value of link that will be entered in the following input (6th last line)

          <input class="form-check-input" type="checkbox" (change)="getSelectedSocialsCards()" [formControl]="control" id="checkbox{{i}}">

                <fa-icon [icon]="faCheckCircle" [ngClass]="socials[i].selected === true ? 'iconColor' : 'iconColor1'"></fa-icon>

                    {{socials[i].name}}

                  {{socials[i].name}} link

                <input type="text" class="form-control" (change)="getSelectedSocialsCards()" formControlName="socialLink">

I've declared socialLink inside formGroup

socialLink:new FormControl(null, [Validators.required])

this is my component.ts code for the same

getSelectedSocialsCards() {
this.selectedSocialsCards = [];
this.socialsArray.controls.forEach((control, i) => {
  this.socials[i].selected = false;
  if (control.value) {
    this.socials[i].selected = true;
    this.socials[i].link = this.addForm.get('socialLink').value;
   let linksValue = {'socialName': this.socials[i].name, 'socialLink': this.socials[i].link}
    this.selectedSocialsCards.push(linksValue);
  }
});
console.log(this.selectedSocialsCards);
this.socialError =  this.selectedSocialsCards.length > 0 ? false : true;
this.addForm.patchValue({socialsCheck: this.selectedSocialsCards});

}

So far I'm able to get the last value inserted intot he input field and that is the value of all the links.

I've tried to resolve the issue but couldn't find any solution. I'll be obliged if anyone can help me with this.
Thank you


问:
If I use a class more than once in an application, will it be compiled just once into the exe?
I'm evaluating the many possibilities for a trial protection system and came up with the following question:

If I use my "trial check" class more than once (scattered several times over the application), will it be compiled just once into the exe?

The reason why I'm asking is that if it's only compiled once into the exe, then patching this single class will invalidate all places where it is used.

If it's compiled just once, are there any viable alternatives to prevent this?

Thanks!

EDIT: I'm actually not trying to roll my own protection system, I'm looking at several existing solutions like OnGuard, mxProtector and TRegWare. It was while looking at the various solutions source-code, that I came up with this question.

答:
If you use the inline keyword for functions and methods where possible, the executable code will be "multi-plicated".  There are some limitations to the use of inlining, though (see the linked doc). </p>

<p>I agree with Ain and Marco that spending effort on protection schemes may be more bother than benefit, and that it makes more sense to use existing solutions than to roll your own.  </p>

Body:
If you use the inline keyword for functions and methods where possible, the executable code will be "multi-plicated".  There are some limitations to the use of inlining, though (see the linked doc).

I agree with Ain and Marco that spending effort on protection schemes may be more bother than benefit, and that it makes more sense to use existing solutions than to roll your own.


问:
how to get file download in swagger UI?
I need to generate a link in swagger in result which will download the file, but none of the solutions privded seem to work for me
see my code -

'''

```<code>[HttpGet]
/// <response code="200">success</response>
[SwaggerResponse((int)HttpStatusCode.OK, "Download a file.", typeof(FileContentResult))]
[Route("api/Controller/DownloadFile")]
public ActionResult DownloadFile(string fileName)
        {
            try
            {
                var bytes = System.IO.File.ReadAllBytesAsync("\\\\test-dm.com\\testfile\\" + fileName);
                return PhysicalFile("application/pdf", Path.GetFileName("\\\\test-dm.com\\testfile\\" + fileName));
            }
            catch (Exception ex)
            {
                var bytes = new byte[0];
                return File("text/plain", "test.pdf"); ;
            }
        }
</code>```

'''

See my startup -

```<code>services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "M2PPortal", Version = "v1" });

            });
</code>```

[enter image description here][1]

see image
[1]: https://i.stack.imgur.com/VwcG1.jpg

i have seen only where other have download file link is coming, how should i configure for it.

This is my first question here, let me know if there are any issues in my query or any other info is required.

答:
See result image, which was as expectedUsing below code gave the expected result, basically a link to the file -

```<code> [HttpGet]
        /// <response code="200">success</response>
        [SwaggerResponse((int)HttpStatusCode.OK, "Download a file.", typeof(FileContentResult))]
        [Route("api/Controller/DownloadFile")]
        public FileContentResult DownloadFile(string fileName)
        {
            try
            {
                return File(System.IO.File.ReadAllBytes(_configuration.GetValue<string>("FilePath:PathofFiles") + fileName), "application/pdf", fileName);
            }
            catch (Exception ex)
            {
               // write a generic return value which could be used to handle error
            }
        }
</code>```

using FileContentResult instead of action or ActionResult  or HttpResponseMessage.
No changes where required in Configureservices or configure

Title: how to get file download in swagger UI?

Body:
I need to generate a link in swagger in result which will download the file, but none of the solutions privded seem to work for me
see my code -

'''

[HttpGet]
/// <response code="200">success</response>
[SwaggerResponse((int)HttpStatusCode.OK, "Download a file.", typeof(FileContentResult))]
[Route("api/Controller/DownloadFile")]
public ActionResult DownloadFile(string fileName)
        {
            try
            {
                var bytes = System.IO.File.ReadAllBytesAsync("\\\\test-dm.com\\testfile\\" + fileName);
                return PhysicalFile("application/pdf", Path.GetFileName("\\\\test-dm.com\\testfile\\" + fileName));
            }
            catch (Exception ex)
            {
                var bytes = new byte[0];
                return File("text/plain", "test.pdf"); ;
            }
        }

'''

See my startup -

services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "M2PPortal", Version = "v1" });

            });

[enter image description here][1]

see image
[1]: https://i.stack.imgur.com/VwcG1.jpg

i have seen only where other have download file link is coming, how should i configure for it.

This is my first question here, let me know if there are any issues in my query or any other info is required.

Body:
See result image, which was as expectedUsing below code gave the expected result, basically a link to the file -

 [HttpGet]
        /// <response code="200">success</response>
        [SwaggerResponse((int)HttpStatusCode.OK, "Download a file.", typeof(FileContentResult))]
        [Route("api/Controller/DownloadFile")]
        public FileContentResult DownloadFile(string fileName)
        {
            try
            {
                return File(System.IO.File.ReadAllBytes(_configuration.GetValue<string>("FilePath:PathofFiles") + fileName), "application/pdf", fileName);
            }
            catch (Exception ex)
            {
               // write a generic return value which could be used to handle error
            }
        }

using FileContentResult instead of action or ActionResult  or HttpResponseMessage.
No changes where required in Configureservices or configure


问:
python method as argument
So I know in python everything is an 'object' meaning that it can be passed as an argument to a method. But I'm trying to understand how exactly does this work. So I was trying out the following example:

```<code>class A:

    def __init__(self):
        self.value = 'a'

    def my_method(self)
        print self.value

class B:

   def __init__(self):
       self.values = 'b'

   def my_method(self, method):
       method()

a = A()
b = B()
b.my_method(a.my_method)
</code>```

Now first this was written just to see how things work. I know I should for example check if my_method 's argument is callable. Now my question is:

How exactly is the method passed here? I mean the output I'm recieving is 'a' so I'm guessing that when a object method is passed as parameter so is the actual object ? In this case when I pass a.my_method the instance a is also passed ?

答:
Functions are 'first-class objects' in Python. What that means is that a function is an object as much as a list or an integer. When you define a function, you are actually binding the function object to the name you use in the def.

Functions can be bound to other names or passed as parameters to functions (or stored in lists, or...).

source: http://mail.python.org/pipermail/tutor/2005-October/042616.html

Title: python method as argument

Body:
So I know in python everything is an 'object' meaning that it can be passed as an argument to a method. But I'm trying to understand how exactly does this work. So I was trying out the following example:

class A:

    def __init__(self):
        self.value = 'a'

    def my_method(self)
        print self.value

class B:

   def __init__(self):
       self.values = 'b'

   def my_method(self, method):
       method()

a = A()
b = B()
b.my_method(a.my_method)

Now first this was written just to see how things work. I know I should for example check if my_method 's argument is callable. Now my question is:

How exactly is the method passed here? I mean the output I'm recieving is 'a' so I'm guessing that when a object method is passed as parameter so is the actual object ? In this case when I pass a.my_method the instance a is also passed ?