问:
Cant reselect previous selected item in CollectionView in Xamarin.Forms on iOS

TLDR

CollectionView broken in iOS, cant find any solution online. Weak Google fu or just not seeing the answer.

The problem

I have a CollectionView (Lets call it A) that contains items that are only strings values for filtering on a different CollectionView (Lets call it B) containing results from selecting a filter option in CollectionView A.

I have 3 different filtering options: "All", "Close to you", "Online" in CollectionView A.

The problem is that on iOS when I select for example filter option "All" in CollectionView A for the first time on the page it does the filtering and shows the results in CollectionView B, when I choose for example filtering option "Online" in CollectionView A it filters and shows the results in CollectionView B.

But when I choose filtering option "All" for the second time in CollectionView A its not responding, no event triggers, no commands runs and its not disabled. It is only showing, but I cant do anything with it.

Expected result

Can reselect the previous item on iOS, in Android no problem.

Actual result

Cant reselect previous item on iOS, need to back to previous page in stack and then navigate back to page to reset filtering.

The xaml markup

This is the xaml markup for the CollectionView A as explained above, the only holding string values to filter on.

```<code><CollectionView ItemsSource="{Binding FilterLocations}"
                Grid.Row="2"
                SelectedItem="{Binding SelectedFilterLocation}"
                SelectionMode="Single"
                HeightRequest="50">
   <CollectionView.ItemsLayout>
      <LinearItemsLayout Orientation="Horizontal"
                         ItemSpacing="10" />
   </CollectionView.ItemsLayout>
      <CollectionView.ItemTemplate>
         <DataTemplate x:DataType="x:String">
            <StackLayout xct:TouchEffect.NativeAnimation="True">
               <Frame BorderColor="{StaticResource BorderColor}"
                      x:Name="subCategoryFrame"
                      Padding="14, 10">
                  <Label Text="{Binding .}"
                         x:Name="subCategoryName"
                         FontFamily="{StaticResource FontPoppinsLight}"
                         TextColor="{StaticResource PrimaryAlt}" />
               </Frame>
            </StackLayout>
         </DataTemplate>
      </CollectionView.ItemTemplate>
         <CollectionView.Header>
            <BoxView WidthRequest="0"
                     HeightRequest="1"
                     BackgroundColor="Transparent" />
         </CollectionView.Header>
         <CollectionView.Footer>
            <BoxView WidthRequest="{StaticResource NormalSpacingDouble}"
                     HeightRequest="1"
                     BackgroundColor="Transparent" />
         </CollectionView.Footer>
      </CollectionView>
</code>```

The CollectionView A is in SelectionMode:Single, and the SelectedItem is bound to a ICommand on its bound ViewModel. And in the ViewModel the selection of a item in CollectionView A will trigger a filtering in CollectionView B

What I done so far

I set up so if a item in the CollectionView A is disabled it become Red, but it dont become Red.

I have tried to add a event in the Code behind, to try and set SelectedItem to null, but that back fired and just made all events go twice, one for selecting the item on the screen and second for altering the SelectedItem in the code behind.

Code:

```<code>private void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
      if (Device.RuntimePlatform == Device.iOS)
      {
         var collectionView = sender as CollectionView;
         if (collectionView == null) return;

         if (collectionView.SelectedItem != null)
         {
             collectionView.SelectedItem = null;
         }
      }
}
</code>```

(I know it is a big no no to do logic stuff in the Code Behind that is not design logic, but I need to get this solved or have a quick and dirty fix because of time pressure.)

Sorry for the wall of text

答:
First Bind the collection view into the event selectionchange.

```<code><CollectionView ItemsSource="{Binding FilterLocations}"
                Grid.Row="2"
                SelectedItem="{Binding SelectedFilterLocation}"
                SelectionMode="Single"
                HeightRequest="50"
                SelectionChanged="collection_SelectionChanged">

</code>```

then inside the event put selected item to null.

```<code>private async void collection_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   try
   {
      var Sender = sender as CollectionView;
      if (Sender.SelectedItem == null)
          return;

       Sender.SelectedItem = null;
    }
    catch (Exception ex)
    {

     }
}
</code>```

Body:
TLDR

CollectionView broken in iOS, cant find any solution online. Weak Google fu or just not seeing the answer.

The problem

I have a CollectionView (Lets call it A) that contains items that are only strings values for filtering on a different CollectionView (Lets call it B) containing results from selecting a filter option in CollectionView A.

I have 3 different filtering options: "All", "Close to you", "Online" in CollectionView A.

The problem is that on iOS when I select for example filter option "All" in CollectionView A for the first time on the page it does the filtering and shows the results in CollectionView B, when I choose for example filtering option "Online" in CollectionView A it filters and shows the results in CollectionView B.

But when I choose filtering option "All" for the second time in CollectionView A its not responding, no event triggers, no commands runs and its not disabled. It is only showing, but I cant do anything with it.

Expected result

Can reselect the previous item on iOS, in Android no problem.

Actual result

Cant reselect previous item on iOS, need to back to previous page in stack and then navigate back to page to reset filtering.

The xaml markup

This is the xaml markup for the CollectionView A as explained above, the only holding string values to filter on.

<CollectionView ItemsSource="{Binding FilterLocations}"
                Grid.Row="2"
                SelectedItem="{Binding SelectedFilterLocation}"
                SelectionMode="Single"
                HeightRequest="50">
   <CollectionView.ItemsLayout>
      <LinearItemsLayout Orientation="Horizontal"
                         ItemSpacing="10" />
   </CollectionView.ItemsLayout>
      <CollectionView.ItemTemplate>
         <DataTemplate x:DataType="x:String">
            <StackLayout xct:TouchEffect.NativeAnimation="True">
               <Frame BorderColor="{StaticResource BorderColor}"
                      x:Name="subCategoryFrame"
                      Padding="14, 10">

               </Frame>
            </StackLayout>
         </DataTemplate>
      </CollectionView.ItemTemplate>
         <CollectionView.Header>
            <BoxView WidthRequest="0"
                     HeightRequest="1"
                     BackgroundColor="Transparent" />
         </CollectionView.Header>
         <CollectionView.Footer>
            <BoxView WidthRequest="{StaticResource NormalSpacingDouble}"
                     HeightRequest="1"
                     BackgroundColor="Transparent" />
         </CollectionView.Footer>
      </CollectionView>

The CollectionView A is in SelectionMode:Single, and the SelectedItem is bound to a ICommand on its bound ViewModel. And in the ViewModel the selection of a item in CollectionView A will trigger a filtering in CollectionView B

What I done so far

I set up so if a item in the CollectionView A is disabled it become Red, but it dont become Red.

I have tried to add a event in the Code behind, to try and set SelectedItem to null, but that back fired and just made all events go twice, one for selecting the item on the screen and second for altering the SelectedItem in the code behind.

Code:

private void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
      if (Device.RuntimePlatform == Device.iOS)
      {
         var collectionView = sender as CollectionView;
         if (collectionView == null) return;

         if (collectionView.SelectedItem != null)
         {
             collectionView.SelectedItem = null;
         }
      }
}

(I know it is a big no no to do logic stuff in the Code Behind that is not design logic, but I need to get this solved or have a quick and dirty fix because of time pressure.)

Sorry for the wall of text

Body:
First Bind the collection view into the event selectionchange.

<CollectionView ItemsSource="{Binding FilterLocations}"
                Grid.Row="2"
                SelectedItem="{Binding SelectedFilterLocation}"
                SelectionMode="Single"
                HeightRequest="50"
                SelectionChanged="collection_SelectionChanged">

then inside the event put selected item to null.

private async void collection_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   try
   {
      var Sender = sender as CollectionView;
      if (Sender.SelectedItem == null)
          return;

       Sender.SelectedItem = null;
    }
    catch (Exception ex)
    {

     }
}


来源: stackexchange

问:
how it is that pointer to struct shows the wrong values?
I use ARM-M4 with GCC for ARM (10_2021.10)
I have a problem where a pointer to struct displays the wrong values.

__copy_table_start__ is define in the linker file, I see it's location in the map file and this is how I found it's true value (and the values make sense, they are correct)

Here is my code

```<code>#pragma GCC optimize("O0")
static void DataInit(void)
{
    typedef struct {
      uint32_t const* src;
      uint32_t* dest;
      uint32_t  wlen;
    } __copy_table_t;

    extern const __copy_table_t __copy_table_start__;
    extern const __copy_table_t __copy_table_end__;
    extern const __zero_table_t __zero_table_start__;
    extern const __zero_table_t __zero_table_end__;

    static volatile __copy_table_t const* pTable;

    pTable = &__copy_table_start__;

    for (; pTable < &__copy_table_end__; ++pTable) {
      for(uint32_t i=0u; i<pTable->wlen; ++i) {
        pTable->dest[i] = pTable->src[i];
      }
    }
}
</code>```

And what I see in the debugger, right after pTable = &__copy_table_start__; is that:

```<code>__copy_table_start__.src = 0x14A0D380
__copy_table_start__.dest = 0x00100000
__copy_table_start__.wlen = 0x38A

pTable->src = 0x14A0D380
pTable->dest = 0x14A0D380
pTable->wlen = 0x14A0D380
</code>```

How can that be?

UPDATE:
I did another experiment, I created another struct variable and a pointer to that variable and get the same results. first time I see this kind of behavior.

```<code>const __copy_table_t mine = {(uint32_t const*)0x12345678, (uint32_t *)0x00004545, 0x89890000};

static volatile __copy_table_t const* my_ptr;
my_ptr = &mine;
</code>```

The result is that my_ptr->src = my_ptr->dest = my_ptr->wlen = 0x12345678

答:
Apparently the problem is with Keil (the IDE).
It displays the wrong values.

When I created 3 new parameters and loaded the data to them:

```<code>my_src = (uint32_t)pTable->src;
my_dest = (uint32_t)pTable->dest;
my_len = (uint32_t)pTable->wlen;
</code>```

Those parameters got the correct values.
What threw me off was that doing a single step in debug skipped the entire for loop (the first one), as if the internal for loop didn't do anything. It actually did what it was supposed to do, but one parameter that was supposed to be reset after that didn't update in the IDE.

ContentLicense: CC BY-SA 4.0

Body:
I use ARM-M4 with GCC for ARM (10_2021.10)
I have a problem where a pointer to struct displays the wrong values.

__copy_table_start__ is define in the linker file, I see it's location in the map file and this is how I found it's true value (and the values make sense, they are correct)

Here is my code

