问:
Disable offline mode and rerun the build
```<code>A problem occurred configuring root project 'customerapp'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not resolve com.android.tools.build:gradle:4.1.3.
     Required by:
         project :
      > No cached version of com.android.tools.build:gradle:4.1.3 available for offline mode.
      > No cached version of com.android.tools.build:gradle:4.1.3 available for offline mode.
   > Could not resolve com.google.gms:google-services:4.3.5.
     Required by:
         project :
      > No cached version of com.google.gms:google-services:4.3.5 available for offline mode.
      > No cached version of com.google.gms:google-services:4.3.5 available for offline mode.
   > Could not resolve com.android.tools.build:gradle:4.1.3.
     Required by:
         project : > com.jakewharton:butterknife-gradle-plugin:9.0.0-rc2
      > No cached version of com.android.tools.build:gradle:4.1.3 available for offline mode.
      > No cached version of com.android.tools.build:gradle:4.1.3 available for offline mode.
   > Could not resolve org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.71.
     Required by:
         project : > com.jakewharton:butterknife-gradle-plugin:9.0.0-rc2
      > No cached version of org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.71 available for offline mode.
      > No cached version of org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.71 available for offline mode.
   > Could not resolve org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.71.
     Required by:
         project : > io.realm:realm-gradle-plugin:7.0.0 > io.realm:realm-transformer:7.0.0
      > No cached version of org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.71 available for offline mode.
      > No cached version of org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.71 available for offline mode.

Possible solution:
 - Disable offline mode and rerun the build
</code>```

Already checked and applied these answers:-

No cached version of com.android.tools.build:aapt2:3.2.0-alpha18-4804415 available for offline mode

enable & disable Gradle offline mode?

enable/disable offline mode in andriod studio 4.0

Gradle not searching dependencies online

答:
I had a similar problem. This is solution that worked for me (Android Studion 4.1.1):

As Rodrigo said in the answer above above, go to View > Tool Windows > Gradle

Right click on the project in Gradle tab and select "Refresh Gradle Dependencies"

Clean / Rebuild if needed. You may also need to Invalidate cache and restart android studio (File -> Invalidate cache / restart).

Body:
A problem occurred configuring root project 'customerapp'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not resolve com.android.tools.build:gradle:4.1.3.
     Required by:
         project :
      > No cached version of com.android.tools.build:gradle:4.1.3 available for offline mode.
      > No cached version of com.android.tools.build:gradle:4.1.3 available for offline mode.
   > Could not resolve com.google.gms:google-services:4.3.5.
     Required by:
         project :
      > No cached version of com.google.gms:google-services:4.3.5 available for offline mode.
      > No cached version of com.google.gms:google-services:4.3.5 available for offline mode.
   > Could not resolve com.android.tools.build:gradle:4.1.3.
     Required by:
         project : > com.jakewharton:butterknife-gradle-plugin:9.0.0-rc2
      > No cached version of com.android.tools.build:gradle:4.1.3 available for offline mode.
      > No cached version of com.android.tools.build:gradle:4.1.3 available for offline mode.
   > Could not resolve org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.71.
     Required by:
         project : > com.jakewharton:butterknife-gradle-plugin:9.0.0-rc2
      > No cached version of org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.71 available for offline mode.
      > No cached version of org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.71 available for offline mode.
   > Could not resolve org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.71.
     Required by:
         project : > io.realm:realm-gradle-plugin:7.0.0 > io.realm:realm-transformer:7.0.0
      > No cached version of org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.71 available for offline mode.
      > No cached version of org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.71 available for offline mode.

Possible solution:
 - Disable offline mode and rerun the build

Already checked and applied these answers:-

No cached version of com.android.tools.build:aapt2:3.2.0-alpha18-4804415 available for offline mode

enable & disable Gradle offline mode?

enable/disable offline mode in andriod studio 4.0

Gradle not searching dependencies online


来源: stackexchange

问:
Pine script: ist it possible to evaluate next candle values? to get relative lowest

I'm trying to detect the if each candle is the lowest value, checking 5 previous candles lows and 5 next candles lows

I found no problem with previous:

if ta.lowest(low, 5) == low
    line.new(bar_index - 1, low, bar_index + 1, low, color = color.red, width = 1)

To evaluate if current canle is lower than next ones, I've tried to use negative value on "ta.lowest(low, -5)" but it does not work.
Can you give me a hand?

答:
I'm trying to detect the if each candle is the lowest value, checking
5 previous candles lows and 5 next candles lows

What you have described is implemented in the built-in ta.pivotlow() function, it searches for a pattern and finds the lowest value in the given range to the left (leftbars= argument) and to the right (rightbars=).

As was mentioned, you can't look into the future bars, so the result of the pivot function lags to the amount of bars declared with the rightbars= argument. Note that the plotshape() function uses the same offset as the rightbars= argument.

```<code>//@version=5
indicator("pivotlow", overlay = true)
leftbars = 5
rightbars = 5
pivLow = ta.pivotlow(leftbars, rightbars)
plotshape(pivLow, style = shape.labelup, location = location.belowbar, offset = - rightbars)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to detect the if each candle is the lowest value, checking
5 previous candles lows and 5 next candles lows

What you have described is implemented in the built-in ta.pivotlow() function, it searches for a pattern and finds the lowest value in the given range to the left (leftbars= argument) and to the right (rightbars=).

As was mentioned, you can't look into the future bars, so the result of the pivot function lags to the amount of bars declared with the rightbars= argument. Note that the plotshape() function uses the same offset as the rightbars= argument.

//@version=5
indicator("pivotlow", overlay = true)
leftbars = 5
rightbars = 5
pivLow = ta.pivotlow(leftbars, rightbars)
plotshape(pivLow, style = shape.labelup, location = location.belowbar, offset = - rightbars)


问:
How can distribute one table data to another table
I have two tables Orderapproval and stock:

Table 1:  Orderapproval

itemcode
approvalqty

1
25

2
10

Table 2: stock

itemcode
stockqty
batch
date

1
5
aa
2021-02-01

1
10
bb
2021-02-10

1
15
cc
2021-02-02

2
5
dd
2021-02-01

2
20
aa
2021-02-05

we have stock batch-wise.
when we get an order request for an item
we are trying to pick up items from the old batch first & so on
How can I get a result set like this:

itemcode
qty
batch
date

1
5
aa
2021-02-01

1
15
cc
2021-02-02

1
5
bb
2021-02-10

2
5
dd
2021-02-01

I am trying as......

Declare @StockTable table
(ItemCode int,BranchCode int,Qty int)
Insert Into @StockTable values
(1,       101,          5),
(1,       102,           10),
(1,       101,          15),
(2,       102,           5),
(2,       103,           20)

Declare @Orderapproval table (ItemCode int,Qty int)
Insert Into @Orderapproval values
(1,25),
(2,10)

;with T1 as (
Select A.*
,ToDist  = cast(D.Qty as int),
running_total = SUM(D.Qty) OVER (PARTITION BY  A.ItemCode,BranchCode  ORDER BY  BranchCode  DESC
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW)

```<code>     From  @StockTable A

     Join  @Orderapproval D on A.ItemCode=D.ItemCode    )
</code>```

, T2 as (
Select *,   prev_running_total = LAG(Qty,1,0) OVER (PARTITION BY  ItemCode ORDER BY  BranchCode  DESC) From T1

)

select *,
CASE WHEN prev_running_total >= ToDist THEN 0

WHEN running_total > ToDist THEN ToDist - prev_running_total

ELSE qty
END 'qty'
from T2;

I didn't get the right output.
Please suggest  a better way

答:
I tried it on SQLite 3.30

Schema:

```<code>CREATE TABLE stock (
  id INT,
  itemcode INT,
  stockqty INT,
  batch CHAR,
  date DATE
);
INSERT INTO stock (id, itemcode, stockqty, batch, date) VALUES (1, 1, 5, 'aa', '2021-02-01');
INSERT INTO stock (id, itemcode, stockqty, batch, date) VALUES (2, 1, 10, 'bb', '2021-02-10');
INSERT INTO stock (id, itemcode, stockqty, batch, date) VALUES (3, 1, 15, 'cc', '2021-02-02');
INSERT INTO stock (id, itemcode, stockqty, batch, date) VALUES (4, 2, 5, 'dd', '2021-02-01');
INSERT INTO stock (id, itemcode, stockqty, batch, date) VALUES (5, 2, 20, 'aa', '2021-02-05');

