问:
Why my text is centred in Column even I set crossAxisAlignment: CrossAxisAlignment.start in flutter?

I want the Column() to start at the very start(left) of the Card(), so I putted my text() in a column, and I have set the crossAxisAlignment: CrossAxisAlignment.start, set container width to double.infinity, but the text still align in the centre of the container.

What did I do wrong?

Thanks in advance guys.

```<code>class _ClassCardState extends State<ClassCard> {
  var _isExpanded = false;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Container(
          padding: const EdgeInsets.only(
            left: 10,
            right: 10,
            top: 40,
          ),
          width: double.infinity,
          child: GestureDetector(
            onTap: () {
              setState(() {
                _isExpanded = !_isExpanded;
              });
            },
            child: Card(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
              ),
              elevation: 0.3,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  children: <Widget>[
                    Container(
                      // padding: const EdgeInsets.only(left: 20),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'Yoga (Beginner)',
                            style: TextStyle(
                              color: Colors.black87,
                              fontWeight: FontWeight.bold,
                              fontSize: 20,
                            ),
                          ),
                          SizedBox(
                            height: 3,
                          ),
                          Text(
                            'Stretch',
                          ),
                          SizedBox(
                            height: 3,
                          ),
                          Text('30mins'),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 30,
                    ),
                    // if (_isExpanded)
                    // TimeSlot(),
                    if (_isExpanded)
                      SizedBox(
                        height: 10,
                      ),
                    if (_isExpanded)
                      Text(
                        'Sheung Wan MAXFIT',
                        style: TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.bold,
                        ),
                      )
                  ],
                ),
              ),
            ),
          ),
        ),
        // Positioned(
        //   child: Container(
        //     child: ClipRRect(
        //       borderRadius: BorderRadius.circular(10),
        //       child: Image.asset(
        //         './assets/images/yoga.png',
        //         fit: BoxFit.cover,
        //       ),
        //     ),
        //     height: 118,
        //     width: 90,
        //   ),
        //   left: 30,
        //   top: 15,
        // ),
      ],
    );
  }
}
</code>```

答:
Set
crossAxisAlignment: CrossAxisAlignment.start
for the first column on line 26

Body:
I want the Column() to start at the very start(left) of the Card(), so I putted my text() in a column, and I have set the crossAxisAlignment: CrossAxisAlignment.start, set container width to double.infinity, but the text still align in the centre of the container.

What did I do wrong?

Thanks in advance guys.

class _ClassCardState extends State<ClassCard> {
  var _isExpanded = false;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Container(
          padding: const EdgeInsets.only(
            left: 10,
            right: 10,
            top: 40,
          ),
          width: double.infinity,
          child: GestureDetector(
            onTap: () {
              setState(() {
                _isExpanded = !_isExpanded;
              });
            },
            child: Card(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
              ),
              elevation: 0.3,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  children: <Widget>[
                    Container(
                      // padding: const EdgeInsets.only(left: 20),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'Yoga (Beginner)',
                            style: TextStyle(
                              color: Colors.black87,
                              fontWeight: FontWeight.bold,
                              fontSize: 20,
                            ),
                          ),
                          SizedBox(
                            height: 3,
                          ),
                          Text(
                            'Stretch',
                          ),
                          SizedBox(
                            height: 3,
                          ),
                          Text('30mins'),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 30,
                    ),
                    // if (_isExpanded)
                    // TimeSlot(),
                    if (_isExpanded)
                      SizedBox(
                        height: 10,
                      ),
                    if (_isExpanded)
                      Text(
                        'Sheung Wan MAXFIT',
                        style: TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.bold,
                        ),
                      )
                  ],
                ),
              ),
            ),
          ),
        ),
        // Positioned(
        //   child: Container(
        //     child: ClipRRect(
        //       borderRadius: BorderRadius.circular(10),
        //       child: Image.asset(
        //         './assets/images/yoga.png',
        //         fit: BoxFit.cover,
        //       ),
        //     ),
        //     height: 118,
        //     width: 90,
        //   ),
        //   left: 30,
        //   top: 15,
        // ),
      ],
    );
  }
}


来源: stackexchange

问:
DL4J: Wrong input size - expected matrix
I’m trying to get my network to evaluate an INDArray. This is my network:
public class DQN {

```<code>private final int inputSize;
private final int outputSize;
private final MultiLayerNetwork network;

public DQN(int inputSize, int outputSize){

    this.inputSize = inputSize;
    this.outputSize = outputSize;

    MultiLayerConfiguration config = setConfig();
    this.network = new MultiLayerNetwork(config);
    this.network.init();
}

private MultiLayerConfiguration setConfig(){
    return new NeuralNetConfiguration.Builder()
            .seed(12345)
            .weightInit(WeightInit.XAVIER)
            .updater(new AdaGrad(0.5))
            .activation(Activation.RELU)
            .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
            .l2(0.0001)
            .list()
            .layer(0, new DenseLayer.Builder().nIn(this.inputSize).nOut(250).weightInit(WeightInit.XAVIER).activation(Activation.RELU) //First hidden layer
                    .build())
            .layer(1, new OutputLayer.Builder().nIn(250).nOut(this.outputSize).weightInit(WeightInit.XAVIER).activation(Activation.SOFTMAX) //Output layer
                    .lossFunction(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
                    .build())
            .build();
}

public INDArray evaluate(INDArray vec){
    return this.network.output(vec);
}
</code>```

}

Unfortunately, whenever I try to call evaluate with my INDArray, I get:

```<code>Exception in thread "Thread-2" org.deeplearning4j.exception.DL4JInvalidInputException: Input that is not a matrix; expected matrix (rank 2), got rank 1 array with shape [23]. Missing preprocessor or wrong input type? (layer name: layer0, layer index: 0, layer type: DenseLayer)
    at org.deeplearning4j.nn.layers.BaseLayer.preOutputWithPreNorm(BaseLayer.java:308)
    at org.deeplearning4j.nn.layers.BaseLayer.preOutput(BaseLayer.java:291)
    at org.deeplearning4j.nn.layers.BaseLayer.activate(BaseLayer.java:339)
    at org.deeplearning4j.nn.layers.AbstractLayer.activate(AbstractLayer.java:258)
    at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.outputOfLayerDetached(MultiLayerNetwork.java:1303)
    at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.output(MultiLayerNetwork.java:2415)
    at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.output(MultiLayerNetwork.java:2378)
    at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.output(MultiLayerNetwork.java:2369)
    at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.output(MultiLayerNetwork.java:2356)
    at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.output(MultiLayerNetwork.java:2452)
    at wmaclean.rl.dqn.DQN.evaluate(DQN.java:51)
</code>```

My inputs are rank-1 vectors with 23 elements, but the net seems to be wanting a matrix. Does anyone know why? Thanks :)

答:
Found my issue. For anyone having similar issues, make sure you specify the shape when creating the INDArray:</p>

```<code>Nd4j.create(data, **new int[]{1, vectorSizeCount}**)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I’m trying to get my network to evaluate an INDArray. This is my network:
public class DQN {

private final int inputSize;
private final int outputSize;
private final MultiLayerNetwork network;

public DQN(int inputSize, int outputSize){

    this.inputSize = inputSize;
    this.outputSize = outputSize;

    MultiLayerConfiguration config = setConfig();
    this.network = new MultiLayerNetwork(config);
    this.network.init();
}

private MultiLayerConfiguration setConfig(){
    return new NeuralNetConfiguration.Builder()
            .seed(12345)
            .weightInit(WeightInit.XAVIER)
            .updater(new AdaGrad(0.5))
            .activation(Activation.RELU)
            .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
            .l2(0.0001)
            .list()
            .layer(0, new DenseLayer.Builder().nIn(this.inputSize).nOut(250).weightInit(WeightInit.XAVIER).activation(Activation.RELU) //First hidden layer
                    .build())
            .layer(1, new OutputLayer.Builder().nIn(250).nOut(this.outputSize).weightInit(WeightInit.XAVIER).activation(Activation.SOFTMAX) //Output layer
                    .lossFunction(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
                    .build())
            .build();
}

public INDArray evaluate(INDArray vec){
    return this.network.output(vec);
}

}

Unfortunately, whenever I try to call evaluate with my INDArray, I get:

Exception in thread "Thread-2" org.deeplearning4j.exception.DL4JInvalidInputException: Input that is not a matrix; expected matrix (rank 2), got rank 1 array with shape [23]. Missing preprocessor or wrong input type? (layer name: layer0, layer index: 0, layer type: DenseLayer)
    at org.deeplearning4j.nn.layers.BaseLayer.preOutputWithPreNorm(BaseLayer.java:308)
    at org.deeplearning4j.nn.layers.BaseLayer.preOutput(BaseLayer.java:291)
    at org.deeplearning4j.nn.layers.BaseLayer.activate(BaseLayer.java:339)
    at org.deeplearning4j.nn.layers.AbstractLayer.activate(AbstractLayer.java:258)
    at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.outputOfLayerDetached(MultiLayerNetwork.java:1303)
    at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.output(MultiLayerNetwork.java:2415)
    at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.output(MultiLayerNetwork.java:2378)
    at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.output(MultiLayerNetwork.java:2369)
    at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.output(MultiLayerNetwork.java:2356)
    at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.output(MultiLayerNetwork.java:2452)
    at wmaclean.rl.dqn.DQN.evaluate(DQN.java:51)

My inputs are rank-1 vectors with 23 elements, but the net seems to be wanting a matrix. Does anyone know why? Thanks :)

Body:
Found my issue. For anyone having similar issues, make sure you specify the shape when creating the INDArray:

Nd4j.create(data, **new int[]{1, vectorSizeCount}**)


问:
Finding the longest word in a .txt file without punctuation marks
I am doing Python file I/O exercises and albeit made a huge progress on an exercise in which I try to find the longest words in each line of a .txt file, I can't get rid of the punctuation marks.

Here is the code I have:

```<code>with open("original-3.txt", 'r') as file1:
lines = file1.readlines()
for line in lines:
    if not line == "\n":
        print(max(line.split(), key=len))
</code>```

This is the output I get

This is the original-3.txt file where I am reading the data from

```<code>'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.

"Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!"