#pragma GCC optimize("O0")
static void DataInit(void)
{
    typedef struct {
      uint32_t const* src;
      uint32_t* dest;
      uint32_t  wlen;
    } __copy_table_t;

    extern const __copy_table_t __copy_table_start__;
    extern const __copy_table_t __copy_table_end__;
    extern const __zero_table_t __zero_table_start__;
    extern const __zero_table_t __zero_table_end__;

    static volatile __copy_table_t const* pTable;

    pTable = &__copy_table_start__;

    for (; pTable < &__copy_table_end__; ++pTable) {
      for(uint32_t i=0u; i<pTable->wlen; ++i) {
        pTable->dest[i] = pTable->src[i];
      }
    }
}

And what I see in the debugger, right after pTable = &__copy_table_start__; is that:

__copy_table_start__.src = 0x14A0D380
__copy_table_start__.dest = 0x00100000
__copy_table_start__.wlen = 0x38A

pTable->src = 0x14A0D380
pTable->dest = 0x14A0D380
pTable->wlen = 0x14A0D380

How can that be?

UPDATE:
I did another experiment, I created another struct variable and a pointer to that variable and get the same results. first time I see this kind of behavior.

const __copy_table_t mine = {(uint32_t const*)0x12345678, (uint32_t *)0x00004545, 0x89890000};

static volatile __copy_table_t const* my_ptr;
my_ptr = &mine;

The result is that my_ptr->src = my_ptr->dest = my_ptr->wlen = 0x12345678

Body:
Apparently the problem is with Keil (the IDE).
It displays the wrong values.

When I created 3 new parameters and loaded the data to them:

my_src = (uint32_t)pTable->src;
my_dest = (uint32_t)pTable->dest;
my_len = (uint32_t)pTable->wlen;

Those parameters got the correct values.
What threw me off was that doing a single step in debug skipped the entire for loop (the first one), as if the internal for loop didn't do anything. It actually did what it was supposed to do, but one parameter that was supposed to be reset after that didn't update in the IDE.


问:
Adding a column in AWS glue dynamic dataframe
I am very new to AWS Glue. I am working on a small project and the ask is to read a file from S3 bucket, transpose it and load it in a mysql table.  The source data in S3 bucket looks as below

    +----+----+-------+-----+---+--+--------+
    |cost|data|minutes|name |sms|id|category|
    +----+----+-------+-----+---+--+--------+
    |  5 |1000|  200  |prod1|500|p1|service |
    +----+----+-------+-----+---+--+--------+
```
<p>The target table structure is
Product_id, Parameter, value</p>
<p>I am expecting target table to have following values</p>
<p>p1, cost, 5</p>
<p>P1, data, 1000</p>
<p>I am able to load the target table with ID and Value. But I am not able to populate the parameter column. This column is not present in the input data and I want to populate a string depending on which column value I am populating.</p>
<p>Here is the code I used for cost.</p>
<pre class="lang-python prettyprint-override"><code>import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job

## @params: [JOB_NAME]
args = getResolvedOptions(sys.argv, ['JOB_NAME'])

sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'], args)

## @type: DataSource
## @args: [database = "mainclouddb", table_name = "s3product", transformation_ctx = "datasource0"]
## @return: datasource0
## @inputs: []
datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "mainclouddb", table_name = "s3product", transformation_ctx = "datasource0")

## @type: ApplyMapping
## @args: [mapping = [("cost", "long", "value", "int"), ("id", "string", "product_id", "string")], transformation_ctx = "applymapping1"]
## @return: applymapping1
## @inputs: [frame = datasource0]
applymapping1 = ApplyMapping.apply(frame = datasource0, mappings = [("cost", "long", "value", "int"), ("id", "string", "product_id", "string")], transformation_ctx = "applymapping1")

## @type: SelectFields
## @args: [paths = ["product_id", "parameter", "value"], transformation_ctx = "selectfields2"]
## @return: selectfields2
## @inputs: [frame = applymapping1]
selectfields2 = SelectFields.apply(frame = applymapping1, paths = ["product_id", "parameter", "value"], transformation_ctx = "selectfields2")

## @type: ResolveChoice
## @args: [choice = "MATCH_CATALOG", database = "mainclouddb", table_name = "mysqlmaincloud_product_parameter_mapping", transformation_ctx = "resolvechoice3"]
## @return: resolvechoice3
## @inputs: [frame = selectfields2]
resolvechoice3 = ResolveChoice.apply(frame = selectfields2, choice = "MATCH_CATALOG", database = "mainclouddb", table_name = "mysqlmaincloud_product_parameter_mapping", transformation_ctx = "resolvechoice3")

## @type: ResolveChoice
## @args: [choice = "make_cols", transformation_ctx = "resolvechoice4"]
## @return: resolvechoice4
## @inputs: [frame = resolvechoice3]
resolvechoice4 = ResolveChoice.apply(frame = resolvechoice3, choice = "make_cols", transformation_ctx = "resolvechoice4")

## @type: DataSink
## @args: [database = "mainclouddb", table_name = "mysqlmaincloud_product_parameter_mapping", transformation_ctx = "datasink5"]
## @return: datasink5
## @inputs: [frame = resolvechoice4]
datasink5 = glueContext.write_dynamic_frame.from_catalog(frame = resolvechoice4, database = "mainclouddb", table_name = "mysqlmaincloud_product_parameter_mapping", transformation_ctx = "datasink5")

job.commit()
</code>```

Can somebody help me to add this new column to my data frame so that it can be made available in the table?

Thanks

答:
One way to add columns to a dynamicframe directly without converting a spark dataframe in between is to use a Map transformation (note that this is different from ApplyMapping).

So let's assume that your input dynframe (with the data looking like in your example row) is called dyf_in.

You can do something like the following to create 2 separate dynamicframes, one with the cost entries, and another with the data entries:

```<code>from awsglue.gluetypes import _create_dynamic_record
def getCosts(rec):
  return _create_dynamic_record({
    'Product_id':rec['id'],
    'Parameter':'cost',
    'value':rec['cost'
  }
def getDatas(rec):
  return _create_dynamic_record({
    'Product_id':rec['id'],
    'Parameter':'data',
    'value':rec['data']
  }

dyf_costs = Map.apply(frame=dyf_in, f=getCosts, transformation_ctx='dyf_costs')
dyf_datas = Map.apply(frame=dyf_in, f=getDatas, transformation_ctx='dyf_datas')
</code>```

And then you either push those dynamicframes into the same sink, or use something like Join (after adding an extra column in the Map funcs to use as a unique join key, and then dropping it afterwards) to concatenate the two dynamicframes into a single one.

One thing I'm not sure if Glue is able to do (at least with Map) is do this sort of a transpose (which is what you're sort of trying to do?) directly without running through the same dynamicframe twice as my example does.

Glue Databrew seems to have some sort of a transpose function available, but I don't know much about Databrew, and maybe it's not even applicable to your situation, so I won't comment on that further.

Body:
I am very new to AWS Glue. I am working on a small project and the ask is to read a file from S3 bucket, transpose it and load it in a mysql table.  The source data in S3 bucket looks as below

    +----+----+-------+-----+---+--+--------+
    |cost|data|minutes|name |sms|id|category|
    +----+----+-------+-----+---+--+--------+
    |  5 |1000|  200  |prod1|500|p1|service |
    +----+----+-------+-----+---+--+--------+

The target table structure is
Product_id, Parameter, value

I am expecting target table to have following values

p1, cost, 5

P1, data, 1000

I am able to load the target table with ID and Value. But I am not able to populate the parameter column. This column is not present in the input data and I want to populate a string depending on which column value I am populating.

Here is the code I used for cost.

import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job

## @params: [JOB_NAME]
args = getResolvedOptions(sys.argv, ['JOB_NAME'])

sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'], args)

## @type: DataSource
## @args: [database = "mainclouddb", table_name = "s3product", transformation_ctx = "datasource0"]
## @return: datasource0
## @inputs: []
datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "mainclouddb", table_name = "s3product", transformation_ctx = "datasource0")

## @type: ApplyMapping
## @args: [mapping = [("cost", "long", "value", "int"), ("id", "string", "product_id", "string")], transformation_ctx = "applymapping1"]
## @return: applymapping1
## @inputs: [frame = datasource0]
applymapping1 = ApplyMapping.apply(frame = datasource0, mappings = [("cost", "long", "value", "int"), ("id", "string", "product_id", "string")], transformation_ctx = "applymapping1")

## @type: SelectFields
## @args: [paths = ["product_id", "parameter", "value"], transformation_ctx = "selectfields2"]
## @return: selectfields2
## @inputs: [frame = applymapping1]
selectfields2 = SelectFields.apply(frame = applymapping1, paths = ["product_id", "parameter", "value"], transformation_ctx = "selectfields2")

## @type: ResolveChoice
## @args: [choice = "MATCH_CATALOG", database = "mainclouddb", table_name = "mysqlmaincloud_product_parameter_mapping", transformation_ctx = "resolvechoice3"]
## @return: resolvechoice3
## @inputs: [frame = selectfields2]
resolvechoice3 = ResolveChoice.apply(frame = selectfields2, choice = "MATCH_CATALOG", database = "mainclouddb", table_name = "mysqlmaincloud_product_parameter_mapping", transformation_ctx = "resolvechoice3")

## @type: ResolveChoice
## @args: [choice = "make_cols", transformation_ctx = "resolvechoice4"]
## @return: resolvechoice4
## @inputs: [frame = resolvechoice3]
resolvechoice4 = ResolveChoice.apply(frame = resolvechoice3, choice = "make_cols", transformation_ctx = "resolvechoice4")

## @type: DataSink
## @args: [database = "mainclouddb", table_name = "mysqlmaincloud_product_parameter_mapping", transformation_ctx = "datasink5"]
## @return: datasink5
## @inputs: [frame = resolvechoice4]
datasink5 = glueContext.write_dynamic_frame.from_catalog(frame = resolvechoice4, database = "mainclouddb", table_name = "mysqlmaincloud_product_parameter_mapping", transformation_ctx = "datasink5")

job.commit()

Can somebody help me to add this new column to my data frame so that it can be made available in the table?

Thanks

Body:
One way to add columns to a dynamicframe directly without converting a spark dataframe in between is to use a Map transformation (note that this is different from ApplyMapping).

So let's assume that your input dynframe (with the data looking like in your example row) is called dyf_in.

You can do something like the following to create 2 separate dynamicframes, one with the cost entries, and another with the data entries:

from awsglue.gluetypes import _create_dynamic_record
def getCosts(rec):
  return _create_dynamic_record({
    'Product_id':rec['id'],
    'Parameter':'cost',
    'value':rec['cost'
  }
def getDatas(rec):
  return _create_dynamic_record({
    'Product_id':rec['id'],
    'Parameter':'data',
    'value':rec['data']
  }

dyf_costs = Map.apply(frame=dyf_in, f=getCosts, transformation_ctx='dyf_costs')
dyf_datas = Map.apply(frame=dyf_in, f=getDatas, transformation_ctx='dyf_datas')

And then you either push those dynamicframes into the same sink, or use something like Join (after adding an extra column in the Map funcs to use as a unique join key, and then dropping it afterwards) to concatenate the two dynamicframes into a single one.

One thing I'm not sure if Glue is able to do (at least with Map) is do this sort of a transpose (which is what you're sort of trying to do?) directly without running through the same dynamicframe twice as my example does.

Glue Databrew seems to have some sort of a transpose function available, but I don't know much about Databrew, and maybe it's not even applicable to your situation, so I won't comment on that further.


问:
Flutter : I want to share title and main_img(dynamic data) when i click share icon using whats app and gmail?
eg :- details about the question ........................................................................................................................................................................................................................................................................ I want to share image and title using whatsapp and gmail. I tried with   url_launcher: ^5.4.2 and   share: ^0.5.3 but not working . when i click share icon to share title and image nothing happened. anyone help me. below i've mentioned the details page code please find and check that.

Deatils Page :

```<code> import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:odia_rasiphala/HomePage.dart';
import 'dart:convert';
import 'package:esys_flutter_share/esys_flutter_share.dart';
import 'package:launch_review/launch_review.dart';
import 'package:share/share.dart';

class DetailsPage extends StatelessWidget {
  const DetailsPage(
      {Key? key,
      required this.title,
      required this.main_img,
      required this.eng_title,
      required this.content})
      : super(key: key);

  // Declare a field that holds the strings passed to this class.
  final String title;
  final String main_img;
  final String content;
  final String eng_title;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async => false,
        child: new Scaffold(
          appBar: new AppBar(
            title: new Text('ଆଜିର ରାଶିଫଳ'),
            leading: new IconButton(
              icon: new Icon(Icons.arrow_back_outlined),
              onPressed: () => Navigator.pushReplacement(context,
                  new MaterialPageRoute(builder: (context) => HomePage())),
            ),
            actions: [
              IconButton(
                onPressed: () async {

                  ;
                },
                icon: Icon(Icons.share),
              ),
            ],
          ),
          body: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Image.network(
                main_img,
                width: 200.0,
                height: 200.0,
              ),

              Text(title, style: TextStyle(color: Colors.black, fontSize: 19)),
              Text(eng_title,
                  style: TextStyle(color: Colors.black, fontSize: 19)),
              Padding(padding: EdgeInsets.only(top: 20.0)),

              Text("( " + "10 Feb 2022" + " )",
                  style: TextStyle(color: Colors.grey, fontSize: 19)),
              // Padding(padding: EdgeInsets.only(top: 30.0)),

              Padding(
                  padding: const EdgeInsets.only(
                    left: 30.0,
                    right: 30.0,
                    top: 15.0,
                  ),
                  child: Text(
                    content,
                    style: TextStyle(color: Colors.black, fontSize: 17),
                    textAlign: TextAlign.justify,
                  )),

              GestureDetector(
                onTap: () {

                },
                child: Container(
                    width: 300.00,
                    height: 150.00,
                    child: Image.network(
                      "https://lh3.googleusercontent.com/-R7wqNDfZ7H4/YgTuUsboyKI/AAAAAAAAAlQ/6UpZ7orQPdgLBkzwZeHmPN0V2z-tR38rgCNcBGAsYHQ/s0/wayindia.png?authuser=0",
                    )),
              )

            ],
          ),
        ));
  }
}
</code>```

答: Try using one of the premade plugin dependencies listed below, the share package is nor deprecated. You could either use share_plus or flutter_share

Body:
eg :- details about the question ........................................................................................................................................................................................................................................................................ I want to share image and title using whatsapp and gmail. I tried with   url_launcher: ^5.4.2 and   share: ^0.5.3 but not working . when i click share icon to share title and image nothing happened. anyone help me. below i've mentioned the details page code please find and check that.

Deatils Page :

 import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:odia_rasiphala/HomePage.dart';
import 'dart:convert';
import 'package:esys_flutter_share/esys_flutter_share.dart';
import 'package:launch_review/launch_review.dart';
import 'package:share/share.dart';

class DetailsPage extends StatelessWidget {
  const DetailsPage(
      {Key? key,
      required this.title,
      required this.main_img,
      required this.eng_title,
      required this.content})
      : super(key: key);

  // Declare a field that holds the strings passed to this class.
  final String title;
  final String main_img;
  final String content;
  final String eng_title;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async => false,
        child: new Scaffold(
          appBar: new AppBar(
            title: new Text('ଆଜିର ରାଶିଫଳ'),
            leading: new IconButton(
              icon: new Icon(Icons.arrow_back_outlined),
              onPressed: () => Navigator.pushReplacement(context,
                  new MaterialPageRoute(builder: (context) => HomePage())),
            ),
            actions: [
              IconButton(
                onPressed: () async {

                  ;
                },
                icon: Icon(Icons.share),
              ),
            ],
          ),
          body: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Image.network(
                main_img,
                width: 200.0,
                height: 200.0,
              ),

              Text(title, style: TextStyle(color: Colors.black, fontSize: 19)),
              Text(eng_title,
                  style: TextStyle(color: Colors.black, fontSize: 19)),
              Padding(padding: EdgeInsets.only(top: 20.0)),

              Text("( " + "10 Feb 2022" + " )",
                  style: TextStyle(color: Colors.grey, fontSize: 19)),
              // Padding(padding: EdgeInsets.only(top: 30.0)),

              Padding(
                  padding: const EdgeInsets.only(
                    left: 30.0,
                    right: 30.0,
                    top: 15.0,
                  ),
                  child: Text(
                    content,
                    style: TextStyle(color: Colors.black, fontSize: 17),
                    textAlign: TextAlign.justify,
                  )),

              GestureDetector(
                onTap: () {

                },
                child: Container(
                    width: 300.00,
                    height: 150.00,
                    child: Image.network(
                      "https://lh3.googleusercontent.com/-R7wqNDfZ7H4/YgTuUsboyKI/AAAAAAAAAlQ/6UpZ7orQPdgLBkzwZeHmPN0V2z-tR38rgCNcBGAsYHQ/s0/wayindia.png?authuser=0",
                    )),
              )

            ],
          ),
        ));
  }
}


问:
With TMS TDBAdvGrid, how to color lines with different colors depending on cell values?
All is in the title.
How can we also make an officehint customisable for each row. Mean when mousemove on a row, display the information of this record (from a db query).

Thanks

答:
You can color individual cells using the CellProperties property of the grid. You can use this to color an entire row:

```<code>var
  RowIndex: Integer;
  ColIndex: Integer;

with MyDBAdvGrid do
begin
  // you choose the row index; you may want to iterate all rows to
  // color each of them
  RowIndex := 2;
  // now iterate all (non-fixed, visible) cells in the row and color each cell
  for ColIndex := FixedCols to ColCount - 1 do
  begin
    CellProperties[ColIndex, RowIndex].BrushColor := clYellow;
    CellProperties[ColIndex, RowIndex].FontColor := clGreen;
  end;
end;
</code>```

To fill your office hint with record data I would suggest updating it when the user moves the mouse. Use the MouseToCell function to get row and column under the mouse, then use MyDBAdvGrid.AllCells[ColIndex, RowIndex] to access the cell content.

ContentLicense: CC BY-SA 3.0

Body:
You can color individual cells using the CellProperties property of the grid. You can use this to color an entire row:

var
  RowIndex: Integer;
  ColIndex: Integer;

with MyDBAdvGrid do
begin
  // you choose the row index; you may want to iterate all rows to
  // color each of them
  RowIndex := 2;
  // now iterate all (non-fixed, visible) cells in the row and color each cell
  for ColIndex := FixedCols to ColCount - 1 do
  begin
    CellProperties[ColIndex, RowIndex].BrushColor := clYellow;
    CellProperties[ColIndex, RowIndex].FontColor := clGreen;
  end;
end;

To fill your office hint with record data I would suggest updating it when the user moves the mouse. Use the MouseToCell function to get row and column under the mouse, then use MyDBAdvGrid.AllCells[ColIndex, RowIndex] to access the cell content.


问:
How to create this chart in R or ggplot
Below is the code to create the data frame.

```<code>df <- data.frame (ID  = c('C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9','C10', 'C11', 'C12','C13', 'C14'),
                  A = c(1, 1, 2, 2, 2, 1, 1, 1, 2, 1, 1, 2, 2, 2),
                  B = c(3, 3, 1, 1, 1, 1, 1, 2, 3, 3, 2, 2, 2, 2)
                  )
</code>```

Code to create the Category column:

```<code>df$Cat <- ifelse(df$A == 2 & df$B == 2, 'MID',
                 ifelse(df$A == 2 & df$B == 1, 'GONE',
                        ifelse(df$A == 1 & df$B == 1, 'GONE',
                               ifelse(df$A == 1 & df$B == 2, 'GONE',
                                      ifelse(df$A == 2 |df$A == 1 & df$B == 3, 'UP',

                               'NO')))))
</code>```

The chart I need to create:

How can I create the chart I want from the data above? I have tried using Treemaps for this but I don't think that will work because it only allows comparing quantities by size in a fixed space. So what can be used? Any help will be greatly appreciate

答:
What you need is geom_raster.

To label the tiles as in your question, I would create an extra dataframe called df_annotate with all the aes specifies in that dataframe. In this case, you can control where the label appears on the graph (just set different A and B values as you like).

Here I set the values of A and B so that the labels appears at the position similar to your drawing. Remember to use data = df_annotate in the geom_text().

Prepare df_annotate for geom_text

```<code>library(tidyverse)

df_annotate <- df %>% group_by(Cat) %>%
  summarize(sum_Cat = n()) %>%
  mutate(sum_Cat_number = paste(sum_Cat, Cat),
         A = c(1, 2, 1.5),
         B = c(2, 2, 3))
</code>```

ggplot

```<code>df %>%
  ggplot(aes(B, A, fill = Cat)) +
  geom_raster() +
  ylim(c(0.5, 3)) +
  geom_text(data = df_annotate, aes(B, A, label = sum_Cat_number), inherit.aes = F)
</code>```

Title: How to create this chart in R or ggplot

Body:
Below is the code to create the data frame.

df <- data.frame (ID  = c('C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9','C10', 'C11', 'C12','C13', 'C14'),
                  A = c(1, 1, 2, 2, 2, 1, 1, 1, 2, 1, 1, 2, 2, 2),
                  B = c(3, 3, 1, 1, 1, 1, 1, 2, 3, 3, 2, 2, 2, 2)
                  )

Code to create the Category column:

df$Cat <- ifelse(df$A == 2 & df$B == 2, 'MID',
                 ifelse(df$A == 2 & df$B == 1, 'GONE',
                        ifelse(df$A == 1 & df$B == 1, 'GONE',
                               ifelse(df$A == 1 & df$B == 2, 'GONE',
                                      ifelse(df$A == 2 |df$A == 1 & df$B == 3, 'UP',

                               'NO')))))