CREATE TABLE orderapproval (
  id INT,
  itemcode INT,
  approvalqty INT
);
INSERT INTO orderapproval (id, itemcode, approvalqty) VALUES (1, 1, 25);
INSERT INTO orderapproval (id, itemcode, approvalqty) VALUES (2, 2, 10);
</code>```

Query:

```<code>with a as ( SELECT *, sum(stockqty) over (partition by itemcode order by date ) as acc FROM stock)
select a.itemcode, case when acc<=approvalqty then stockqty else approvalqty-(acc-stockqty) end as qty, batch, date from a
inner join orderapproval o
on a.itemcode = o.itemcode
where qty > 0
order by a.itemcode, date
</code>```

Result:

itemcode
qty
batch
date

1
5
aa
2021-02-01

1
15
cc
2021-02-02

1
5
bb
2021-02-10

2
5
dd
2021-02-01

2
5
aa
2021-02-05

db-fiddle

Body:
I have two tables Orderapproval and stock:

Table 1:  Orderapproval

itemcode
approvalqty

1
25

2
10

Table 2: stock

itemcode
stockqty
batch
date

1
5
aa
2021-02-01

1
10
bb
2021-02-10

1
15
cc
2021-02-02

2
5
dd
2021-02-01

2
20
aa
2021-02-05

we have stock batch-wise.
when we get an order request for an item
we are trying to pick up items from the old batch first & so on
How can I get a result set like this:

itemcode
qty
batch
date

1
5
aa
2021-02-01

1
15
cc
2021-02-02

1
5
bb
2021-02-10

2
5
dd
2021-02-01

I am trying as......

Declare @StockTable table
(ItemCode int,BranchCode int,Qty int)
Insert Into @StockTable values
(1,       101,          5),
(1,       102,           10),
(1,       101,          15),
(2,       102,           5),
(2,       103,           20)

Declare @Orderapproval table (ItemCode int,Qty int)
Insert Into @Orderapproval values
(1,25),
(2,10)

;with T1 as (
Select A.*
,ToDist  = cast(D.Qty as int),
running_total = SUM(D.Qty) OVER (PARTITION BY  A.ItemCode,BranchCode  ORDER BY  BranchCode  DESC
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW)

     From  @StockTable A

     Join  @Orderapproval D on A.ItemCode=D.ItemCode    )

, T2 as (
Select *,   prev_running_total = LAG(Qty,1,0) OVER (PARTITION BY  ItemCode ORDER BY  BranchCode  DESC) From T1

)

select *,
CASE WHEN prev_running_total >= ToDist THEN 0

WHEN running_total > ToDist THEN ToDist - prev_running_total

ELSE qty
END 'qty'
from T2;

I didn't get the right output.
Please suggest  a better way

Body:
I tried it on SQLite 3.30

Schema:

CREATE TABLE stock (
  id INT,
  itemcode INT,
  stockqty INT,
  batch CHAR,
  date DATE
);
INSERT INTO stock (id, itemcode, stockqty, batch, date) VALUES (1, 1, 5, 'aa', '2021-02-01');
INSERT INTO stock (id, itemcode, stockqty, batch, date) VALUES (2, 1, 10, 'bb', '2021-02-10');
INSERT INTO stock (id, itemcode, stockqty, batch, date) VALUES (3, 1, 15, 'cc', '2021-02-02');
INSERT INTO stock (id, itemcode, stockqty, batch, date) VALUES (4, 2, 5, 'dd', '2021-02-01');
INSERT INTO stock (id, itemcode, stockqty, batch, date) VALUES (5, 2, 20, 'aa', '2021-02-05');

CREATE TABLE orderapproval (
  id INT,
  itemcode INT,
  approvalqty INT
);
INSERT INTO orderapproval (id, itemcode, approvalqty) VALUES (1, 1, 25);
INSERT INTO orderapproval (id, itemcode, approvalqty) VALUES (2, 2, 10);

Query:

with a as ( SELECT *, sum(stockqty) over (partition by itemcode order by date ) as acc FROM stock)
select a.itemcode, case when acc<=approvalqty then stockqty else approvalqty-(acc-stockqty) end as qty, batch, date from a
inner join orderapproval o
on a.itemcode = o.itemcode
where qty > 0
order by a.itemcode, date

Result:

itemcode
qty
batch
date

1
5
aa
2021-02-01

1
15
cc
2021-02-02

1
5
bb
2021-02-10

2
5
dd
2021-02-01

2
5
aa
2021-02-05

db-fiddle


问:
How to make repaint for JDialog in Swing?
How to make repaint for JDialog in Swing?
If I click on convert button in JDialog I need to change GUI design of JDialog but it's not happening? Is their any solution?

```<code>    _convertAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            String para = new String();
            _task.setBookTypeId(13);
             initComponents();
           //   validate();
           //   repaint();
            setVisible(true);
        }
      };
</code>```

I'm setting booking type id is 13 .

```<code>if(_task.getBookTypeId()== 1){
    String colnames[] = {"Leg","Departure", "Date","Time", "Arrival","Date", "Time","How","Aircraft","PIC","Copilot"};
    MyTableModel mytablemodel = new MyTableModel(colnames);
    legdetailsTable = new JTable(mytablemodel);
    legdetailsTable.setRowSelectionAllowed(true);
}else {
    System.out.println("Brokered booking table");
    String   colnames[] = {"Leg","Departure", "Date","Time", "Arrival","Date", "Time","How"};
    MyTableModel mytablemodel = new MyTableModel(colnames);
    legdetailsTable = new JTable(mytablemodel);
    legdetailsTable.setRowSelectionAllowed(true);
}
</code>```

Using Id I'm changing componenents in initcomponents method.

答:
You can get the Window of the current  Component or any Component and than call repaint().

```<code>SwingUtilities.getWindowAncestor( this ).repaint();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How to make repaint for JDialog in Swing?
If I click on convert button in JDialog I need to change GUI design of JDialog but it's not happening? Is their any solution?

    _convertAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            String para = new String();
            _task.setBookTypeId(13);
             initComponents();
           //   validate();
           //   repaint();
            setVisible(true);
        }
      };

I'm setting booking type id is 13 .

if(_task.getBookTypeId()== 1){
    String colnames[] = {"Leg","Departure", "Date","Time", "Arrival","Date", "Time","How","Aircraft","PIC","Copilot"};
    MyTableModel mytablemodel = new MyTableModel(colnames);
    legdetailsTable = new JTable(mytablemodel);
    legdetailsTable.setRowSelectionAllowed(true);
}else {
    System.out.println("Brokered booking table");
    String   colnames[] = {"Leg","Departure", "Date","Time", "Arrival","Date", "Time","How"};
    MyTableModel mytablemodel = new MyTableModel(colnames);
    legdetailsTable = new JTable(mytablemodel);
    legdetailsTable.setRowSelectionAllowed(true);
}

Using Id I'm changing componenents in initcomponents method.

Body:
You can get the Window of the current  Component or any Component and than call repaint().

SwingUtilities.getWindowAncestor( this ).repaint();


问:
How to stretch list of images with vertical scrolling to fill screen
I have an html code that looks something like this:

```<code><ul>
  <li>
      <img src='...'
  </li>
  <li>
      <img src='...'
  </li>
  <li>
      <img src='...'
  </li>
...

</code>```

And the scss code looks like this:

```<code>ul {
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  overflow-x: auto;
  align-items: center;

  li {
    flex: 0 0 auto;
    position: relative;
    justify-content: center;
    background-color: white;
    box-sizing: border-box;
    padding: 10px 10px 25px;
    margin: 5px 5px 0 0;
    user-select: none;
    transition: background-color 0.5s;
  }
}
</code>```

The result is a list of images,with vertical scrolling, the images have their native resolution.
What i am trying to do, is to stretch the images, so that each image fills let's say 70% of the page width, or 100% , whatever.
I tried adding a img { width: 50vw; } , or setting the li width to different widths in percentages or vw, but nothing worked so far, any ideas?
Result:
https://imgur.com/0Q94QXe

答:
The problem is not in the code but in the image, if the image is too small it does not extend to the whole screen unless forced with px not to stretch

but if the image is in good quality with quite high resolution set only width: 100%; and everything works smoothly.

If my code didn't help, please update your code and add an image.

ul {
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  overflow-x: auto;
  align-items: center;

  li {
    flex: 0 0 auto;
    position: relative;
    justify-content: center;
    background-color: white;
    box-sizing: border-box;
    padding: 10px 10px 25px;
    margin: 5px 5px 0 0;
    user-select: none;
    transition: background-color 0.5s;
  }
  img{
    width: 100%;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>
      <img src='https://wallpaper.dog/large/994963.jpg'
  </li>
  <li>
      <img src='https://wallpaper.dog/large/994963.jpg'
  </li>
  <li>
      <img src='https://wallpaper.dog/large/994963.jpg'
  </li>
</ul></code>```

Body:
I have an html code that looks something like this:

      <img src='...'

      <img src='...'

      <img src='...'

...

And the scss code looks like this:

ul {
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  overflow-x: auto;
  align-items: center;

  li {
    flex: 0 0 auto;
    position: relative;
    justify-content: center;
    background-color: white;
    box-sizing: border-box;
    padding: 10px 10px 25px;
    margin: 5px 5px 0 0;
    user-select: none;
    transition: background-color 0.5s;
  }
}

The result is a list of images,with vertical scrolling, the images have their native resolution.
What i am trying to do, is to stretch the images, so that each image fills let's say 70% of the page width, or 100% , whatever.
I tried adding a img { width: 50vw; } , or setting the li width to different widths in percentages or vw, but nothing worked so far, any ideas?
Result:
https://imgur.com/0Q94QXe

Body:
The problem is not in the code but in the image, if the image is too small it does not extend to the whole screen unless forced with px not to stretch

but if the image is in good quality with quite high resolution set only width: 100%; and everything works smoothly.

If my code didn't help, please update your code and add an image.

ul {
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  overflow-x: auto;
  align-items: center;

  li {
    flex: 0 0 auto;
    position: relative;
    justify-content: center;
    background-color: white;
    box-sizing: border-box;
    padding: 10px 10px 25px;
    margin: 5px 5px 0 0;
    user-select: none;
    transition: background-color 0.5s;
  }
  img{
    width: 100%;
  }

<ul>
  <li>
      <img src='https://wallpaper.dog/large/994963.jpg'
  </li>
  <li>
      <img src='https://wallpaper.dog/large/994963.jpg'
  </li>
  <li>
      <img src='https://wallpaper.dog/large/994963.jpg'
  </li>
</ul>


问:
Using DynamoDB with Vert.x
I am using Vert.x and I am trying to get items from DynamoDB table, by sort key and partition key. Here is how I build the client

```<code>private static DynamoDbAsyncClient buildDynamoDBAsyncClient(final Vertx vertx) {
        return VertxSdkClient.withVertx(DynamoDbAsyncClient.builder(), vertx.getOrCreateContext())
                .build();
    }
</code>```

And how I request the data.

```<code>    private List<CompletableFuture<List<Map<String, Object>>>> getOverrideMetadataRecord(Promise<OverrideMetadataEntry> promise) {
        final List<CompletableFuture<List<Map<String, Object>>>> resultList = new ArrayList<>();

                    final Map<String, KeysAndAttributes> requestItems = new HashMap<>();
                    requestItems.put(tableName, KeysAndAttributes.builder().keys(Arrays.asList(createMapKeyToGet())).build());
                    final BatchGetItemRequest batchGetItemRequest = BatchGetItemRequest.builder()
                            .requestItems(requestItems).build();
                    final CompletableFuture<List<Map<String, Object>>> futureBatchResponseData =
                            dynamoDbAsyncClient.batchGetItem(batchGetItemRequest).thenApply(this::getResponseData);
                    resultList.add(futureBatchResponseData);

                    return resultList;

    }
</code>```

I don't receive any objects and then I get operation timeout. What am I missing ? thank you in advance

答: Don't post the same question twice just cause you want an answer fast.</p>

Title: Using DynamoDB with Vert.x

Body:
I am using Vert.x and I am trying to get items from DynamoDB table, by sort key and partition key. Here is how I build the client

private static DynamoDbAsyncClient buildDynamoDBAsyncClient(final Vertx vertx) {
        return VertxSdkClient.withVertx(DynamoDbAsyncClient.builder(), vertx.getOrCreateContext())
                .build();
    }

And how I request the data.

    private List<CompletableFuture<List<Map<String, Object>>>> getOverrideMetadataRecord(Promise<OverrideMetadataEntry> promise) {
        final List<CompletableFuture<List<Map<String, Object>>>> resultList = new ArrayList<>();

                    final Map<String, KeysAndAttributes> requestItems = new HashMap<>();
                    requestItems.put(tableName, KeysAndAttributes.builder().keys(Arrays.asList(createMapKeyToGet())).build());
                    final BatchGetItemRequest batchGetItemRequest = BatchGetItemRequest.builder()
                            .requestItems(requestItems).build();
                    final CompletableFuture<List<Map<String, Object>>> futureBatchResponseData =
                            dynamoDbAsyncClient.batchGetItem(batchGetItemRequest).thenApply(this::getResponseData);
                    resultList.add(futureBatchResponseData);

                    return resultList;

    }

I don't receive any objects and then I get operation timeout. What am I missing ? thank you in advance


问:
Lock Mouse in primary screen
I have an application which use secondary monitor to display content. I dont want user to move curser to secondary monitor. I need to restrict the user to use mouse in primary monitor only. How can i do this.

Thanks

答:
The following article describes creating a global hook: Global Hook (code project)

I think this is closer to what you're asking because you wouldn't want to continuously poll with GetCursorPos() function, mentioned in the other answer. However, using the hook and the MouseMove event handler, I would use SetCursorPos() to keep it within bounds.

Cheers,

Jonno

Title: Lock Mouse in primary screen


问:
Flutter Decorate Drop Down Button
I have a dropdown button, and im trying to decorate or customize the dropdown but only the list of items that is shown when trying to select the item in the list of items, i want the inside to look like this

```<code>Center locationDropDown() {
    return Center(
      child: Container(
        margin: const EdgeInsets.all(40),
        padding: const EdgeInsets.symmetric(
          horizontal: 12,
        ),
        decoration: BoxDecoration(
          color: Colors.blue.shade50,
          borderRadius: BorderRadius.circular(15),
        ),
        child: DropdownButtonFormField<String>(
          iconSize: 28,
          iconEnabledColor: Colors.blue,
          isDense: false,
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Please select a location';
            }
          },
          decoration: const InputDecoration(
            enabledBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.transparent),
            ),
          ),
          value: chooseLocation,
          hint: const Text(
            'Select your project',
            style: TextStyle(fontSize: 15, color: Colors.blue),
          ),
          isExpanded: true,
          items: workingData!.map((account) {
            return DropdownMenuItem(
              child: Text(
                account.name + ' (${account.location})',
              ),
              value: account.id,
            );
          }).toList(),
          onChanged: (String? displayedValue) {
            setState(
              () {
                chooseLocation = displayedValue!;
              },
            );
          },
        ),
      ),
    );
  }