He took his vorpal sword in hand:
Long time the manxome foe he sought,
So rested he by the Tumtum tree,
And stood a while in thought.

And, as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!

One two! One two! And through and through
The vorpal blade went snicker-snack!
He left it dead, and with its head
He went galumphing back.

"And hast thou slain the Jabberwock?
Come to my arms, my beamish boy!"
"Oh frabjous day! Callooh! Callay!"
He chortled in his joy.

'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.
</code>```

As you can see, I am getting the punctuation marks like ["," ";" "?" "!"]

How do you think I can only get the words themselves?

Thank you

答:
This solution does not use regular expressions. It splits the line into words, and then sanitizes each word so that it only contains alphabetical characters.

with open("original-3.txt", 'r') as file1:
    lines = file1.readlines()
    for line in lines:
        if not line == "\n":
            words = line.split()
            for i, word in enumerate(words):
                words[i] = "".join([letter for letter in word if letter.isalpha()])
            print(max(words, key=len))
```

Body:
I am doing Python file I/O exercises and albeit made a huge progress on an exercise in which I try to find the longest words in each line of a .txt file, I can't get rid of the punctuation marks.

Here is the code I have:

with open("original-3.txt", 'r') as file1:
lines = file1.readlines()
for line in lines:
    if not line == "\n":
        print(max(line.split(), key=len))

This is the output I get

This is the original-3.txt file where I am reading the data from

'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.

"Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!"

He took his vorpal sword in hand:
Long time the manxome foe he sought,
So rested he by the Tumtum tree,
And stood a while in thought.

And, as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!

One two! One two! And through and through
The vorpal blade went snicker-snack!
He left it dead, and with its head
He went galumphing back.

"And hast thou slain the Jabberwock?
Come to my arms, my beamish boy!"
"Oh frabjous day! Callooh! Callay!"
He chortled in his joy.

'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.

As you can see, I am getting the punctuation marks like ["," ";" "?" "!"]

How do you think I can only get the words themselves?

Thank you


问:
SQL select TOP records partition by couples of column from multiple columns
What i want to get is all the customer which total cost is TOP2, with all the properties are needed.),

The question is SQL used is too complicated, If there's a way to simplipy it?

The date table & my SQL is something like below:

area
customer
property
cost

area1
cus1
property11
cost11

area1
cus1
property12
cost12

area1
cus2
property21
cost21

```<code>SELECT
    area,
    customer,
    property,
    SUM(cost) AS cost
FROM
    table
WHERE
    customer IN
             (SELECT
                  f.customer
             FROM
                 (SELECT
                      p.area,
                      p.customer,
                      ROW_NUMBER() OVER(PARTITION BY area ORDER BY cost) AS number,
                      p.cost
                 FROM
                    (SELECT
                          area,
                          costomer,
                          SUM(cost) AS cost
                     FROM
                         table
                     GROUP BY
                         costomer
                     )a
                 WHERE number <=2
                 )aa
             )aaa
GROUP BY
    area,
    customer,
    property

</code>```

答:
You can use ROW_NUMBER() window function (or RANK() if you want ties included):

```<code>select t.area, t.customer, t.properties, t.cost
from (
  select area, customer, collect_set(property) properties, sum(cost) cost,
    row_number() over (partition by area order by sum(cost) desc) rn
  from tablename
  group by area, customer
) t
where t.rn <= 2
</code>```

Body:
What i want to get is all the customer which total cost is TOP2, with all the properties are needed.),

The question is SQL used is too complicated, If there's a way to simplipy it?

The date table & my SQL is something like below:

area
customer
property
cost

area1
cus1
property11
cost11

area1
cus1
property12
cost12

area1
cus2
property21
cost21

SELECT
    area,
    customer,
    property,
    SUM(cost) AS cost
FROM
    table
WHERE
    customer IN
             (SELECT
                  f.customer
             FROM
                 (SELECT
                      p.area,
                      p.customer,
                      ROW_NUMBER() OVER(PARTITION BY area ORDER BY cost) AS number,
                      p.cost
                 FROM
                    (SELECT
                          area,
                          costomer,
                          SUM(cost) AS cost
                     FROM
                         table
                     GROUP BY
                         costomer
                     )a
                 WHERE number <=2
                 )aa
             )aaa
GROUP BY
    area,
    customer,
    property

Body:
You can use ROW_NUMBER() window function (or RANK() if you want ties included):

select t.area, t.customer, t.properties, t.cost
from (
  select area, customer, collect_set(property) properties, sum(cost) cost,
    row_number() over (partition by area order by sum(cost) desc) rn
  from tablename
  group by area, customer
) t
where t.rn <= 2


问:
how can I manipulate the layout of an itemrow of a recyclerView after a complete swipe of it?
I have a recyclerView with swipe functionality, but every time that I swipe an item, it is dismissed, and this is not what I am looking for. What I want is something like the WhatsApp swipe, that is, after a swipe, I can perform an action with that row without dismissing it. In this case, for example, I have a TextView with its visibility set to INVISIBLE, and after a complete swipe, I want it to become visible in the swiped row. Is there a way I can achieve this?

My AdapterClas:

```<code>public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

List <MyModel> list;
Context context;

public MyAdapter(List<MyModel> list, Context context) {
    this.list = list;
    this.context = context;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View itemLista = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row,parent,false);

    return new MyViewHolder(itemLista);
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

    MyModel myModel = list.get(position);

    holder.txt1.setText(String.valueOf(myModel.getPosition()));

}

@Override
public int getItemCount() {
    return list.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder{

    TextView txt1;
    TextView txt2;

    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        txt1 = itemView.findViewById(R.id.row_textView);
        txt2 = itemView.findViewById(R.id.row_textView2);

        //I WANT TO MAKE THIS txt2 BECOME VISIBLE AFTER SWIPE

    }
}
</code>```

The swipe functionality:

```<code>public void swipe () {
    ItemTouchHelper.Callback itemTouch = new ItemTouchHelper.Callback() {
        @Override
        public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
            int dragFlag = ItemTouchHelper.ACTION_STATE_IDLE;
            int swipeFlag = ItemTouchHelper.START|ItemTouchHelper.END;

            return makeMovementFlags(dragFlag,swipeFlag);

        }

        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
            Toast.makeText(MainActivity.this, "Swiped", Toast.LENGTH_SHORT).show();

        }
    };

    new ItemTouchHelper(itemTouch).attachToRecyclerView(recyclerView);
}
</code>```

My RecyclerView layout row:

```<code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_margin="6dp"
android:orientation="vertical"
android:background="@android:color/holo_orange_light"
android:layout_height="wrap_content">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/row_textView"
    android:textColor="@android:color/black"
    android:textSize="22sp"
    />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="22sp"
    android:visibility="invisible"
    android:id="@+id/row_textView2"/>
</code>```

答:
add this code to your swipe section then will be ok.</p>

```<code>@Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
        Toast.makeText(MainActivity.this, "Swiped", Toast.LENGTH_SHORT).show();
        viewHolder.itemView.setVisibility(View.VISIBLE);
        yourAdapter.notifyDataSetChanged();
    }
};
</code>```

Body:
I have a recyclerView with swipe functionality, but every time that I swipe an item, it is dismissed, and this is not what I am looking for. What I want is something like the WhatsApp swipe, that is, after a swipe, I can perform an action with that row without dismissing it. In this case, for example, I have a TextView with its visibility set to INVISIBLE, and after a complete swipe, I want it to become visible in the swiped row. Is there a way I can achieve this?

My AdapterClas:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

List <MyModel> list;
Context context;

public MyAdapter(List<MyModel> list, Context context) {
    this.list = list;
    this.context = context;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View itemLista = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row,parent,false);

    return new MyViewHolder(itemLista);
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

    MyModel myModel = list.get(position);

    holder.txt1.setText(String.valueOf(myModel.getPosition()));

}

@Override
public int getItemCount() {
    return list.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder{

    TextView txt1;
    TextView txt2;

    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        txt1 = itemView.findViewById(R.id.row_textView);
        txt2 = itemView.findViewById(R.id.row_textView2);

        //I WANT TO MAKE THIS txt2 BECOME VISIBLE AFTER SWIPE

    }
}

The swipe functionality:

public void swipe () {
    ItemTouchHelper.Callback itemTouch = new ItemTouchHelper.Callback() {
        @Override
        public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
            int dragFlag = ItemTouchHelper.ACTION_STATE_IDLE;
            int swipeFlag = ItemTouchHelper.START|ItemTouchHelper.END;

            return makeMovementFlags(dragFlag,swipeFlag);

        }

        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
            Toast.makeText(MainActivity.this, "Swiped", Toast.LENGTH_SHORT).show();

        }
    };

    new ItemTouchHelper(itemTouch).attachToRecyclerView(recyclerView);
}

My RecyclerView layout row:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_margin="6dp"
android:orientation="vertical"
android:background="@android:color/holo_orange_light"
android:layout_height="wrap_content">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/row_textView"
    android:textColor="@android:color/black"
    android:textSize="22sp"
    />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="22sp"
    android:visibility="invisible"
    android:id="@+id/row_textView2"/>

Body:
add this code to your swipe section then will be ok.

@Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
        Toast.makeText(MainActivity.this, "Swiped", Toast.LENGTH_SHORT).show();
        viewHolder.itemView.setVisibility(View.VISIBLE);
        yourAdapter.notifyDataSetChanged();
    }
};


问:
Is there a timestamp feature in GTM event data?
I'm creating an event data via GTM, and typically if it's sent to GA the timezone will follow the GA timezone but if I sent it to a different endpoint how do I capture the timestamp for the GTM event? Would I have to populate it in the dataLayer? </p>

答:
You may create a custom variable using javascript. That custom variable will return the current timestamp (beware that you may need to deal with browsers timezones, if that is important to you).

Go to Variables and add a new using the type Custom JavaScript:

Then the code could be along this lines (grabbed from here), depending on the format you want to return:

```<code>function() {
 try {
  var timestamp = new Date();
  var time = timestamp.toString().split(' ');
  return time[3]+ " " +time[1]+ " " +time[2]+ " "+time[4];
 } catch(e) {
  return "unknown";
 }
}
</code>```