The chart I need to create:

How can I create the chart I want from the data above? I have tried using Treemaps for this but I don't think that will work because it only allows comparing quantities by size in a fixed space. So what can be used? Any help will be greatly appreciate

Body:
What you need is geom_raster.

To label the tiles as in your question, I would create an extra dataframe called df_annotate with all the aes specifies in that dataframe. In this case, you can control where the label appears on the graph (just set different A and B values as you like).

Here I set the values of A and B so that the labels appears at the position similar to your drawing. Remember to use data = df_annotate in the geom_text().

Prepare df_annotate for geom_text

library(tidyverse)

df_annotate <- df %>% group_by(Cat) %>%
  summarize(sum_Cat = n()) %>%
  mutate(sum_Cat_number = paste(sum_Cat, Cat),
         A = c(1, 2, 1.5),
         B = c(2, 2, 3))

ggplot

df %>%
  ggplot(aes(B, A, fill = Cat)) +
  geom_raster() +
  ylim(c(0.5, 3)) +
  geom_text(data = df_annotate, aes(B, A, label = sum_Cat_number), inherit.aes = F)


问:
backtick " ` " in request body in bash shell script while calling CURL
I'm writing CURL COMMAND

HTTP_Method : POST

API : api/databricks/query

```<code>Request body  {"query":" GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB` to `userID` " }
</code>```

The query,I have execute using POSTMAN it's working

```<code>curl --location --request POST 'https://<databick_workspace-url>/api/sql/databricks/query' \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB-NAME` to `userID` " }
# Working, And user can access DB
</code>```

I believe the problem is with backticks,

```<code>// Function
function grantReadAccess() {
  local path="/api/sql/databricks/query"
  local url="https://<databricks-workspace-url>/${path}"
  printf 'curl %q' "${url}"
  local DATABASENAME="DB-NAME"
  local userID="userID"

  local content="GRANT SELECT,READ_METADATA,USAGE on DATABASE \`${DATABASENAME}\` to \`${userID}\` "
  echo "------------$content"
  // OUTPUT Here : GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB-NAME` to `userID`
  // Same I have to pass in request body
  local permissionToGroup=$(
    curl -X POST "${url}" -H "Authorization: Bearer ${authtoken}" -H "Content-Type: application/json" -d '{ "query": \"'"${content}"'\" } ')
    //Required in this {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB` to `userID` " }

  echo "${permissionToGroup}"
}

// Tried In Postman insted of using backtick
 1. Single Quote "'" {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE 'DB' to 'userID' "
 2. Blacket "(" {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE (DB) to (userID) "

Error

{
  "query": "grant SELECT, READ_METADATA, USAGE on DATABASE 'DB' to 'useID' ",
    "data": null,
    "error": " org.apache.spark.sql.catalyst.parser.ParseException: \nOperation not allowed: grant(line 1, pos 0)\n\n== SQL ==\ngrant SELECT, READ_METADATA, USAGE on DATABASE 'DB"
}

</code>```

The above function is not working,

答:
Always use a tool that understands JSON when you need to build JSON. In this context, the widely-accepted tool is for the job is jq.

```<code>curl -X POST "${url}" \
  -H "Authorization: Bearer ${authtoken}" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg content "$content" '{"query": $content}')"
</code>```

Body:
I'm writing CURL COMMAND

HTTP_Method : POST

API : api/databricks/query

Request body  {"query":" GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB` to `userID` " }

The query,I have execute using POSTMAN it's working

curl --location --request POST 'https://<databick_workspace-url>/api/sql/databricks/query' \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB-NAME` to `userID` " }
# Working, And user can access DB

I believe the problem is with backticks,

// Function
function grantReadAccess() {
  local path="/api/sql/databricks/query"
  local url="https://<databricks-workspace-url>/${path}"
  printf 'curl %q' "${url}"
  local DATABASENAME="DB-NAME"
  local userID="userID"

  local content="GRANT SELECT,READ_METADATA,USAGE on DATABASE \`${DATABASENAME}\` to \`${userID}\` "
  echo "------------$content"
  // OUTPUT Here : GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB-NAME` to `userID`
  // Same I have to pass in request body
  local permissionToGroup=$(
    curl -X POST "${url}" -H "Authorization: Bearer ${authtoken}" -H "Content-Type: application/json" -d '{ "query": \"'"${content}"'\" } ')
    //Required in this {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB` to `userID` " }

  echo "${permissionToGroup}"
}

// Tried In Postman insted of using backtick
 1. Single Quote "'" {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE 'DB' to 'userID' "
 2. Blacket "(" {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE (DB) to (userID) "

Error

{
  "query": "grant SELECT, READ_METADATA, USAGE on DATABASE 'DB' to 'useID' ",
    "data": null,
    "error": " org.apache.spark.sql.catalyst.parser.ParseException: \nOperation not allowed: grant(line 1, pos 0)\n\n== SQL ==\ngrant SELECT, READ_METADATA, USAGE on DATABASE 'DB"
}

The above function is not working,

Body:
Always use a tool that understands JSON when you need to build JSON. In this context, the widely-accepted tool is for the job is jq.

curl -X POST "${url}" \
  -H "Authorization: Bearer ${authtoken}" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg content "$content" '{"query": $content}')"


问:
imageSource property is unavailable on Squish IDE?
I would like to know if an image is green or red in a button I test with Squish.

My problem is that the imageSource property of my Qt object button is blank in Squish IDE so I don't know if it displays a green image or a red image.

Anyone knows how to fix this ?

It seems that if I don't have this property I can't test the color of my button with Squish since there isn't any other information in my Qt object to find out the color.

答:
I managed to pull it off !

I looked in SquishIDE and found the image which was in a child object in the Application Objects View. This object was unreachable with the picker, that's why it was hard to find it.
Then I just had to access the object with its real name.


问:
PySpark : How to aggregate on a column with count of the different
I want to aggregate on the Identifiant column with count of different state and represent all the state.

Identifiant
state

ID01
NY

ID02
NY

ID01
CA

ID03
CA

ID01
CA

ID03
NY

ID01
NY

ID01
CA

ID01
NY

I'd like to obtain this dataset:

Identifiant
NY
CA

ID01
3
3

ID02
1
0

ID03
1
1

答:
Group by Identifiant and pivot State column:

```<code>from pyspark.sql import functions as F

result = (df.groupBy("Identifiant")
          .pivot("State")
          .count().na.fill(0)
          )

result.show()
#+-----------+---+---+
#|Identifiant| CA| NY|
#+-----------+---+---+
#|       ID03|  1|  1|
#|       ID01|  3|  3|
#|       ID02|  0|  1|
#+-----------+---+---+
</code>```

Body:
Group by Identifiant and pivot State column:

from pyspark.sql import functions as F

result = (df.groupBy("Identifiant")
          .pivot("State")
          .count().na.fill(0)
          )

result.show()
#+-----------+---+---+
#|Identifiant| CA| NY|
#+-----------+---+---+
#|       ID03|  1|  1|
#|       ID01|  3|  3|
#|       ID02|  0|  1|
#+-----------+---+---+


问:
Angular FormGroup validator doesn't preserve setError on FormControl
I have a form group to manage time of day as follows:

```<code>      time: new FormGroup({
        date: new FormControl(new Date()),
        startTime: new FormControl(null),
        startTimeMeridian: new FormControl(MERIDIAN.PM),
        stopTime: new FormControl(null),
        stopTimeMeridian: new FormControl(MERIDIAN.PM)
      }, [MyCustomValidators.futureDateTime()]),
</code>```

Inside my futureDateTime() validator on the group I do some logic to validate the formGroup and if it's invalid I do the following:

```<code>control.get('startTime').setErrors(MY_CUSTOM_ERROR) // MY_CUSTOM_ERROR is a valid error object
</code>```

or the same except on control.get('stopTime'). This works the FIRST time and appropriately sets the error on the FormControls when they first enter the invalid state. The second time though, they have empty error objects.

I set debug points to narrow down what's happening and my FormGroup validator is appropriately setting the error on the control again, but it looks like something within Angular's code is clearing the error object.

How can I set error objects on a control from a FormGroup validator?

EDIT:

I'm not sure what was removing my error, but I was able to change my error object structure to an Array of errors, and then set them on the FormGroup instead.

Instead of the formControls startTime or stopTime having errors, I now set them on the FormGroup and my UI will check for any relevant feedback inside the FormGroup's errors.

答:
I found this solution from a different question on github:
github solution to how to setErrors in FormGroups

but fromgroup.valid didn't take this error into account in my code so I manually checked for it with a boolean parameter, in this example:

pseudo-code:

```<code>const timeError: boolean = "startTime before new Date()"
const formStartTimeControl = this.time.controls.startTime;
if (timeError) {
    setTimeout(() => {
        formStartTimeControl.markAsDirty();
        formStartTimeControl.markAsTouched();
        formStartTimeControl.setErrors(MY_CUSTOM_ERROR);
    }, 1);
} else {
    setTimeout(() => {
        formStartTimeControl.markAsDirty();
        formStartTimeControl.markAsTouched();
        formStartTimeControl.setErrors(null);
    }, 1);
}
// [...] other code
if(formGroup.valid && !timeError){
    // continue with submitting code
}
</code>```

but that and that you have to set a timeout for the code to work makes it look like a dodgy solution to me, would be interesting to see if there is a better one out there.

Body:
I have a form group to manage time of day as follows:

      time: new FormGroup({
        date: new FormControl(new Date()),
        startTime: new FormControl(null),
        startTimeMeridian: new FormControl(MERIDIAN.PM),
        stopTime: new FormControl(null),
        stopTimeMeridian: new FormControl(MERIDIAN.PM)
      }, [MyCustomValidators.futureDateTime()]),

Inside my futureDateTime() validator on the group I do some logic to validate the formGroup and if it's invalid I do the following:

control.get('startTime').setErrors(MY_CUSTOM_ERROR) // MY_CUSTOM_ERROR is a valid error object

or the same except on control.get('stopTime'). This works the FIRST time and appropriately sets the error on the FormControls when they first enter the invalid state. The second time though, they have empty error objects.

I set debug points to narrow down what's happening and my FormGroup validator is appropriately setting the error on the control again, but it looks like something within Angular's code is clearing the error object.

How can I set error objects on a control from a FormGroup validator?

EDIT:

I'm not sure what was removing my error, but I was able to change my error object structure to an Array of errors, and then set them on the FormGroup instead.

Instead of the formControls startTime or stopTime having errors, I now set them on the FormGroup and my UI will check for any relevant feedback inside the FormGroup's errors.

Body:
I found this solution from a different question on github:
github solution to how to setErrors in FormGroups

but fromgroup.valid didn't take this error into account in my code so I manually checked for it with a boolean parameter, in this example:

pseudo-code:

const timeError: boolean = "startTime before new Date()"
const formStartTimeControl = this.time.controls.startTime;
if (timeError) {
    setTimeout(() => {
        formStartTimeControl.markAsDirty();
        formStartTimeControl.markAsTouched();
        formStartTimeControl.setErrors(MY_CUSTOM_ERROR);
    }, 1);
} else {
    setTimeout(() => {
        formStartTimeControl.markAsDirty();
        formStartTimeControl.markAsTouched();
        formStartTimeControl.setErrors(null);
    }, 1);
}
// [...] other code
if(formGroup.valid && !timeError){
    // continue with submitting code
}

but that and that you have to set a timeout for the code to work makes it look like a dodgy solution to me, would be interesting to see if there is a better one out there.


问:
Bloc listener not invoked without a delay
I have defined the following cubit.

@injectable
class AuthCubit extends Cubit<AuthState> {
  final IAuthService _authService;

  AuthCubit(this._authService) : super(const AuthState.initial());

  void authCheck() {
    emit(_authService.signedInUser.fold(
      () => AuthState.unauthenticated(none()),
      (user) => AuthState.authenticated(user),
    ));
  }
}
```
<p>But the BlocListener which listens to this bloc is not getting invoked even after <code>emit</code> is called. But everything works as expected when I add a zero delay before the emit call.</p>
<pre class="lang-dart prettyprint-override"><code>Future<void> authCheck() async {
  await Future.delayed(Duration.zero);
  emit(_authService.signedInUser.fold(
    () => AuthState.unauthenticated(none()),
    (user) => AuthState.authenticated(user),
  ));
}
</code>```

I tried out this delay because for other events which made some backend call (with some delay) emit worked perfectly. But I'm pretty sure this is not how it should work. Am I missing something here?

EDIT:
Adding the SplashPage widget code which uses BlocListener.

class SplashPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocListener<AuthCubit, AuthState>(
      listener: (context, state) {
        print(state);
      },
      child: Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      ),
    );
  }
}
```
<p>Place where authCheck() is called,</p>
<pre class="lang-dart prettyprint-override"><code>class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider<AuthCubit>(
          create: (_) => getIt<AuthCubit>()..authCheck(),
        ),
      ],
      child: MaterialApp(
        ....
      ),
    );
  }
}
</code>```