</code>```

答:
you need to specify the side: property. By default it is BorderSide.none.

```<code>  decoration: ShapeDecoration(
        shape: RoundedRectangleBorder(
          side: BorderSide(width: 1.0, style: BorderStyle.solid),
          borderRadius: BorderRadius.all(Radius.circular(5.0)),
        ),
      ),
</code>```

Example;-

```<code>// main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        // Remove the debug banner
        debugShowCheckedModeBanner: false,
        title: 'Kindacode.com',
        theme: ThemeData(
          primarySwatch: Colors.indigo,
        ),
        home: HomePage());
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<String> _animals = ["Dog", "Cat", "Crocodile", "Dragon"];

  String? _selectedColor;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Center(
        child: Container(
          width: 300,
          padding: EdgeInsets.symmetric(vertical: 5, horizontal: 15),
          decoration: BoxDecoration(
              color: Theme.of(context).primaryColor,
              borderRadius: BorderRadius.circular(30)),
          child: DropdownButton<String>(
            onChanged: (value) {
              setState(() {
                _selectedColor = value;
              });
            },
            value: _selectedColor,

            // Hide the default underline
            underline: Container(),
            hint: Center(
                child: Text(
              'Select the aniaml you love',
              style: TextStyle(color: Colors.white),
            )),
            icon: Icon(
              Icons.arrow_downward,
              color: Colors.yellow,
            ),
            isExpanded: true,

            // The list of options
            items: _animals
                .map((e) => DropdownMenuItem(
                      child: Container(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          e,
                          style: TextStyle(fontSize: 18),
                        ),
                      ),
                      value: e,
                    ))
                .toList(),

            // Customize the selected item
            selectedItemBuilder: (BuildContext context) => _animals
                .map((e) => Center(
                      child: Text(
                        e,
                        style: TextStyle(
                            fontSize: 18,
                            color: Colors.amber,
                            fontStyle: FontStyle.italic,
                            fontWeight: FontWeight.bold),
                      ),
                    ))
                .toList(),
          ),
        ),
      ),
    );
  }
}
</code>```

Title: Flutter Decorate Drop Down Button

Body:
I have a dropdown button, and im trying to decorate or customize the dropdown but only the list of items that is shown when trying to select the item in the list of items, i want the inside to look like this

Center locationDropDown() {
    return Center(
      child: Container(
        margin: const EdgeInsets.all(40),
        padding: const EdgeInsets.symmetric(
          horizontal: 12,
        ),
        decoration: BoxDecoration(
          color: Colors.blue.shade50,
          borderRadius: BorderRadius.circular(15),
        ),
        child: DropdownButtonFormField<String>(
          iconSize: 28,
          iconEnabledColor: Colors.blue,
          isDense: false,
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Please select a location';
            }
          },
          decoration: const InputDecoration(
            enabledBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.transparent),
            ),
          ),
          value: chooseLocation,
          hint: const Text(
            'Select your project',
            style: TextStyle(fontSize: 15, color: Colors.blue),
          ),
          isExpanded: true,
          items: workingData!.map((account) {
            return DropdownMenuItem(
              child: Text(
                account.name + ' (${account.location})',
              ),
              value: account.id,
            );
          }).toList(),
          onChanged: (String? displayedValue) {
            setState(
              () {
                chooseLocation = displayedValue!;
              },
            );
          },
        ),
      ),
    );
  }

Body:
you need to specify the side: property. By default it is BorderSide.none.

  decoration: ShapeDecoration(
        shape: RoundedRectangleBorder(
          side: BorderSide(width: 1.0, style: BorderStyle.solid),
          borderRadius: BorderRadius.all(Radius.circular(5.0)),
        ),
      ),

Example;-

// main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        // Remove the debug banner
        debugShowCheckedModeBanner: false,
        title: 'Kindacode.com',
        theme: ThemeData(
          primarySwatch: Colors.indigo,
        ),
        home: HomePage());
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<String> _animals = ["Dog", "Cat", "Crocodile", "Dragon"];

  String? _selectedColor;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Center(
        child: Container(
          width: 300,
          padding: EdgeInsets.symmetric(vertical: 5, horizontal: 15),
          decoration: BoxDecoration(
              color: Theme.of(context).primaryColor,
              borderRadius: BorderRadius.circular(30)),
          child: DropdownButton<String>(
            onChanged: (value) {
              setState(() {
                _selectedColor = value;
              });
            },
            value: _selectedColor,

            // Hide the default underline
            underline: Container(),
            hint: Center(
                child: Text(
              'Select the aniaml you love',
              style: TextStyle(color: Colors.white),
            )),
            icon: Icon(
              Icons.arrow_downward,
              color: Colors.yellow,
            ),
            isExpanded: true,

            // The list of options
            items: _animals
                .map((e) => DropdownMenuItem(
                      child: Container(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          e,
                          style: TextStyle(fontSize: 18),
                        ),
                      ),
                      value: e,
                    ))
                .toList(),

            // Customize the selected item
            selectedItemBuilder: (BuildContext context) => _animals
                .map((e) => Center(
                      child: Text(
                        e,
                        style: TextStyle(
                            fontSize: 18,
                            color: Colors.amber,
                            fontStyle: FontStyle.italic,
                            fontWeight: FontWeight.bold),
                      ),
                    ))
                .toList(),
          ),
        ),
      ),
    );
  }
}


问:
With GitLab CI/CD, how to have code cloned in a container by user:group 'java:java', instead of 'root?
In a GitLab repo, I have a Dockerfile with the following lines,

```<code>FROM python:alpine
RUN addgroup -S java
RUN adduser -s /bin/bash -S -G java java
USER java
WORKDIR /home/java
</code>```

so that when the image is instantiated (container running), it will run as user ‘java’

When GitLab CI/CD clones the project code however, it is owned by root in directory /home/java

This is unexpected behavior, I would expect it to be owned by user ‘java’

How do I get the code to be cloned by user ‘java’, and owned (user:group), by user:group ‘java:java’?

答:
Projects in GitLab are cloned with the GitLab runner helper image, which is using root. It will also use umask 0000 to avoid permission issues, if data is cached.

See this GitLab issue for more details.

To fix your issue, add an environment variable:
FF_DISABLE_UMASK_FOR_DOCKER_EXECUTOR=true

This will disable the umask usage and the runner tries to get UID and GID from the image of the build container.

Body:
In a GitLab repo, I have a Dockerfile with the following lines,

FROM python:alpine
RUN addgroup -S java
RUN adduser -s /bin/bash -S -G java java
USER java
WORKDIR /home/java

so that when the image is instantiated (container running), it will run as user ‘java’

When GitLab CI/CD clones the project code however, it is owned by root in directory /home/java

This is unexpected behavior, I would expect it to be owned by user ‘java’

How do I get the code to be cloned by user ‘java’, and owned (user:group), by user:group ‘java:java’?


问:
How to bind Itemsource of DataGridto the IsReadOnly property of the internal DataGridTextColumn?
I have a DataGrid (below) that takes in SimulatedItems as an ItemsSource which is from my viewmodel. The SimulatedItems is an ObservableCollection of SimulatedItem. Inside SimulatedItem there is a variable DriverID, NameID and Active. Both the DataGridTextColumns below correctly reference these variables inside for Binding but for IsReadOnly it does not work. It appears IsReadOnly is attempting to bind to my viewmodel rather than the SimulatedItems. How do I get IsReadOnly to bind to my item from ItemsSource?

```<code><DataGrid Grid.Row="1" ItemsSource="{Binding SimulatedItems}">
  <DataGrid.Columns>
    <DataGridTextColumn
      Header="NameID"
      Binding="{Binding NameID}"
      IsReadOnly="{Binding Active}">
    </DataGridTextColumn>
    <DataGridTextColumn
      Header="DriverID"
      Binding="{Binding Path=DriverID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
      IsReadOnly="{Binding Active}">
    </DataGridTextColumn>
  </DataGrid.Columns>
</DataGrid>
</code>```

答:
Unfortunately this will not work.

DataContexts do not work with DataGridColumns. The binding can't find the datacontext.

Read more about it here
https://thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/

Solution:
Use templates

```<code><DataGrid Grid.Row="1" ItemsSource="{Binding SimulatedItems}">
     <DataGrid.Columns>
           <DataGridTemplateColumn Header="NameID" Width="200">
                 <DataGridTemplateColumn.CellTemplate>
                      <DataTemplate>
                          <TextBox Text="{Binding NameID}" IsReadOnly="{Binding  Active}" BorderThickness="0" Background="Transparent"/>
                      </DataTemplate>
                 </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn Header="DriverID" Width="200">
                  <DataGridTemplateColumn.CellTemplate>
                         <DataTemplate>
                             <TextBox Text="{Binding Path=DriverID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="{Binding Active}" BorderThickness="0" Background="Transparent"/>
                         </DataTemplate>
                  </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
     </DataGrid.Columns>