After that, a variable with the name given (in this case I used 'Timestamp') will become available as {{Timestamp}} You then can plug it in the event or whatever tag you are creating. You may even use it as {{Timestamp}} inside a Javascript tag. The variable will return a timestamp in the format: 2020 May 30 11:41:44

Body:
You may create a custom variable using javascript. That custom variable will return the current timestamp (beware that you may need to deal with browsers timezones, if that is important to you).

Go to Variables and add a new using the type Custom JavaScript:

Then the code could be along this lines (grabbed from here), depending on the format you want to return:

function() {
 try {
  var timestamp = new Date();
  var time = timestamp.toString().split(' ');
  return time[3]+ " " +time[1]+ " " +time[2]+ " "+time[4];
 } catch(e) {
  return "unknown";
 }
}

After that, a variable with the name given (in this case I used 'Timestamp') will become available as {{Timestamp}} You then can plug it in the event or whatever tag you are creating. You may even use it as {{Timestamp}} inside a Javascript tag. The variable will return a timestamp in the format: 2020 May 30 11:41:44


问:
Looking for dynamically creating and placing a picture box
I'm trying to place red crosses when the user double click on the screen.
So I have a picture box that extract X and Y position when we double click on it. (with a GetX() & GetY()) function.

I'm trying to dynamically create a picture box and fill it with my "cross.png" file.
Here's what I've tried so far :

```<code>Dim pb As New PictureBox
        pb.Width = 100 'or whatever
        pb.Height = 200
        pb.Top = 50 'or whatever
        pb.Left = 50
        pb.ImageLocation = "C:\Users\Over_\Desktop\proto_mini_project_-_face_recognition (1)\proto mini project - face recognition\proto mini project - face recognition\cross.png"
        Me.Controls.Add(pb)
</code>```

I've found this solutions on StackOverflow but I don't really understand how to use it, or maybe I'm missing something.
Alose I execute this part of the code in :

```<code>    Private Sub PictureBox2_Click(sender As Object, e As EventArgs) Handles faceImage.DoubleClick
</code>```

If anyone got an idea/solution I would gladly take it.
Kind regards,
Mehdi.

答:
I've found the solution to my problem.
The new picture box wasn't in foreground, so i've added the following line :
pb.BringToFront()

Body:
I'm trying to place red crosses when the user double click on the screen.
So I have a picture box that extract X and Y position when we double click on it. (with a GetX() & GetY()) function.

I'm trying to dynamically create a picture box and fill it with my "cross.png" file.
Here's what I've tried so far :

Dim pb As New PictureBox
        pb.Width = 100 'or whatever
        pb.Height = 200
        pb.Top = 50 'or whatever
        pb.Left = 50
        pb.ImageLocation = "C:\Users\Over_\Desktop\proto_mini_project_-_face_recognition (1)\proto mini project - face recognition\proto mini project - face recognition\cross.png"
        Me.Controls.Add(pb)

I've found this solutions on StackOverflow but I don't really understand how to use it, or maybe I'm missing something.
Alose I execute this part of the code in :

    Private Sub PictureBox2_Click(sender As Object, e As EventArgs) Handles faceImage.DoubleClick

If anyone got an idea/solution I would gladly take it.
Kind regards,
Mehdi.


答:
You have two Columns in the layout. You also had to add crossAxisAlignment: CrossAxisAlignment.start to the first Column

```<code>Card(
  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
  elevation: 0.3,
  child: Padding(
    padding: const EdgeInsets.all(8.0),
    child: Column( // THIS COLUMN NEED crossAxisAlignment
      crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            // padding: const EdgeInsets.only(left: 20),
            child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[

//// rest of code
</code>```

Title: Why my text is centred in Column even I set crossAxisAlignment: CrossAxisAlignment.start in flutter?

Body:
You have two Columns in the layout. You also had to add crossAxisAlignment: CrossAxisAlignment.start to the first Column