and the AuthState is a freezed union

@freezed
abstract class AuthState with _$AuthState {
  const factory AuthState.initial() = _Initial;
  const factory AuthState.authenticated(User user) = _Authenticated;
  const factory AuthState.unauthenticated(Option<AuthFailure> failure) = _Unauthenticated;
  const factory AuthState.authInProgress() = _AuthInProgress;
}

```

Also, when I implemented a bloc (instead of Cubit) with the same functionality, everything worked as expected.

答:
For me, the delay does not work perfectly. So I found this solution, maybe help someone:

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addPostFrameCallback((_) async {
      await myCubit.doSomethingFun();
    });
  }
```

And @Pieter is right, listener only be invoked when the widget is built.

Body:
I have defined the following cubit.

@injectable
class AuthCubit extends Cubit<AuthState> {
  final IAuthService _authService;

  AuthCubit(this._authService) : super(const AuthState.initial());

  void authCheck() {
    emit(_authService.signedInUser.fold(
      () => AuthState.unauthenticated(none()),
      (user) => AuthState.authenticated(user),
    ));
  }
}

But the BlocListener which listens to this bloc is not getting invoked even after emit is called. But everything works as expected when I add a zero delay before the emit call.

Future<void> authCheck() async {
  await Future.delayed(Duration.zero);
  emit(_authService.signedInUser.fold(
    () => AuthState.unauthenticated(none()),
    (user) => AuthState.authenticated(user),
  ));
}

I tried out this delay because for other events which made some backend call (with some delay) emit worked perfectly. But I'm pretty sure this is not how it should work. Am I missing something here?

EDIT:
Adding the SplashPage widget code which uses BlocListener.

class SplashPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocListener<AuthCubit, AuthState>(
      listener: (context, state) {
        print(state);
      },
      child: Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      ),
    );
  }
}

Place where authCheck() is called,

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider<AuthCubit>(
          create: (_) => getIt<AuthCubit>()..authCheck(),
        ),
      ],
      child: MaterialApp(
        ....
      ),
    );
  }
}

and the AuthState is a freezed union

@freezed
abstract class AuthState with _$AuthState {
  const factory AuthState.initial() = _Initial;
  const factory AuthState.authenticated(User user) = _Authenticated;
  const factory AuthState.unauthenticated(Option<AuthFailure> failure) = _Unauthenticated;
  const factory AuthState.authInProgress() = _AuthInProgress;
}

Also, when I implemented a bloc (instead of Cubit) with the same functionality, everything worked as expected.

Body:
For me, the delay does not work perfectly. So I found this solution, maybe help someone:

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addPostFrameCallback((_) async {
      await myCubit.doSomethingFun();
    });
  }

And @Pieter is right, listener only be invoked when the widget is built.


问:
Making new list of Object Attribute then calling each attribute with a incrementing int variable
This might be a stupid question but I am new to C# coding and object-oriented programming. I'm trying to assign strings to a Class attribute while using an incrementing variable called "x".
But after increment x once, C# tells me "System.ArgumentOutOfRangeException: 'Index was out of range".

I just not getting it, it should be able to create a lot of clients with this.

```<code>        int x = 0;
        private void buttonSubmit_Click(object sender, EventArgs e)
        {

            List<Client> newClient = new List<Client>();  //creates a variable called "newClient" which is a list of Client object
            newClient.Add(new Client());                  // calling a constructor to create a Client Object
            newClient[x].Name = textBoxName.Text;         //newclient[0]
            newClient[x].Address = textBoxAddress.Text;
            newClient[x].Birthday = textBoxBirthDay.Text;
            newClient[x].Gender = textBoxGender.Text;
            newClient[x].PhoneNumber = textBoxPhoneNumber.Text;
            newClient[x].Income = textBoxIncome.Text;

            string Output = newClient[x].Name + " " + newClient[x].Address + " " + newClient[x].birthday + " " + newClient[x].Gender + " " + newClient[x].PhoneNumber + " " + newClient[x].Income;
            labelOutput.Text += Output + "\n";
            x++;
        }
</code>```

答:
I edit your function to works as you want !!!!

```<code>    List<Client> newClient = new List<Client>();  //creates a variable called "newClient" which is a list of Client object
    private void buttonSubmit_Click(object sender, EventArgs e)
    {

        var tobeInsertedClient = new Client()
        {
            Name = textBoxName.Text,
            Address = textBoxAddress.Text,
            Birthday = textBoxBirthDay.Text,
            Gender = textBoxGender.Text,
            PhoneNumber = textBoxPhoneNumber.Text,
            Income = textBoxIncome.Text
        };
        newClient.Add(tobeInsertedClient);

        string Output = tobeInsertedClient.Name + " " + tobeInsertedClient.Address + " " + tobeInsertedClient.birthday + " " + tobeInsertedClient.Gender + " " + tobeInsertedClient.PhoneNumber + " " + tobeInsertedClient.Income;
        labelOutput.Text += Output + "\n";
    }
</code>```

You can Initialize an object with brackets {} and then you can use it in the scope you want :D

Body:
This might be a stupid question but I am new to C# coding and object-oriented programming. I'm trying to assign strings to a Class attribute while using an incrementing variable called "x".
But after increment x once, C# tells me "System.ArgumentOutOfRangeException: 'Index was out of range".

I just not getting it, it should be able to create a lot of clients with this.

        int x = 0;
        private void buttonSubmit_Click(object sender, EventArgs e)
        {

            List<Client> newClient = new List<Client>();  //creates a variable called "newClient" which is a list of Client object
            newClient.Add(new Client());                  // calling a constructor to create a Client Object
            newClient[x].Name = textBoxName.Text;         //newclient[0]
            newClient[x].Address = textBoxAddress.Text;
            newClient[x].Birthday = textBoxBirthDay.Text;
            newClient[x].Gender = textBoxGender.Text;
            newClient[x].PhoneNumber = textBoxPhoneNumber.Text;
            newClient[x].Income = textBoxIncome.Text;

            string Output = newClient[x].Name + " " + newClient[x].Address + " " + newClient[x].birthday + " " + newClient[x].Gender + " " + newClient[x].PhoneNumber + " " + newClient[x].Income;
            labelOutput.Text += Output + "\n";
            x++;
        }

Body:
I edit your function to works as you want !!!!

    List<Client> newClient = new List<Client>();  //creates a variable called "newClient" which is a list of Client object
    private void buttonSubmit_Click(object sender, EventArgs e)
    {

        var tobeInsertedClient = new Client()
        {
            Name = textBoxName.Text,
            Address = textBoxAddress.Text,
            Birthday = textBoxBirthDay.Text,
            Gender = textBoxGender.Text,
            PhoneNumber = textBoxPhoneNumber.Text,
            Income = textBoxIncome.Text
        };
        newClient.Add(tobeInsertedClient);

        string Output = tobeInsertedClient.Name + " " + tobeInsertedClient.Address + " " + tobeInsertedClient.birthday + " " + tobeInsertedClient.Gender + " " + tobeInsertedClient.PhoneNumber + " " + tobeInsertedClient.Income;
        labelOutput.Text += Output + "\n";
    }

You can Initialize an object with brackets {} and then you can use it in the scope you want :D


问:
Java multilevel menu structure
I'm building a web application in Java (Tapestry 5).
I want to create a multilevel menu where I can show the root elements for example at the top of my page and the children of the selected on the left.

To implement this I was thinking to use a tree structure like this:

```<code>public class SiteMap {

private List<MenuItem> root;

public class MenuItem {

    private String pageFileName;
    private String pageNavigationName;

    private List<MenuItem> children;
    private MenuItem parent;

    public MenuItem(String pageFileName, String pageNavigationName, MenuItem parent) {
        this.pageFileName = pageFileName;
        this.pageNavigationName = pageNavigationName;
        this.parent = parent;
    }

    public String getPageFileName() {
        return pageFileName;
    }

    public String getPageNavigationName() {
        return pageNavigationName;
    }

    public List<MenuItem> getChildren() {
        return children;
    }

    public MenuItem getParent() {
        return this.parent;
    }
}
}
</code>```

Now what if I want to build a menu based on the children of 1 parent item (only have the pageFileName - String) somewhere in the tree. Ill have to traverse recursively through the tree to find this parent item based on the pageFileName (String) , which seems not a good way.

Is this (using a tree structure) the right way to implement this? Or is there a better option?
Any thoughts and hints are appreciated!

Thanks in advance!

Nathan

答:
Why not use MenuItem for both parent and children and keep a reference from each child to its parent?</p>