</DataGrid>
</code>```

Body:
I have a DataGrid (below) that takes in SimulatedItems as an ItemsSource which is from my viewmodel. The SimulatedItems is an ObservableCollection of SimulatedItem. Inside SimulatedItem there is a variable DriverID, NameID and Active. Both the DataGridTextColumns below correctly reference these variables inside for Binding but for IsReadOnly it does not work. It appears IsReadOnly is attempting to bind to my viewmodel rather than the SimulatedItems. How do I get IsReadOnly to bind to my item from ItemsSource?

<DataGrid Grid.Row="1" ItemsSource="{Binding SimulatedItems}">
  <DataGrid.Columns>
    <DataGridTextColumn
      Header="NameID"
      Binding="{Binding NameID}"
      IsReadOnly="{Binding Active}">
    </DataGridTextColumn>
    <DataGridTextColumn
      Header="DriverID"
      Binding="{Binding Path=DriverID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
      IsReadOnly="{Binding Active}">
    </DataGridTextColumn>
  </DataGrid.Columns>
</DataGrid>

Body:
Unfortunately this will not work.

DataContexts do not work with DataGridColumns. The binding can't find the datacontext.

Read more about it here
https://thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/

Solution:
Use templates

<DataGrid Grid.Row="1" ItemsSource="{Binding SimulatedItems}">
     <DataGrid.Columns>
           <DataGridTemplateColumn Header="NameID" Width="200">
                 <DataGridTemplateColumn.CellTemplate>
                      <DataTemplate>
                          <TextBox Text="{Binding NameID}" IsReadOnly="{Binding  Active}" BorderThickness="0" Background="Transparent"/>
                      </DataTemplate>
                 </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn Header="DriverID" Width="200">
                  <DataGridTemplateColumn.CellTemplate>
                         <DataTemplate>
                             <TextBox Text="{Binding Path=DriverID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="{Binding Active}" BorderThickness="0" Background="Transparent"/>
                         </DataTemplate>
                  </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
     </DataGrid.Columns>
</DataGrid>


问:
Obtain the L1 imbalance measure for cem methodology in Matchit
Is there a way to obtain the L1 difference (as the one from the cem package) with Matchit?

I have looked through other questions and the documention but I can't seem to find an answer

Thanks,
Andriy

答:
You can use the L1.meas() and L1.profile() functions from the cem package. The syntax for these two functions is the same. Here is how you would use them:

with(m.out, cem::L1.meas(treat, X, weights = weights))
```

You do not need to change any arguments to match your data except the m.out variable, which should be the matchit object.

Body:
You can use the L1.meas() and L1.profile() functions from the cem package. The syntax for these two functions is the same. Here is how you would use them:

with(m.out, cem::L1.meas(treat, X, weights = weights))

You do not need to change any arguments to match your data except the m.out variable, which should be the matchit object.


问:
Android webview div style="height: auto" displays black screen
I am using webview to display html pages in an android application. I was having difficulty with scrolling so used scrollview and set the height of the div to auto style=”height:auto;”. That solved the scrolling issue perfectly. </p>

<p>However, this led to another issue that because the height of the div is set to auto, if the div is say 200px, then nothing appears after the  tag. This means that whenever the div is less than the height of the screen the remainder of the screen is black. Is there any way to set the background of the empty part of the screen to white instead? Thanks. </p>

答:
I am back and i finally found a solution - typically, it was simple but hopefully someone else can benefit from it.

basically all I had to do was in the main.xml file change the background from black to white as follows

android:background="#ffffff"

and that was that!

Body:
I am using webview to display html pages in an android application. I was having difficulty with scrolling so used scrollview and set the height of the div to auto style=”height:auto;”. That solved the scrolling issue perfectly.

However, this led to another issue that because the height of the div is set to auto, if the div is say 200px, then nothing appears after the  tag. This means that whenever the div is less than the height of the screen the remainder of the screen is black. Is there any way to set the background of the empty part of the screen to white instead? Thanks.


问:
Sequelize belongs to many get and post request
I have belongs to many associations of the model Technology and Project. At the same time, on the client, I have two tables, free technologies and technologies on the project. Please tell me (or suggest how to do it) how to make a get request for all free technologies and a post request to add them to the table on the project. I figured out all the associations, but stopped at this one. I will be grateful for any help.

models/Project.js

```<code>const {
  Model
} = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class Project extends Model {

    static associate(models) {
      Project.hasMany(models.Role, { foreignKey: "projectId", as: "roles" });
      Project.belongsToMany(models.Technology, { foreignKey: "projectId", through: "ProjectsTechnologies"});
    }
  };
  Project.init({
    title: DataTypes.STRING,
    description: DataTypes.STRING,
    image: DataTypes.STRING
  }, {
    sequelize,
    modelName: "Project",
  });
  return Project;
};
</code>```

models/Technology.js

```<code>const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Technology extends Model {

    static associate(models) {
      Technology.belongsToMany(models.Project, { foreignKey: "technologyId", through: "ProjectsTechnologies"});
    }
  }
  Technology.init({
    name: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'Technology',
  });
  return Technology;
};
</code>```

*models/ProjectsTechs

```<code>const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class ProjectsTechnologies extends Model {

    static associate(models) {
      ProjectsTechnologies.belongsTo(models.Project, {foreignKey: "projectId"});
      ProjectsTechnologies.belongsTo(models.Technology, {foreignKey: "technologyId"});
    }
  };
  ProjectsTechnologies.init({
    projectId: DataTypes.STRING,
    technologyId: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'ProjectsTechnologies',
  });
  return ProjectsTechnologies;
};
</code>```

Currently I'm doing this get request for get all free technologies

```<code>router.get("/techologies", async (req, res) => {
  const listOfTech = await Technology.findAll({
    include: [
      {
        model: Project,
        as: "projects",
        through: {
          model: ProjectsTechnologies
        }
      }
    ]
  });
  res.json(listOfTech);
});
</code>```

And post req for posting technologies in "On project" table

```<code>router.post("/create/:id", async (req, res) => {
  const technology = await ProjectsTechnologies.create(req.body);
  const project = await Project.findOne({
    where: {
      id: req.params.id
    }
  });
  res.json(technology);
});
</code>```

I also keep trying to do it differently, because these options don't seem right to me.

答:
To query a list of technologies that are not used in any of projects you need to use a subquery in where option:

const listOfTech = await Technology.findAll({
    where: Sequelize.literal('NOT EXISTS (SELECT 1 FROM `ProjectsTechnologies` where `ProjectsTechnologies`.`technologyId`=`Technology`.`id`)')
  });
```

Body:
I have belongs to many associations of the model Technology and Project. At the same time, on the client, I have two tables, free technologies and technologies on the project. Please tell me (or suggest how to do it) how to make a get request for all free technologies and a post request to add them to the table on the project. I figured out all the associations, but stopped at this one. I will be grateful for any help.

models/Project.js

const {
  Model
} = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class Project extends Model {

    static associate(models) {
      Project.hasMany(models.Role, { foreignKey: "projectId", as: "roles" });
      Project.belongsToMany(models.Technology, { foreignKey: "projectId", through: "ProjectsTechnologies"});
    }
  };
  Project.init({
    title: DataTypes.STRING,
    description: DataTypes.STRING,
    image: DataTypes.STRING
  }, {
    sequelize,
    modelName: "Project",
  });
  return Project;
};

models/Technology.js

const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Technology extends Model {

    static associate(models) {
      Technology.belongsToMany(models.Project, { foreignKey: "technologyId", through: "ProjectsTechnologies"});
    }
  }
  Technology.init({
    name: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'Technology',
  });
  return Technology;
};

*models/ProjectsTechs

const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class ProjectsTechnologies extends Model {

    static associate(models) {
      ProjectsTechnologies.belongsTo(models.Project, {foreignKey: "projectId"});
      ProjectsTechnologies.belongsTo(models.Technology, {foreignKey: "technologyId"});
    }
  };
  ProjectsTechnologies.init({
    projectId: DataTypes.STRING,
    technologyId: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'ProjectsTechnologies',
  });
  return ProjectsTechnologies;
};

Currently I'm doing this get request for get all free technologies

router.get("/techologies", async (req, res) => {
  const listOfTech = await Technology.findAll({
    include: [
      {
        model: Project,
        as: "projects",
        through: {
          model: ProjectsTechnologies
        }
      }
    ]
  });
  res.json(listOfTech);
});

And post req for posting technologies in "On project" table

router.post("/create/:id", async (req, res) => {
  const technology = await ProjectsTechnologies.create(req.body);
  const project = await Project.findOne({
    where: {
      id: req.params.id
    }
  });
  res.json(technology);
});

I also keep trying to do it differently, because these options don't seem right to me.


问:
JSF Components alignment inside panelGroup
I have a selectOneRadio element with layout="custom" inside a dataTable. Below is the xhtml code-

```<code><p:dataTable var="varlist" value="#{testbean.testlist}">
    <p:column headerText="Choose Option" width="120">
        <p:selectOneRadio id="customRadio" value="#{varlist.varlistValue}"
            layout="custom" required="true">
            <f:selectItem itemValue="10" />
            <f:selectItem itemValue="20" />
        </p:selectOneRadio>

        <h:panelGrid columns="1">
            <h:panelGroup>
                <p:radioButton id="opt1" for="customRadio" itemIndex="0" />
                <h:outputLabel for="opt1" value="OPTION 1" styleClass="radiolabelOption"/>
            </h:panelGroup>

            <h:panelGroup>
                <p:radioButton id="opt2" for="customRadio" itemIndex="1" />
                <h:outputLabel for="opt2" value="OPTION 2" styleClass="radiolabelOption"/>
            </h:panelGroup>
        </h:panelGrid>
    </p:column>
</p:dataTable>

<style type="text/css">
    .radiolabelOption {
      margin-left: 10px;
    }
</style>
</code>```

So this is how it appears in browser-

As we can see, the outputLabel appears to the bottom with respect to radioButton. But i want that to look centre, w.r.t radioButton as shown below -

I tried below lines of code like

style="display:block; text-align:center"  OR

style="margin: 0 auto;"

But none of them produces the desired result.

So How to do it?

答:
Give <h:panelGroup> these styles

.panelGroup{
  display: flex;
  align-items: center;
}
```