Card(
  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
  elevation: 0.3,
  child: Padding(
    padding: const EdgeInsets.all(8.0),
    child: Column( // THIS COLUMN NEED crossAxisAlignment
      crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            // padding: const EdgeInsets.only(left: 20),
            child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[

//// rest of code


问:
cannot find module '@angular/http'?
I added the following property to my systemjs.config.js map object in my Angular 2 app:

```<code>'@angular/http': 'https://npmcdn.com/@angular/http'
</code>```

When I ctrl-click on the url it attempts to download a js file. However, when I try to import from '@angular/http' at the top of my service.ts, the compiler returns the error "Cannot find module '@angular/http'.`"

Is there an additional step that I'm missing in order for this module to be recognized and usable by my angular app? I'm using Angular version 2.0.0-rc.4.

答:
@angular/http is deprecated.

Try:

```<code>import { HttpClient } from '@angular/common/http';
</code>```

refer to https://angular.io/guide/deprecations#angularhttp for more info.

If you insist on using @angular/http try:

```<code>npm install @angular/http@latest

import { Http } from '@angular/http';
</code>```

ContentLicense: CC BY-SA 3.0

Title: cannot find module '@angular/http'?

Body:
I added the following property to my systemjs.config.js map object in my Angular 2 app:

'@angular/http': 'https://npmcdn.com/@angular/http'

When I ctrl-click on the url it attempts to download a js file. However, when I try to import from '@angular/http' at the top of my service.ts, the compiler returns the error "Cannot find module '@angular/http'.`"

Is there an additional step that I'm missing in order for this module to be recognized and usable by my angular app? I'm using Angular version 2.0.0-rc.4.

Body:
@angular/http is deprecated.

Try:

import { HttpClient } from '@angular/common/http';

refer to https://angular.io/guide/deprecations#angularhttp for more info.

If you insist on using @angular/http try:

npm install @angular/http@latest

import { Http } from '@angular/http';


问:
Change dynamically (using JMX) the folder being watched for new files
I'm using SpringBoot to watch a folder for new files.
The configuration looks like this:

```<code>@Configuration
@ManagedResource
public class FileWatcherConfig {
    Logger log = LoggerFactory.getLogger(FileWatcherConfig.class);

    @Value("${filewatcher.path:C:\\test}")
    String pathname;

    @Bean
    public FileSystemWatcher fileSystemWatcher() {
        FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(true, Duration.ofMillis(5000L), Duration.ofMillis(3000L));
        fileSystemWatcher.addSourceDirectory(new File(pathname));
        fileSystemWatcher.addListener(new MyFileChangeListener());
        fileSystemWatcher.start();
        log.info("started fileSystemWatcher");
        return fileSystemWatcher;
    }

    @PreDestroy
    public void onDestroy() {
        fileSystemWatcher().stop();
    }

    @ManagedOperation
    public void setPathname(String pathname) {
        this.pathname = pathname;
    }

    @ManagedAttribute
    public String getPathname(){
        return pathname;
    }
}
</code>```

Although I'm able to change the pathname value in runtime using jconsole the application still watches the initial folder.

答:
When you change the path via JMX, all that's doing is assigning a new value to the pathname field in the FileWatcherConfig bean.

You'll need to write additional code to update the FileSystemWatcher bean with the new path after it changes -- including potentially stopping it, removing the current listener, and then updating the source directory.

Body:
I'm using SpringBoot to watch a folder for new files.
The configuration looks like this:

@Configuration
@ManagedResource
public class FileWatcherConfig {
    Logger log = LoggerFactory.getLogger(FileWatcherConfig.class);

    @Value("${filewatcher.path:C:\\test}")
    String pathname;

    @Bean
    public FileSystemWatcher fileSystemWatcher() {
        FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(true, Duration.ofMillis(5000L), Duration.ofMillis(3000L));
        fileSystemWatcher.addSourceDirectory(new File(pathname));
        fileSystemWatcher.addListener(new MyFileChangeListener());
        fileSystemWatcher.start();
        log.info("started fileSystemWatcher");
        return fileSystemWatcher;
    }

    @PreDestroy
    public void onDestroy() {
        fileSystemWatcher().stop();
    }

    @ManagedOperation
    public void setPathname(String pathname) {
        this.pathname = pathname;
    }

    @ManagedAttribute
    public String getPathname(){
        return pathname;
    }
}

Although I'm able to change the pathname value in runtime using jconsole the application still watches the initial folder.


问:
Incompatible type exception occurs when using the each function in DolphinDB
I want to calculates the maximum value of each column in a table.The table is defined as bellow,

```<code>t = table(1 2 3 as id, 4 5 6 as value, `IBM`MSFT`GOOG as name);
</code>```

When I calculates the first 2 columns, it is OK.

```<code>>each(max, t[`id`value]);
[3,6]
</code>```

But I calculates all columns as bellow,

```<code>each(max, t[`id`value`name]);
</code>```

Incompatible type exception occurs

Can you tell me what is wrong? Thank you！

答: Higher order function each requires the return of individual has identical type. In your case, the last sub-tasks returns a string, which is incompatible with the result of first two sub-tasks. Please switch from each to loop and the final result will be a tuple containing mixed types of data.

Body:
I want to calculates the maximum value of each column in a table.The table is defined as bellow,

t = table(1 2 3 as id, 4 5 6 as value, `IBM`MSFT`GOOG as name);

When I calculates the first 2 columns, it is OK.

>each(max, t[`id`value]);
[3,6]

But I calculates all columns as bellow,

each(max, t[`id`value`name]);

Incompatible type exception occurs

Can you tell me what is wrong? Thank you！


问:
How To Highlight Specific Text Within A Cell Based On Other Text using Python?
In my excel file two columns are there.Column A has paragraph and column B has words.my requirement is what are words present in column B should be highlighted in column A.like if pest in column B.How many pest are there in column A first row should be highlighted.As sure in second row sure should be highlighted.I have written code but it is highlighting whole lines

my code:

```<code>from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import PatternFill
from openpyxl.styles import colors
from openpyxl.styles import Font, Color
import pandas as pd
ft = Font(color=colors.GREEN, bold=True)
wb = load_workbook('sample_sentence.xlsx')
ws = wb.active
a1 = ws['A']
for a in a1:
    a2 = a
for cell1 in ws['A']:
   for cell in ws['B']:
      if cell.value.lower() in cell1.value.lower():
         a2.font = ft
         wb.save('sample_sentence.xlsx')
</code>```

my requirement is in first A1 column pest should be highlighted second A2 column sure should be highlighted

答:
In VBA this could be solved as:

```<code>Function Highlight(r As Range, t As String) As String
    Dim Search As Range
    Dim SearchIn As String
    Dim Position As Integer
    Dim Color As Long
    Color = RGB(255, 0, 0)

    SearchIn = r.Text
    Position = InStr(1, SearchIn, t, vbTextCompare)
    r.Characters(Start:=Position, Length:=Len(t)).Font.Color = Color

    Highlight = t
End Function
</code>```

In your call use: =Highlight(A1,"pest")   will turn the word "pest" into a red color.

Body:
In my excel file two columns are there.Column A has paragraph and column B has words.my requirement is what are words present in column B should be highlighted in column A.like if pest in column B.How many pest are there in column A first row should be highlighted.As sure in second row sure should be highlighted.I have written code but it is highlighting whole lines

my code:

from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import PatternFill
from openpyxl.styles import colors
from openpyxl.styles import Font, Color
import pandas as pd
ft = Font(color=colors.GREEN, bold=True)
wb = load_workbook('sample_sentence.xlsx')
ws = wb.active
a1 = ws['A']
for a in a1:
    a2 = a
for cell1 in ws['A']:
   for cell in ws['B']:
      if cell.value.lower() in cell1.value.lower():
         a2.font = ft
         wb.save('sample_sentence.xlsx')

my requirement is in first A1 column pest should be highlighted second A2 column sure should be highlighted

Body:
In VBA this could be solved as:

Function Highlight(r As Range, t As String) As String
    Dim Search As Range
    Dim SearchIn As String
    Dim Position As Integer
    Dim Color As Long
    Color = RGB(255, 0, 0)

    SearchIn = r.Text
    Position = InStr(1, SearchIn, t, vbTextCompare)
    r.Characters(Start:=Position, Length:=Len(t)).Font.Color = Color

    Highlight = t
End Function

In your call use: =Highlight(A1,"pest")   will turn the word "pest" into a red color.


问:
Pandas to create columns based on starting Character
I have below data parsed Data from the Linux Machine into a text file.

What i Want..

Any line Startswith cn: should be comes under column Group_Name by constituting it.

Below cn: there are lines starting nisNetgroupTriple:, value after this is hostname should comes under Column Host_Name.

Where there is only Group_Name just need to be None in the Host_Name column

I am able to do that in Shell way but looking it in Pandas way..

Sample Data.

Below is just sample data but the actual data is Much bigger..

```<code>cn: Infra_SAT_IMEC_TR-KPQ01
nisNetgroupTriple: kht1562.khatigusain.com.com
nisNetgroupTriple: kht1187.khatigusain.com.com

cn: Infra_RDC_IMEC_US-KDC02_SWDC02_SW

cn: Infra_RDC_APAC_CN-KHA02_SWHA02_SW

cn: Infra_SAT_EMEA_AT-GRK02_RS_SW

cn: Infra_SAT_APAC_CN-KPH04
nisNetgroupTriple: kht1402.khatigusain.com.com
nisNetgroupTriple: kht1964.khatigusain.com.com
</code>```

DataFrame:

```<code>                      cn: Infra_SAT_IMEC_TR-KPQ01
0  nisNetgroupTriple: kht1562.khatigusain.com.com
1  nisNetgroupTriple: kht1187.khatigusain.com.com
2           cn: Infra_RDC_IMEC_US-KDC02_SWDC02_SW
3           cn: Infra_RDC_APAC_CN-KHA02_SWHA02_SW
4               cn: Infra_SAT_EMEA_AT-GRK02_RS_SW
5                     cn: Infra_SAT_APAC_CN-KPH04
6  nisNetgroupTriple: kht1402.khatigusain.com.com
7  nisNetgroupTriple: kht1964.khatigusain.com.com
Index(['cn: Infra_SAT_IMEC_TR-KPQ01'], dtype='object')
</code>```

Desired Data:

```<code>Group_Name                              Host_Name
Infra_SAT_IMEC_TR-KPQ01                 kht1562.khatigusain.com.com
Infra_SAT_IMEC_TR-KPQ01                 kht1187.khatigusain.com.com
Infra_RDC_IMEC_US-KDC02_SWDC02_SW       None
Infra_RDC_APAC_CN-KHA02_SWHA02_SW       None
Infra_SAT_EMEA_AT-GRK02_RS_SW           None
Infra_SAT_APAC_CN-KPH04                 kht1402.khatigusain.com.com
Infra_SAT_APAC_CN-KPH04                 kht1964.khatigusain.com.com
</code>```

I tried to lot googling around and tried to get some clue but didn't get anything, i'm still trying.

答:
You would need to prepare data in a suitable way. This is how you could do that:

Demo data in file:

```<code>with open ("data.txt", "w") as f:
    f.write("""cn: Infra_SAT_IMEC_TR-KPQ01
nisNetgroupTriple: kht1562.khatigusain.com.com
nisNetgroupTriple: kht1187.khatigusain.com.com

cn: Infra_RDC_IMEC_US-KDC02_SWDC02_SW

cn: Infra_RDC_APAC_CN-KHA02_SWHA02_SW

cn: Infra_SAT_EMEA_AT-GRK02_RS_SW

cn: Infra_SAT_APAC_CN-KPH04
nisNetgroupTriple: kht1402.khatigusain.com.com
nisNetgroupTriple: kht1964.khatigusain.com.com""")
</code>```

Read and parse data into dict - and create df from dict:

```<code>data = {}

with open("data.txt") as f:
    key = None
    for line in f:
        if not line.strip():
            continue
        if line.startswith("cn:"):
            key = line.split(":",1)[1].strip()
            data.setdefault(key, []) # key can have multiple occurences in file
        elif line.startswith("nisNetgroupTriple:"):
            data[key].append(line.split(":",1)[1].strip())
print(data)

import pandas as pd

df = pd.DataFrame( (k,v.strip() or None) for k,va in data.items() for v in (va or " ") )
df.columns = ["Group_Name","Host_Name"]
print(df)
</code>```

Output:

```<code>                          Group_Name                    Host_Name
0  Infra_RDC_APAC_CN-KHA02_SWHA02_SW                         None
1            Infra_SAT_IMEC_TR-KPQ01  kht1562.khatigusain.com.com
2            Infra_SAT_IMEC_TR-KPQ01  kht1187.khatigusain.com.com
3  Infra_RDC_IMEC_US-KDC02_SWDC02_SW                         None
4            Infra_SAT_APAC_CN-KPH04  kht1402.khatigusain.com.com
5            Infra_SAT_APAC_CN-KPH04  kht1964.khatigusain.com.com
6      Infra_SAT_EMEA_AT-GRK02_RS_SW                         None
</code>```

Body:
I have below data parsed Data from the Linux Machine into a text file.

What i Want..

Any line Startswith cn: should be comes under column Group_Name by constituting it.

Below cn: there are lines starting nisNetgroupTriple:, value after this is hostname should comes under Column Host_Name.

Where there is only Group_Name just need to be None in the Host_Name column

I am able to do that in Shell way but looking it in Pandas way..

Sample Data.

Below is just sample data but the actual data is Much bigger..

cn: Infra_SAT_IMEC_TR-KPQ01
nisNetgroupTriple: kht1562.khatigusain.com.com
nisNetgroupTriple: kht1187.khatigusain.com.com

cn: Infra_RDC_IMEC_US-KDC02_SWDC02_SW

cn: Infra_RDC_APAC_CN-KHA02_SWHA02_SW

cn: Infra_SAT_EMEA_AT-GRK02_RS_SW

cn: Infra_SAT_APAC_CN-KPH04
nisNetgroupTriple: kht1402.khatigusain.com.com
nisNetgroupTriple: kht1964.khatigusain.com.com

DataFrame:

                      cn: Infra_SAT_IMEC_TR-KPQ01
0  nisNetgroupTriple: kht1562.khatigusain.com.com
1  nisNetgroupTriple: kht1187.khatigusain.com.com
2           cn: Infra_RDC_IMEC_US-KDC02_SWDC02_SW
3           cn: Infra_RDC_APAC_CN-KHA02_SWHA02_SW
4               cn: Infra_SAT_EMEA_AT-GRK02_RS_SW
5                     cn: Infra_SAT_APAC_CN-KPH04
6  nisNetgroupTriple: kht1402.khatigusain.com.com
7  nisNetgroupTriple: kht1964.khatigusain.com.com
Index(['cn: Infra_SAT_IMEC_TR-KPQ01'], dtype='object')

Desired Data:

Group_Name                              Host_Name
Infra_SAT_IMEC_TR-KPQ01                 kht1562.khatigusain.com.com
Infra_SAT_IMEC_TR-KPQ01                 kht1187.khatigusain.com.com
Infra_RDC_IMEC_US-KDC02_SWDC02_SW       None
Infra_RDC_APAC_CN-KHA02_SWHA02_SW       None
Infra_SAT_EMEA_AT-GRK02_RS_SW           None
Infra_SAT_APAC_CN-KPH04                 kht1402.khatigusain.com.com
Infra_SAT_APAC_CN-KPH04                 kht1964.khatigusain.com.com

I tried to lot googling around and tried to get some clue but didn't get anything, i'm still trying.

Body:
You would need to prepare data in a suitable way. This is how you could do that:

Demo data in file:

with open ("data.txt", "w") as f:
    f.write("""cn: Infra_SAT_IMEC_TR-KPQ01
nisNetgroupTriple: kht1562.khatigusain.com.com
nisNetgroupTriple: kht1187.khatigusain.com.com

cn: Infra_RDC_IMEC_US-KDC02_SWDC02_SW

cn: Infra_RDC_APAC_CN-KHA02_SWHA02_SW

cn: Infra_SAT_EMEA_AT-GRK02_RS_SW

cn: Infra_SAT_APAC_CN-KPH04
nisNetgroupTriple: kht1402.khatigusain.com.com
nisNetgroupTriple: kht1964.khatigusain.com.com""")

Read and parse data into dict - and create df from dict:

data = {}

with open("data.txt") as f:
    key = None
    for line in f:
        if not line.strip():
            continue
        if line.startswith("cn:"):
            key = line.split(":",1)[1].strip()
            data.setdefault(key, []) # key can have multiple occurences in file
        elif line.startswith("nisNetgroupTriple:"):
            data[key].append(line.split(":",1)[1].strip())
print(data)

import pandas as pd

df = pd.DataFrame( (k,v.strip() or None) for k,va in data.items() for v in (va or " ") )
df.columns = ["Group_Name","Host_Name"]
print(df)

Output:

                          Group_Name                    Host_Name
0  Infra_RDC_APAC_CN-KHA02_SWHA02_SW                         None
1            Infra_SAT_IMEC_TR-KPQ01  kht1562.khatigusain.com.com
2            Infra_SAT_IMEC_TR-KPQ01  kht1187.khatigusain.com.com
3  Infra_RDC_IMEC_US-KDC02_SWDC02_SW                         None
4            Infra_SAT_APAC_CN-KPH04  kht1402.khatigusain.com.com
5            Infra_SAT_APAC_CN-KPH04  kht1964.khatigusain.com.com
6      Infra_SAT_EMEA_AT-GRK02_RS_SW                         None


问:
How to convert timedelta to hours
I have a timedelta Dataframe

```<code>JC time
1 3days 21:02:05
2 1days 23:50:07
3 6days 19:28:36
</code>```

but i want

```<code>1 93:02:05
2 47:50:07
3 163:28:36
</code>```

How can I convert it?

答:
Use, the combination of pd.to_timedelta, Series.dt.components, DataFrame.agg & Series.str.zfill:

```<code>d = pd.to_timedelta(df['time']).dt.components[['days', 'hours', 'minutes', 'seconds']]
d['hours'] = d['hours'].add(d.pop('days') * 24)

df['time'] = d.astype(str).agg(lambda s: ':'.join(s.str.zfill(2)), axis=1)
</code>```

Result:

```<code># print(df)

   JC       time
0   1   93:02:05
1   2   47:50:07
2   3  163:28:36
</code>```

Title: How to convert timedelta to hours

Body:
I have a timedelta Dataframe

JC time
1 3days 21:02:05
2 1days 23:50:07
3 6days 19:28:36

but i want

1 93:02:05
2 47:50:07
3 163:28:36

How can I convert it?

Body:
Use, the combination of pd.to_timedelta, Series.dt.components, DataFrame.agg & Series.str.zfill:

d = pd.to_timedelta(df['time']).dt.components[['days', 'hours', 'minutes', 'seconds']]
d['hours'] = d['hours'].add(d.pop('days') * 24)

df['time'] = d.astype(str).agg(lambda s: ':'.join(s.str.zfill(2)), axis=1)

Result:

# print(df)

   JC       time
0   1   93:02:05
1   2   47:50:07
2   3  163:28:36


问:
How to get Password AutoFill to work with ASWebAuthenticationSession?
I have a sample HTML form that follows the password auto-fill requirements. When navigating to the web page without the app, using the built-in Safari app, the native Password AutoFill dialogs for the login and signup forms correctly show:

However, when viewed within the app, the same flow does not trigger the dialog in neither the login or signup submission. It simply dismisses the login/signup screen without any error.

This is how my view controller looks like:

```<code>class ViewController: UIViewController {

    @IBAction func didTapLoginButton() {
        let session = ASWebAuthenticationSession(
            url: URL(string: "https://example.com/login.html")!,
            callbackURLScheme: "customscheme") {
                print($0, $1)
        }

        session.prefersEphemeralWebBrowserSession = true
        session.presentationContextProvider = self
        session.start()
    }
}

extension ViewController: ASWebAuthenticationPresentationContextProviding {

    func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
        view.window!
    }
}
</code>```

Is there a way to make the Password AutoFill to work with the mobile app via ASWebAuthenticationSession? I also tried SFSafariViewController but same issue. I have a sample iOS app here. Any help or experience is greatly appreciated!

答:
From the docs:

Password AutoFill recommends credentials only for your app’s
  associated domain, and the user must authenticate using Face ID or
  Touch ID before accessing these credentials.

Make sure the app is associated with your domain (example.com in your code). This will allow iCloud Keychain to identify the login form and suggest any stored credentials for that domain.

Associate your app with the domain, as described here.

Add the html tags to your login form, as described here.

Make sure the user is properly authenticated on the iOS device before launching the ASWebAuthenticationSession.

Body:
I have a sample HTML form that follows the password auto-fill requirements. When navigating to the web page without the app, using the built-in Safari app, the native Password AutoFill dialogs for the login and signup forms correctly show:

However, when viewed within the app, the same flow does not trigger the dialog in neither the login or signup submission. It simply dismisses the login/signup screen without any error.

This is how my view controller looks like:

class ViewController: UIViewController {

    @IBAction func didTapLoginButton() {
        let session = ASWebAuthenticationSession(
            url: URL(string: "https://example.com/login.html")!,
            callbackURLScheme: "customscheme") {
                print($0, $1)
        }

        session.prefersEphemeralWebBrowserSession = true
        session.presentationContextProvider = self
        session.start()
    }
}

extension ViewController: ASWebAuthenticationPresentationContextProviding {

    func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
        view.window!
    }
}

Is there a way to make the Password AutoFill to work with the mobile app via ASWebAuthenticationSession? I also tried SFSafariViewController but same issue. I have a sample iOS app here. Any help or experience is greatly appreciated!


问:
Issue with incrementing index Counter inside useEffect Hook in ReactJS
In this part of code, I try to take a state variable 'lastIndex' and try to increment it using setlastIndex but the value of lastIndex doesn't increment and remains 0 . I am new to React Hooks, please help me. If such an exact query already been asked before in stack overflow then please send the link.</p>

```<code>function App() {
  const [myAppointment, setmyAppointment] = useState([])
  **const [lastIndex, setlastIndex] = useState(0)**
  const [orderBy, setorderBy] = useState('petName')
  const [orderDir, setorderDir] = useState('asc')
  const [queryText, setqueryText] = useState('')
  useEffect(() => {
      fetch('./data.json')
      .then(response=> response.json())
      .then(result=>{
        **const apts=result.map(item=>{
          item.aptId = lastIndex
          setlastIndex(lastIndex => lastIndex+1)
          return item
        })**
        setmyAppointment(apts)
      })
  },[])
</code>```

答:
You should understand that lastIndex doesnt increase each time you call setlastIndex function, so just declare it outside loop and increase each time assigning to aptId property. And after loop set state with the last value

```<code>then(result=>{
  let currentIndex = lastIndex
  result.forEach(item=>{
    item.aptId = ++currentIndex
  })
  setmyAppointment(result)
  setlastIndex(currentIndex)
})
</code>```

map is not needed, you can use result to save it in setmyAppointments

Body:
In this part of code, I try to take a state variable 'lastIndex' and try to increment it using setlastIndex but the value of lastIndex doesn't increment and remains 0 . I am new to React Hooks, please help me. If such an exact query already been asked before in stack overflow then please send the link.

function App() {
  const [myAppointment, setmyAppointment] = useState([])
  **const [lastIndex, setlastIndex] = useState(0)**
  const [orderBy, setorderBy] = useState('petName')
  const [orderDir, setorderDir] = useState('asc')
  const [queryText, setqueryText] = useState('')
  useEffect(() => {
      fetch('./data.json')
      .then(response=> response.json())
      .then(result=>{
        **const apts=result.map(item=>{
          item.aptId = lastIndex
          setlastIndex(lastIndex => lastIndex+1)
          return item
        })**
        setmyAppointment(apts)
      })
  },[])

Body:
You should understand that lastIndex doesnt increase each time you call setlastIndex function, so just declare it outside loop and increase each time assigning to aptId property. And after loop set state with the last value

then(result=>{
  let currentIndex = lastIndex
  result.forEach(item=>{
    item.aptId = ++currentIndex
  })
  setmyAppointment(result)
  setlastIndex(currentIndex)
})

map is not needed, you can use result to save it in setmyAppointments


问:
Set HTTP Expires Header in DotNetNuke?
How can I set the the HTTP Expires header in DotNetNuke generated pages? </p>

答:
I have confirmed that this works on IIS 7 and DNN 5.6

Open IIS Manager

Click on the DNN website

Double Click HTTP Response Headers

Click (upper right) Set Common Headers

Check the Checkbox "Expire Web Content"

Enter your desired TTL

Press OK

Verify with Firebug

To verify that it is working:

Open Firebug Net Tab

Reload page

Browse to any of the page resources

Click the "+"

Look for "Cache-Control  no-cache"

Caching of Dynamic Content

DNN has internal caching for dynamic content. To adjust this, go into the host settings and turn off caching. That has nothing to do with HTTP Headers. Note: It's best to adjust caching at the module-level rather than host level. DNN is built to run with heavy caching. It can be lightning-fast if configured correctly, and very slow without caching.

Title: Set HTTP Expires Header in DotNetNuke?


问:
Why is channel layer not communicating with Redis in my django project?
Goodday everyone, I am new to channels and Redis and i tried to follow the this part of the channels documentation, which says;

Let’s make sure that the channel layer can communicate with Redis. Open a Django shell and run the following
commands:

```<code>$ python3 manage.py shell
>>> import channels.layers

>>> channel_layer = channels.layers.get_channel_layer()

>>> from asgiref.sync import async_to_sync

>>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'})

>>> async_to_sync(channel_layer.receive)('test_channel'){'type': 'hello'}
</code>```

but i run into this error;

```<code>>>> import channels.layers
>>> channel_layer = channels.layers.get_channel_layer()
>>> from asgiref.sync import async_to_sync

>>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'})
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\LENOVO\Project\BuildUp\lib\site-packages\asgiref\sync.py", line 116, in __call__
    return call_result.result()
  File "C:\Python37\Lib\concurrent\futures\_base.py", line 428, in result
    return self.__get_result()
  File "C:\Python37\Lib\concurrent\futures\_base.py", line 384, in __get_result
    raise self._exception
  File "C:\Users\LENOVO\Project\BuildUp\lib\site-packages\asgiref\sync.py", line 156, in main_wrap
    result = await self.awaitable(*args, **kwargs)
  File "C:\Users\LENOVO\Project\BuildUp\lib\site-packages\channels_redis\core.py", line 293, in send
    async with self.connection(index) as connection:
  File "C:\Users\LENOVO\Project\BuildUp\lib\site-packages\channels_redis\core.py", line 820, in __aenter__
    self.conn = await self.pool.pop()
  File "C:\Users\LENOVO\Project\BuildUp\lib\site-packages\channels_redis\core.py", line 70, in pop
    conns.append(await aioredis.create_redis(**self.host, loop=loop))
  File "C:\Users\LENOVO\Project\BuildUp\lib\site-packages\aioredis\commands\__init__.py", line 175, in create_redis
    loop=loop)
  File "C:\Users\LENOVO\Project\BuildUp\lib\site-packages\aioredis\connection.py", line 113, in create_connection
    timeout)
  File "C:\Python37\Lib\asyncio\tasks.py", line 414, in wait_for
    return await fut
  File "C:\Users\LENOVO\Project\BuildUp\lib\site-packages\aioredis\stream.py", line 24, in open_connection
    lambda: protocol, host, port, **kwds)
  File "C:\Python37\Lib\asyncio\base_events.py", line 954, in create_connection
    raise exceptions[0]
  File "C:\Python37\Lib\asyncio\base_events.py", line 941, in create_connection
    await self.sock_connect(sock, address)
  File "C:\Python37\Lib\asyncio\selector_events.py", line 464, in sock_connect
    return await fut
  File "C:\Python37\Lib\asyncio\selector_events.py", line 494, in _sock_connect_cb
    raise OSError(err, f'Connect call failed {address}')
ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 6379)
</code>```

And i have 'channels' in my INSTALLED_APPS, I also have the CHANNEL_LAYERS in my settings;

```<code>CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}
</code>```

I am using python 3.7.5 and when i enter 'pip freeze' command i see the following;

```<code>aioredis==1.3.1
asgiref==3.2.3
async-timeout==3.0.1
attrs==19.3.0
autobahn==19.11.1
Automat==0.8.0
cffi==1.13.2
channels==2.4.0
channels-redis==2.4.1
constantly==15.1.0
cryptography==2.8
daphne==2.4.1
Django==3.0.1
django-countries==5.5
django-crispy-forms==1.8.1
djangorestframework==3.11.0
hiredis==1.0.1
hyperlink==19.0.0
idna==2.8
incremental==17.5.0
msgpack==0.6.2
Pillow==6.2.1
pyasn1==0.4.8
pyasn1-modules==0.2.7
pycparser==2.19
PyHamcrest==1.9.0
pyOpenSSL==19.1.0
pytz==2019.3
service-identity==18.1.0
six==1.13.0
sqlparse==0.3.0
Twisted==19.10.0
txaio==18.8.1
zope.interface==4.7.1
</code>```

答:
Did you run redis instance like this?

```<code>docker run -p 6379:6379 -d redis:5
</code>```

Check from promp using:

```<code>docker container ls
</code>```

You should see an instance of redis.

Body:
Goodday everyone, I am new to channels and Redis and i tried to follow the this part of the channels documentation, which says;

Let’s make sure that the channel layer can communicate with Redis. Open a Django shell and run the following
commands:

$ python3 manage.py shell
>>> import channels.layers

>>> channel_layer = channels.layers.get_channel_layer()

>>> from asgiref.sync import async_to_sync

>>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'})

>>> async_to_sync(channel_layer.receive)('test_channel'){'type': 'hello'}

but i run into this error;

>>> import channels.layers
>>> channel_layer = channels.layers.get_channel_layer()
>>> from asgiref.sync import async_to_sync

>>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'})
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\LENOVO\Project\BuildUp\lib\site-packages\asgiref\sync.py", line 116, in __call__
    return call_result.result()
  File "C:\Python37\Lib\concurrent\futures\_base.py", line 428, in result
    return self.__get_result()
  File "C:\Python37\Lib\concurrent\futures\_base.py", line 384, in __get_result
    raise self._exception
  File "C:\Users\LENOVO\Project\BuildUp\lib\site-packages\asgiref\sync.py", line 156, in main_wrap
    result = await self.awaitable(*args, **kwargs)
  File "C:\Users\LENOVO\Project\BuildUp\lib\site-packages\channels_redis\core.py", line 293, in send
    async with self.connection(index) as connection:
  File "C:\Users\LENOVO\Project\BuildUp\lib\site-packages\channels_redis\core.py", line 820, in __aenter__
    self.conn = await self.pool.pop()
  File "C:\Users\LENOVO\Project\BuildUp\lib\site-packages\channels_redis\core.py", line 70, in pop
    conns.append(await aioredis.create_redis(**self.host, loop=loop))
  File "C:\Users\LENOVO\Project\BuildUp\lib\site-packages\aioredis\commands\__init__.py", line 175, in create_redis
    loop=loop)
  File "C:\Users\LENOVO\Project\BuildUp\lib\site-packages\aioredis\connection.py", line 113, in create_connection
    timeout)
  File "C:\Python37\Lib\asyncio\tasks.py", line 414, in wait_for
    return await fut
  File "C:\Users\LENOVO\Project\BuildUp\lib\site-packages\aioredis\stream.py", line 24, in open_connection
    lambda: protocol, host, port, **kwds)
  File "C:\Python37\Lib\asyncio\base_events.py", line 954, in create_connection
    raise exceptions[0]
  File "C:\Python37\Lib\asyncio\base_events.py", line 941, in create_connection
    await self.sock_connect(sock, address)
  File "C:\Python37\Lib\asyncio\selector_events.py", line 464, in sock_connect
    return await fut
  File "C:\Python37\Lib\asyncio\selector_events.py", line 494, in _sock_connect_cb
    raise OSError(err, f'Connect call failed {address}')
ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 6379)