```<code>List<MenuItem> children; // empty/null for leaf nodes
MenuItem parent; // null for root nodes
</code>```

Title: Java multilevel menu structure

Body:
I'm building a web application in Java (Tapestry 5).
I want to create a multilevel menu where I can show the root elements for example at the top of my page and the children of the selected on the left.

To implement this I was thinking to use a tree structure like this:

public class SiteMap {

private List<MenuItem> root;

public class MenuItem {

    private String pageFileName;
    private String pageNavigationName;

    private List<MenuItem> children;
    private MenuItem parent;

    public MenuItem(String pageFileName, String pageNavigationName, MenuItem parent) {
        this.pageFileName = pageFileName;
        this.pageNavigationName = pageNavigationName;
        this.parent = parent;
    }

    public String getPageFileName() {
        return pageFileName;
    }

    public String getPageNavigationName() {
        return pageNavigationName;
    }

    public List<MenuItem> getChildren() {
        return children;
    }

    public MenuItem getParent() {
        return this.parent;
    }
}
}

Now what if I want to build a menu based on the children of 1 parent item (only have the pageFileName - String) somewhere in the tree. Ill have to traverse recursively through the tree to find this parent item based on the pageFileName (String) , which seems not a good way.

Is this (using a tree structure) the right way to implement this? Or is there a better option?
Any thoughts and hints are appreciated!

Thanks in advance!

Nathan

Body:
Why not use MenuItem for both parent and children and keep a reference from each child to its parent?

List<MenuItem> children; // empty/null for leaf nodes
MenuItem parent; // null for root nodes


问:
Android popup menu customize menu item (padding, text size etch.)
I am implementing a popup menu for my android application. I want to be able to customize the items of the menu and change the default values (for the item padding, margin, padding between item icons etch.). Currently i am able to change only the text color and size of each item with the properties:

```<code><item name="android:textColor">@color/white</item>
<item name="android:textSize">20sp</item>
<item name="android:textStyle">bold</item>
</code>```

which are set within :

```<code><style name="PopupMenu" parent="@android:style/Widget.PopupMenu">
</code>```

How is this possible, which attributes i need to set in the styling of the menu?

答:
Hello, You can create customized layout specifically for the popup and you can give each items different margin padding..

Check out below code.

```<code> private fun createPopUp() {
        val popUpView: View = layoutInflater.inflate(R.layout.popup, null)
       val  mpopup = PopupWindow(
            popUpView, ConstraintLayout.LayoutParams.WRAP_CONTENT,
            ConstraintLayout.LayoutParams.WRAP_CONTENT, true
       )

        popUpView.close.setOnClickListener{
            mpopup.dismiss()
        }
    }
</code>```

Here is the code for the popup layout you can create a separate XML for that and add layout and items into that with each attributes available within.

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:orientation="vertical"
    android:padding="@dimen/_16sdp">

    <Button
        android:id="@+id/close"
        android:layout_width="160dp"
        android:layout_height="60dp"
        android:layout_alignParentTop="true"
        android:layout_centerInParent="true"
        android:text="@string/date"
        android:textColor="@color/white" />

</RelativeLayout>
</code>```

Body:
I am implementing a popup menu for my android application. I want to be able to customize the items of the menu and change the default values (for the item padding, margin, padding between item icons etch.). Currently i am able to change only the text color and size of each item with the properties:

<item name="android:textColor">@color/white</item>
<item name="android:textSize">20sp</item>
<item name="android:textStyle">bold</item>

which are set within :

Body:
Hello, You can create customized layout specifically for the popup and you can give each items different margin padding..

Check out below code.

 private fun createPopUp() {
        val popUpView: View = layoutInflater.inflate(R.layout.popup, null)
       val  mpopup = PopupWindow(
            popUpView, ConstraintLayout.LayoutParams.WRAP_CONTENT,
            ConstraintLayout.LayoutParams.WRAP_CONTENT, true
       )

        popUpView.close.setOnClickListener{
            mpopup.dismiss()
        }
    }

Here is the code for the popup layout you can create a separate XML for that and add layout and items into that with each attributes available within.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:orientation="vertical"
    android:padding="@dimen/_16sdp">

    <Button
        android:id="@+id/close"
        android:layout_width="160dp"
        android:layout_height="60dp"
        android:layout_alignParentTop="true"
        android:layout_centerInParent="true"
        android:text="@string/date"
        android:textColor="@color/white" />

</RelativeLayout>


问:
How to disable in flutter stepper the first cancel button
I currently have a stepper that also works perfectly, but I have the question how to disable the back button at the first step, but in the others it should be displayed.

I modified the stepper with the controlsBuilder but i didnt found a solution where i can disable the back button.

Thanks in advance

Here is a small code snippet from my stepper (not fully):

```<code> controlsBuilder: (BuildContext context,
                    {VoidCallback onStepContinue, VoidCallback onStepCancel}) {
                  return Row(
                    children: <Widget>[
                      FlatButton(
                        onPressed: onStepContinue,
                        child: const Text('Weiter',
                            style: TextStyle(color: Colors.white)),
                        color: Colors.blue,
                      ),
                      new Padding(
                        padding: new EdgeInsets.all(10),
                      ),
                      FlatButton(
                        onPressed: onStepCancel,
                        child: const Text(
                          'Zurück',
                          style: TextStyle(color: Colors.white),
                        ),
                        color: Colors.blue,
                      ),
                    ],
                  );
                },