Body:
I have a selectOneRadio element with layout="custom" inside a dataTable. Below is the xhtml code-

            <f:selectItem itemValue="10" />
            <f:selectItem itemValue="20" />

        <h:panelGrid columns="1">
            <h:panelGroup>

                <h:outputLabel for="opt1" value="OPTION 1" styleClass="radiolabelOption"/>
            </h:panelGroup>

            <h:panelGroup>

                <h:outputLabel for="opt2" value="OPTION 2" styleClass="radiolabelOption"/>
            </h:panelGroup>
        </h:panelGrid>

So this is how it appears in browser-

As we can see, the outputLabel appears to the bottom with respect to radioButton. But i want that to look centre, w.r.t radioButton as shown below -

I tried below lines of code like

style="display:block; text-align:center"  OR

style="margin: 0 auto;"

But none of them produces the desired result.

So How to do it?


问:
Accessible in-line modal?
When it comes to accessibility, what is the proper design pattern or technique for appending an inline panel that would have a header, body text, and optional close button?

For context, I've been tasked with creating an accessible multi-select quiz question that appends a correct or incorrect feedback panel under the question after the user presses submit. I think normally this sort of feedback would appear in a modal popup that covers the other content and traps focus, but this particular design needs the feedback panel to appear in the page directly under the submit button, and still allow the user the tab back through the answer options (even though they would be aria-disabled after submitting).

The feedback panel would have a title header, body text, and an optional close button. There would be no close button if the user got it all correct or they ran out of attempts.

Is there a suitable aria-role or known design pattern for this sort of appended panel? And what should I send focus to once the feedback panel appears, the header? The close button?

In case its relevant, for the multiselect answer options I am using native checkboxes with s

答:
Option 1

The first would be to add role="alert" to the appended box (assuming you will only add it once per page as otherwise we would use aria-live).

This would then be announced to screen reader users.

Option 2

Option 2 is that you can just append the box to the page and use focus management. So the box appears and you would move focus to the heading of the box via JavaScript (with tabindex="-1" on the heading for example). This needs to happen from an expected action (so "submit answer" button that you said you have).

I would probably go with option 2 as it is the easiest way to not introduce more accessibility issues by mistake.

There are other ways you can achieve this with aria-live, aria-labelledby etc. etc. but the above two options are the most straight forward.

Title: Accessible in-line modal?


问:
react-native run-android plugin not found and compile sdk is not specified
When running command npx react-native run-android --port=80 --verbose
I get error:

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=80

And then above that I can see:

```<code>1: Task failed with an exception.

-----------
* Where:
Build file 'C:\location\node_modules\react-native-create-thumbnail\android\build.gradle' line: 23

* What went wrong:
A problem occurred evaluating project ':react-native-create-thumbnail'.
> Plugin with id 'maven' not found.

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

2: Task failed with an exception.
-----------
* What went wrong:
A problem occurred configuring project ':react-native-create-thumbnail'.
> compileSdkVersion is not specified.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================
</code>```

What I have done so far:

Created a fresh project and seen that working to ensure my development environment is functioning correctly

In gradle-wrapper.properties set the distributionUrl to https\://services.gradle.org/distributions/gradle-7.0-all.zip

Ensured correct SDK versions are installed

Checked versions in code

```<code>def DEFAULT_BUILD_TOOLS_VERSION = '28.0.3'
def DEFAULT_MIN_SDK_VERSION = 16
def DEFAULT_TARGET_SDK_VERSION = 28

def safeExtGet(prop, fallback) {
    rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
}

apply plugin: 'com.android.library'
apply plugin: 'maven'

buildscript {
    // The Android Gradle plugin is only required when opening the android folder stand-alone.
    // This avoids unnecessary downloads and potential conflicts when the library is included as a
    // module dependency in an application project.
    // ref: https://docs.gradle.org/current/userguide/tutorial_using_tasks.html#sec:build_script_external_dependencies
    if (project == rootProject) {
        repositories {
            google()
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:3.4.1'
        }
    }
}

apply plugin: 'com.android.library'
apply plugin: 'maven'

android {
    compileSdkVersion safeExtGet('compileSdkVersion', DEFAULT_COMPILE_SDK_VERSION)
    buildToolsVersion safeExtGet('buildToolsVersion', DEFAULT_BUILD_TOOLS_VERSION)
    defaultConfig {
        minSdkVersion safeExtGet('minSdkVersion', DEFAULT_MIN_SDK_VERSION)
        targetSdkVersion safeExtGet('targetSdkVersion', DEFAULT_TARGET_SDK_VERSION)
        versionCode 1
        versionName "1.0"
    }
    lintOptions {
        abortOnError false
    }
}

repositories {
    // ref: https://www.baeldung.com/maven-local-repository
    mavenLocal()
    maven {
        // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
        url "$rootDir/../node_modules/react-native/android"
    }
    maven {
        // Android JSC is installed from npm
        url "$rootDir/../node_modules/jsc-android/dist"
    }
    google()
    jcenter()
}
</code>```

I'm at a loss here, any help would be greatly appreciated.

答:
Gradle 7.0 removed support for maven and now you need maven-publish
https://docs.gradle.org/7.0/userguide/publishing_maven.html#publishing_maven

similar to SO: Plugin with id 'maven' not found

Body:
When running command npx react-native run-android --port=80 --verbose
I get error:

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=80

And then above that I can see:

1: Task failed with an exception.

-----------
* Where:
Build file 'C:\location\node_modules\react-native-create-thumbnail\android\build.gradle' line: 23

* What went wrong:
A problem occurred evaluating project ':react-native-create-thumbnail'.
> Plugin with id 'maven' not found.

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

2: Task failed with an exception.
-----------
* What went wrong:
A problem occurred configuring project ':react-native-create-thumbnail'.
> compileSdkVersion is not specified.

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

What I have done so far:

Created a fresh project and seen that working to ensure my development environment is functioning correctly

In gradle-wrapper.properties set the distributionUrl to https\://services.gradle.org/distributions/gradle-7.0-all.zip

Ensured correct SDK versions are installed

Checked versions in code

def DEFAULT_BUILD_TOOLS_VERSION = '28.0.3'
def DEFAULT_MIN_SDK_VERSION = 16
def DEFAULT_TARGET_SDK_VERSION = 28

def safeExtGet(prop, fallback) {
    rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
}

apply plugin: 'com.android.library'
apply plugin: 'maven'

buildscript {
    // The Android Gradle plugin is only required when opening the android folder stand-alone.
    // This avoids unnecessary downloads and potential conflicts when the library is included as a
    // module dependency in an application project.
    // ref: https://docs.gradle.org/current/userguide/tutorial_using_tasks.html#sec:build_script_external_dependencies
    if (project == rootProject) {
        repositories {
            google()
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:3.4.1'
        }
    }
}

apply plugin: 'com.android.library'
apply plugin: 'maven'

android {
    compileSdkVersion safeExtGet('compileSdkVersion', DEFAULT_COMPILE_SDK_VERSION)
    buildToolsVersion safeExtGet('buildToolsVersion', DEFAULT_BUILD_TOOLS_VERSION)
    defaultConfig {
        minSdkVersion safeExtGet('minSdkVersion', DEFAULT_MIN_SDK_VERSION)
        targetSdkVersion safeExtGet('targetSdkVersion', DEFAULT_TARGET_SDK_VERSION)
        versionCode 1
        versionName "1.0"
    }
    lintOptions {
        abortOnError false
    }
}

repositories {
    // ref: https://www.baeldung.com/maven-local-repository
    mavenLocal()
    maven {
        // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
        url "$rootDir/../node_modules/react-native/android"
    }
    maven {
        // Android JSC is installed from npm
        url "$rootDir/../node_modules/jsc-android/dist"
    }
    google()
    jcenter()
}

I'm at a loss here, any help would be greatly appreciated.


问:
Is there a way to configure SSO oauth2 Prometheus via Nginx Ingress and Oauth2-proxy
I want all users who access Prometheus GUI to be able to log in via SSO keycloak which supports the oauth2 protocol, but now the current configuration, before reaching prometheus gui, there is an nginx server and on the upstreams I have several websites like: grafana , prometheus etc. I searched on the google what is the best solution to do that and I found the Oauth2-proxy that can be done this but after the authentication, the oauth2-proxy is redirect me to the auth page and not to prometheus, everything works ok but not the redirect url.

nginx.conf

```<code>user root;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

        listen 443 ssl default_server;
        server_name example.com;

        location /oauth2/ {
                proxy_pass       http://127.0.0.1:4180;
                proxy_set_header Host                    $host;
                proxy_set_header X-Real-IP               $remote_addr;
                proxy_set_header X-Scheme                $scheme;
                proxy_set_header X-Auth-Request-Redirect "https://example.com/prometheus";
        }

        location = /oauth2/auth {
                proxy_pass       http://127.0.0.1:4180;
                proxy_set_header Host             $host;
                proxy_set_header X-Real-IP        $remote_addr;
                proxy_set_header X-Scheme         $scheme;
                proxy_set_header Content-Length   "";
                proxy_pass_request_body           off;
        }

        location ^~ /prometheus/  {
                auth_request /oauth2/auth;
                error_page 401 = /oauth2/sign_in;

                auth_request_set $user   $upstream_http_x_auth_request_user;
                auth_request_set $email  $upstream_http_x_auth_request_email;
                proxy_set_header X-User  $user;
                proxy_set_header X-Email $email;

                auth_request_set $token  $upstream_http_x_auth_request_access_token;
                proxy_set_header X-Access-Token $token;

                auth_request_set $auth_cookie $upstream_http_set_cookie;
                add_header Set-Cookie $auth_cookie;

                auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1;

                if ($auth_cookie ~* "(; .*)") {
                        set $auth_cookie_name_0 $auth_cookie;
                        set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1";
                }

                if ($auth_cookie_name_upstream_1) {
                        add_header Set-Cookie $auth_cookie_name_0;
                        add_header Set-Cookie $auth_cookie_name_1;
                }

                proxy_set_header   X-Forwarded-For $remote_addr;
                proxy_set_header   Host $http_host;
                proxy_pass         "http://192.168.1.20:9090/prometheus/"; # This is where my web server is hosted
                }
</code>```

oauth2-proxy.cfg

```<code>provider="keycloak"
provider_display_name="SSO connect"
ssl_insecure_skip_verify=true
login_url="https://auth.keycloak/oauth2/authorize"
redeem_url="https://auth.keycloak/oauth2/token"
validate_url="https://auth.keycloak/oauth2/userinfo"
client_id="8m67vhg34hgj-232k-786j-90cf-45656gjh5f64g"
client_secret="sd;kfposdfk546idfj;"
cookie_secure="true"
redirect_url="https://example.com/prometheus/oauth2/callback"
upstreams="http://192.168.1.20:9090/prometheus/" # My website server
email_domains="*"
cookie_secret="AkaBxYPzIvMdQziWECV6Ow=="
http_address = "127.0.0.1:4180"
https_address = ":443"
reverse_proxy = true
</code>```