And i have 'channels' in my INSTALLED_APPS, I also have the CHANNEL_LAYERS in my settings;

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}

I am using python 3.7.5 and when i enter 'pip freeze' command i see the following;

aioredis==1.3.1
asgiref==3.2.3
async-timeout==3.0.1
attrs==19.3.0
autobahn==19.11.1
Automat==0.8.0
cffi==1.13.2
channels==2.4.0
channels-redis==2.4.1
constantly==15.1.0
cryptography==2.8
daphne==2.4.1
Django==3.0.1
django-countries==5.5
django-crispy-forms==1.8.1
djangorestframework==3.11.0
hiredis==1.0.1
hyperlink==19.0.0
idna==2.8
incremental==17.5.0
msgpack==0.6.2
Pillow==6.2.1
pyasn1==0.4.8
pyasn1-modules==0.2.7
pycparser==2.19
PyHamcrest==1.9.0
pyOpenSSL==19.1.0
pytz==2019.3
service-identity==18.1.0
six==1.13.0
sqlparse==0.3.0
Twisted==19.10.0
txaio==18.8.1
zope.interface==4.7.1

Body:
Did you run redis instance like this?

docker run -p 6379:6379 -d redis:5

Check from promp using:

docker container ls

You should see an instance of redis.


问:
mongodb $slice elements out of deep nested array
I have a deep nested array like this:

```<code>_id: userId,
posts: [
   {
      _id: postId,
      comments: [{...},{...}]
   }
]
</code>```

I have 2 Inputs:

userId
postId

Now i want to slice the last 5 elements out of the comments array with $slice: [-5, 5] but i dont exactly know how to select such a deep nested array correctly.

My attempt was to slice it out like this, but it failed:

```<code>  let result = await Post.aggregate([
    {
      $match: {
        _id: userId,
        "posts._id": postId
      }
    },
    {
      "posts.$.comments": {
        $slice: [-5, 5]
      }
    },
    {
      $project: {
        posts: 1
      }
    }
  ]);
</code>```

答:
You can simply use $map expression and return a new sliced comments array and set it back again to posts array:

```<code>db.collection.aggregate([
  {
    $match: {
      _id: userId,
      "posts._id": postId
    }
  },
  {
    "$addFields": {
      "posts": {
        "$map": {
          "input": "$posts", "as": "p",
          "in": {
            "_id": "$$p._id",
            "comments": { "$slice": [ "$$p.comments", -5, 5 ] }
          }
        }
      }
    }
  },
  {
    $project: {
      posts: {
        $filter: {
          input: "$posts", as: "posts",
          cond: { $eq: [ "$$posts._id", postId ] }
        }
      }
    }
  }
])
</code>```

I have not tested the slicing part. Please check the $slice docs once to match it with your requirement.

Body:
I have a deep nested array like this:

_id: userId,
posts: [
   {
      _id: postId,
      comments: [{...},{...}]
   }
]

I have 2 Inputs:

userId
postId

Now i want to slice the last 5 elements out of the comments array with $slice: [-5, 5] but i dont exactly know how to select such a deep nested array correctly.

My attempt was to slice it out like this, but it failed:

  let result = await Post.aggregate([
    {
      $match: {
        _id: userId,
        "posts._id": postId
      }
    },
    {
      "posts.$.comments": {
        $slice: [-5, 5]
      }
    },
    {
      $project: {
        posts: 1
      }
    }
  ]);

Body:
You can simply use $map expression and return a new sliced comments array and set it back again to posts array:

db.collection.aggregate([
  {
    $match: {
      _id: userId,
      "posts._id": postId
    }
  },
  {
    "$addFields": {
      "posts": {
        "$map": {
          "input": "$posts", "as": "p",
          "in": {
            "_id": "$$p._id",
            "comments": { "$slice": [ "$$p.comments", -5, 5 ] }
          }
        }
      }
    }
  },
  {
    $project: {
      posts: {
        $filter: {
          input: "$posts", as: "posts",
          cond: { $eq: [ "$$posts._id", postId ] }
        }
      }
    }
  }
])

I have not tested the slicing part. Please check the $slice docs once to match it with your requirement.


问:
Implicit Intent is not working due to context issue
Here is my code :-

Favourite Activity

```<code>import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat.startActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.security.AccessController.getContext

//this is my calling activity
class FavouriteActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.favourite_activity)
        val mToolbar: Toolbar = findViewById(R.id.toolbar_favourite)
        setSupportActionBar(mToolbar)
        getSupportActionBar()?.setDisplayHomeAsUpEnabled(true);
        getSupportActionBar()?.setDisplayShowHomeEnabled(true);
        setTitle("Favourite Activity");

        //getting recyclerview from xml
        val recyclerView = findViewById(R.id.recyclerView) as RecyclerView
        //adding a layoutmanager
        recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        //it can be staggered and grid
        //creating our adapter
        val adapter = CustomAdapter(star)   //here I am calling the adapter activity
        //now adding the adapter to recyclerview
        recyclerView.adapter = adapter

    }
  override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return true
    }
}
</code>```