List<Step> steps = [
      Step(
        title: const Text('TEST'),
        isActive: true,
        state: StepState.complete,
        content: Column(children: <Widget>[
          RadioListTile(
            value: 1,
            groupValue: selectedRadioTile,
            title: Text("XX"),
            onChanged: (val) {
              setSelectedRadioTile(val);
            },
            activeColor: Colors.blue,
            selected: true,
          ),
          RadioListTile(
            value: 2,
            groupValue: selectedRadioTile,
            title: Text("XX"),
            onChanged: (val) {
              setSelectedRadioTile(val);
            },
            activeColor: Colors.blue,
            selected: false,
          ),
        ]),
      ),```
```

答:
In Flutter Version: 2.10.0

Just initialize a boolean variable globally

bool hide = true;

Then,

```<code>  controlsBuilder: (BuildContext context, ControlsDetails details) {
          return Row(
            children: <Widget>[
              TextButton(
                onPressed: details.onStepContinue,
                child: Text(hide == true ? '' : 'Confirm'),
              ),
              TextButton(
                onPressed: details.onStepCancel,
                child: Text(hide == true ? '' :'Cancel'),
              ),
            ],
          );
        },
</code>```

it will disappear 'Confirm' as well as 'Cancel' button. If you have no need these actually.

Body:
I currently have a stepper that also works perfectly, but I have the question how to disable the back button at the first step, but in the others it should be displayed.

I modified the stepper with the controlsBuilder but i didnt found a solution where i can disable the back button.

Thanks in advance

Here is a small code snippet from my stepper (not fully):

 controlsBuilder: (BuildContext context,
                    {VoidCallback onStepContinue, VoidCallback onStepCancel}) {
                  return Row(
                    children: <Widget>[
                      FlatButton(
                        onPressed: onStepContinue,
                        child: const Text('Weiter',
                            style: TextStyle(color: Colors.white)),
                        color: Colors.blue,
                      ),
                      new Padding(
                        padding: new EdgeInsets.all(10),
                      ),
                      FlatButton(
                        onPressed: onStepCancel,
                        child: const Text(
                          'Zurück',
                          style: TextStyle(color: Colors.white),
                        ),
                        color: Colors.blue,
                      ),
                    ],
                  );
                },

List<Step> steps = [
      Step(
        title: const Text('TEST'),
        isActive: true,
        state: StepState.complete,
        content: Column(children: <Widget>[
          RadioListTile(
            value: 1,
            groupValue: selectedRadioTile,
            title: Text("XX"),
            onChanged: (val) {
              setSelectedRadioTile(val);
            },
            activeColor: Colors.blue,
            selected: true,
          ),
          RadioListTile(
            value: 2,
            groupValue: selectedRadioTile,
            title: Text("XX"),
            onChanged: (val) {
              setSelectedRadioTile(val);
            },
            activeColor: Colors.blue,
            selected: false,
          ),
        ]),
      ),```

Body:
In Flutter Version: 2.10.0

Just initialize a boolean variable globally

bool hide = true;

Then,

  controlsBuilder: (BuildContext context, ControlsDetails details) {
          return Row(
            children: <Widget>[
              TextButton(
                onPressed: details.onStepContinue,
                child: Text(hide == true ? '' : 'Confirm'),
              ),
              TextButton(
                onPressed: details.onStepCancel,
                child: Text(hide == true ? '' :'Cancel'),
              ),
            ],
          );
        },

it will disappear 'Confirm' as well as 'Cancel' button. If you have no need these actually.


问:
Python progress bar for git clone
Im using GitPython to clone a repo within my program. I figured how to display the the status of the clone with the clone_from command but I want the status to look more like a tqdm progress bar. I tried using the requests library to get the size of the file but I'm still unsure how to implement it. Tried doing something like this below but it's not working. Any help appreciated, thanks.</p>

```<code>url = 'git@github.com:somegithubrepo/repo.git'
r = requests.get(url, stream=True)
total_length = r.headers.get('content-length')

for i in tqdm(range(len(total_length??))):
    git.Git(pathName).clone(url)
</code>```

答:
I know the question seems to mainly focus on using tqdm, however, if one wanted to use alive-progress progress bar, here is a working example that dispatches a progress bar for each step of the cloning process:

from __future__ import annotations

import git
from alive_progress import alive_bar

class GitRemoteProgress(git.RemoteProgress):
    OP_CODES = [
        "BEGIN",
        "CHECKING_OUT",
        "COMPRESSING",
        "COUNTING",
        "END",
        "FINDING_SOURCES",
        "RECEIVING",
        "RESOLVING",
        "WRITING",
    ]
    OP_CODE_MAP = {
        getattr(git.RemoteProgress, _op_code): _op_code for _op_code in OP_CODES
    }

    def __init__(self) -> None:
        super().__init__()
        self.alive_bar_instance = None

    @classmethod
    def get_curr_op(cls, op_code: int) -> str:
        """Get OP name from OP code."""
        # Remove BEGIN- and END-flag and get op name
        op_code_masked = op_code & cls.OP_MASK
        return cls.OP_CODE_MAP.get(op_code_masked, "?").title()

    def update(
        self,
        op_code: int,
        cur_count: str | float,
        max_count: str | float | None = None,
        message: str | None = "",
    ) -> None:
        cur_count = float(cur_count)
        max_count = float(max_count)

        # Start new bar on each BEGIN-flag
        if op_code & self.BEGIN:
            self.curr_op = self.get_curr_op(op_code)
            self._dispatch_bar(title=self.curr_op)

        self.bar(cur_count / max_count)
        self.bar.text(message)

        # End progress monitoring on each END-flag
        if op_code & git.RemoteProgress.END:
            self._destroy_bar()

    def _dispatch_bar(self, title: str | None = "") -> None:
        """Create a new progress bar"""
        self.alive_bar_instance = alive_bar(manual=True, title=title)
        self.bar = self.alive_bar_instance.__enter__()

    def _destroy_bar(self) -> None:
        """Destroy an existing progress bar"""
        self.alive_bar_instance.__exit__(None, None, None)
```
<p>Using it full clone:</p>
<pre class="lang-py prettyprint-override"><code>project_url = "https://github.com/u-boot/u-boot"

print("Cloning Git Repository 'u-boot' ('master' branch)...")
git.Repo.clone_from(
    url=project_url,
    to_path="u-boot",
    progress=GitRemoteProgress(),
)
print("Done.")
</code>```

Using it - shallow clone:

project_url = "https://github.com/u-boot/u-boot"

print("Cloning Git Repository 'u-boot' ('master' branch)...")
git.Repo.clone_from(
    url=project_url,
    to_path="u-boot",
    depth=1,
    progress=GitRemoteProgress(),
)
print("Done.")
```

PS: u-boot repo used due to its large size and therefore followable cloning progress

PPS: The recording uses rich's print, hence the fancy colors :-)

Title: Python progress bar for git clone

Body:
Im using GitPython to clone a repo within my program. I figured how to display the the status of the clone with the clone_from command but I want the status to look more like a tqdm progress bar. I tried using the requests library to get the size of the file but I'm still unsure how to implement it. Tried doing something like this below but it's not working. Any help appreciated, thanks.

url = 'git@github.com:somegithubrepo/repo.git'
r = requests.get(url, stream=True)
total_length = r.headers.get('content-length')

for i in tqdm(range(len(total_length??))):
    git.Git(pathName).clone(url)

Body:
I know the question seems to mainly focus on using tqdm, however, if one wanted to use alive-progress progress bar, here is a working example that dispatches a progress bar for each step of the cloning process:

from __future__ import annotations

import git
from alive_progress import alive_bar

class GitRemoteProgress(git.RemoteProgress):
    OP_CODES = [
        "BEGIN",
        "CHECKING_OUT",
        "COMPRESSING",
        "COUNTING",
        "END",
        "FINDING_SOURCES",
        "RECEIVING",
        "RESOLVING",
        "WRITING",
    ]
    OP_CODE_MAP = {
        getattr(git.RemoteProgress, _op_code): _op_code for _op_code in OP_CODES
    }

    def __init__(self) -> None:
        super().__init__()
        self.alive_bar_instance = None

    @classmethod
    def get_curr_op(cls, op_code: int) -> str:
        """Get OP name from OP code."""
        # Remove BEGIN- and END-flag and get op name
        op_code_masked = op_code & cls.OP_MASK
        return cls.OP_CODE_MAP.get(op_code_masked, "?").title()

    def update(
        self,
        op_code: int,
        cur_count: str | float,
        max_count: str | float | None = None,
        message: str | None = "",
    ) -> None:
        cur_count = float(cur_count)
        max_count = float(max_count)

        # Start new bar on each BEGIN-flag
        if op_code & self.BEGIN:
            self.curr_op = self.get_curr_op(op_code)
            self._dispatch_bar(title=self.curr_op)

        self.bar(cur_count / max_count)
        self.bar.text(message)

        # End progress monitoring on each END-flag
        if op_code & git.RemoteProgress.END:
            self._destroy_bar()

    def _dispatch_bar(self, title: str | None = "") -> None:
        """Create a new progress bar"""
        self.alive_bar_instance = alive_bar(manual=True, title=title)
        self.bar = self.alive_bar_instance.__enter__()

    def _destroy_bar(self) -> None:
        """Destroy an existing progress bar"""
        self.alive_bar_instance.__exit__(None, None, None)

Using it full clone:

project_url = "https://github.com/u-boot/u-boot"

print("Cloning Git Repository 'u-boot' ('master' branch)...")
git.Repo.clone_from(
    url=project_url,
    to_path="u-boot",
    progress=GitRemoteProgress(),
)
print("Done.")

Using it - shallow clone:

project_url = "https://github.com/u-boot/u-boot"

print("Cloning Git Repository 'u-boot' ('master' branch)...")
git.Repo.clone_from(
    url=project_url,
    to_path="u-boot",
    depth=1,
    progress=GitRemoteProgress(),
)
print("Done.")

PS: u-boot repo used due to its large size and therefore followable cloning progress

PPS: The recording uses rich's print, hence the fancy colors :-)


问:
How to mitigate useless React renders when large state is present but only one changes?
I have a search query component. User types query, clicks run and executes it. However, due to how state is organized, it causes excessive re renders. Following is a simplification of it. This organization of the code feels natural to me. QueryEditor is normally a complex editor, hence it stores its own value. Similar for query results. I got the value of it on each change, updated the query in the parent component. However this causes all HTML elements in the parent component to re-render even though their state does not change.

First of all, not being very familiar with the concepts;

Is this expected behavior? What I've done might not be ideal, but causing every DOM elment to rerenders because parent state changed feels unncesseary to me. Or maybe I'm doing something wrong.

How would this be improved? Obviously thing to improve is not get every change as a callback, but I did not find a good way to call a method of child component to getValue()     from a parent component.

Link if you want: https://codesandbox.io/s/purple-architecture-5kpx5?file=/src/App.tsx You can clearly see the performance impact with React DevTools and see the render time increases with the number of elements even the elements did not change but the query text changes.

function App() {
  console.log("Re-render?");

  const [name, setName] = useState("mustafa");
  const [query, setQuery] = useState("");
  const [data, setData] = useState<number[]>([]);

  const runQuery = () => {
    console.log("using query...", query);
    setData([...Array(data.length + 1000).keys()]);
  };

  return (

Hello {name}

Please enter your query

      <QueryEditor
        onChange={(e) => {
          setQuery(e.target.value);
        }}
      />

      <button onClick={runQuery}>Run Query</button>

Results

      {data.length > 0 &&
There are {data.length} results
}
      {data.length > 0 && <DataResults data={data} />}

  );
}

interface EditorProps {
  onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void;
}

function QueryEditor({ onChange }: EditorProps) {
  return <textarea onChange={onChange} />;
}

function DataResults({ data }: { data: number[] }) {
  return (

        {data.map((a) => (

Item {a}

        ))}

  );
}

```

答:
useState will always cause re-rendering. When you type in the textarea, you update query which cause rerendering (it's the normal behaviour of useState).
In your case, you don't use query until you click the button to run the query.
You can change const [query, setQuery] = useState("");  by  const query = useRef(""). Then your QueryEditor onChange function becomes

```<code>{(e) => {
  query.current = (e.target.value);
}}
</code>```

This way you should not have all these re renders.
PS : when you run the query, you must use query.current instead of just query

Body:
useState will always cause re-rendering. When you type in the textarea, you update query which cause rerendering (it's the normal behaviour of useState).
In your case, you don't use query until you click the button to run the query.
You can change const [query, setQuery] = useState("");  by  const query = useRef(""). Then your QueryEditor onChange function becomes

{(e) => {
  query.current = (e.target.value);
}}

This way you should not have all these re renders.
PS : when you run the query, you must use query.current instead of just query


问:
OTP above Keyboard not display in my iOS device (textContentType ={'oneTimeCode'} not working in iOS) React Native
enter image description here

I need this type of functionality and I have iPhone 11 which has an iOS 15.3.

but getting this result

enter image description here

I am trying to Copy OTP from the authenticator application and when back to the application then tap on text input then above keyboard view does not display OTP highlighted with a red box in the first screenshot

答:
You need to make the text field of OTP type in attribute inspector under content type to One Time Password. You can check the following link for complete information :

Visit https://medium.com/@shankarmadeshvaran/how-to-implement-automatic-otp-verification-in-ios-7813c6116a1d


问:
Call Function out of React Component
I want to update a shopping cart when I click on a Product. But I don't know, how to call the function in another component.

This is, where the function is written and the state of the cart is hold.

```<code>    export const Cart = () => {
    const [userId, setUserId] = useState(7);
    const [cart, setCart] = useState([]);
    const [outfitName, setOutfitName] = useState("");

    const sendOutfit = () => {
        axios.post(`{url}/postOutfit`, {
            userId,
            outfitName,
            cart,
        });
    };

    function addToCart(id) {
        cart.push(id);
        setCart(cart);
    }
...
}
</code>```

Here I want to call the addToCart function.

```<code>import { Cart } from "../../sites/Cart/Cart";
...

 <div className="product-name">
                    <button
                        className="button is-small is-outlined is-primary"
                        onClick={() =>
                            Cart.addToCart(product.id) & changeButtonText
                        }
                    >
                        {buttonText}
                    </button>
                </div>
</code>```

When I try to execute this, I get the following error message:

Do you have any suggestion for me?

Thank you very much!

答:
Methods in React return JSX values and in this way it is not correct to export a method, if you want to export the method of addToCart to a another component you need to send this method as propeties or using state management for example as follows:

```<code>    export const Cart = () => {
    const [userId, setUserId] = useState(7);
    const [cart, setCart] = useState([]);
    const [outfitName, setOutfitName] = useState("");

    const sendOutfit = () => {
        axios.post(`{url}/postOutfit`, {
            userId,
            outfitName,
            cart,
        });
    };

    function addToCart(id) {
        cart.push(id);
        setCart(cart);
    }

   return <AnotherComponent addCartFunc={addToCart} />

}
</code>```

Then you can use this method in the host component as follows:

```<code>export const Cart = ({addCartFunc}) => {
   return (
        <div className="product-name">
            <button
                className="button is-small is-outlined is-primary"
                onClick={() =>
                    addCartFunc(product.id) & changeButtonText
                }
            >
                {buttonText}
            </button>
        </div>
   )
}
</code>```

Title: Call Function out of React Component

Body:
I want to update a shopping cart when I click on a Product. But I don't know, how to call the function in another component.

This is, where the function is written and the state of the cart is hold.

    export const Cart = () => {
    const [userId, setUserId] = useState(7);
    const [cart, setCart] = useState([]);
    const [outfitName, setOutfitName] = useState("");

    const sendOutfit = () => {
        axios.post(`{url}/postOutfit`, {
            userId,
            outfitName,
            cart,
        });
    };

    function addToCart(id) {
        cart.push(id);
        setCart(cart);
    }
...
}

Here I want to call the addToCart function.

import { Cart } from "../../sites/Cart/Cart";
...

                    <button
                        className="button is-small is-outlined is-primary"
                        onClick={() =>
                            Cart.addToCart(product.id) & changeButtonText
                        }
                    >
                        {buttonText}
                    </button>

When I try to execute this, I get the following error message:

Do you have any suggestion for me?

Thank you very much!

Body:
Methods in React return JSX values and in this way it is not correct to export a method, if you want to export the method of addToCart to a another component you need to send this method as propeties or using state management for example as follows:

    export const Cart = () => {
    const [userId, setUserId] = useState(7);
    const [cart, setCart] = useState([]);
    const [outfitName, setOutfitName] = useState("");

    const sendOutfit = () => {
        axios.post(`{url}/postOutfit`, {
            userId,
            outfitName,
            cart,
        });
    };

    function addToCart(id) {
        cart.push(id);
        setCart(cart);
    }

   return <AnotherComponent addCartFunc={addToCart} />

}

Then you can use this method in the host component as follows:

export const Cart = ({addCartFunc}) => {
   return (
        <div className="product-name">
            <button
                className="button is-small is-outlined is-primary"
                onClick={() =>
                    addCartFunc(product.id) & changeButtonText
                }
            >
                {buttonText}
            </button>
        </div>
   )
}


问:
I want to add a reaction to my embed but it doesnt really work.... [Discord.js v12.5]
I want to add a reaction to this embed that is automatically sent to a specific channel after a user is done answering some questions. It's a discord application system. I believe I'm doing this right, since I've done this before the same way but now in this exact code, it doesn't work. This is my code :

```<code> function send_finished(){
             let embed = new Discord.MessageEmbed()
             .setColor("#CD8BF2")
             .setTitle("A new Discord Helper application from: " + user.tag)
             .setDescription(`${user}`)
             .setFooter(user.tag, user.displayAvatarURL({dynamic:true}))
             .setTimestamp()
             for(let i = 0; i < config.QUESTIONS.length; i++){
                 try{
                     embed.addField(config.QUESTIONS[i], '```' + String(answers[i]).substr(0, 1024) + '```')
                 }catch{
                 }
             }

             channel_tosend.send(embed);
             embed.react('✅')

             user.send("Thanks for applying to: " + message.guild.name)

         }
</code>```

This is the error i get :

```<code>            embed.react('✅')
                  ^

TypeError: embed.react is not a function
</code>```

Any help or actually telling me what the heck I'm doing wrong?

答:
Perhaps:</p>
```<code>let embed = new Discord.RichEmbed()

message.channel.send({embed: embed});
message.channel.send({embed: embed}).then(embedMessage => {
    embedMessage.react("");
});
</code>```

Body:
I want to add a reaction to this embed that is automatically sent to a specific channel after a user is done answering some questions. It's a discord application system. I believe I'm doing this right, since I've done this before the same way but now in this exact code, it doesn't work. This is my code :

 function send_finished(){
             let embed = new Discord.MessageEmbed()
             .setColor("#CD8BF2")
             .setTitle("A new Discord Helper application from: " + user.tag)
             .setDescription(`${user}`)
             .setFooter(user.tag, user.displayAvatarURL({dynamic:true}))
             .setTimestamp()
             for(let i = 0; i < config.QUESTIONS.length; i++){
                 try{
                     embed.addField(config.QUESTIONS[i], '```' + String(answers[i]).substr(0, 1024) + '```')
                 }catch{
                 }
             }

             channel_tosend.send(embed);
             embed.react('✅')

             user.send("Thanks for applying to: " + message.guild.name)

         }

This is the error i get :

            embed.react('✅')
                  ^

TypeError: embed.react is not a function

Any help or actually telling me what the heck I'm doing wrong?

Body:
Perhaps:

let embed = new Discord.RichEmbed()

message.channel.send({embed: embed});
message.channel.send({embed: embed}).then(embedMessage => {
    embedMessage.react("");
});


问:
functions not calling correctly in onclick
I have a button and with this button, I am trying to call two functions but instead, they seem to be cancelling each other out.

In the console it shows this I have numbered them and connected them to the function for example line 1 comes from the console.log in function "addValue".

line 1 - ['Name:  graphqless  Description:    REST and GraphQ… URL:   https://github.com/tylerbuchea/graphqless']

line 2 - []

line - 3 RepoList.js?5216:74 ['Name:  graphqless  Description:    REST and GraphQ… URL:   https://github.com/tylerbuchea/graphqless']
Localstorage is empty.

The desired output is as follows when I click the button, function one should be called and only after clicking again should function 2 be called.

the value is a string

The functions

```<code>const favs = JSON.parse(localStorage.getItem('name') || []);

    function addValue(e) {
        if (e.target.value !== "") {

          if (!favs.includes(e.target.value)) {
            favs.push(e.target.value);
            localStorage.setItem("name", JSON.stringify(favs));
//line 1
console.log(favs);
            document.getElementById("favsarray").innerHTML =  favs
          }
        }
      }

//Check if value is in the array, if it then remove the value from both the array and localstorage
  f

unction removeValue(e, value) {
        if (e.target.value !== "") {
          //delete from array
          favs.pop(e.target.value);
//line 2
console.log(favs);
          //change the div text
          document.getElementById("favsarray").innerHTML = favs;
          //get the values from localstorage- parse
          const stored = JSON.parse(localStorage.getItem("name"));
          //delete the value
          delete stored[(value, e.target.value)];
          //store the new array as a string
          localStorage.setItem("name", JSON.stringify(favs));
//line 3
console.log(stored);
        }
      }
</code>```

This is how I am calling the function

```<code>onClick={(e)=> {addValue(e); removeValue(e);}}
</code>```

答:
You need to add logic to determines the state. Somehow you need a boolean to know what state you are in. so either you flip a boolean variable or you add remove a class.

Using a Boolean

function doAdd(elem) {
  console.log("add called", elem);
}

function doRemove(elem) {
  console.log("remove called", elem);
}

let actionSate = false;
function doAction(e) {
  const elem = e.currentTarget;
  actionSate = !actionSate;
  if (actionSate) {
    doAdd(elem);
  } else {
    doRemove(elem);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" onclick="doAction(event)">Click</button></code>```

Using a class allows you to have more than one trigger. Each one can work by themselves.

function doAdd(elem) {
  console.log("add called", elem);
}

function doRemove(elem) {
  console.log("remove called", elem);
}

function doAction(e) {
  const elem = e.currentTarget;
  elem.classList.toggle("action");
  if (elem.classList.contains("action")) {
    doAdd(elem);
  } else {
    doRemove(elem);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.action {
  color: blue;
}</code>```

<button type="button" onclick="doAction(event)">Click 1</button>
<button type="button" onclick="doAction(event)">Click 2</button>```

Body:
I have a button and with this button, I am trying to call two functions but instead, they seem to be cancelling each other out.

In the console it shows this I have numbered them and connected them to the function for example line 1 comes from the console.log in function "addValue".

line 1 - ['Name:  graphqless  Description:    REST and GraphQ… URL:   https://github.com/tylerbuchea/graphqless']

line 2 - []

line - 3 RepoList.js?5216:74 ['Name:  graphqless  Description:    REST and GraphQ… URL:   https://github.com/tylerbuchea/graphqless']
Localstorage is empty.

The desired output is as follows when I click the button, function one should be called and only after clicking again should function 2 be called.

the value is a string

The functions

const favs = JSON.parse(localStorage.getItem('name') || []);

    function addValue(e) {
        if (e.target.value !== "") {

          if (!favs.includes(e.target.value)) {
            favs.push(e.target.value);
            localStorage.setItem("name", JSON.stringify(favs));
//line 1
console.log(favs);
            document.getElementById("favsarray").innerHTML =  favs
          }
        }
      }

//Check if value is in the array, if it then remove the value from both the array and localstorage
  f

unction removeValue(e, value) {
        if (e.target.value !== "") {
          //delete from array
          favs.pop(e.target.value);
//line 2
console.log(favs);
          //change the div text
          document.getElementById("favsarray").innerHTML = favs;
          //get the values from localstorage- parse
          const stored = JSON.parse(localStorage.getItem("name"));
          //delete the value
          delete stored[(value, e.target.value)];
          //store the new array as a string
          localStorage.setItem("name", JSON.stringify(favs));
//line 3
console.log(stored);
        }
      }

This is how I am calling the function

onClick={(e)=> {addValue(e); removeValue(e);}}

Body:
You need to add logic to determines the state. Somehow you need a boolean to know what state you are in. so either you flip a boolean variable or you add remove a class.

Using a Boolean

function doAdd(elem) {
  console.log("add called", elem);
}

function doRemove(elem) {
  console.log("remove called", elem);
}

let actionSate = false;
function doAction(e) {
  const elem = e.currentTarget;
  actionSate = !actionSate;
  if (actionSate) {
    doAdd(elem);
  } else {
    doRemove(elem);
  }
}

<button type="button" onclick="doAction(event)">Click</button>

Using a class allows you to have more than one trigger. Each one can work by themselves.

function doAdd(elem) {
  console.log("add called", elem);
}

function doRemove(elem) {
  console.log("remove called", elem);
}

function doAction(e) {
  const elem = e.currentTarget;
  elem.classList.toggle("action");
  if (elem.classList.contains("action")) {
    doAdd(elem);
  } else {
    doRemove(elem);
  }
}

.action {
  color: blue;
}

<button type="button" onclick="doAction(event)">Click 1</button>
<button type="button" onclick="doAction(event)">Click 2</button>


问:
How to track directories but not their files with Git?
I've recently started using Git and am having trouble with just one thing. How can I track directories without tracking their contents?

For example the site I'm working on allows uploads. I want to track the uploads directory so that it is created when branching, etc. but obviously not the files within it (test files whilst in develop branch or the real files in master).

In my .gitignore I have the following:

```uploads/*.*```

Have also tried (which ignores the whole directory):

```uploads/```

This directory may also contain sub directories (uploads/thumbs/ uploads/videos/) I would like to be able to track these but not their files.

Is this possible with Git? I've searched everywhere without finding an answer.

答:
(In your example, directory is uploads.)

In the root directory, in a .gitignore file, put:

```<code>directory/*
!*.gitkeep
</code>```

Then save an empty .gitkeep file in directory.

ContentLicense: CC BY-SA 2.5

Body:
I've recently started using Git and am having trouble with just one thing. How can I track directories without tracking their contents?

For example the site I'm working on allows uploads. I want to track the uploads directory so that it is created when branching, etc. but obviously not the files within it (test files whilst in develop branch or the real files in master).

In my .gitignore I have the following:

uploads/*.*

Have also tried (which ignores the whole directory):

uploads/

This directory may also contain sub directories (uploads/thumbs/ uploads/videos/) I would like to be able to track these but not their files.

Is this possible with Git? I've searched everywhere without finding an answer.

Body:
(In your example, directory is uploads.)

In the root directory, in a .gitignore file, put:

directory/*
!*.gitkeep

Then save an empty .gitkeep file in directory.