oauth2 bin command :

```<code>[root@nginx]# ./oauth2-proxy --config=/etc/nginx/oauth2-proxy.cfg

[2022/02/03 17:23:54] [proxy.go:89] mapping path "/prometheus/" => upstream "http://192.168.1.20:9090/prometheus/"
[2022/02/03 17:23:54] [oauthproxy.go:148] OAuthProxy configured for Keycloak Client ID: 8m67vhg34hgj-232k-786j-90cf-45656gjh5f64g
[2022/02/03 17:23:54] [oauthproxy.go:154] Cookie settings: name:_oauth2_proxy secure(https):true httponly:true expiry:168h0m0s domains: path:/ samesite: refresh:disabled
</code>```

The oauth2-proxy port 4180 is listening ok :

```<code>[root@nginx]# netstat -naptu | grep 4180
tcp        0      0 127.0.0.1:4180          0.0.0.0:*               LISTEN      26031/./oauth2-prox
</code>```

Here is the page of prometheus login point out on oauth2-proxy for authentication

After authentication, is redirect me to the https://auth.keycloak page and not to the upstream https://example.com/prometheus

On the outh2-proxy I have this output whenever I want to access "https://example.com/prometheus"

```<code>9 Safari/537.36" 401 13 0.000
[2022/02/03 17:29:59] [validator.go:77] Rejecting invalid redirect "https://example.com": domain / port not in whitelist
[2022/02/03 17:29:59] [director.go:85] Invalid redirect provided in X-Auth-Request-Redirect header: https://example.com
[2022/02/03 17:29:59] [validator.go:77] Rejecting invalid redirect "https://example.com": domain / port not in whitelist
[2022/02/03 17:29:59] [director.go:85] Invalid redirect provided in X-Auth-Request-Redirect header: https://example.com
</code>```

What I'm missing here .. I don't have any ideas anymore.

答:
I found the solution:

Step1. Download oauth2-proxy binary - my version is oauth2-proxy v7.2.1

Step2. Create oauth2-proxy as services in order to run "start| stop | status".

```<code>[root@nginx]# cat oauth2_proxy.service
[Unit]
Description=oauth2_proxy daemon
After=syslog.target network.target

[Service]
ExecStart=/var/opt/oauth2-proxy --config=/etc/nginx/oauth2-proxy.cfg
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=always

[Install]
WantedBy=multi-user.target
</code>```

Running Status oauth2_proxy command

```<code>[root@nginx]# systemctl status oauth2_proxy
● oauth2_proxy.service - oauth2_proxy daemon
   Loaded: loaded (/etc/systemd/system/multi-user.target.wants/oauth2_proxy.service; bad; vendor preset: disabled)
   Active: active (running) since Tue 2022-02-08 11:03:05 CET; 1 day 22h ago
 Main PID: 34114 (oauth2-proxy)
   CGroup: /system.slice/oauth2_proxy.service
           └─34114 /var/opt/oauth2-proxy --config=/etc/nginx/oauth2-proxy.cfg

Feb 08 11:03:05 nginx.local systemd[1]: Started oauth2_proxy daemon.
Feb 08 11:03:05 nginx.local oauth2-proxy[34114]: [2022/02/08 11:03:05] [logging.go:27] Redirecting logging to file: /var/log/oauth2/oauth2_proxy.log
</code>```

Step3. Create  ouath2-proxy.cfg and add the below lines:

```<code>provider="oidc"
provider_display_name="SSO Connect"
login_url="https://auth.keycloak/oauth2/authorize"
validate_url="https://auth.keycloak/oauth2/token"
profile_url="https://auth.keycloak/oauth2/userinfo"
client_id="8m67vhg34hgj-232k-786j-90cf-45656gjh5f64g"
client_secret="sd;kfposdfk546idfj"
redirect_url="https://example.com/oauth2/callback"
upstreams=["http://192.168.1.20:9090/prometheus/"] # My website server
###OIDC settings
#reverse_proxy=true
oidc_issuer_url="https://auth.keycloak"
insecure_oidc_allow_unverified_email=true

email_domains=["*"]
cookie_secret="AkaBxYPzIvMdQziWECV6Ow=="
http_address="127.0.0.1:4180"
whitelist_domains="tool.example.com"
cookie_domains=["tool.example.com"]
cookie_secure="false"
cookie_samesite="lax"
pass_authorization_header = true
pass_access_token = true
pass_user_headers = true
set_authorization_header = true
set_xauthrequest = true
cookie_refresh = "1m"
cookie_expire = "30m"
scope="openid email profile"
</code>```

Step4. Add lines below on nginx.conf in order to make the authentication and redirecting to prometheus upstream

```<code>  location /oauth2/ {
    proxy_pass       http://127.0.0.1:4180;
    proxy_set_header Host                    $host;
    proxy_set_header X-Real-IP               $remote_addr;
    proxy_set_header X-Scheme                $scheme;
    proxy_set_header X-Auth-Request-Redirect $request_uri;
  }
  location = /oauth2/auth {
    proxy_pass       http://127.0.0.1:4180;
    proxy_set_header Host             $host;
    proxy_set_header X-Real-IP        $remote_addr;
    proxy_set_header X-Scheme         $scheme;
    proxy_set_header Content-Length   "";
    proxy_pass_request_body           off;
  }

  location ^~ /prometheus/ {
    auth_request /oauth2/auth;
    error_page 401 = /oauth2/sign_in;

    auth_request_set $user   $upstream_http_x_auth_request_user;
    auth_request_set $email  $upstream_http_x_auth_request_email;
    proxy_set_header X-User  $user;
    proxy_set_header X-Email $email;

    auth_request_set $auth_cookie $upstream_http_set_cookie;
    add_header Set-Cookie $auth_cookie;

    proxy_pass http://prometheus_backend/prometheus/;
  }
</code>```

I hope you don't have any problems and make it works.

Body:
I want all users who access Prometheus GUI to be able to log in via SSO keycloak which supports the oauth2 protocol, but now the current configuration, before reaching prometheus gui, there is an nginx server and on the upstreams I have several websites like: grafana , prometheus etc. I searched on the google what is the best solution to do that and I found the Oauth2-proxy that can be done this but after the authentication, the oauth2-proxy is redirect me to the auth page and not to prometheus, everything works ok but not the redirect url.

nginx.conf

user root;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

        listen 443 ssl default_server;
        server_name example.com;

        location /oauth2/ {
                proxy_pass       http://127.0.0.1:4180;
                proxy_set_header Host                    $host;
                proxy_set_header X-Real-IP               $remote_addr;
                proxy_set_header X-Scheme                $scheme;
                proxy_set_header X-Auth-Request-Redirect "https://example.com/prometheus";
        }

        location = /oauth2/auth {
                proxy_pass       http://127.0.0.1:4180;
                proxy_set_header Host             $host;
                proxy_set_header X-Real-IP        $remote_addr;
                proxy_set_header X-Scheme         $scheme;
                proxy_set_header Content-Length   "";
                proxy_pass_request_body           off;
        }

        location ^~ /prometheus/  {
                auth_request /oauth2/auth;
                error_page 401 = /oauth2/sign_in;

                auth_request_set $user   $upstream_http_x_auth_request_user;
                auth_request_set $email  $upstream_http_x_auth_request_email;
                proxy_set_header X-User  $user;
                proxy_set_header X-Email $email;

                auth_request_set $token  $upstream_http_x_auth_request_access_token;
                proxy_set_header X-Access-Token $token;

                auth_request_set $auth_cookie $upstream_http_set_cookie;
                add_header Set-Cookie $auth_cookie;

                auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1;

                if ($auth_cookie ~* "(; .*)") {
                        set $auth_cookie_name_0 $auth_cookie;
                        set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1";
                }

                if ($auth_cookie_name_upstream_1) {
                        add_header Set-Cookie $auth_cookie_name_0;
                        add_header Set-Cookie $auth_cookie_name_1;
                }

                proxy_set_header   X-Forwarded-For $remote_addr;
                proxy_set_header   Host $http_host;
                proxy_pass         "http://192.168.1.20:9090/prometheus/"; # This is where my web server is hosted
                }

oauth2-proxy.cfg

provider="keycloak"
provider_display_name="SSO connect"
ssl_insecure_skip_verify=true
login_url="https://auth.keycloak/oauth2/authorize"
redeem_url="https://auth.keycloak/oauth2/token"
validate_url="https://auth.keycloak/oauth2/userinfo"
client_id="8m67vhg34hgj-232k-786j-90cf-45656gjh5f64g"
client_secret="sd;kfposdfk546idfj;"
cookie_secure="true"
redirect_url="https://example.com/prometheus/oauth2/callback"
upstreams="http://192.168.1.20:9090/prometheus/" # My website server
email_domains="*"
cookie_secret="AkaBxYPzIvMdQziWECV6Ow=="
http_address = "127.0.0.1:4180"
https_address = ":443"
reverse_proxy = true

oauth2 bin command :

[root@nginx]# ./oauth2-proxy --config=/etc/nginx/oauth2-proxy.cfg

[2022/02/03 17:23:54] [proxy.go:89] mapping path "/prometheus/" => upstream "http://192.168.1.20:9090/prometheus/"
[2022/02/03 17:23:54] [oauthproxy.go:148] OAuthProxy configured for Keycloak Client ID: 8m67vhg34hgj-232k-786j-90cf-45656gjh5f64g
[2022/02/03 17:23:54] [oauthproxy.go:154] Cookie settings: name:_oauth2_proxy secure(https):true httponly:true expiry:168h0m0s domains: path:/ samesite: refresh:disabled

The oauth2-proxy port 4180 is listening ok :

[root@nginx]# netstat -naptu | grep 4180
tcp        0      0 127.0.0.1:4180          0.0.0.0:*               LISTEN      26031/./oauth2-prox

Here is the page of prometheus login point out on oauth2-proxy for authentication

After authentication, is redirect me to the https://auth.keycloak page and not to the upstream https://example.com/prometheus

On the outh2-proxy I have this output whenever I want to access "https://example.com/prometheus"

9 Safari/537.36" 401 13 0.000
[2022/02/03 17:29:59] [validator.go:77] Rejecting invalid redirect "https://example.com": domain / port not in whitelist
[2022/02/03 17:29:59] [director.go:85] Invalid redirect provided in X-Auth-Request-Redirect header: https://example.com
[2022/02/03 17:29:59] [validator.go:77] Rejecting invalid redirect "https://example.com": domain / port not in whitelist
[2022/02/03 17:29:59] [director.go:85] Invalid redirect provided in X-Auth-Request-Redirect header: https://example.com