CustomAdapter class

```<code>class CustomAdapter(val userList: ArrayList<User>) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    //this method is returning the view for each item in the list
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapter.ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.list_layout_favourite, parent, false)
        return ViewHolder(v)
    }

    //this method is binding the data on the list
    override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
        holder.bindItems(userList[position])

        holder.imgCopy.setOnClickListener(View.OnClickListener {
            holder.shareString(userList[position])
            Toast.makeText(holder.itemView.getContext(),"Copy Button Clicked", Toast.LENGTH_SHORT).show()

        })
    }

    //this method is giving the size of the list
    override fun getItemCount(): Int {
        return userList.size
    }

    //the class is holding the list view
    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val imgCopy: ImageView = itemView.findViewById(R.id.img_copy) as ImageView

        val textViewName = itemView.findViewById(R.id.tvTitle) as TextView

        fun bindItems(user: User) {

            textViewName.text = user.name

        }

        fun shareString(user: User)
        {
            val message : String = user.name
            val intent = Intent()
            intent.action = Intent.ACTION_SEND
            intent.putExtra(Intent.EXTRA_TEXT,message)
            intent.type = "text/plain"
            startActivity(Intent.createChooser(intent,"Share to :"))    ///Issue occur right here
          }}}
</code>```

Getting error : Required context , found Intent.

it is working fine in other FragmentActivity.
I have tried various methods to called the context. but anything is not working.
I have also passed the context from Fragment activity, but that also not worked.
Please let me know is there any way to start Intent.
As I am always getting error and stuck due to this.

答:
The startActivity available in the ViewHolder class is different from the  one available in activites. So in this method (available in viewholder), the first parameter should be a context. So pass the context as follows:

```<code>startActivity(itemView.context, Intent.createChooser(intent,"Share to :"))
</code>```

Body:
Here is my code :-

Favourite Activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat.startActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.security.AccessController.getContext

//this is my calling activity
class FavouriteActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.favourite_activity)
        val mToolbar: Toolbar = findViewById(R.id.toolbar_favourite)
        setSupportActionBar(mToolbar)
        getSupportActionBar()?.setDisplayHomeAsUpEnabled(true);
        getSupportActionBar()?.setDisplayShowHomeEnabled(true);
        setTitle("Favourite Activity");

        //getting recyclerview from xml
        val recyclerView = findViewById(R.id.recyclerView) as RecyclerView
        //adding a layoutmanager
        recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        //it can be staggered and grid
        //creating our adapter
        val adapter = CustomAdapter(star)   //here I am calling the adapter activity
        //now adding the adapter to recyclerview
        recyclerView.adapter = adapter

    }
  override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return true
    }
}

CustomAdapter class

class CustomAdapter(val userList: ArrayList<User>) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    //this method is returning the view for each item in the list
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapter.ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.list_layout_favourite, parent, false)
        return ViewHolder(v)
    }

    //this method is binding the data on the list
    override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
        holder.bindItems(userList[position])

        holder.imgCopy.setOnClickListener(View.OnClickListener {
            holder.shareString(userList[position])
            Toast.makeText(holder.itemView.getContext(),"Copy Button Clicked", Toast.LENGTH_SHORT).show()

        })
    }

    //this method is giving the size of the list
    override fun getItemCount(): Int {
        return userList.size
    }

    //the class is holding the list view
    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val imgCopy: ImageView = itemView.findViewById(R.id.img_copy) as ImageView

        val textViewName = itemView.findViewById(R.id.tvTitle) as TextView

        fun bindItems(user: User) {

            textViewName.text = user.name

        }

        fun shareString(user: User)
        {
            val message : String = user.name
            val intent = Intent()
            intent.action = Intent.ACTION_SEND
            intent.putExtra(Intent.EXTRA_TEXT,message)
            intent.type = "text/plain"
            startActivity(Intent.createChooser(intent,"Share to :"))    ///Issue occur right here
          }}}

Getting error : Required context , found Intent.

it is working fine in other FragmentActivity.
I have tried various methods to called the context. but anything is not working.
I have also passed the context from Fragment activity, but that also not worked.
Please let me know is there any way to start Intent.
As I am always getting error and stuck due to this.

Body:
The startActivity available in the ViewHolder class is different from the  one available in activites. So in this method (available in viewholder), the first parameter should be a context. So pass the context as follows:

startActivity(itemView.context, Intent.createChooser(intent,"Share to :"))


问:
React Native: dim background of modal screen
How can I dim the background of my modal? I'm using a stack navigator with mode modal for clarity. I've managed to get the background to be transparent but not sure how to dim the background screen. Here is my stack navigator code:

```<code>import {createStackNavigator} from 'react-navigation-stack';
import Home from '../components/home/Home';
import Settings from '../components/settings/Settings';

const AppStack = createStackNavigator(
  {
    Home: {
      screen: Home,
    },
    Settings: {
      screen: Settings,
      navigationOptions: {
        gestureResponseDistance: {vertical: 800},
      },
    },
  },
  {
    mode: 'modal',
    headerMode: 'none',
    transparentCard: true,
  },
);

export default AppStack;

</code>```

Thanks in advance!

答:
You might need to add another property of opacity in your code to the cardStyle. You can read more about it in a similar github issue raised here. https://github.com/react-navigation/react-navigation/issues/7085

```<code> {
mode: "modal",
headerMode: "none",
transparentCard: true,
defaultNavigationOptions: {
  gesturesEnabled: false
},
cardStyle: {
  // makes transparentCard work for android
  opacity: 1.0
}
</code>```

Body:
How can I dim the background of my modal? I'm using a stack navigator with mode modal for clarity. I've managed to get the background to be transparent but not sure how to dim the background screen. Here is my stack navigator code:

import {createStackNavigator} from 'react-navigation-stack';
import Home from '../components/home/Home';
import Settings from '../components/settings/Settings';

const AppStack = createStackNavigator(
  {
    Home: {
      screen: Home,
    },
    Settings: {
      screen: Settings,
      navigationOptions: {
        gestureResponseDistance: {vertical: 800},
      },
    },
  },
  {
    mode: 'modal',
    headerMode: 'none',
    transparentCard: true,
  },
);

export default AppStack;

Thanks in advance!

