问:
how to condition same time product to insert and update in laravel
I am tring Order update.I need to update multi product in different row. when I update the product then it only updated created fields. i want to update current row and then new product insert in different row.

```<code>$product_id = $request->product_id;
$seller_id = Auth::user()->id;
$price = $request->product_price;

$quantity = $request->product_qty;
$payment_status = $request->payment_status;
$delivery_status = $request->delivery_status;
$shipping_type = "home_delivery";
$shipping_charge = $request->shipping_cost;

$user = Address::all()->where('user_id', $request->user_id)->first();
$cname= DB::table('users')->where('id', $user->user_id)->value('name');

$shipping_address = [

    'user_id'=>$request->user_id,
    'name'=> $request->name,
    'phone'=>$request->phone,
    'email'=>$user->email,
    'city'=>$user->city,
    'postal_code'=>$user->postal_code,
    'country'=>$user->country,
    'address'=>$request->address,

];

$order_id=$request->id;
$order =  Order::findOrFail($order_id)->update([

    'seller_id' => Auth::user()->id,
    'shipping_address' => json_encode($shipping_address),
    'payment_status' => $request->payment_status,
    'payment_type' =>  $request->payment_option,
    'payment_details' => $request->payment_option,
    'coupon_discount' => $request->coupon_discount,
    'round_amount' => $request->round_discount,
    'grand_total' => $request->grand_total,
]);

for($i = 0; $i <= count($request->product_id)-1; $i++){

    $data = [
        'order_id' => $order_id,
        'product_id' => $product_id[$i],
        'seller_id' => $seller_id,
        'price' => $price[$i],
        'quantity' => $quantity[$i],
        'payment_status' => $payment_status,
        'delivery_status' => $delivery_status,
        'shipping_type' => $shipping_type,
        'shipping_cost' => $shipping_charge,
    ];

    if(!empty(OrderDetail::where('order_id', $order_id))){
        OrderDetail::where('order_id', $order_id)->update($data);
    }
    else{
        Orderdetail::insert($data);
    }

    $product_stock_info = ProductStock::where('product_id', $product_id[$i])->first();
    // dd($product_id[$i]);
    $stock = $product_stock_info->qty;
    $updateStock = $stock - $quantity[$i];
    $product_stock_info->qty = $updateStock;
    $product_stock_info->save();
}
</code>```

my problem is here

```<code>if(!empty(OrderDetail::where('order_id', $order_id))){
  OrderDetail::where('order_id', $order_id)->update($data);
} else {
  Orderdetail::insert($data);
}
</code>```

答:
You can use updateOrCreate method .

the updateOrCreate method persists the model, so there's no need to manually call the save method

```<code>$flight = Flight::updateOrCreate(
        ['departure' => 'Oakland', 'destination' => 'San Diego'],
        ['price' => 99, 'discounted' => 1]
    );
</code>```

as like

```<code>$whereData = [
              'order_id' => $order_id
             ];
OrderDetail::updateOrCreate($whereData ,$data);
</code>```

Body:
I am tring Order update.I need to update multi product in different row. when I update the product then it only updated created fields. i want to update current row and then new product insert in different row.

$product_id = $request->product_id;
$seller_id = Auth::user()->id;
$price = $request->product_price;

$quantity = $request->product_qty;
$payment_status = $request->payment_status;
$delivery_status = $request->delivery_status;
$shipping_type = "home_delivery";
$shipping_charge = $request->shipping_cost;

$user = Address::all()->where('user_id', $request->user_id)->first();
$cname= DB::table('users')->where('id', $user->user_id)->value('name');

$shipping_address = [

    'user_id'=>$request->user_id,
    'name'=> $request->name,
    'phone'=>$request->phone,
    'email'=>$user->email,
    'city'=>$user->city,
    'postal_code'=>$user->postal_code,
    'country'=>$user->country,
    'address'=>$request->address,

];

$order_id=$request->id;
$order =  Order::findOrFail($order_id)->update([

    'seller_id' => Auth::user()->id,
    'shipping_address' => json_encode($shipping_address),
    'payment_status' => $request->payment_status,
    'payment_type' =>  $request->payment_option,
    'payment_details' => $request->payment_option,
    'coupon_discount' => $request->coupon_discount,
    'round_amount' => $request->round_discount,
    'grand_total' => $request->grand_total,
]);

for($i = 0; $i <= count($request->product_id)-1; $i++){

    $data = [
        'order_id' => $order_id,
        'product_id' => $product_id[$i],
        'seller_id' => $seller_id,
        'price' => $price[$i],
        'quantity' => $quantity[$i],
        'payment_status' => $payment_status,
        'delivery_status' => $delivery_status,
        'shipping_type' => $shipping_type,
        'shipping_cost' => $shipping_charge,
    ];

    if(!empty(OrderDetail::where('order_id', $order_id))){
        OrderDetail::where('order_id', $order_id)->update($data);
    }
    else{
        Orderdetail::insert($data);
    }

    $product_stock_info = ProductStock::where('product_id', $product_id[$i])->first();
    // dd($product_id[$i]);
    $stock = $product_stock_info->qty;
    $updateStock = $stock - $quantity[$i];
    $product_stock_info->qty = $updateStock;
    $product_stock_info->save();
}

my problem is here

if(!empty(OrderDetail::where('order_id', $order_id))){
  OrderDetail::where('order_id', $order_id)->update($data);
} else {
  Orderdetail::insert($data);
}

Body:
You can use updateOrCreate method .

the updateOrCreate method persists the model, so there's no need to manually call the save method

$flight = Flight::updateOrCreate(
        ['departure' => 'Oakland', 'destination' => 'San Diego'],
        ['price' => 99, 'discounted' => 1]
    );

as like

$whereData = [
              'order_id' => $order_id
             ];
OrderDetail::updateOrCreate($whereData ,$data);


来源: stackexchange

问:
How to work with child and dynamic routes?
Using Nuxt2, I'm building a structure that I need dynamic routes.

This makes it necessary for navigation with more information.

Route: /lab/1/lad/2

Inside the route(page) lab I have two files, index.vue and a _id.vue

Inside the side learning to do the same, but including only the _id.vue

```<code>pages
--| lab/
-----| index.vue
-----| _id.vue
-----| lad/
--------| _id.vue
</code>```

Page not found.

Could anyone help with this question?

Much obliged.

答:
In Nuxt2, try to make the _id as directory and add its own index.vue :

```<code>pages
--| lab/
-----| index.vue
-----| _id/
--------| index.vue
--------| lad/
-----------| _id.vue
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Using Nuxt2, I'm building a structure that I need dynamic routes.

This makes it necessary for navigation with more information.

Route: /lab/1/lad/2

Inside the route(page) lab I have two files, index.vue and a _id.vue

Inside the side learning to do the same, but including only the _id.vue

pages
--| lab/
-----| index.vue
-----| _id.vue
-----| lad/
--------| _id.vue

Page not found.

Could anyone help with this question?

Much obliged.

Body:
In Nuxt2, try to make the _id as directory and add its own index.vue :

pages
--| lab/
-----| index.vue
-----| _id/
--------| index.vue
--------| lad/
-----------| _id.vue


问:
How to get pressed char from System.Windows.Input.KeyEventArgs?
I have System.Windows.Input.KeyEventArgs e variable. I want to get real char. For example, i press } button on keyboard. And normally it returns string like  oem.. but i want to get } char. How to do ?

[EDIT] I use this in TextBox .

答:
See this post... how to capture the '#' character on different locale keyboards in WPF/C#?

it has a utility function called GetCharFromKey(Key key) which gets locale specific character from the Key of the Keyboard event args.

Very useful.

ContentLicense: CC BY-SA 3.0


问:
The difference between readr::read_csv() and read_csv()
I saw some people use readr::read_csv() command instead of read_csv().
What is the difference between readr::read_csv and read_csv?

Thanks!

答:
There are two reasons why you would want to use the <package>::<function> command instead of <function>:

you don't want to upload the whole package, but you want to have access to a single function

the function name of one package is the same as the function name of another package; to distinguish them, declare the package to which it belongs with <package>::.

For example both dplyr and stats contain filter function. If you load dplyr after stats you will have dplyr::filter() masks stats::filter(), so to distinguish them we use dplyr::filter() or stats::filter().


问:
Run while loop in background and execute the entire script - Bash
I am trying to run a condition at specific interval in while loop but the issue is that it is only executing the test function, I am trying that the test function keep on getting executed at specific interval and the script should move to the next function as well keeping test function running in the background. Any help would be appreciated</p>
```<code>test(){
     while true;
     do
          echo "Hello"
          sleep 5
     done
}

function2(){
     echo "I am inside function2"
}
test
function2
</code>```

答:
You can tell bash to run a command in a separate subshell, asynchronously, with a single trailing ampersand &. So you can make test run separately like this:

test(){
     while true;
     do
          echo "Hello"
          sleep 5
     done
}

function2(){
     echo "I am inside function2"
}
test &
function2
```
<p>However, this will cause the script to terminate before <code>test</code> is finished running! You can make the program wait for <code>test &</code> to finish at a later point in the program by using <code>wait</code>:</p>
<pre class="lang-sh prettyprint-override"><code>test(){
     while true;
     do
          echo "Hello"
          sleep 5
     done
}

function2(){
     echo "I am inside function2"
}
test & p1=$!

function2