What I'm missing here .. I don't have any ideas anymore.

Body:
I found the solution:

Step1. Download oauth2-proxy binary - my version is oauth2-proxy v7.2.1

Step2. Create oauth2-proxy as services in order to run "start| stop | status".

[root@nginx]# cat oauth2_proxy.service
[Unit]
Description=oauth2_proxy daemon
After=syslog.target network.target

[Service]
ExecStart=/var/opt/oauth2-proxy --config=/etc/nginx/oauth2-proxy.cfg
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=always

[Install]
WantedBy=multi-user.target

Running Status oauth2_proxy command

[root@nginx]# systemctl status oauth2_proxy
● oauth2_proxy.service - oauth2_proxy daemon
   Loaded: loaded (/etc/systemd/system/multi-user.target.wants/oauth2_proxy.service; bad; vendor preset: disabled)
   Active: active (running) since Tue 2022-02-08 11:03:05 CET; 1 day 22h ago
 Main PID: 34114 (oauth2-proxy)
   CGroup: /system.slice/oauth2_proxy.service
           └─34114 /var/opt/oauth2-proxy --config=/etc/nginx/oauth2-proxy.cfg

Feb 08 11:03:05 nginx.local systemd[1]: Started oauth2_proxy daemon.
Feb 08 11:03:05 nginx.local oauth2-proxy[34114]: [2022/02/08 11:03:05] [logging.go:27] Redirecting logging to file: /var/log/oauth2/oauth2_proxy.log

Step3. Create  ouath2-proxy.cfg and add the below lines:

provider="oidc"
provider_display_name="SSO Connect"
login_url="https://auth.keycloak/oauth2/authorize"
validate_url="https://auth.keycloak/oauth2/token"
profile_url="https://auth.keycloak/oauth2/userinfo"
client_id="8m67vhg34hgj-232k-786j-90cf-45656gjh5f64g"
client_secret="sd;kfposdfk546idfj"
redirect_url="https://example.com/oauth2/callback"
upstreams=["http://192.168.1.20:9090/prometheus/"] # My website server
###OIDC settings
#reverse_proxy=true
oidc_issuer_url="https://auth.keycloak"
insecure_oidc_allow_unverified_email=true

email_domains=["*"]
cookie_secret="AkaBxYPzIvMdQziWECV6Ow=="
http_address="127.0.0.1:4180"
whitelist_domains="tool.example.com"
cookie_domains=["tool.example.com"]
cookie_secure="false"
cookie_samesite="lax"
pass_authorization_header = true
pass_access_token = true
pass_user_headers = true
set_authorization_header = true
set_xauthrequest = true
cookie_refresh = "1m"
cookie_expire = "30m"
scope="openid email profile"

Step4. Add lines below on nginx.conf in order to make the authentication and redirecting to prometheus upstream

  location /oauth2/ {
    proxy_pass       http://127.0.0.1:4180;
    proxy_set_header Host                    $host;
    proxy_set_header X-Real-IP               $remote_addr;
    proxy_set_header X-Scheme                $scheme;
    proxy_set_header X-Auth-Request-Redirect $request_uri;
  }
  location = /oauth2/auth {
    proxy_pass       http://127.0.0.1:4180;
    proxy_set_header Host             $host;
    proxy_set_header X-Real-IP        $remote_addr;
    proxy_set_header X-Scheme         $scheme;
    proxy_set_header Content-Length   "";
    proxy_pass_request_body           off;
  }

  location ^~ /prometheus/ {
    auth_request /oauth2/auth;
    error_page 401 = /oauth2/sign_in;

    auth_request_set $user   $upstream_http_x_auth_request_user;
    auth_request_set $email  $upstream_http_x_auth_request_email;
    proxy_set_header X-User  $user;
    proxy_set_header X-Email $email;

    auth_request_set $auth_cookie $upstream_http_set_cookie;
    add_header Set-Cookie $auth_cookie;

    proxy_pass http://prometheus_backend/prometheus/;
  }

I hope you don't have any problems and make it works.


问:
Running Cypress Script on Browser Stack getting an error spawn npm ENOENT
I was trying to Integrate my Cypress scripts and execute in Browser Stack.
While executing the script from the Visual code terminal using browserstack-cypress run I am receiving the following error. Appreciate if someone can advise on how to resolve

Issue that shows is Erro: spwan npm ENOENT

答: Keeping "cache_dependencies": false in run_settings in browserstack.json may help. Reference: https://www.browserstack.com/docs/automate/cypress/npm-packages#npm-dependency-caching</p>


问:
Set a http only cookie next API
I'm trying to set a cookie using my nextjs api.

I tried to do "res.cookie" (based off expressJS), but res.cookie is apparently undefined in my API. res itself is not undefined, just the cookie property is undefined.

Then i tried the following code:

```<code> import { serialize } from "cookie";
 res.setHeader(
            "Set-Cookie",
            serialize("jwt", `${response.data.access_token}`, {
                maxAge: 5000,
                expires: new Date("01 12 2021"),
                secure: true,
                httpOnly: true,
                sameSite: "lax",
            })
        );

        res.send("done");
</code>```

This is also not working, It is not setting the cookie on my frontend.

答:
What I did to make this work is add a path to my options. Also had to change the expiration date to a valid date that is not in the past.</p>
```<code>import { serialize } from "cookie";
     res.setHeader(
                "Set-Cookie",
                serialize("jwt", `${response.data.access_token}`, {
                    maxAge: 5000,
                    expires: new Date("01 12 2022"),
                    secure: true,
                    httpOnly: true,
                    sameSite: "lax",
                    path : '/'
                })
            );

        res.send("done");
</code>```

Title: Set a http only cookie next API

Body:
I'm trying to set a cookie using my nextjs api.

I tried to do "res.cookie" (based off expressJS), but res.cookie is apparently undefined in my API. res itself is not undefined, just the cookie property is undefined.

Then i tried the following code:

 import { serialize } from "cookie";
 res.setHeader(
            "Set-Cookie",
            serialize("jwt", `${response.data.access_token}`, {
                maxAge: 5000,
                expires: new Date("01 12 2021"),
                secure: true,
                httpOnly: true,
                sameSite: "lax",
            })
        );

        res.send("done");

This is also not working, It is not setting the cookie on my frontend.

Body:
What I did to make this work is add a path to my options. Also had to change the expiration date to a valid date that is not in the past.

import { serialize } from "cookie";
     res.setHeader(
                "Set-Cookie",
                serialize("jwt", `${response.data.access_token}`, {
                    maxAge: 5000,
                    expires: new Date("01 12 2022"),
                    secure: true,
                    httpOnly: true,
                    sameSite: "lax",
                    path : '/'
                })
            );

        res.send("done");


问:
Struts2 request PUT parameter on body
i want to add parameter for HTTP Request PUT on the body, but i only can do like this

```<code>http://localhost:9996/Events/employee/{id}.json?name={name}
</code>```

so how to put name on body?

here my controller

```<code>public class EmployeeController implements ModelDriven<Object>{
private static final long serialVersionUID = 1L;
private String id;
private String name;
private Object model;
private EmployeeRepository employeeRepository = new EmployeeRepository();

//GET
public HttpHeaders index() {
    model = employeeRepository.findAllEmployee();
    return new DefaultHttpHeaders("index").disableCaching();
}

// GET
public HttpHeaders show() {
    model = employeeRepository.getEmployeeById(id);
    return new DefaultHttpHeaders("show").disableCaching();
}

//POST
public HttpHeaders create() {
    Integer empId = Integer.parseInt(id);
    Employee emp = new Employee(empId, name, "PQR");
    employeeRepository.addEmployee(emp);
    model = employeeRepository.findAllEmployee();
    return new DefaultHttpHeaders("create").disableCaching();
}

//PUT
public HttpHeaders update() {
    Integer empId = Integer.parseInt(id);
    Employee emp = new Employee(empId, name, "PQR");
    employeeRepository.updateEmployee(emp);
    model = employeeRepository.findAllEmployee();
    return new DefaultHttpHeaders("update").disableCaching();
}

//DELETE
public HttpHeaders destroy() {
    employeeRepository.deleteEmployee(id);
    model = employeeRepository.findAllEmployee();
    return new DefaultHttpHeaders("destroy").disableCaching();
}

public  String  getId()                 { return id; }
public  void    setId(String id)        { this.id = id; }
public  String  getName()               { return name; }
public  void    setName(String name)    { this.name = name; }
public  Object  getModel()              { return model; }
</code>```

答:
You need to add the JSON Interceptor for your action and it should look something like the code below.

```<code><package name="movies" extends="rest-default, json-default">

        <interceptors>
            <interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/>

            <interceptor-stack name="jsonStack">
                <interceptor-ref name="json"/>
                <interceptor-ref name="defaultStack"/>
            </interceptor-stack>
        </interceptors>

<action name="movies" class="com.struts.movie.action.MoviesController">
            <interceptor-ref name="jsonStack"/>

            <result type="json">
                <!-- declarations for mappings from Request JSON Body goes here-->
                <param name="root">movie</param>
            </result>
        </action>

 </package>
</code>```

One catch over here is, which I encountered, for a simple JSON Structure, like the one below,

```<code>{
    "hello": {
        "name":"kav"
    },
    "uid":"fdsfds"
}
</code>```

where hello was intended to map to a POJO class Hello.java which was declared as a variable (private Hello hello; with its public getters and setters) in the controller. And uid was intended to map to a String variable uid declared in the controller (as private String uid; with its public getters and setters). This got mapped exactly without hello being mentioned in the <result type="json"> tag, like <param name="root">hello</param>.

In the case of movie, it wasn't so, as it had nested objects, like the code below,

```<code>public class Movie{

    private String movieName;
    private String movieID;
    .... other variables
    private List<Actor> actors;
    private List<Review> reviews;

   // Declarations of constructor, Getters & Setters
}
</code>```

Not sure why it happens so.

Title: Struts2 request PUT parameter on body

Body:
i want to add parameter for HTTP Request PUT on the body, but i only can do like this

http://localhost:9996/Events/employee/{id}.json?name={name}

so how to put name on body?

here my controller