Body:
You might need to add another property of opacity in your code to the cardStyle. You can read more about it in a similar github issue raised here. https://github.com/react-navigation/react-navigation/issues/7085

 {
mode: "modal",
headerMode: "none",
transparentCard: true,
defaultNavigationOptions: {
  gesturesEnabled: false
},
cardStyle: {
  // makes transparentCard work for android
  opacity: 1.0
}


问:
Change specific values in dataframe
I have df like this:

```<code>Name   Value       NUM_SC

A      1000        421

B      2000        127

C      3000        511

D      2000        718

E      1500        511 (may duplicate)
</code>```

And I would like to multiply some Values by (-1) based on their NUM_SC. For example, for 511 and 127 in NUM_SC multiply Value by (-1). What worked for me is:

```<code>for i in negative_sc:
    for j in range(76818):
        if df.NUM_SC[j] == i:
            df.Values[j] *= (-1)
</code>```

where  negative_sc containts NUM_SC for which I would like multiply Value by (-1). In this example negative_sc = (511,127).

But this method takes a lot of time. I tried something like this:

```<code>for i in negative_sc:
   df[df.NUM_SC == i].Values *= (-1)
</code>```

But this produced error and didn't yield any results.

What is the best way to handle tasks like this? Change values in one column based on values in another column

Thanks a lot!

答:
try this, using isin create a mask for columns you would like need to negate.</p>

```<code>negative_sc = [511, 127]

mask = df['NUM_SC'].isin(negative_sc)

df.loc[mask, 'Value'] = df.loc[mask, 'Value'] * -1
</code>```

Title: Change specific values in dataframe

Body:
I have df like this:

Name   Value       NUM_SC

A      1000        421

B      2000        127

C      3000        511

D      2000        718

E      1500        511 (may duplicate)

And I would like to multiply some Values by (-1) based on their NUM_SC. For example, for 511 and 127 in NUM_SC multiply Value by (-1). What worked for me is:

for i in negative_sc:
    for j in range(76818):
        if df.NUM_SC[j] == i:
            df.Values[j] *= (-1)

where  negative_sc containts NUM_SC for which I would like multiply Value by (-1). In this example negative_sc = (511,127).

But this method takes a lot of time. I tried something like this:

for i in negative_sc:
   df[df.NUM_SC == i].Values *= (-1)

But this produced error and didn't yield any results.

What is the best way to handle tasks like this? Change values in one column based on values in another column

Thanks a lot!

Body:
try this, using isin create a mask for columns you would like need to negate.

negative_sc = [511, 127]

mask = df['NUM_SC'].isin(negative_sc)

df.loc[mask, 'Value'] = df.loc[mask, 'Value'] * -1


问:
How to add a transition effect to an image when changing its SRC with Javascript?
I want to add a transition effect to an image tag when changing its SRC. I have the following:

```<code>let bverse = document.getElementById('bible-verse');

setTimeout(function(){
    bverse.src="../images/bverses/verse2.jpg";
}, 5000);
</code>```

I have managed to add a transition effect to the background image with:

JavaScript:

```<code>let slider = document.getElementById('hero-slider');

setTimeout(function(){
    slider.style.backgroundImage="url(../images/hero/slider-2.jpg)";
}, 5000);
</code>```

CSS:

```<code>.hero-bg {
    background-image: url(../images/hero/slider-0.jpg);
    transition: background-image 2s;
}
</code>```

But I dont' seem to get the same effect when adding the same styles to the CSS of the bible-verse class. How can I add a transition effect to the bible-verse img tag, without the need of a div container?

答:
Transition property won't work with properties like background-image

Here you have the list oof animatable css properties: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties

But you could do some workaround here by animating image with @keyframes animations. It depends on what effect you would like to achieve. But I have one example. If you would like to create an animation of image sliding, you could create two images, one would be hidden under the visible image, and via @keyframes you could just move the first visible behind the container it is in and then delete it, when it is offscreen. It would have to been done with combining JavaScript (to add a class that animates an image, delete image, etc) and CSS (to animate an image).

Body:
I want to add a transition effect to an image tag when changing its SRC. I have the following:

let bverse = document.getElementById('bible-verse');

setTimeout(function(){
    bverse.src="../images/bverses/verse2.jpg";
}, 5000);

I have managed to add a transition effect to the background image with:

JavaScript:

let slider = document.getElementById('hero-slider');

setTimeout(function(){
    slider.style.backgroundImage="url(../images/hero/slider-2.jpg)";
}, 5000);

CSS:

.hero-bg {
    background-image: url(../images/hero/slider-0.jpg);
    transition: background-image 2s;
}

But I dont' seem to get the same effect when adding the same styles to the CSS of the bible-verse class. How can I add a transition effect to the bible-verse img tag, without the need of a div container?


问:
Change color text with click on Angular
I want to make a simple thing that the user input a color that he choose and make the color begin on some paragraph .

The input and the click button that the user send the inputColor to the typescript  :

```<code><form>
    <input #inputColor  type="text"/>
    <button type="button" (click)="changeColorText(inputColor)"></button>
    </form>
</code>```

The function changeColorText() on the typescript :

```<code>export class HelloWorld implements OnInit {
public inputColor:string;

  constructor() { }

  ngOnInit(): void {
  }

  public changeColorText(str:string) :void {
    this.inputColor = str;
  }

}
</code>```

The problem :

The paragraph change the color if i choose one (Witout input from the user) :

```<code><p style="color:blue">Hello World !</p>
</code>```

But I want what the user put in the box to make the paragraph like the color that sent, I couldn't find the correct syntax here:

```<code><p style="color:{{inputColor}}">Hello World !</p> // ERROR !!!!

<p style=`color:{{inputColor}}`>Hello World !</p> // No compilation error .. but not working:
</code>```

答:
Have you tried with:

```<code><form>
    <input #inputColor  type="text"/>
    <button type="button" (click)="changeColorText(inputColor.value)">ClickMe</button>
</form>

<p style="color: {{inputColor.value}}">Hello World !</p>
</code>```

You have to take the value from inputColor as it's an HTMLElement on this side.

Another option, is to have different names from the element and your string, for example:

```<code><form>
    <input #inputColor  type="text"/>
    <button type="button" (click)="changeColorText(inputColor.value)">ClickMe</button>
</form>

<p style="color: {{inputColorStr}}">Hello World !</p>
</code>```

With

```<code>  public inputColorStr: string;

  public changeColorText(str: string): void {
    this.inputColorStr = str;
  }
</code>```

Title: Change color text with click on Angular

Body:
I want to make a simple thing that the user input a color that he choose and make the color begin on some paragraph .

The input and the click button that the user send the inputColor to the typescript  :

<form>
    <input #inputColor  type="text"/>
    <button type="button" (click)="changeColorText(inputColor)"></button>
    </form>

The function changeColorText() on the typescript :

export class HelloWorld implements OnInit {
public inputColor:string;

  constructor() { }

  ngOnInit(): void {
  }

  public changeColorText(str:string) :void {
    this.inputColor = str;
  }

}

The problem :

The paragraph change the color if i choose one (Witout input from the user) :

Hello World !

But I want what the user put in the box to make the paragraph like the color that sent, I couldn't find the correct syntax here:

Hello World !
 // ERROR !!!!

<p style=`color:{{inputColor}}`>Hello World !
 // No compilation error .. but not working:

Body:
Have you tried with:

<form>
    <input #inputColor  type="text"/>
    <button type="button" (click)="changeColorText(inputColor.value)">ClickMe</button>
</form>

<p style="color: {{inputColor.value}}">Hello World !</p>

You have to take the value from inputColor as it's an HTMLElement on this side.

Another option, is to have different names from the element and your string, for example:

<form>
    <input #inputColor  type="text"/>
    <button type="button" (click)="changeColorText(inputColor.value)">ClickMe</button>
</form>

<p style="color: {{inputColorStr}}">Hello World !</p>

With

  public inputColorStr: string;

  public changeColorText(str: string): void {
    this.inputColorStr = str;
  }


问:
QTabWidget insert a QSplitter can't switch when the splitter disabled
I insert a QFrame and QTabWidget in the QSplitter. And I wanna forbidden to adjust the size of elements in QSplitter. So I call method of 'setDisabled' in QSplitter. It's useful for disabling resizing the elements. But I also can't switch tab of QTabWidget. Who can give me some suggestions? Thanks very much......

```<code>import sys
from PyQt5.QtWidgets import QApplication, QWidget, QSplitter, QHBoxLayout, QFrame, QTabWidget
from PyQt5.QtCore import Qt
class Example1(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(0, 0, 600, 600)
        self.setWindowTitle("Demo")
        self.layout = QHBoxLayout()

        top_frame = QFrame()
        top_frame.setFrameShape(QFrame.StyledPanel)

        bottom_frame = QTabWidget(self)
        tab1 = QWidget()
        tab2 = QWidget()
        bottom_frame.setTabText(0, "Generic")
        bottom_frame.setTabText(1, "Other")
        bottom_frame.addTab(tab1, "Tab 1")
        bottom_frame.addTab(tab2, "Tab 2")

        splitter = QSplitter()
        splitter.setOrientation(Qt.Vertical)
        splitter.addWidget(top_frame)
        splitter.addWidget(bottom_frame)
        splitter.setSizes([300, 300])
        **splitter.setDisabled(True)**

        self.layout.addWidget(splitter)
        self.setLayout(self.layout)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example1()
    sys.exit(app.exec_())

</code>```

the running result of the program

答:
QSplitter lets you get hold of its handles, which are the GUI element visible to the user. If you have two widgets in a splitter, you have a single visible handle; the handle at index 0 is always invisible.

You can manipulate that widget explicitely, e.g. disable it. Try:

```<code>splitter.handle(1).enabled = False
</code>```

This disables only said GUI element, while the rest of the splitter (your two content widgets) will stay enabled.

Body:
I insert a QFrame and QTabWidget in the QSplitter. And I wanna forbidden to adjust the size of elements in QSplitter. So I call method of 'setDisabled' in QSplitter. It's useful for disabling resizing the elements. But I also can't switch tab of QTabWidget. Who can give me some suggestions? Thanks very much......

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QSplitter, QHBoxLayout, QFrame, QTabWidget
from PyQt5.QtCore import Qt
class Example1(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(0, 0, 600, 600)
        self.setWindowTitle("Demo")
        self.layout = QHBoxLayout()

        top_frame = QFrame()
        top_frame.setFrameShape(QFrame.StyledPanel)

        bottom_frame = QTabWidget(self)
        tab1 = QWidget()
        tab2 = QWidget()
        bottom_frame.setTabText(0, "Generic")
        bottom_frame.setTabText(1, "Other")
        bottom_frame.addTab(tab1, "Tab 1")
        bottom_frame.addTab(tab2, "Tab 2")

        splitter = QSplitter()
        splitter.setOrientation(Qt.Vertical)
        splitter.addWidget(top_frame)
        splitter.addWidget(bottom_frame)
        splitter.setSizes([300, 300])
        **splitter.setDisabled(True)**

        self.layout.addWidget(splitter)
        self.setLayout(self.layout)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example1()
    sys.exit(app.exec_())

the running result of the program

Body:
QSplitter lets you get hold of its handles, which are the GUI element visible to the user. If you have two widgets in a splitter, you have a single visible handle; the handle at index 0 is always invisible.

You can manipulate that widget explicitely, e.g. disable it. Try:

splitter.handle(1).enabled = False

This disables only said GUI element, while the rest of the splitter (your two content widgets) will stay enabled.


问:
Silverlight - How do I make the Listbox selection region the same shape as the list box item
I am using a Listbox with a the ItemsPanelTemplate set to a Canvas. This is so I can position Polygons on the canvas and still have them selectable. The problem I am having is the selection region is not shaped to the same size as the polygon (it is a rectangular shape that covers the extent of the polygon)</p>

```<code><ListBox Name="LayoutList" ItemsSource="{Binding LayoutItems}" ItemContainerStyle="{StaticResource LayoutItemStyle}">
<ListBox.ItemsPanel>
    <ItemsPanelTemplate>
        <Canvas x:Name="LayoutCanvas" Background="Beige">
        </Canvas>
    </ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
    <DataTemplate>
        <Polygon Points="{Binding Points}" Stroke="{Binding Stroke}" StrokeThickness="1"/>
    </DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</code>```

答:
The selection region is determined by the item container; I'm not certain, but you might be able to do what you want by modifying the ListBox.ItemContainerStyle (instead of or in addition to the DataTemplate). Something like this:</p>

```<code><ListBox>

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <Polygon Points="{Binding Points}" Stroke="{Binding Stroke}" StrokeThickness="1"/>

                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ListBox.ItemContainerStyle>

</ListBox>
</code>```

Body:
I am using a Listbox with a the ItemsPanelTemplate set to a Canvas. This is so I can position Polygons on the canvas and still have them selectable. The problem I am having is the selection region is not shaped to the same size as the polygon (it is a rectangular shape that covers the extent of the polygon)

<ListBox Name="LayoutList" ItemsSource="{Binding LayoutItems}" ItemContainerStyle="{StaticResource LayoutItemStyle}">
<ListBox.ItemsPanel>
    <ItemsPanelTemplate>
        <Canvas x:Name="LayoutCanvas" Background="Beige">
        </Canvas>
    </ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
    <DataTemplate>
        <Polygon Points="{Binding Points}" Stroke="{Binding Stroke}" StrokeThickness="1"/>
    </DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Body:
The selection region is determined by the item container; I'm not certain, but you might be able to do what you want by modifying the ListBox.ItemContainerStyle (instead of or in addition to the DataTemplate). Something like this:

<ListBox>

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <Polygon Points="{Binding Points}" Stroke="{Binding Stroke}" StrokeThickness="1"/>

                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ListBox.ItemContainerStyle>

</ListBox>