wait $p1
</code>```

Body:
I am trying to run a condition at specific interval in while loop but the issue is that it is only executing the test function, I am trying that the test function keep on getting executed at specific interval and the script should move to the next function as well keeping test function running in the background. Any help would be appreciated

test(){
     while true;
     do
          echo "Hello"
          sleep 5
     done
}

function2(){
     echo "I am inside function2"
}
test
function2

Body:
You can tell bash to run a command in a separate subshell, asynchronously, with a single trailing ampersand &. So you can make test run separately like this:

test(){
     while true;
     do
          echo "Hello"
          sleep 5
     done
}

function2(){
     echo "I am inside function2"
}
test &
function2

However, this will cause the script to terminate before test is finished running! You can make the program wait for test & to finish at a later point in the program by using wait:

test(){
     while true;
     do
          echo "Hello"
          sleep 5
     done
}

function2(){
     echo "I am inside function2"
}
test & p1=$!

function2

wait $p1


问:
GetX Flutter v4.6.1 some issues
In my project I used GetX v4.6.1. When it Build on debug mode, I faced this bugs

```<code>/C:/Users/ALIF/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_material_app.dart:275:17: Error: No named parameter with the name 'useInheritedMediaQuery'.
                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
/C:/src/flutter/packages/flutter/lib/src/material/app.dart:217:9: Context: Found this candidate, but the arguments don't match.
  const MaterialApp.router({
/C:/Users/ALIF/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_material_app.dart:322:17: Error: No named parameter with the name 'useInheritedMediaQuery'.                                                                                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
/C:/src/flutter/packages/flutter/lib/src/material/app.dart:166:9: Context: Found this candidate, but the arguments don't match.
  const MaterialApp({
        ^^^^^^^^^^^
/C:/Users/ALIF/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_cupertino_app.dart:252:17: Error: No named parameter with the name 'useInheritedMediaQuery'.                                                                                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
/C:/src/flutter/packages/flutter/lib/src/cupertino/app.dart:189:9: Context: Found this candidate, but the arguments don't match.
  const CupertinoApp.router({
        ^^^^^^^^^^^^^^^^^^^
/C:/Users/ALIF/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_cupertino_app.dart:292:17: Error: No named parameter with the name 'useInheritedMediaQuery'.
                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
/C:/src/flutter/packages/flutter/lib/src/cupertino/app.dart:145:9: Context: Found this candidate, but the arguments don't match.
  const CupertinoApp({
        ^^^^^^^^^^^^

FAILURE: Build failed with an exception.

* Where:
Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1035

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 23s
Running Gradle task 'assembleDebug'...
Running Gradle task 'assembleDebug'... Done                        87.9s
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

I'm also already followed this references but still not resolve the issues. First time I faced this issues is when at MyApp widget (root) on my project would change from MaterialApp to be GetMaterialApp, only.

答:
I hv same issue. I solved by reducing GetX version into :

```<code>#In pubspec.yaml use get package like below :

get: 4.5.1
</code>```

This doesn't work for me:

```<code>#In pubspec.yaml use get package like below :

get: 4.6.1
</code>```

Title: GetX Flutter v4.6.1 some issues

Body:
In my project I used GetX v4.6.1. When it Build on debug mode, I faced this bugs

/C:/Users/ALIF/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_material_app.dart:275:17: Error: No named parameter with the name 'useInheritedMediaQuery'.
                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
/C:/src/flutter/packages/flutter/lib/src/material/app.dart:217:9: Context: Found this candidate, but the arguments don't match.
  const MaterialApp.router({
/C:/Users/ALIF/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_material_app.dart:322:17: Error: No named parameter with the name 'useInheritedMediaQuery'.                                                                                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
/C:/src/flutter/packages/flutter/lib/src/material/app.dart:166:9: Context: Found this candidate, but the arguments don't match.
  const MaterialApp({
        ^^^^^^^^^^^
/C:/Users/ALIF/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_cupertino_app.dart:252:17: Error: No named parameter with the name 'useInheritedMediaQuery'.                                                                                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
/C:/src/flutter/packages/flutter/lib/src/cupertino/app.dart:189:9: Context: Found this candidate, but the arguments don't match.
  const CupertinoApp.router({
        ^^^^^^^^^^^^^^^^^^^
/C:/Users/ALIF/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_cupertino_app.dart:292:17: Error: No named parameter with the name 'useInheritedMediaQuery'.
                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
/C:/src/flutter/packages/flutter/lib/src/cupertino/app.dart:145:9: Context: Found this candidate, but the arguments don't match.
  const CupertinoApp({
        ^^^^^^^^^^^^

FAILURE: Build failed with an exception.

* Where:
Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1035

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 23s
Running Gradle task 'assembleDebug'...
Running Gradle task 'assembleDebug'... Done                        87.9s
Exception: Gradle task assembleDebug failed with exit code 1

I'm also already followed this references but still not resolve the issues. First time I faced this issues is when at MyApp widget (root) on my project would change from MaterialApp to be GetMaterialApp, only.

Body:
I hv same issue. I solved by reducing GetX version into :

#In pubspec.yaml use get package like below :

get: 4.5.1

This doesn't work for me:

#In pubspec.yaml use get package like below :

get: 4.6.1


问:
How to aggregate two rows with the same value in another column?
I have a dataframe like this:

name
cluster

'sock'
1

'graceful'
2

'disgrace'
2

'fixture'
3

'winnow'
4

'window'
4

and a function common_substring that takes in two strings and returns the longest common substring.

I want to return

name
cluster

'sock'
1

'grace'
2

'fixture'
3

'win'
4

I know I'm supposed to group by cluster, but I'm struggling with how to aggregate and apply a function that takes two values.

答:
Use GroupBy.agg with aggregate function for pass function if length of group is not 1, then pass all values in column in list:

```<code>#https://stackoverflow.com/questions/40556491
from functools import partial, reduce
from itertools import chain
from typing import Iterator

def ngram(seq: str, n: int) -> Iterator[str]:
    return (seq[i: i+n] for i in range(0, len(seq)-n+1))

def allngram(seq: str) -> set:
    lengths = range(len(seq)+1)
    ngrams = map(partial(ngram, seq), lengths)
    return set(chain.from_iterable(ngrams))

def func(x):
    seqs_ngrams = map(allngram, x.tolist())
    intersection = reduce(set.intersection, seqs_ngrams)
    longest = max(intersection, key=len)
    return longest

df['name'] = df['name'].str.strip("'")

df = df.groupby('cluster')['name'].agg(func).reset_index()
print (df)
   cluster     name
0        1     sock
1        2    grace
2        3  fixture
3        4      win
</code>```

Body:
Use GroupBy.agg with aggregate function for pass function if length of group is not 1, then pass all values in column in list:

#https://stackoverflow.com/questions/40556491
from functools import partial, reduce
from itertools import chain
from typing import Iterator

def ngram(seq: str, n: int) -> Iterator[str]:
    return (seq[i: i+n] for i in range(0, len(seq)-n+1))

def allngram(seq: str) -> set:
    lengths = range(len(seq)+1)
    ngrams = map(partial(ngram, seq), lengths)
    return set(chain.from_iterable(ngrams))

def func(x):
    seqs_ngrams = map(allngram, x.tolist())
    intersection = reduce(set.intersection, seqs_ngrams)
    longest = max(intersection, key=len)
    return longest

df['name'] = df['name'].str.strip("'")

df = df.groupby('cluster')['name'].agg(func).reset_index()
print (df)
   cluster     name
0        1     sock
1        2    grace
2        3  fixture
3        4      win


问:
JavaScript object related question that what will be the output of below code?

var x = 3;
var one = {
  x:2,
  two: {
    x:1,
    three:function(){
        return this.x;

    }
  }
}

var go = one.two.three;

 console.log(one.two.three() + "" + go());
 ```

Anyone can explain to me why output coming 13 why not 1-undefined?

答:
Interesting. I think it has something to do with scopes.

console.log(one.two.three() + "" + go());
//equals console.log(1 + "" + 3);
```
<p>will output <code>13</code> (String) because:</p>
<ul>
<li><code>one.two.three()</code> returns <code>1</code></li>
<li><code>go()</code> returns <code>3</code></li>
<li>those numbers are concatenated into String with <code>""</code> (empty string) in between (instead of <code>-</code> as you may have asked)</li>
</ul>
<hr />
<p><strong>Why <code>go()</code> returns <code>3</code></strong></p>
<pre class="lang-js prettyprint-override"><code>var x = 3;

// var go = one.two.three;
// equals
var go = function() {
  return this.x
}
</code>```

The declaration var go = one.two.three; assigns one.two's three method as a function into the variable go in the global scope. The same scope with go, one, and x (with the value 3), that was declared before declaring one and go (var x= 3;).

Based on your whole codes, this.x's this is in the global scope. and this.x is 3. So running go() returns 3.

one.two.three is a global function
→ notice there's no (), so assigning a function to global scope's variable go will make the function's scope global.
→ go function is run under global's scope

Why one.two.three() returns 1

Well, one.two.three is a method inside the object two, which is inside the object one. While the definition looks the same,

function() {
  return this.x;
}
```
<p>when you run <code>three</code> method of <code>two</code> object, <code>return this.x</code>'s <code>this</code> refers to the method's parent object (which is <code>two</code>, <code>three</code>'s parent object is <code>two</code>).
So,
<code>this.x</code> refers to
<code>two.x</code> which is <code>1</code>.</p>
<p>Hence, in this case <code>return this.x;</code> outputs <code>1</code>.</p>
<p><code>one.two.three()</code> is <code>1</code>
→ notice the <code>()</code> which means <code>run the function</code>
→ <code>three</code> method is run under <code>two</code>'s scope</p>
<hr />
<p><strong>Addition</strong></p>
<p>This will output <code>1-undefined</code> because:</p>
<ul>
<li><code>y</code> is not defined in the global/<code>one</code>/<code>go</code> scope</li>
<li>I use <code>-</code> as a delimiter in <code>console.log</code></li>
</ul>
<pre class="lang-js prettyprint-override"><code>var one = {
  y:2,
  two: {
    y: 1,
    three:function(){
        return this.y;

    }
  }
}

var go = one.two.three;

console.log(one.two.three() + "-" + go());
</code>```

Body:
var x = 3;
var one = {
  x:2,
  two: {
    x:1,
    three:function(){
        return this.x;

    }
  }
}

var go = one.two.three;

 console.log(one.two.three() + "" + go());

Anyone can explain to me why output coming 13 why not 1-undefined?

Body:
Interesting. I think it has something to do with scopes.

console.log(one.two.three() + "" + go());
//equals console.log(1 + "" + 3);

will output 13 (String) because:

one.two.three() returns 1

go() returns 3

those numbers are concatenated into String with "" (empty string) in between (instead of - as you may have asked)

Why go() returns 3

var x = 3;

// var go = one.two.three;
// equals
var go = function() {
  return this.x
}

The declaration var go = one.two.three; assigns one.two's three method as a function into the variable go in the global scope. The same scope with go, one, and x (with the value 3), that was declared before declaring one and go (var x= 3;).

Based on your whole codes, this.x's this is in the global scope. and this.x is 3. So running go() returns 3.

one.two.three is a global function
→ notice there's no (), so assigning a function to global scope's variable go will make the function's scope global.
→ go function is run under global's scope

Why one.two.three() returns 1

Well, one.two.three is a method inside the object two, which is inside the object one. While the definition looks the same,

function() {
  return this.x;
}

when you run three method of two object, return this.x's this refers to the method's parent object (which is two, three's parent object is two).
So,
this.x refers to
two.x which is 1.

Hence, in this case return this.x; outputs 1.

one.two.three() is 1
→ notice the () which means run the function
→ three method is run under two's scope

Addition

This will output 1-undefined because:

y is not defined in the global/one/go scope

I use - as a delimiter in console.log

var one = {
  y:2,
  two: {
    y: 1,
    three:function(){
        return this.y;

    }
  }
}

var go = one.two.three;

console.log(one.two.three() + "-" + go());


问:
Kotlin exclude ktlint directories in maven
I am trying to remove generate-sources directory from giving klint errors, else adding a few scripts in exclude as an alternative

From here I figured we could do this in gradle
https://github.com/JLLeitschuh/ktlint-gradle/issues/97

This feature in gradle is shown as follows

```<code>ktlint {
    filter {
        exclude("**/generated/**")
        include("**/kotlin/**")
    }
}
</code>```

So far I have tried doing this in Maven, but it still does linting on some unavoidable generated sources.
https://github.com/gantsign/ktlint-maven-plugin/issues/341

```<code><sourcesExcludes>
   <sourcesExcludes>directoryToExclude<sourcesExclude>
</sourcesExcludes>
</code>```

Using above in maven plugin

```<code><plugin>
  <groupId>com.github.gantsign.maven</groupId>
  <artifactId>ktlint-maven-plugin</artifactId>
  <version>1.7.0</version>
  <executions>
    <execution>
      <configuration>
          <sourcesExcludes>
              <sourcesExclude>**/generated-sources/graphql/com/expediagroup/dataquality/api/utils/**</sourcesExclude>
          </sourcesExcludes>
      </configuration>
      <phase>prepare-package</phase>
      <goals>
        <goal>format</goal>
        <goal>check</goal>
      </goals>
    </execution>
  </executions>
</plugin>
</code>```

Any help on how I can exclude generated-sources directory is appreciated.

答:
I found the solution here
https://github.com/gantsign/ktlint-maven-plugin/issues/341

And we just have to use below to avoid target files.

```<code><configuration>
    <sourceRoots>${project.build.sourceDirectory}</sourceRoots>
</configuration>
</code>```

Body:
I am trying to remove generate-sources directory from giving klint errors, else adding a few scripts in exclude as an alternative

From here I figured we could do this in gradle
https://github.com/JLLeitschuh/ktlint-gradle/issues/97

This feature in gradle is shown as follows

ktlint {
    filter {
        exclude("**/generated/**")
        include("**/kotlin/**")
    }
}

So far I have tried doing this in Maven, but it still does linting on some unavoidable generated sources.
https://github.com/gantsign/ktlint-maven-plugin/issues/341

<sourcesExcludes>
   <sourcesExcludes>directoryToExclude<sourcesExclude>
</sourcesExcludes>

Using above in maven plugin

<plugin>
  <groupId>com.github.gantsign.maven</groupId>
  <artifactId>ktlint-maven-plugin</artifactId>
  <version>1.7.0</version>
  <executions>
    <execution>
      <configuration>
          <sourcesExcludes>
              <sourcesExclude>**/generated-sources/graphql/com/expediagroup/dataquality/api/utils/**</sourcesExclude>
          </sourcesExcludes>
      </configuration>
      <phase>prepare-package</phase>
      <goals>
        <goal>format</goal>
        <goal>check</goal>
      </goals>
    </execution>
  </executions>
</plugin>

Any help on how I can exclude generated-sources directory is appreciated.

Body:
I found the solution here
https://github.com/gantsign/ktlint-maven-plugin/issues/341

And we just have to use below to avoid target files.

<configuration>
    <sourceRoots>${project.build.sourceDirectory}</sourceRoots>
</configuration>


问:
Best way to map Text and Image while loading the data
I have a csv file which looks somewhat like in the photo.

I'm building a model that takes both image and its corresponding text (df['Content'] as input .

I wanted to know the best way to load this data in the following way:

Loading the images from df['Image_location'] into a tensor.

And preserving the order of the image to the corresponding text.

Preserving the corresponding label (df['Sentiment'])

Any ideas on how this can be done?

答:
You can try using the tf.data.Dataset API.

Create dummy data:

import numpy
from PIL import Image

for i in range(1, 3):
  imarray = numpy.random.rand(64,64,3) * 255
  im = Image.fromarray(imarray.astype('uint8')).convert('RGBA')
  im.save('result_image{}.png'.format(i))
```
<p>Process:</p>
```import tensorflow as tf
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(data= {'Location': ['some.txt', 'some-other.txt'],
                         'Content': ['This road was ok', 'This was wonderful'],
                         'Score': [0.0353, -0.341],
                         'Sentiment': ['Neutral', 'Positive'],
                         'Image_location': ['/content/result_image1.png', '/content/result_image2.png']})

features = df[['Content', 'Image_location']]
labels = df['Sentiment']

dataset = tf.data.Dataset.from_tensor_slices((features, labels))
def process_path(x):
  content, image_path = x[0], x[1]
  img = tf.io.read_file(image_path)
  img = tf.io.decode_png(img, channels=3)
  return content, img

dataset = dataset.map(lambda x, y: (process_path(x), y))

for x, y in dataset.take(1):
  content = x[0]
  image = x[1]
  print('Content -->', content)
  print('Sentiment -->', y)
  plt.imshow(image.numpy())
```
```Content --> tf.Tensor(b'This road was ok', shape=(), dtype=string)
Sentiment --> tf.Tensor(b'Neutral', shape=(), dtype=string)
```

Body:
You can try using the tf.data.Dataset API.

Create dummy data:

import numpy
from PIL import Image

for i in range(1, 3):
  imarray = numpy.random.rand(64,64,3) * 255
  im = Image.fromarray(imarray.astype('uint8')).convert('RGBA')
  im.save('result_image{}.png'.format(i))

Process:

import tensorflow as tf
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(data= {'Location': ['some.txt', 'some-other.txt'],
                         'Content': ['This road was ok', 'This was wonderful'],
                         'Score': [0.0353, -0.341],
                         'Sentiment': ['Neutral', 'Positive'],
                         'Image_location': ['/content/result_image1.png', '/content/result_image2.png']})

features = df[['Content', 'Image_location']]
labels = df['Sentiment']

dataset = tf.data.Dataset.from_tensor_slices((features, labels))
def process_path(x):
  content, image_path = x[0], x[1]
  img = tf.io.read_file(image_path)
  img = tf.io.decode_png(img, channels=3)
  return content, img

dataset = dataset.map(lambda x, y: (process_path(x), y))

for x, y in dataset.take(1):
  content = x[0]
  image = x[1]
  print('Content -->', content)
  print('Sentiment -->', y)
  plt.imshow(image.numpy())

Content --> tf.Tensor(b'This road was ok', shape=(), dtype=string)
Sentiment --> tf.Tensor(b'Neutral', shape=(), dtype=string)


问:
TypeScript + React: How do I type a `rest` props that collects the rest of the props into an object and later spread them to some element?

function Foo({
  children,
  ...rest
}: {
  children: React.ReactNode;
  /*rest: how do I type `rest`? */
}) {
  return (

      {children}

  );
}

export default function App() {
  return (

      <Foo style={{ background: "blue" }}>Hello CodeSandbox</Foo>

  );
}
```

Here is the demo: https://codesandbox.io/s/how-to-type-rest-huv2z?file=/src/App.tsx:50-412

Foo is used to override the props that span accepts. How do I type rest in Foo?

答:
You can use something like this as a type:</p>
```<code>{
  children: React.ReactNode;
  /*rest: how do I type `rest`? */
} & HTMLProps<HTMLSpanElement>
</code>```

Body:
function Foo({
  children,
  ...rest
}: {
  children: React.ReactNode;
  /*rest: how do I type `rest`? */
}) {
  return (

      {children}

  );
}

export default function App() {
  return (

      <Foo style={{ background: "blue" }}>Hello CodeSandbox</Foo>

  );
}

Here is the demo: https://codesandbox.io/s/how-to-type-rest-huv2z?file=/src/App.tsx:50-412

Foo is used to override the props that span accepts. How do I type rest in Foo?

Body:
You can use something like this as a type:

{
  children: React.ReactNode;
  /*rest: how do I type `rest`? */
} & HTMLProps<HTMLSpanElement>


问:
How to pass multiple array values of checkbox in PHP to another page?
I wanted to create a selection pages (by using checkboxes) where at the end it will show the result from the selection of all the checkboxes. There are about 5 different categories of checkboxes in my first page (only contains HTML) which is for emotions, time, movements, tools & personalization.

First page: index.php

```<code>    <div>
    <form action="process.php" method="post">
    <label>Select your emotions :</label>
    <input type="checkbox" name="emotions[]" value="Sadness"> Sadness
    <input type="checkbox" name="emotions[]" value="Anxiety"> Anxiety
    <input type="checkbox" name="emotions[]" value="Anger"> Anger
    <input type="checkbox" name="emotions[]" value="Disgust"> Disgust
    <input type="checkbox" name="emotions[]" value="Fear"> Fear
    <input type="checkbox" name="emotions[]" value="Surprised"> Surprised
    <br>
    <label>Select your time to commit :</label>
    <input type="checkbox" name="time[]" value="1"> Less than 1 minute
    <input type="checkbox" name="time[]" value="1-3"> 1-3 minutes
    <input type="checkbox" name="time[]" value="3-5"> 3-5 minutes
    <input type="checkbox" name="time[]" value="5-10"> 5-10 minutes
    <input type="checkbox" name="time[]" value="10-15"> 10-15 minutes
    <input type="checkbox" name="time[]" value="15-30"> 15-30 minutes
    <br>
    <label>Select how you want to move :</label>
    <input type="checkbox" name="movement[]" value="Lying Down"> Lying Down
    <input type="checkbox" name="movement[]" value="Sitting"> Sitting
    <input type="checkbox" name="movement[]" value="Standing"> Standing
    <input type="checkbox" name="movement[]" value="Stretching"> Stretching
    <input type="checkbox" name="movement[]" value="Walking"> Walking
    <input type="checkbox" name="movement[]" value="Work-out"> Work-out
    <br>
    <label>Tools around me :</label>
    <input type="checkbox" name="tools[]" value="Me"> Me
    <input type="checkbox" name="tools[]" value="Pen & Paper"> Pen & Paper
    <input type="checkbox" name="tools[]" value="Bottle"> Bottle
    <input type="checkbox" name="tools[]" value="Color Pencils"> Color Pencils
    <input type="checkbox" name="tools[]" value="Drinks"> Drinks
    <input type="checkbox" name="tools[]" value="Snacks"> Snacks
    <label>Personalization :</label>
    <input type="checkbox" name="personalization[]" value="Favorites"> Favorites
    <input type="checkbox" name="personalization[]" value="New"> New
    <input type="checkbox" name="personalization[]" value="Completed"> Completed
    <input type="checkbox" name="personalization[]" value="Islamic"> Islamic
</div>
<div>
    <button type="submit">Submit</button>
</div>
</code>```

2nd page: process.php

```<code><?php
$emotions = (isset($_POST['emotions'])) ? $_POST['emotions'] : array(); ?>
<p><strong>Emotions :</strong>
    <?php
    if (count($emotions) > 0) {
        foreach ($emotions as $emotions) {
            echo $emotions . ' ';
        }
    } else {
        echo "No emotions has been selected";
    }
    ?>
</p>

<?
$time = (isset($_POST['time'])) ? $_POST['time'] : array(); ?>
<p><strong>Time :</strong>
    <?php
    if (count($time) > 0) {
        foreach ($time as $time) {
            echo $time . ' ';
        }
    } else {
        echo "No time has been selected";
    }
    ?>
</p>
<?
$movement = (isset($_POST['movement'])) ? $_POST['movement'] : array(); ?>
<p><strong>Movement :</strong>
    <?php
    if (count($movement) > 0) {
        foreach ($movement as $movement) {
            echo $movement . ' ';
        }
    } else {
        echo "No movements has been selected";
    }
    ?>
</p>

<?
$tools = (isset($_POST['tools'])) ? $_POST['tools'] : array(); ?>
<p><strong>Tools :</strong>
    <?php
    if (count($tools) > 0) {
        foreach ($tools as $tools) {
            echo $tools . ' ';
        }
    } else {
        echo "No tools has been selected";
    }
    ?>
</p>

<?
$personalization = (isset($_POST['personalization'])) ? $_POST['personalization'] : array(); ?>
<p><strong>Personalization :</strong>
    <?php
    if (count($personalization) > 0) {
        foreach ($personalization as $personalization) {
            echo $personalization . ' ';
        }
    } else {
        echo "No personalization has been selected";
    }
    ?>
</p>
</code>```

答: Check if you have entered proper path in action attribute of form tag to reach the "process.php" file</p>

Body:
I wanted to create a selection pages (by using checkboxes) where at the end it will show the result from the selection of all the checkboxes. There are about 5 different categories of checkboxes in my first page (only contains HTML) which is for emotions, time, movements, tools & personalization.

First page: index.php

    <form action="process.php" method="post">
    Select your emotions :
    <input type="checkbox" name="emotions[]" value="Sadness"> Sadness
    <input type="checkbox" name="emotions[]" value="Anxiety"> Anxiety
    <input type="checkbox" name="emotions[]" value="Anger"> Anger
    <input type="checkbox" name="emotions[]" value="Disgust"> Disgust
    <input type="checkbox" name="emotions[]" value="Fear"> Fear
    <input type="checkbox" name="emotions[]" value="Surprised"> Surprised

    Select your time to commit :
    <input type="checkbox" name="time[]" value="1"> Less than 1 minute
    <input type="checkbox" name="time[]" value="1-3"> 1-3 minutes
    <input type="checkbox" name="time[]" value="3-5"> 3-5 minutes
    <input type="checkbox" name="time[]" value="5-10"> 5-10 minutes
    <input type="checkbox" name="time[]" value="10-15"> 10-15 minutes
    <input type="checkbox" name="time[]" value="15-30"> 15-30 minutes

    Select how you want to move :
    <input type="checkbox" name="movement[]" value="Lying Down"> Lying Down
    <input type="checkbox" name="movement[]" value="Sitting"> Sitting
    <input type="checkbox" name="movement[]" value="Standing"> Standing
    <input type="checkbox" name="movement[]" value="Stretching"> Stretching
    <input type="checkbox" name="movement[]" value="Walking"> Walking
    <input type="checkbox" name="movement[]" value="Work-out"> Work-out

    Tools around me :
    <input type="checkbox" name="tools[]" value="Me"> Me
    <input type="checkbox" name="tools[]" value="Pen & Paper"> Pen & Paper
    <input type="checkbox" name="tools[]" value="Bottle"> Bottle
    <input type="checkbox" name="tools[]" value="Color Pencils"> Color Pencils
    <input type="checkbox" name="tools[]" value="Drinks"> Drinks
    <input type="checkbox" name="tools[]" value="Snacks"> Snacks
    Personalization :
    <input type="checkbox" name="personalization[]" value="Favorites"> Favorites
    <input type="checkbox" name="personalization[]" value="New"> New
    <input type="checkbox" name="personalization[]" value="Completed"> Completed
    <input type="checkbox" name="personalization[]" value="Islamic"> Islamic

    <button type="submit">Submit</button>

2nd page: process.php

<?php
$emotions = (isset($_POST['emotions'])) ? $_POST['emotions'] : array(); ?>

Emotions :
    <?php
    if (count($emotions) > 0) {
        foreach ($emotions as $emotions) {
            echo $emotions . ' ';
        }
    } else {
        echo "No emotions has been selected";
    }
    ?>

<?
$time = (isset($_POST['time'])) ? $_POST['time'] : array(); ?>

Time :
    <?php
    if (count($time) > 0) {
        foreach ($time as $time) {
            echo $time . ' ';
        }
    } else {
        echo "No time has been selected";
    }
    ?>

<?
$movement = (isset($_POST['movement'])) ? $_POST['movement'] : array(); ?>

Movement :
    <?php
    if (count($movement) > 0) {
        foreach ($movement as $movement) {
            echo $movement . ' ';
        }
    } else {
        echo "No movements has been selected";
    }
    ?>

<?
$tools = (isset($_POST['tools'])) ? $_POST['tools'] : array(); ?>

Tools :
    <?php
    if (count($tools) > 0) {
        foreach ($tools as $tools) {
            echo $tools . ' ';
        }
    } else {
        echo "No tools has been selected";
    }
    ?>

<?
$personalization = (isset($_POST['personalization'])) ? $_POST['personalization'] : array(); ?>

Personalization :
    <?php
    if (count($personalization) > 0) {
        foreach ($personalization as $personalization) {
            echo $personalization . ' ';
        }
    } else {
        echo "No personalization has been selected";
    }
    ?>


问:
Query By State Machine State Rails 3
I'm using the Transitions gem to create a state machine in my model set up like so:

```<code>require 'transitions'

class Batch < ActiveRecord::Base
  include Transitions

  state_machine do
    state :pending
    state :completed

    event :change_state do
      transitions :to => :completed, :from => [:pending]
    end

  end

end
</code>```

I want to query the model to get all records that have a certain state e.g.:

```<code>Batch.where :current_state => :pending
</code>```

But that doesn't seem to work, and I'm having trouble finding documentation on this. Does anyone know how to do this? (I'm sure it's possible just can't seem to find it) Thanks in advance!

EDIT

Running tail -n development.log gives me:

```<code>ActionView::Template::Error (SQLite3::SQLException: no such column: batches.current_state: SELECT "batches".* FROM "batches" WHERE "batches"."user_id" = 1 AND "batches"."current_state" = 'pending'):
    3: <%= link_to 'New Batch', new_batch_path %>
    4:
    5:
    6: <% unless @pending_batches.length < 1 %>
    7:  You have <%= @pending_batches.length %> batches pending on these urls:
    8:  <% @pending_batches.each do |batch| %>
    9:      <%= batch.url %>
  app/views/batches/index.html.erb:6:in `_app_views_batches_index_html_erb___355556540_17724200__911230187'
  app/controllers/batches_controller.rb:8:in `index'

Rendered /Users/dshipper/.rvm/gems/ruby-1.9.2-p180@artsicle/gems/actionpack-3.0.9/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.5ms)
  Batch Load (0.5ms)  SELECT "batches".* FROM "batches" WHERE "batches"."user_id" = 1 AND "batches"."current_state" = 'pending'
SQLite3::SQLException: no such column: batches.current_state: SELECT "batches".* FROM "batches" WHERE "batches"."user_id" = 1 AND "batches"."current_state" = 'pending'
Rendered /Users/dshipper/.rvm/gems/ruby-1.9.2-p180@artsicle/gems/actionpack-3.0.9/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (6.6ms)
Rendered /Users/dshipper/.rvm/gems/ruby-1.9.2-p180@artsicle/gems/actionpack-3.0.9/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (16.1ms)
  SQL (0.2ms)   SELECT name
 FROM sqlite_master
 WHERE type = 'table' AND NOT name = 'sqlite_sequence'

  Batch Load (0.3ms)  SELECT "batches".* FROM "batches" HAVING "batches"."current_state" = 'pending'
SQLite3::SQLException: a GROUP BY clause is required before HAVING: SELECT "batches".* FROM "batches" HAVING "batches"."current_state" = 'pending'
</code>```

And running grep 'current_state db/schema.rb' return no results. I would expect that though because there's no actual column called current_state, the state of the record is managed by the state machine (not sure exactly where it's storing the state).

答:
I was researching state machines also and, though I haven't implemented it yet in my project, I found this that might be helpful.

Make sure your gemfile  includes

```<code>gem "transitions", :require => ["transitions", "active_record/transitions"]
</code>```

Make sure your model has

```<code>include ActiveRecord::Transitions
</code>```

rather than just

```<code>include Transitions
</code>```

and that it has a column called 'state' as this is where state is persisted.

The problem seemed to have been documented here:

http://dev.netizer.pl/transitions-state-machine-for-rails-3.html/comment-page-1#comment-41

And the documentation on github also outlines the setup for Rails

http://github.com/qoobaa/transitions

Using with Rails

This goes into your Gemfile:

gem "transitions", :require => ["transitions", "active_record/transitions"]

… and this into your AR model:

include ActiveRecord::Transitions

A note about persistence

The property used to persist the models’ state is named state (really!), which should be a string column wide enough to fit your longest state name. It should also be mentioned that #save! is called after every successful event.

Hope this is helpful, good luck!

Title: Query By State Machine State Rails 3

Body:
I'm using the Transitions gem to create a state machine in my model set up like so:

require 'transitions'

class Batch < ActiveRecord::Base
  include Transitions

  state_machine do
    state :pending
    state :completed

    event :change_state do
      transitions :to => :completed, :from => [:pending]
    end

  end

end

I want to query the model to get all records that have a certain state e.g.:

Batch.where :current_state => :pending

But that doesn't seem to work, and I'm having trouble finding documentation on this. Does anyone know how to do this? (I'm sure it's possible just can't seem to find it) Thanks in advance!

EDIT

Running tail -n development.log gives me:

ActionView::Template::Error (SQLite3::SQLException: no such column: batches.current_state: SELECT "batches".* FROM "batches" WHERE "batches"."user_id" = 1 AND "batches"."current_state" = 'pending'):
    3: <%= link_to 'New Batch', new_batch_path %>
    4:
    5:
    6: <% unless @pending_batches.length < 1 %>
    7:  You have <%= @pending_batches.length %> batches pending on these urls:
    8:  <% @pending_batches.each do |batch| %>
    9:      <%= batch.url %>
  app/views/batches/index.html.erb:6:in `_app_views_batches_index_html_erb___355556540_17724200__911230187'
  app/controllers/batches_controller.rb:8:in `index'

Rendered /Users/dshipper/.rvm/gems/ruby-1.9.2-p180@artsicle/gems/actionpack-3.0.9/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.5ms)
  Batch Load (0.5ms)  SELECT "batches".* FROM "batches" WHERE "batches"."user_id" = 1 AND "batches"."current_state" = 'pending'
SQLite3::SQLException: no such column: batches.current_state: SELECT "batches".* FROM "batches" WHERE "batches"."user_id" = 1 AND "batches"."current_state" = 'pending'
Rendered /Users/dshipper/.rvm/gems/ruby-1.9.2-p180@artsicle/gems/actionpack-3.0.9/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (6.6ms)
Rendered /Users/dshipper/.rvm/gems/ruby-1.9.2-p180@artsicle/gems/actionpack-3.0.9/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (16.1ms)
  SQL (0.2ms)   SELECT name
 FROM sqlite_master
 WHERE type = 'table' AND NOT name = 'sqlite_sequence'

  Batch Load (0.3ms)  SELECT "batches".* FROM "batches" HAVING "batches"."current_state" = 'pending'
SQLite3::SQLException: a GROUP BY clause is required before HAVING: SELECT "batches".* FROM "batches" HAVING "batches"."current_state" = 'pending'

And running grep 'current_state db/schema.rb' return no results. I would expect that though because there's no actual column called current_state, the state of the record is managed by the state machine (not sure exactly where it's storing the state).

Body:
I was researching state machines also and, though I haven't implemented it yet in my project, I found this that might be helpful.

Make sure your gemfile  includes

gem "transitions", :require => ["transitions", "active_record/transitions"]

Make sure your model has

include ActiveRecord::Transitions

rather than just

include Transitions

and that it has a column called 'state' as this is where state is persisted.

The problem seemed to have been documented here:

http://dev.netizer.pl/transitions-state-machine-for-rails-3.html/comment-page-1#comment-41

And the documentation on github also outlines the setup for Rails

http://github.com/qoobaa/transitions

Using with Rails

This goes into your Gemfile:

gem "transitions", :require => ["transitions", "active_record/transitions"]

… and this into your AR model:

include ActiveRecord::Transitions

A note about persistence

The property used to persist the models’ state is named state (really!), which should be a string column wide enough to fit your longest state name. It should also be mentioned that #save! is called after every successful event.

Hope this is helpful, good luck!


问:
Created an image gallery with Bootstrap Grid & Flexbox but the some images are not occupying 100% of the flex container
I'm new to web development and I'm trying to create a responsive image gallery with Bootstrap Grid and flexbox but for some reason some of the images are not taking the full height of flex container.

What it looks like right now

* {
  margin: 0px;
  padding: 0px;
}
html,
body {
  position: relative;
}

body {
  overflow-y: auto;
  min-height: 100vh;
}

.container {
  margin-top: 20px;
}

.tile {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.tile img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.2s;
}
.tile img:hover {
  filter: brightness(50%);
  transform: scale(1.1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!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" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="styles.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                class="img-one"
                src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg"
                alt=""
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2013/07/02/22/20/bouquet-142876_960_720.jpg"
                alt=""
                class="img-two"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2013/10/02/23/03/mountains-190055_960_720.jpg"
                alt=""
                class="img-three"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2015/06/19/20/13/sunset-815270_960_720.jpg"
                alt=""
                class="img-four"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2014/01/22/19/44/flower-field-250016_960_720.jpg"
                alt=""
                class="img-five"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2015/04/19/08/32/rose-729509_960_720.jpg"
                alt=""
                class="img-six"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg"
                alt=""
                class="img-seven"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2014/02/27/16/10/tree-276014_960_720.jpg"
                alt=""
                class="img-eight"
              />

          </div>
        </div>
      </div>
    </div>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    ></script>
  </body>
</html></code>```

What should I do so that all images are of the same height, alternatively occupy full height of the flex container?

答:
You could use just heigh 100% including 'a' tag with 'title' parent.

* {
  margin: 0px;
  padding: 0px;
}
html,
body {
  position: relative;
}

body {
  overflow-y: auto;
  min-height: 100vh;
}

.container {
  margin-top: 20px;
}

.tile , a{
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.tile img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.2s;
}
.tile img:hover {
  filter: brightness(50%);
  transform: scale(1.1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!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" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="styles.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                class="img-one"
                src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg"
                alt=""
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2013/07/02/22/20/bouquet-142876_960_720.jpg"
                alt=""
                class="img-two"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2013/10/02/23/03/mountains-190055_960_720.jpg"
                alt=""
                class="img-three"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2015/06/19/20/13/sunset-815270_960_720.jpg"
                alt=""
                class="img-four"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2014/01/22/19/44/flower-field-250016_960_720.jpg"
                alt=""
                class="img-five"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2015/04/19/08/32/rose-729509_960_720.jpg"
                alt=""
                class="img-six"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg"
                alt=""
                class="img-seven"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2014/02/27/16/10/tree-276014_960_720.jpg"
                alt=""
                class="img-eight"
              />

          </div>
        </div>
      </div>
    </div>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    ></script>
  </body>
</html></code>```

Body:
I'm new to web development and I'm trying to create a responsive image gallery with Bootstrap Grid and flexbox but for some reason some of the images are not taking the full height of flex container.

What it looks like right now

* {
  margin: 0px;
  padding: 0px;
}
html,
body {
  position: relative;
}

body {
  overflow-y: auto;
  min-height: 100vh;
}

.container {
  margin-top: 20px;
}

.tile {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.tile img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.2s;
}
.tile img:hover {
  filter: brightness(50%);
  transform: scale(1.1);
}

<!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" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="styles.css" />
    <title>Document</title>

What should I do so that all images are of the same height, alternatively occupy full height of the flex container?

Body:
You could use just heigh 100% including 'a' tag with 'title' parent.

* {
  margin: 0px;
  padding: 0px;
}
html,
body {
  position: relative;
}

body {
  overflow-y: auto;
  min-height: 100vh;
}

.container {
  margin-top: 20px;
}

.tile , a{
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.tile img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.2s;
}
.tile img:hover {
  filter: brightness(50%);
  transform: scale(1.1);
}

<!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" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="styles.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                class="img-one"
                src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg"
                alt=""
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2013/07/02/22/20/bouquet-142876_960_720.jpg"
                alt=""
                class="img-two"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2013/10/02/23/03/mountains-190055_960_720.jpg"
                alt=""
                class="img-three"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2015/06/19/20/13/sunset-815270_960_720.jpg"
                alt=""
                class="img-four"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2014/01/22/19/44/flower-field-250016_960_720.jpg"
                alt=""
                class="img-five"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2015/04/19/08/32/rose-729509_960_720.jpg"
                alt=""
                class="img-six"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg"
                alt=""
                class="img-seven"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2014/02/27/16/10/tree-276014_960_720.jpg"
                alt=""
                class="img-eight"
              />
            </a>
          </div>
        </div>
      </div>
    </div>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    ></script>
  </body>
</html>


问:
How to increase the tabindex in React ul-li search result?
I used ul li to implement search result:

```<code><ul className="search-result">
  <li tabindex="1">title here...</li>
  <li tabindex="2">title here...</li>
  <li tabindex="3">title here...</li>
.
.
.
</ul>
</code>```

and this is the style for each item:

```<code>.search-result{
 li:active, li:focuse {
  font-weight: bold;
  background: #f0f0f0;
 }
}
</code>```

but I'm trying to add a feature which client navigate between result items by using key-down or key-up buttons on the keyboard. but how can I access to current active tabindex in document to increase or decrease that by JavaScript and not tab button?

答:
You need store current tab index in state and update it in keydown eventListener

```<code>import "./styles.css";
import { useState, useEffect } from "react";
import users from "./data";

export default function App() {
  const [searchValue, setSearchValue] = useState("");
  const [currentTab, setCurrentTab] = useState(0);
  const searchResults = users.filter(
    (user) => searchValue.trim() && user.includes(searchValue.trim())
  );
  useEffect(() => {
    const handleKeyDown = (e) => {
      const keyCode = e.keyCode;
      if (keyCode == 38 && searchResults.length - 1 > currentTab)
        setCurrentTab(currentTab + 1);
      if (keyCode == 40 && currentTab >= 1) setCurrentTab(currentTab - 1);
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [searchResults, currentTab]);
  return (
    <div>
      <input
        type="text"
        value={searchValue}
        onChange={(e) => {
          setSearchValue(e.target.value);
          setCurrentTab(0);
        }}
      />
      <ul className="search-result">
        {searchResults.map((result, i) => (
          <li className={currentTab === i ? "active" : ""}>{result}</li>
        ))}
      </ul>
    </div>
  );
}
</code>```

I created a sandbox, you can check it

Body:
I used ul li to implement search result:

title here...

title here...

title here...

.
.
.

and this is the style for each item:

.search-result{
 li:active, li:focuse {
  font-weight: bold;
  background: #f0f0f0;
 }
}

but I'm trying to add a feature which client navigate between result items by using key-down or key-up buttons on the keyboard. but how can I access to current active tabindex in document to increase or decrease that by JavaScript and not tab button?

Body:
You need store current tab index in state and update it in keydown eventListener

import "./styles.css";
import { useState, useEffect } from "react";
import users from "./data";

export default function App() {
  const [searchValue, setSearchValue] = useState("");
  const [currentTab, setCurrentTab] = useState(0);
  const searchResults = users.filter(
    (user) => searchValue.trim() && user.includes(searchValue.trim())
  );
  useEffect(() => {
    const handleKeyDown = (e) => {
      const keyCode = e.keyCode;
      if (keyCode == 38 && searchResults.length - 1 > currentTab)
        setCurrentTab(currentTab + 1);
      if (keyCode == 40 && currentTab >= 1) setCurrentTab(currentTab - 1);
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [searchResults, currentTab]);
  return (
    <div>
      <input
        type="text"
        value={searchValue}
        onChange={(e) => {
          setSearchValue(e.target.value);
          setCurrentTab(0);
        }}
      />
      <ul className="search-result">
        {searchResults.map((result, i) => (
          <li className={currentTab === i ? "active" : ""}>{result}</li>
        ))}
      </ul>
    </div>
  );
}

I created a sandbox, you can check it


问:
How to declare Class fields
I'm trying to create a class with some fields on Google Apps Scripts.  I can't even save the file.  From what I understand of this SO answer, I'm using the correct syntax for class fields.

V8 runtime is enabled.

The error:

Syntax error: ParseError: Unexpected token = line: 5 file: Airtable_Class.gs
```
<p>Line 5 is:  <code>foo = "bar";</code></p>
<p>Here's the whole code:</p>
```class FieldsTest{
  foo = "bar";
}

```

答:
This is a known issue. Add a star (★ on top left) to the issue, if you want this to be implemented.

https://issuetracker.google.com/issues/195752915

According to the tracker, it is supported, but it is blocked by the parser.

Title: How to declare Class fields

Body:
I'm trying to create a class with some fields on Google Apps Scripts.  I can't even save the file.  From what I understand of this SO answer, I'm using the correct syntax for class fields.

V8 runtime is enabled.

The error:

Syntax error: ParseError: Unexpected token = line: 5 file: Airtable_Class.gs

Line 5 is:  foo = "bar";

Here's the whole code:

class FieldsTest{
  foo = "bar";
}


问:
Expander Handler Issue? System.Exception: 'Handler not found for view Xamarin.CommunityToolkit.UI.Views.Expander.'
I'm using Visual Studio 2022 preview 2.0 MAUI. I want to used a expander in MAUI, I have used Xamarin.CommunityToolkit.MauiCompat  nuget. But I am seeing the exception System.Exception: 'Handler not found for view Xamarin.CommunityToolkit.UI.Views.Expander. How can I resolve this issue in MAUI.

My UI is:

```<code><behaviors:Expander>
    <behaviors:Expander.Header>
        <HorizontalStackLayout Margin="33,-10,22,10">
            <Label FontAttributes="Bold" WidthRequest="230" VerticalOptions="Center" Text="Monday" TextColor="{DynamicResource Black}" FontSize="{DynamicResource AppFontSize_Default}"></Label>
            <Image Margin="0,0,30,0" Source="plus.png"  HorizontalOptions="StartAndExpand" VerticalOptions="CenterAndExpand" WidthRequest="15" HeightRequest="20">
                <Image.Triggers>
                    <DataTrigger TargetType="Image" Binding="{Binding Source={RelativeSource AncestorType={x:Type behaviors:Expander}}, Path=IsExpanded}" Value="True">
                        <Setter Property="Source" Value="plus.png" />
                    </DataTrigger>
                </Image.Triggers>
            </Image>
            <RadioButton  BackgroundColor="Transparent" BorderColor="{DynamicResource DefaultColor}"></RadioButton>
        </HorizontalStackLayout>
    </behaviors:Expander.Header>
    <behaviors:Expander.ContentTemplate>
        <DataTemplate>
            <Label Text="{Binding CustomerNotes}" HorizontalOptions="StartAndExpand" TextColor="Black" FontSize="14" Padding="10,0,0,0"></Label>
        </DataTemplate>
    </behaviors:Expander.ContentTemplate>
</behaviors:Expander>
</code>```

I have downloaded the nuget:

Xamarin.CommunityToolkit.MauiCompat

Xamarin.CommunityToolkit.Markup.MauiCompat

Also I have add handler on my MauiProgram.cs page

```<code>// Register ALL handlers in the Xamarin Community Toolkit assembly
handlers.AddCompatibilityRenderers(typeof(Xamarin.CommunityToolkit.UI.Views.MediaElementRenderer).Assembly);

// Register just one handler for the control you need
handlers.AddCompatibilityRenderer(typeof(Xamarin.CommunityToolkit.UI.Views.MediaElement), typeof(Xamarin.CommunityToolkit.UI.Views.MediaElementRenderer));
</code>```

答:
I'm not sure how well the Xamarin Forms Community Toolkit works with MAUI. The Maui Community Toolkit is still in pre-release, but they have plans to add the Expander Control.

You can track the Expander proposal issue on Github.

Body:
I'm using Visual Studio 2022 preview 2.0 MAUI. I want to used a expander in MAUI, I have used Xamarin.CommunityToolkit.MauiCompat  nuget. But I am seeing the exception System.Exception: 'Handler not found for view Xamarin.CommunityToolkit.UI.Views.Expander. How can I resolve this issue in MAUI.

My UI is:

<behaviors:Expander>
    <behaviors:Expander.Header>
        <HorizontalStackLayout Margin="33,-10,22,10">

            <Image Margin="0,0,30,0" Source="plus.png"  HorizontalOptions="StartAndExpand" VerticalOptions="CenterAndExpand" WidthRequest="15" HeightRequest="20">
                <Image.Triggers>
                    <DataTrigger TargetType="Image" Binding="{Binding Source={RelativeSource AncestorType={x:Type behaviors:Expander}}, Path=IsExpanded}" Value="True">
                        <Setter Property="Source" Value="plus.png" />
                    </DataTrigger>
                </Image.Triggers>
            </Image>
            <RadioButton  BackgroundColor="Transparent" BorderColor="{DynamicResource DefaultColor}"></RadioButton>
        </HorizontalStackLayout>
    </behaviors:Expander.Header>
    <behaviors:Expander.ContentTemplate>
        <DataTemplate>

        </DataTemplate>
    </behaviors:Expander.ContentTemplate>
</behaviors:Expander>

I have downloaded the nuget:

Xamarin.CommunityToolkit.MauiCompat

Xamarin.CommunityToolkit.Markup.MauiCompat

Also I have add handler on my MauiProgram.cs page

// Register ALL handlers in the Xamarin Community Toolkit assembly
handlers.AddCompatibilityRenderers(typeof(Xamarin.CommunityToolkit.UI.Views.MediaElementRenderer).Assembly);

// Register just one handler for the control you need
handlers.AddCompatibilityRenderer(typeof(Xamarin.CommunityToolkit.UI.Views.MediaElement), typeof(Xamarin.CommunityToolkit.UI.Views.MediaElementRenderer));


问:
I am getting Problem while using innerHTML and do DOM manipulation using that
I am trying to delete a particular list item
 from the inner HTML. i gave them proper ID also but I am not able to delete it . How to delete these list items after clicking that cross button?

here is my codepen.io link to the code:

```<code>codepen.io/rishabh-2001/pen/VwrZmyG
</code>```

答:
You are not adding listner to cross button after rendering</p>
```<code>function crossBtnListener() {
  let classArr=document.querySelectorAll(".listItem")
  classArr.forEach(itt => {
    itt.addEventListener("click",(e)=>{
      let idFun=e.srcElement.getAttribute("value")
          crossClick(idFun)
    })
  });
}

function render(leads){
   let listItem=""
   for(let i=0;i<leads.length;i++)
   {
       let id_="cross-id"+i;
       let click1="crossClick('"+id_+"')";
    //    let click1=`crossClick(${id_})`;
    //    console.log(click1)

     listItem+=`
          <li class="inner-li">
              <a target='_blank' href='${leads[i]}'>
                 ${leads[i]}
              </a>
              <i value="${leads[i]}" class="fas fa-times-circle listItem"  id="${id_}"></i>
          </li>
       `
   }
   ulEl.innerHTML=listItem;

   crossBtnListener(); //ADDED AFTER RENDERING LIST
}
</code>```

Body:
I am trying to delete a particular list item
 from the inner HTML. i gave them proper ID also but I am not able to delete it . How to delete these list items after clicking that cross button?

here is my codepen.io link to the code:

codepen.io/rishabh-2001/pen/VwrZmyG

Body:
You are not adding listner to cross button after rendering

function crossBtnListener() {
  let classArr=document.querySelectorAll(".listItem")
  classArr.forEach(itt => {
    itt.addEventListener("click",(e)=>{
      let idFun=e.srcElement.getAttribute("value")
          crossClick(idFun)
    })
  });
}

function render(leads){
   let listItem=""
   for(let i=0;i<leads.length;i++)
   {
       let id_="cross-id"+i;
       let click1="crossClick('"+id_+"')";
    //    let click1=`crossClick(${id_})`;
    //    console.log(click1)

     listItem+=`
          <li class="inner-li">
              <a target='_blank' href='${leads[i]}'>
                 ${leads[i]}
              </a>
              <i value="${leads[i]}" class="fas fa-times-circle listItem"  id="${id_}"></i>
          </li>
       `
   }
   ulEl.innerHTML=listItem;

   crossBtnListener(); //ADDED AFTER RENDERING LIST
}


答:
You can't type the spread portion of the object directly, but you can add the necessary properties with the union type (&).

In this case, the extra properties you want to allow are of type React.HTMLAttributes<HTMLSpanElement>. So you end up with:

```<code>function Foo({
  children,
  ...rest
}: {
  children: React.ReactNode;
} & React.HTMLAttributes<HTMLSpanElement>) {
  return (
    <span style={{ background: "red" }} {...rest}>
      {children}
    </span>
  );
}
</code>```

As an aside, you can avoid manually typing the children property using the React.FunctionComponent type. This actually avoids the union definition and is a bit more idiomatic in React code.

```<code>const Foo: React.FunctionComponent<React.HTMLAttributes<HTMLSpanElement>> = ({
  children,
  ...rest
}) => {
  // ...
}
</code>```

Title: TypeScript + React: How do I type a `rest` props that collects the rest of the props into an object and later spread them to some element?

Body:
You can't type the spread portion of the object directly, but you can add the necessary properties with the union type (&).

In this case, the extra properties you want to allow are of type React.HTMLAttributes<HTMLSpanElement>. So you end up with:

function Foo({
  children,
  ...rest
}: {
  children: React.ReactNode;
} & React.HTMLAttributes<HTMLSpanElement>) {
  return (
    <span style={{ background: "red" }} {...rest}>
      {children}
    </span>
  );
}

As an aside, you can avoid manually typing the children property using the React.FunctionComponent type. This actually avoids the union definition and is a bit more idiomatic in React code.

const Foo: React.FunctionComponent<React.HTMLAttributes<HTMLSpanElement>> = ({
  children,
  ...rest
}) => {
  // ...
}


问:
How to run 'implicity_wait()' in a 'for loop' with respect to Web Scraping using Python?
Actually, I want to scrape the 'title' and 'product description' for all the products and from all the pages, and then save it into the '.csv' file.

URL:- hhttps://www.nykaa.com/makeup/body-art/c/3024?page_no=1&sort=popularity&ptype=lst&id=3024&root=nav_2&dir=desc&order=popularity&eq=desktop

This is what, I have tried.

```<code>from msilib.schema import Error
from os import sep
from tkinter import ON
from turtle import goto
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import numpy as np
from random import randint
import pandas as pd
import requests
import csv

title_list = []
para_list = []
expiry_list = []
country_list = []
importer_list = []
address_list = []

myDict = {'body-art': 3024}

browser = webdriver.Chrome(
    r'C:\Users\paart\.wdm\drivers\chromedriver\win32\97.0.4692.71\chromedriver.exe')

browser.maximize_window()
browser.implicitly_wait(20)

for item_name in myDict:
    page_num = 1
    while True:
        try:
            page = f"https://www.nykaa.com/makeup/{item_name}/c/{myDict[item_name]}?page_no={page_num}&sort=popularity&ptype=lst&id={myDict[item_name]}&root=nav_2&dir=desc&order=popularity&eq=desktop"

            print(page)

            requests.get(page)

            soup = BeautifulSoup(requests.get(page).content, 'html.parser')
            urls = [item.get("href")
                    for item in soup.find_all("a", class_="css-qlopj4")]
            # print(urls)
            if len(urls) == 0:
                break
            for i in range(0, 2): #Since, it's a huge amount of data, that's why I have taken 2 products on one page, otherwise it will be in the range(0,30). It will cover all the products from an individual pages.
                try:
                    url = urls[i]

                    browser.get("https://www.nykaa.com" + url)

                    title_data = browser.find_elements(
                        By.CLASS_NAME, 'css-1gc4x7i').text

                    print(title_data)

                    for t in title_data:
                        title_list.append(t)

                    browser.execute_script("document.body.style.zoom='50%'")
                    browser.execute_script("document.body.style.zoom='100%'")

                    # Creates "load more" button object.
                    browser.implicitly_wait(20)
                    loadMore = browser.find_element(
                        By.XPATH, "/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]")
                    loadMore.click()
                    browser.implicitly_wait(20)

                    desc_data = browser.find_elements(By.ID, 'content-details')

                    for desc in desc_data:
                        para_details = browser.find_element(By.XPATH,
                                                            '//*[@id="content-details"]/p[1]').text
                        para_list.append(para_details)
                        expiry = browser.find_element(By.XPATH,
                                                      '//*[@id="content-details"]/p[2]').text
                        expiry_list.append(expiry)
                        country = browser.find_element(By.XPATH,
                                                       '//*[@id="content-details"]/p[3]').text
                        country_list.append(country)
                        importer = browser.find_element(By.XPATH,
                                                        '//*[@id="content-details"]/p[4]').text
                        importer_list.append(importer)
                        address = browser.find_element(By.XPATH,
                                                       '//*[@id="content-details"]/p[5]').text
                        address_list.append(address)

                except:
                    break
        except:
            break
        page_num += 1

title_list = [i.split('.css', 1)[0] for i in title_list]
print(*title_list, sep="\n")
print(*para_list, sep="\n")
print(*expiry_list, sep="\n")
print(*country_list, sep="\n")
print(*importer_list, sep="\n")
print(*address_list, "\n")
data_new = {"Title": title_list, "Para": para_list, "Expiry": expiry_list,
            "Country": country_list, "Importer": importer_list, "Address": address_list}
df = pd.DataFrame(data_new)
df.to_csv("nykaa_makeup_bodyArt_new.csv")
# print(df)
</code>```

The Output, I am receiving is as:

```<code>DevTools listening on ws://127.0.0.1:30887/devtools/browser/a222842a-7ce3-4070-a684-7e8bb8772279
https://www.nykaa.com/makeup/body-art/c/3024?page_no=1&sort=popularity&ptype=lst&id=3024&root=nav_2&dir=desc&order=popularity&eq=desktop
https://www.nykaa.com/makeup/body-art/c/3024?page_no=2&sort=popularity&ptype=lst&id=3024&root=nav_2&dir=desc&order=popularity&eq=desktop
https://www.nykaa.com/makeup/body-art/c/3024?page_no=3&sort=popularity&ptype=lst&id=3024&root=nav_2&dir=desc&order=popularity&eq=desktop
https://www.nykaa.com/makeup/body-art/c/3024?page_no=4&sort=popularity&ptype=lst&id=3024&root=nav_2&dir=desc&order=popularity&eq=desktop
https://www.nykaa.com/makeup/body-art/c/3024?page_no=5&sort=popularity&ptype=lst&id=3024&root=nav_2&dir=desc&order=popularity&eq=desktop

PS E:\Web Scraping - Nykaa>
</code>```

I think, due to the implicity_wait() function, it's not able to fetch the product's title & description. After my code runs, the '.csv' file is created, but it's a blank file. Maybe, I am wrong. Please help me regarding this. Do I need change to add/change some parts of the code?

Thanks

答:
There is no need to set browser.implicitly_wait multiple times.

browser.implicitly_wait is setting the timeout, how much time the driver will try to pool the DOM in order to locate an element on the page before it races exception.

browser.implicitly_wait is normally set per driver session.

This is definetely not a pause command like time.sleep.

So, in case you need to put a pause in your code you should use time.sleep while this is not recommended.

Also, it's much preferably to use Expected Conditions explicit waits rather than browser.implicitly_wait since browser.implicitly_wait waits for element presence i.e. it will release the run when element is just appeared while it may not be completely rendered.

In order to wait for element completely rendered and containing it text you should use something like

wait.until(EC.visibility_of_element_located((By.XPATH, "/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]")))
```

Where "/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]" is XPath of element you wishe to get the text from.

Body:
Actually, I want to scrape the 'title' and 'product description' for all the products and from all the pages, and then save it into the '.csv' file.

URL:- hhttps://www.nykaa.com/makeup/body-art/c/3024?page_no=1&sort=popularity&ptype=lst&id=3024&root=nav_2&dir=desc&order=popularity&eq=desktop

This is what, I have tried.

from msilib.schema import Error
from os import sep
from tkinter import ON
from turtle import goto
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import numpy as np
from random import randint
import pandas as pd
import requests
import csv

title_list = []
para_list = []
expiry_list = []
country_list = []
importer_list = []
address_list = []

myDict = {'body-art': 3024}

browser = webdriver.Chrome(
    r'C:\Users\paart\.wdm\drivers\chromedriver\win32\97.0.4692.71\chromedriver.exe')

browser.maximize_window()
browser.implicitly_wait(20)

for item_name in myDict:
    page_num = 1
    while True:
        try:
            page = f"https://www.nykaa.com/makeup/{item_name}/c/{myDict[item_name]}?page_no={page_num}&sort=popularity&ptype=lst&id={myDict[item_name]}&root=nav_2&dir=desc&order=popularity&eq=desktop"

            print(page)

            requests.get(page)

            soup = BeautifulSoup(requests.get(page).content, 'html.parser')
            urls = [item.get("href")
                    for item in soup.find_all("a", class_="css-qlopj4")]
            # print(urls)
            if len(urls) == 0:
                break
            for i in range(0, 2): #Since, it's a huge amount of data, that's why I have taken 2 products on one page, otherwise it will be in the range(0,30). It will cover all the products from an individual pages.
                try:
                    url = urls[i]

                    browser.get("https://www.nykaa.com" + url)

                    title_data = browser.find_elements(
                        By.CLASS_NAME, 'css-1gc4x7i').text

                    print(title_data)

                    for t in title_data:
                        title_list.append(t)

                    browser.execute_script("document.body.style.zoom='50%'")
                    browser.execute_script("document.body.style.zoom='100%'")

                    # Creates "load more" button object.
                    browser.implicitly_wait(20)
                    loadMore = browser.find_element(
                        By.XPATH, "/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]")
                    loadMore.click()
                    browser.implicitly_wait(20)

                    desc_data = browser.find_elements(By.ID, 'content-details')

                    for desc in desc_data:
                        para_details = browser.find_element(By.XPATH,
                                                            '//*[@id="content-details"]/p[1]').text
                        para_list.append(para_details)
                        expiry = browser.find_element(By.XPATH,
                                                      '//*[@id="content-details"]/p[2]').text
                        expiry_list.append(expiry)
                        country = browser.find_element(By.XPATH,
                                                       '//*[@id="content-details"]/p[3]').text
                        country_list.append(country)
                        importer = browser.find_element(By.XPATH,
                                                        '//*[@id="content-details"]/p[4]').text
                        importer_list.append(importer)
                        address = browser.find_element(By.XPATH,
                                                       '//*[@id="content-details"]/p[5]').text
                        address_list.append(address)

                except:
                    break
        except:
            break
        page_num += 1

title_list = [i.split('.css', 1)[0] for i in title_list]
print(*title_list, sep="\n")
print(*para_list, sep="\n")
print(*expiry_list, sep="\n")
print(*country_list, sep="\n")
print(*importer_list, sep="\n")
print(*address_list, "\n")
data_new = {"Title": title_list, "Para": para_list, "Expiry": expiry_list,
            "Country": country_list, "Importer": importer_list, "Address": address_list}
df = pd.DataFrame(data_new)
df.to_csv("nykaa_makeup_bodyArt_new.csv")
# print(df)

The Output, I am receiving is as:

DevTools listening on ws://127.0.0.1:30887/devtools/browser/a222842a-7ce3-4070-a684-7e8bb8772279
https://www.nykaa.com/makeup/body-art/c/3024?page_no=1&sort=popularity&ptype=lst&id=3024&root=nav_2&dir=desc&order=popularity&eq=desktop
https://www.nykaa.com/makeup/body-art/c/3024?page_no=2&sort=popularity&ptype=lst&id=3024&root=nav_2&dir=desc&order=popularity&eq=desktop
https://www.nykaa.com/makeup/body-art/c/3024?page_no=3&sort=popularity&ptype=lst&id=3024&root=nav_2&dir=desc&order=popularity&eq=desktop
https://www.nykaa.com/makeup/body-art/c/3024?page_no=4&sort=popularity&ptype=lst&id=3024&root=nav_2&dir=desc&order=popularity&eq=desktop
https://www.nykaa.com/makeup/body-art/c/3024?page_no=5&sort=popularity&ptype=lst&id=3024&root=nav_2&dir=desc&order=popularity&eq=desktop

PS E:\Web Scraping - Nykaa>

I think, due to the implicity_wait() function, it's not able to fetch the product's title & description. After my code runs, the '.csv' file is created, but it's a blank file. Maybe, I am wrong. Please help me regarding this. Do I need change to add/change some parts of the code?

Thanks

Body:
There is no need to set browser.implicitly_wait multiple times.

browser.implicitly_wait is setting the timeout, how much time the driver will try to pool the DOM in order to locate an element on the page before it races exception.

browser.implicitly_wait is normally set per driver session.

This is definetely not a pause command like time.sleep.

So, in case you need to put a pause in your code you should use time.sleep while this is not recommended.

Also, it's much preferably to use Expected Conditions explicit waits rather than browser.implicitly_wait since browser.implicitly_wait waits for element presence i.e. it will release the run when element is just appeared while it may not be completely rendered.

In order to wait for element completely rendered and containing it text you should use something like

wait.until(EC.visibility_of_element_located((By.XPATH, "/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]")))

Where "/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]" is XPath of element you wishe to get the text from.


答:
You need to add .tile .picture { height and width inherit } and you can add same for .tile img { height and width: inherit } it will work. I've also created demo for you.

* {
  margin: 0px;
  padding: 0px;
}

html,
body {
  position: relative;
}

body {
  overflow-y: auto;
  min-height: 100vh;
}

.container {
  margin-top: 20px;
}

.tile {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.tile .picture {
  height: inherit;
  width: inherit;
}

.tile img {
  width: inherit;
  height: inherit;
  object-fit: cover;
  transition: all 0.2s;
}

.tile img:hover {
  filter: brightness(50%);
  transform: scale(1.1);
}

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!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" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="styles.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                class="img-one"
                src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg"
                alt=""
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2013/07/02/22/20/bouquet-142876_960_720.jpg"
                alt=""
                class="img-two"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2013/10/02/23/03/mountains-190055_960_720.jpg"
                alt=""
                class="img-three"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2015/06/19/20/13/sunset-815270_960_720.jpg"
                alt=""
                class="img-four"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2014/01/22/19/44/flower-field-250016_960_720.jpg"
                alt=""
                class="img-five"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2015/04/19/08/32/rose-729509_960_720.jpg"
                alt=""
                class="img-six"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg"
                alt=""
                class="img-seven"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2014/02/27/16/10/tree-276014_960_720.jpg"
                alt=""
                class="img-eight"
              />

          </div>
        </div>
      </div>
    </div>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    ></script>
  </body>
</html></code>```

Title: Created an image gallery with Bootstrap Grid & Flexbox but the some images are not occupying 100% of the flex container

Body:
You need to add .tile .picture { height and width inherit } and you can add same for .tile img { height and width: inherit } it will work. I've also created demo for you.

* {
  margin: 0px;
  padding: 0px;
}

html,
body {
  position: relative;
}

body {
  overflow-y: auto;
  min-height: 100vh;
}

.container {
  margin-top: 20px;
}

.tile {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.tile .picture {
  height: inherit;
  width: inherit;
}

.tile img {
  width: inherit;
  height: inherit;
  object-fit: cover;
  transition: all 0.2s;
}

.tile img:hover {
  filter: brightness(50%);
  transform: scale(1.1);
}

<!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" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="styles.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                class="img-one"
                src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg"
                alt=""
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2013/07/02/22/20/bouquet-142876_960_720.jpg"
                alt=""
                class="img-two"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2013/10/02/23/03/mountains-190055_960_720.jpg"
                alt=""
                class="img-three"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2015/06/19/20/13/sunset-815270_960_720.jpg"
                alt=""
                class="img-four"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2014/01/22/19/44/flower-field-250016_960_720.jpg"
                alt=""
                class="img-five"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2015/04/19/08/32/rose-729509_960_720.jpg"
                alt=""
                class="img-six"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg"
                alt=""
                class="img-seven"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2014/02/27/16/10/tree-276014_960_720.jpg"
                alt=""
                class="img-eight"
              />
            </a>
          </div>
        </div>
      </div>
    </div>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    ></script>
  </body>
</html>