public class EmployeeController implements ModelDriven<Object>{
private static final long serialVersionUID = 1L;
private String id;
private String name;
private Object model;
private EmployeeRepository employeeRepository = new EmployeeRepository();

//GET
public HttpHeaders index() {
    model = employeeRepository.findAllEmployee();
    return new DefaultHttpHeaders("index").disableCaching();
}

// GET
public HttpHeaders show() {
    model = employeeRepository.getEmployeeById(id);
    return new DefaultHttpHeaders("show").disableCaching();
}

//POST
public HttpHeaders create() {
    Integer empId = Integer.parseInt(id);
    Employee emp = new Employee(empId, name, "PQR");
    employeeRepository.addEmployee(emp);
    model = employeeRepository.findAllEmployee();
    return new DefaultHttpHeaders("create").disableCaching();
}

//PUT
public HttpHeaders update() {
    Integer empId = Integer.parseInt(id);
    Employee emp = new Employee(empId, name, "PQR");
    employeeRepository.updateEmployee(emp);
    model = employeeRepository.findAllEmployee();
    return new DefaultHttpHeaders("update").disableCaching();
}

//DELETE
public HttpHeaders destroy() {
    employeeRepository.deleteEmployee(id);
    model = employeeRepository.findAllEmployee();
    return new DefaultHttpHeaders("destroy").disableCaching();
}

public  String  getId()                 { return id; }
public  void    setId(String id)        { this.id = id; }
public  String  getName()               { return name; }
public  void    setName(String name)    { this.name = name; }
public  Object  getModel()              { return model; }

Body:
You need to add the JSON Interceptor for your action and it should look something like the code below.

<package name="movies" extends="rest-default, json-default">

        <interceptors>
            <interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/>

            <interceptor-stack name="jsonStack">
                <interceptor-ref name="json"/>
                <interceptor-ref name="defaultStack"/>
            </interceptor-stack>
        </interceptors>

<action name="movies" class="com.struts.movie.action.MoviesController">
            <interceptor-ref name="jsonStack"/>

            <result type="json">
                <!-- declarations for mappings from Request JSON Body goes here-->
                <param name="root">movie</param>
            </result>
        </action>

 </package>

One catch over here is, which I encountered, for a simple JSON Structure, like the one below,

{
    "hello": {
        "name":"kav"
    },
    "uid":"fdsfds"
}

where hello was intended to map to a POJO class Hello.java which was declared as a variable (private Hello hello; with its public getters and setters) in the controller. And uid was intended to map to a String variable uid declared in the controller (as private String uid; with its public getters and setters). This got mapped exactly without hello being mentioned in the <result type="json"> tag, like <param name="root">hello</param>.

In the case of movie, it wasn't so, as it had nested objects, like the code below,

public class Movie{

    private String movieName;
    private String movieID;
    .... other variables
    private List<Actor> actors;
    private List<Review> reviews;

   // Declarations of constructor, Getters & Setters
}

Not sure why it happens so.


问:
I get this error when working with jgritman / httpbuilder
I am new to Groovy and following a tutorial.
Any help would be much appreciated.
I also was unsuccessful in using @Grab.

It is a Groovy project without Maven or Gradle.

I have researched and couldn't find a solution, and the tutorial is not updated.

Course: The Complete Apache Groovy Developer Course

```<code>import groovyx.net.http.RESTClient

String base = 'http://api.icndb.com'

def chuck = new RESTClient(base)
def params = [firstName: "Dan", lastName: "Vega"]

chuck.contentType = ContentType.JSON
chuck.get( path: '/jokes/random', query: params ) { response, json ->
    println response.status
    println json
}
</code>```

Error

```<code>Caught: java.lang.NoClassDefFoundError: groovy/util/slurpersupport/GPathResult
java.lang.NoClassDefFoundError: groovy/util/slurpersupport/GPathResult
    at java.desktop/com.sun.beans.introspect.MethodInfo.get(MethodInfo.java:70)
    at java.desktop/com.sun.beans.introspect.ClassInfo.getMethods(ClassInfo.java:80)
    at groovyx.net.http.ParserRegistry.<init>(ParserRegistry.java:87)
    at groovyx.net.http.HTTPBuilder.<init>(HTTPBuilder.java:194)
    at groovyx.net.http.RESTClient.<init>(RESTClient.java:80)
    at com.thesamoanppprogrammer.practicegroovy.restapi.httpbuilder.todos.run(todos.groovy:7)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Caused by: java.lang.ClassNotFoundException: groovy.util.slurpersupport.GPathResult
</code>```

答:
starting from groovy 3.0 GPathResult moved to another package: groovy.xml.slurpersupport.GPathResult.

but according to error HTTPBuilder  is looking for old package groovy.util.slurpersupport.GPathResult.

You have to downgrade groovy version, or upgrade HTTPBuilder

Body:
I am new to Groovy and following a tutorial.
Any help would be much appreciated.
I also was unsuccessful in using @Grab.

It is a Groovy project without Maven or Gradle.

I have researched and couldn't find a solution, and the tutorial is not updated.

Course: The Complete Apache Groovy Developer Course

import groovyx.net.http.RESTClient

String base = 'http://api.icndb.com'

def chuck = new RESTClient(base)
def params = [firstName: "Dan", lastName: "Vega"]

chuck.contentType = ContentType.JSON
chuck.get( path: '/jokes/random', query: params ) { response, json ->
    println response.status
    println json
}

Error

Caught: java.lang.NoClassDefFoundError: groovy/util/slurpersupport/GPathResult
java.lang.NoClassDefFoundError: groovy/util/slurpersupport/GPathResult
    at java.desktop/com.sun.beans.introspect.MethodInfo.get(MethodInfo.java:70)
    at java.desktop/com.sun.beans.introspect.ClassInfo.getMethods(ClassInfo.java:80)
    at groovyx.net.http.ParserRegistry.<init>(ParserRegistry.java:87)
    at groovyx.net.http.HTTPBuilder.<init>(HTTPBuilder.java:194)
    at groovyx.net.http.RESTClient.<init>(RESTClient.java:80)
    at com.thesamoanppprogrammer.practicegroovy.restapi.httpbuilder.todos.run(todos.groovy:7)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Caused by: java.lang.ClassNotFoundException: groovy.util.slurpersupport.GPathResult


问:
How to VANILLA drag and drop on MOBILE
I've got some code here: https://codepen.io/anon/pen/PrZqqR

What I wanna do is to achieve drag and drop behaviour on screens < 720 px

How do I need to specify my move function at the very end knowing that the box I wanna drag should be position: relative for this purposes. Only vanilla JS is welcome. Thanks!

```<code>else if (window.innerWidth <= 720) {
    for (var i = 0; i < images.length; i++) {
        images[i].addEventListener('touchstart', touchstart);
        images[i].addEventListener('touchend', touchend);

    }
}

function touchstart() {
    window.startTime = new Date();
}

function touchend() {
    window.endTime = new Date();
    if (window.endTime - window.startTime < 1000) {
        // just show preview as time is < 1 sec
        // url for the img src
        let url = "url(" + this.childNodes[1].getAttribute("src") + ")";
        // hide preview text
        document.querySelector(".alert").style.display = "none";
        // set preview image
        target.style.backgroundImage = url;
        target.classList.add("back_set");

        // end of simple click event
    } else {
        // this section handels the dragging story
        // add shake and start dragging, time is > 1 sec
        console.log("more than 1 sec");
        // make draggable
        this.setAttribute("draggable", "true");
        this.style.position = "absolute";
        // make shake animation
        this.style.animation = "shake 1s infinite";
        var x = parseInt(this.style.left);
        var y = parseInt(this.style.top);
        this.addEventListener("touchmove", move);
    }
}

function move() {
    console.log("moving");
}
</code>```

答:
This way you can drag an element by touch and collect its id and final position.
It is actually working for me.

HTML:

```<code><!-- Div element you want to drag with touch -->
<div class="draggable" id="_draggable">
</div>
</code>```

JavaScript:

```<code>let box = document.querySelector(".draggable");

box.addEventListener('touchmove', (e) => {
    //Gets movement in px of the touch movement
    let touchLocation = e.targetTouches[0];
    //Gets element data
    currentElement = e.target;
    //Gets element id
    currentElementId = currentElement.id;

    //Moves element
    box.style.left = touchLocation.pageX + 'px';
    box.style.top = touchLocation.pageY + 'px';
})

box.addEventListener('touchend', (e) => {
    //Picks up the id of the dragged element
    console.log(currentElementId)

    //Picks up the new element position
    let x = parseInt(box.style.left);
    let y = parseInt(box.style.top);

})
</code>```

Remember the drag element must have position: absolute; or position: relative;

Please let me know if you need anything else.

Title: How to VANILLA drag and drop on MOBILE

Body:
I've got some code here: https://codepen.io/anon/pen/PrZqqR

What I wanna do is to achieve drag and drop behaviour on screens < 720 px

How do I need to specify my move function at the very end knowing that the box I wanna drag should be position: relative for this purposes. Only vanilla JS is welcome. Thanks!

else if (window.innerWidth <= 720) {
    for (var i = 0; i < images.length; i++) {
        images[i].addEventListener('touchstart', touchstart);
        images[i].addEventListener('touchend', touchend);

    }
}

function touchstart() {
    window.startTime = new Date();
}

function touchend() {
    window.endTime = new Date();
    if (window.endTime - window.startTime < 1000) {
        // just show preview as time is < 1 sec
        // url for the img src
        let url = "url(" + this.childNodes[1].getAttribute("src") + ")";
        // hide preview text
        document.querySelector(".alert").style.display = "none";
        // set preview image
        target.style.backgroundImage = url;
        target.classList.add("back_set");

        // end of simple click event
    } else {
        // this section handels the dragging story
        // add shake and start dragging, time is > 1 sec
        console.log("more than 1 sec");
        // make draggable
        this.setAttribute("draggable", "true");
        this.style.position = "absolute";
        // make shake animation
        this.style.animation = "shake 1s infinite";
        var x = parseInt(this.style.left);
        var y = parseInt(this.style.top);
        this.addEventListener("touchmove", move);
    }
}

function move() {
    console.log("moving");
}

Body:
This way you can drag an element by touch and collect its id and final position.
It is actually working for me.

HTML:

<!-- Div element you want to drag with touch -->
<div class="draggable" id="_draggable">
</div>

JavaScript:

let box = document.querySelector(".draggable");

box.addEventListener('touchmove', (e) => {
    //Gets movement in px of the touch movement
    let touchLocation = e.targetTouches[0];
    //Gets element data
    currentElement = e.target;
    //Gets element id
    currentElementId = currentElement.id;

    //Moves element
    box.style.left = touchLocation.pageX + 'px';
    box.style.top = touchLocation.pageY + 'px';
})

box.addEventListener('touchend', (e) => {
    //Picks up the id of the dragged element
    console.log(currentElementId)

    //Picks up the new element position
    let x = parseInt(box.style.left);
    let y = parseInt(box.style.top);

})

Remember the drag element must have position: absolute; or position: relative;

Please let me know if you need anything else.