问:
Extra padding above table view headers in iOS 15
How to change the extra padding above UITableView section headers that has started to appear in iOS 15?

答:
In case you are like me having trouble in some grouped style tableViews after setting sectionHeaderTopPadding but still seeing that annoying gap for the first section, just add the following in your VC's viewDidLoad:

```<code>tableView.tableHeaderView = UIView(frame: CGRect(x: .zero, y: .zero, width: .zero, height: CGFloat.leastNonzeroMagnitude))
</code>```

Found in here

Body:
In case you are like me having trouble in some grouped style tableViews after setting sectionHeaderTopPadding but still seeing that annoying gap for the first section, just add the following in your VC's viewDidLoad:

tableView.tableHeaderView = UIView(frame: CGRect(x: .zero, y: .zero, width: .zero, height: CGFloat.leastNonzeroMagnitude))

Found in here


来源: stackexchange

问:
Default radio button option with jquery
I am trying to hide/show different divs using the method shown here.

```<code><style>
    .box{
        color: #fff;
        padding: 20px;
        display: none;
        margin-top: 20px;
    }
    .red{ background: #ff0000; }
    .green{ background: #228B22; }
    .blue{ background: #0000ff; }
    label{ margin-right: 15px; }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $('input[type="radio"]').click(function(){
        var inputValue = $(this).attr("value");
        var targetBox = $("." + inputValue);
        $(".box").not(targetBox).hide();
        $(targetBox).show();
    });
});
</script>
</head>
<body>
    <div>
        <label><input type="radio" name="colorRadio" value="red" checked = "checked"> red</label>
        <label><input type="radio" name="colorRadio" value="green"> green</label>
        <label><input type="radio" name="colorRadio" value="blue"> blue</label>
    </div>
    <div class="red box">You have selected <strong>red radio button</strong> so i am here</div>
    <div class="green box">You have selected <strong>green radio button</strong> so i am here</div>
    <div class="blue box">You have selected <strong>blue radio button</strong> so i am here</div>
</body>
</code>```

I would like to have the red button clicked by default when the page loads. However if I just change the label to this:

```<code><label><input type="radio" name="colorRadio" value="red" checked = "checked"> red</label>
</code>```

It shows as clicked:

but I have to click it again to actually load the red div:

Is there an elegant way to fix that so it is showing the red div when the page loads?

Thanks a lot,
Alex

答:
How about just adding the $('.red').show() to set which box should be shown as default?

$(document).ready(function () {
  $('input[type="radio"]').click(function () {
    var inputValue = $(this).attr('value');
    var targetBox = $('.' + inputValue);
    $('.box').not(targetBox).hide();
    $(targetBox).show();
  });

  $('.red').show();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  color: #fff;
  padding: 20px;
  display: none;
  margin-top: 20px;
}
.red {
  background: #ff0000;
}
.green {
  background: #228b22;
}
.blue {
  background: #0000ff;
}
label {
  margin-right: 15px;
}</code>```

        <input type="radio" name="colorRadio" value="red" checked> red
        <input type="radio" name="colorRadio" value="green"> green
        <input type="radio" name="colorRadio" value="blue"> blue

You have selected red radio button so i am here

You have selected green radio button so i am here

You have selected blue radio button so i am here

```

ContentLicense: CC BY-SA 4.0

Title: Default radio button option with jquery

Body:
I am trying to hide/show different divs using the method shown here.

        <input type="radio" name="colorRadio" value="red" checked = "checked"> red
        <input type="radio" name="colorRadio" value="green"> green
        <input type="radio" name="colorRadio" value="blue"> blue

You have selected red radio button so i am here

You have selected green radio button so i am here

You have selected blue radio button so i am here

I would like to have the red button clicked by default when the page loads. However if I just change the label to this:

<input type="radio" name="colorRadio" value="red" checked = "checked"> red

It shows as clicked:

but I have to click it again to actually load the red div:

Is there an elegant way to fix that so it is showing the red div when the page loads?

Thanks a lot,
Alex

Body:
How about just adding the $('.red').show() to set which box should be shown as default?

$(document).ready(function () {
  $('input[type="radio"]').click(function () {
    var inputValue = $(this).attr('value');
    var targetBox = $('.' + inputValue);
    $('.box').not(targetBox).hide();
    $(targetBox).show();
  });

  $('.red').show();
});

.box {
  color: #fff;
  padding: 20px;
  display: none;
  margin-top: 20px;
}
.red {
  background: #ff0000;
}
.green {
  background: #228b22;
}
.blue {
  background: #0000ff;
}
label {
  margin-right: 15px;
}

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<body>
    <div>
        <label><input type="radio" name="colorRadio" value="red" checked> red</label>
        <label><input type="radio" name="colorRadio" value="green"> green</label>
        <label><input type="radio" name="colorRadio" value="blue"> blue</label>
    </div>
    <div class="red box">You have selected <strong>red radio button</strong> so i am here</div>
    <div class="green box">You have selected <strong>green radio button</strong> so i am here</div>
    <div class="blue box">You have selected <strong>blue radio button</strong> so i am here</div>
</body>


问:
Error when trying to find an element using SELENIUM
Hopefully someone can help me out here.

My goal is to successfully connect to this website using Python (Selenium + Chromedriver) and successfully search for an address in the search bar. Im struggling to manage to find the actual search bar itself using Selenium. The HTML code doesn't have an ID or NAME to distinguish it by, all it has is a class and when i search for the class, i get an error saying it cannot be found.

Hopefully this is an easy fix and im just being silly. Thanks a lot.

P.S First post - please drop some hints on what to change next time :)

CODE

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)

driver.get("https://creeper.banano.cc/")
search = driver.find_element_by_class_name("ValidatedSearch form-control form-control-lg ")
```
<p>ERROR CODE</p>
```NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":".ValidatedSearch form-control form-control-lg "}
```

Python Code + HTML of Website

答:
The error here is you have multiple class names in a function only expecting one. ValidatedSearch, form-control, and form-control-lg are different classes, since classes can't have spaces in them. So what you're looking for is this:

```<code>search = driver.find_element_by_class_name("ValidatedSearch")
</code>```

This targets the first tag in the ValidatedSearch class that it finds.

Body:
Hopefully someone can help me out here.

My goal is to successfully connect to this website using Python (Selenium + Chromedriver) and successfully search for an address in the search bar. Im struggling to manage to find the actual search bar itself using Selenium. The HTML code doesn't have an ID or NAME to distinguish it by, all it has is a class and when i search for the class, i get an error saying it cannot be found.

Hopefully this is an easy fix and im just being silly. Thanks a lot.

P.S First post - please drop some hints on what to change next time :)

CODE

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)

driver.get("https://creeper.banano.cc/")
search = driver.find_element_by_class_name("ValidatedSearch form-control form-control-lg ")

ERROR CODE

NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":".ValidatedSearch form-control form-control-lg "}

Python Code + HTML of Website

Body:
The error here is you have multiple class names in a function only expecting one. ValidatedSearch, form-control, and form-control-lg are different classes, since classes can't have spaces in them. So what you're looking for is this:

search = driver.find_element_by_class_name("ValidatedSearch")

This targets the first tag in the ValidatedSearch class that it finds.


问:
JavaScript to get value from HTML table cell
I'm trying to extract the text from a multi-row, multi-column html table. A column from the table is defined below. All the id values are dynamic so I'll need to reference other attributes or tags to fetch it. The value I'm trying to fetch here is "PERS". It is the only cell containing text.

 PERS

```
<p>I was expecting this to work but no such luck ...</p>
<pre class="lang-js prettyprint-override"><code>  var input1rw = document.getElementsByClassName('x-grid-cell x-grid-td x-grid-cell-TIMM103-Block-2-colstate-ResourceCode-0 grid-cell-error-input x-unselectable');
  var input1cl = input1rw[0];
  console.log('result: ', input1cl.innerText);
</code>```

After several hours of failure, I'd greatly appreciate some help from the experts.

答:
```<code>function GetCellValues() {
  var table = document.getElementById('mytable');
    for (var r = 0, n = table.rows.length; r < n; r++) {
        for (var c = 0, m = table.rows[r].cells.length; c < m; c++)
        {
            alert(table.rows[r].cells[c].innerHTML);
        }
    }
}
</code>```

Body:
I'm trying to extract the text from a multi-row, multi-column html table. A column from the table is defined below. All the id values are dynamic so I'll need to reference other attributes or tags to fetch it. The value I'm trying to fetch here is "PERS". It is the only cell containing text.

 PERS

I was expecting this to work but no such luck ...

  var input1rw = document.getElementsByClassName('x-grid-cell x-grid-td x-grid-cell-TIMM103-Block-2-colstate-ResourceCode-0 grid-cell-error-input x-unselectable');
  var input1cl = input1rw[0];
  console.log('result: ', input1cl.innerText);

After several hours of failure, I'd greatly appreciate some help from the experts.


问:
Problem with Regular expression for getting substring in colon-delimited data
I am using a regular expression which gets the substring associated with a match
i.e

```<code>"(MAC:[A-Z0-9]{12})"
</code>```

This regex will find the occurences of MAC:(Some characters) in a string.
This regex is working for characters less than 10 i.e

```<code> "(MAC:[A-Z0-9]{8})"   -   WORKS

but,

 "(MAC:[A-Z0-9]{8})"   -   THROWS EXCEPTION
</code>```

Any help appreciated regarding the same.

EDIT: I use something like this:

```<code>MatchCollection macName = Regex.Matches(otherdata,
                                        @"(MAC:[A-Z0-9]{10})+",
                                        RegexOptions.IgnoreCase);
</code>```

To extract the characters after MAC:

```<code>"ADMIN:1EXT:0NOR:0OUT:1PRI:1BAT:1MOD:1MAC:BFEBFBFF000006FB00:1E:37:54:AE:C8"
</code>```

I should get the string after using the regex:

```<code>MAC:BFEBFBFF000006FB00:1E:37:54:AE:C8
</code>```

I hope I have explained myself clearly.

答:
Or this one:

```<code>"(MAC:[\d\w:]+?[\d\w:]*)"
</code>```

This one makes additional check to be sure that this is good match.

ContentLicense: CC BY-SA 3.0

Body:
I am using a regular expression which gets the substring associated with a match
i.e

"(MAC:[A-Z0-9]{12})"

This regex will find the occurences of MAC:(Some characters) in a string.
This regex is working for characters less than 10 i.e

 "(MAC:[A-Z0-9]{8})"   -   WORKS

but,

 "(MAC:[A-Z0-9]{8})"   -   THROWS EXCEPTION

Any help appreciated regarding the same.

EDIT: I use something like this:

MatchCollection macName = Regex.Matches(otherdata,
                                        @"(MAC:[A-Z0-9]{10})+",
                                        RegexOptions.IgnoreCase);

To extract the characters after MAC:

"ADMIN:1EXT:0NOR:0OUT:1PRI:1BAT:1MOD:1MAC:BFEBFBFF000006FB00:1E:37:54:AE:C8"

I should get the string after using the regex:

MAC:BFEBFBFF000006FB00:1E:37:54:AE:C8

I hope I have explained myself clearly.

Body:
Or this one:

"(MAC:[\d\w:]+?[\d\w:]*)"

This one makes additional check to be sure that this is good match.


问:
Formatting GKE local ssd using lvm and btrfs
I'm trying to format the local ssd that GKE node pools provide using btrfs. The drive comes preformatted with ext4. Is there a way to prevent this so that I can format it using btrfs?

I would prefer not to forcibly unmount the drive or modify the Node in GKE, but haven't been able to find a canonical way of doing this. The answer might be to run my own kubernetes cluster, but would prefer not to do this.

I use terraform to create the cluster and ansible to perform the actual modification of the underlying host:

```<code>---
- hosts: localhost
  connection: local
  become: yes
  tasks:
    - name: Update the apt package index
      apt:
        name: "*"
        state: latest
        update_cache: yes
        force_apt_get: yes

    - name: Install btrfs partition tools
      apt:
        name:
          - parted
          - btrfs-progs
        state: latest

    - name: Enable btrfs
      community.general.modprobe:
        name: btrfs
        state: present

    - name: Unmount existing partition
      ansible.posix.mount:
        path: /mnt/stateful_partition/kube-ephemeral-ssd
        state: unmounted

    - name: Delete existing ext4 partition
      parted:
        device: /dev/nvme0n1
        # number: 1
        state: absent

    - name: create partition
      parted:
        device: /dev/nvme0
        number: 1
        flags: [ lvm ]
        state: present

    - name: Create Volume Group
      community.general.lvg:
        vg: replays
        pvs: /dev/nvme0n1
</code>```

答:
Did some digging through the GKE node initialization scripts and figured out where the setting enabling this was. I was able to disable it by modifying the kube-env metadata field in the instance template that GKE generates.

I wrote a script in typescript to do this modification every time I start the cluster. It's pretty rough and uncommented, so if you need help doing this or node customization in general, just comment.

<s>
With a bit more research it looks like it's possible, but pretty ugly. The local SSD isn't simply blank storage, it's used by the kubernetes service  itself to store files it uses.

ScyllaDB is doing something similar to what I want to get an xfs filesystem on the local storage.

It does this via a script that:

Shuts the kubernetes service on the node down.

Copies the kubernetes files on the local ssd to a temp directory.

Formats the local storage as xfs.

Copies the kubernetes files to the newly created xfs drive.

Restarts the kubernetes service.

All this happens in a systemd service to ensure it keeps running when the  containers in the daemonset that starts this process shutdown due to the kubernetes service being stopped.

I think I'll investigate other hosted services.

Script: https://github.com/scylladb/scylla-operator/blob/6e9424fa2c4206c1e3e6fd74b9398e5a36d91f26/hack/gke/xfs-formatter/xfs-formatter.sh
Daemonset: https://github.com/scylladb/scylla-operator/blob/master/examples/gke/xfs-formatter-daemonset.yaml
</s>

Body:
I'm trying to format the local ssd that GKE node pools provide using btrfs. The drive comes preformatted with ext4. Is there a way to prevent this so that I can format it using btrfs?

I would prefer not to forcibly unmount the drive or modify the Node in GKE, but haven't been able to find a canonical way of doing this. The answer might be to run my own kubernetes cluster, but would prefer not to do this.

I use terraform to create the cluster and ansible to perform the actual modification of the underlying host:

---
- hosts: localhost
  connection: local
  become: yes
  tasks:
    - name: Update the apt package index
      apt:
        name: "*"
        state: latest
        update_cache: yes
        force_apt_get: yes

    - name: Install btrfs partition tools
      apt:
        name:
          - parted
          - btrfs-progs
        state: latest

    - name: Enable btrfs
      community.general.modprobe:
        name: btrfs
        state: present

    - name: Unmount existing partition
      ansible.posix.mount:
        path: /mnt/stateful_partition/kube-ephemeral-ssd
        state: unmounted

    - name: Delete existing ext4 partition
      parted:
        device: /dev/nvme0n1
        # number: 1
        state: absent

    - name: create partition
      parted:
        device: /dev/nvme0
        number: 1
        flags: [ lvm ]
        state: present

    - name: Create Volume Group
      community.general.lvg:
        vg: replays
        pvs: /dev/nvme0n1


问:
Terraform | Change a resource created by a public module
Let's say that I'm creating an AWS ECS cluster with the help of a public or internal module that I cannot directly change. That module is creating, besides the ECS, let's say a couple of SGs, some alb, maybe an ACM cert, etc. It's all good BUT, for the sake of this problem, I don't like the SGs configs and would like to change them but the developer did not provide a var for that.

Is there a way for me to reference a particular SG(or any other resource) created by that module and then overwrite/change/replace its config?

Or do I have to create a PR in the repo of that module to add the necessary vars/changes?

答:
In Terraform it's the responsibility of a module author to decide the scope of that module and tailor its input variables and output values to meet that scope. There is no way to add additional customization capabilities to a module from the perspective of a caller, because that would then cause your customizations to be effectively a compatibility constraint on future changes to the module which the module author has no awareness of, and therefore cannot predict.

If a particular module doesn't meet your needs then your options are, unfortunately, much the same as they are for third-party libraries in most language ecosystems:

Send a feature request to the maintainers (and possibly also a pull request to implement that feature) and see if the maintainers are willing to accept your new requirement into their scope.

Assuming that the module uses a suitable open source license, use it as the basis for your own module which meets a similar need as the original module but that is extended to meet your specific requirements.


问:
Two-dimensional array in Swift
I get so confused about 2D arrays in Swift. Let me describe step by step. And would you please correct me if I am wrong.

First of all; declaration of an empty array:

```<code>class test{
    var my2Darr = Int[][]()
}
</code>```

Secondly fill the array. (such as my2Darr[i][j] = 0 where i, j are for-loop variables)

```<code>class test {
    var my2Darr = Int[][]()
    init() {
        for(var i:Int=0;i<10;i++) {
            for(var j:Int=0;j<10;j++) {
                my2Darr[i][j]=18   /*  Is this correct?  */
            }
        }
    }
}
</code>```

And Lastly, Editing element of in array

```<code>class test {
    var my2Darr = Int[][]()
    init() {
        ....  //same as up code
    }
    func edit(number:Int,index:Int){
        my2Darr[index][index] = number
        // Is this correct? and What if index is bigger
        // than i or j... Can we control that like
        if (my2Darr[i][j] == nil) { ...  }   */
    }
}
</code>```

答:
I would use a 1D array and just index it separately. For example consider using:

```<code>struct MatrixIndexer {
    var rows: Int
    var columns: Int

    var count: Int {
        return rows * columns
    }

    subscript(_ r: Int, _ c: Int) -> Int {
        precondition(r < rows && c < columns)
        return r * columns + c
    }

    func coordinate(_ i: Int) -> (row: Int, column: Int) {
        precondition(i < count)
        return (i / columns, i % columns)
    }
}

let at = MatrixIndexer(rows: 16, columns: 8)
var array2D: [Float] = Array(repeating: 0, count: at.count)

array2D[at[3, 4]] = 3
array2D[at[5, 2]] = 6
</code>```

(If you want a single struct to pass around, you could introduce an Array2D which contains the MatrixIndexer and an Array).

Why is this a good idea? First, you get nicer operations out of the box such as:

Collection extensions: map, filter, reduce

iterate all elements in a singe loop

easy copying

Ensure the invariant that each row and column is the same size

Second, it is also much better for performance.

Faster access time by reducing memory allocation. Each element is contiguous with the next, instead of each row being a separate point off in memory.

Use one allocation and deallocation command instead of many (allocators are often slow for a variety of reasons)

Title: Two-dimensional array in Swift

Body:
I get so confused about 2D arrays in Swift. Let me describe step by step. And would you please correct me if I am wrong.

First of all; declaration of an empty array:

class test{
    var my2Darr = Int[][]()
}

Secondly fill the array. (such as my2Darr[i][j] = 0 where i, j are for-loop variables)

class test {
    var my2Darr = Int[][]()
    init() {
        for(var i:Int=0;i<10;i++) {
            for(var j:Int=0;j<10;j++) {
                my2Darr[i][j]=18   /*  Is this correct?  */
            }
        }
    }
}

And Lastly, Editing element of in array

class test {
    var my2Darr = Int[][]()
    init() {
        ....  //same as up code
    }
    func edit(number:Int,index:Int){
        my2Darr[index][index] = number
        // Is this correct? and What if index is bigger
        // than i or j... Can we control that like
        if (my2Darr[i][j] == nil) { ...  }   */
    }
}

Body:
I would use a 1D array and just index it separately. For example consider using:

struct MatrixIndexer {
    var rows: Int
    var columns: Int

    var count: Int {
        return rows * columns
    }

    subscript(_ r: Int, _ c: Int) -> Int {
        precondition(r < rows && c < columns)
        return r * columns + c
    }

    func coordinate(_ i: Int) -> (row: Int, column: Int) {
        precondition(i < count)
        return (i / columns, i % columns)
    }
}

let at = MatrixIndexer(rows: 16, columns: 8)
var array2D: [Float] = Array(repeating: 0, count: at.count)

array2D[at[3, 4]] = 3
array2D[at[5, 2]] = 6

(If you want a single struct to pass around, you could introduce an Array2D which contains the MatrixIndexer and an Array).

Why is this a good idea? First, you get nicer operations out of the box such as:

Collection extensions: map, filter, reduce

iterate all elements in a singe loop

easy copying

Ensure the invariant that each row and column is the same size

Second, it is also much better for performance.

Faster access time by reducing memory allocation. Each element is contiguous with the next, instead of each row being a separate point off in memory.

Use one allocation and deallocation command instead of many (allocators are often slow for a variety of reasons)


问:
CSS: how to add background but not only in the text
I'm making a copy of the page of Google as a school project and i'm trying to set up the background color of the last part of the footer but it's only filling the color around the letters, how I can fill the whole part of background there?

p {
  padding: 15px 30px;
  font-size: 15px;
  border-bottom: 1px solid #f2f2f2;
  background-color: #f2f2f2;
  color: #70757a;
  display: block;
}

.izq,
.der {
  font-size: 14px;
  color: #70757a;
  margin-block-end: 10px;
  background-color: #f2f2f2;
}

.izq {
  margin-left: 40px;
  float: left;
}

.der {
  margin-right: 40px;
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <div>
    <p>México</p>
  </div>
  <div id="abajo">Sobre Google
    Publicidad
    Negocios
    Cómo funciona la Búsqueda
    Privacidad
    Condiciones
    Preferencias </div>
</footer></code>```

答:
You need to add a height to div id="abajo" and then add a background to that. If you don't want any margin between the top part and the bottom part, add margin-block-end: 0px; to the p css. I changed the background to be a little darker so it is easier to see. Also, if this is viewed on a smaller screen, part of the footer will pop out of the bottom.

p {
  padding: 15px 30px;
  font-size: 15px;
  background-color: #bbb;
  color: #70757a;
  display: block;
  margin-block-end: 0px;
}
.izq, .der {
  font-size: 14px;
  color: #70757a;
  margin-block-end: 10px;
}
.izq {
  margin-left: 40px;
  float:left;
}
.der {
  margin-right: 40px;
  float: right;
}
#abajo {
  height: 25px;
  background: #bbb
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <div id="asdf"><p>México</p></div>
  <div id="abajo">
    Sobre Google
    Publicidad
    Negocios
    Cómo funciona la Búsqueda
    Privacidad
    Condiciones
    Preferencias
  </div>
</footer></code>```

Body:
I'm making a copy of the page of Google as a school project and i'm trying to set up the background color of the last part of the footer but it's only filling the color around the letters, how I can fill the whole part of background there?

p {
  padding: 15px 30px;
  font-size: 15px;
  border-bottom: 1px solid #f2f2f2;
  background-color: #f2f2f2;
  color: #70757a;
  display: block;
}

.izq,
.der {
  font-size: 14px;
  color: #70757a;
  margin-block-end: 10px;
  background-color: #f2f2f2;
}

.izq {
  margin-left: 40px;
  float: left;
}

.der {
  margin-right: 40px;
  float: right;
}

México

Sobre Google
    Publicidad
    Negocios
    Cómo funciona la Búsqueda
    Privacidad
    Condiciones
    Preferencias

Body:
You need to add a height to div id="abajo" and then add a background to that. If you don't want any margin between the top part and the bottom part, add margin-block-end: 0px; to the p css. I changed the background to be a little darker so it is easier to see. Also, if this is viewed on a smaller screen, part of the footer will pop out of the bottom.

p {
  padding: 15px 30px;
  font-size: 15px;
  background-color: #bbb;
  color: #70757a;
  display: block;
  margin-block-end: 0px;
}
.izq, .der {
  font-size: 14px;
  color: #70757a;
  margin-block-end: 10px;
}
.izq {
  margin-left: 40px;
  float:left;
}
.der {
  margin-right: 40px;
  float: right;
}
#abajo {
  height: 25px;
  background: #bbb
}

<footer>
  <div id="asdf"><p>México</p></div>
  <div id="abajo">
    <a href="https://about.google/?utm_source=google-MX&utm_medium=referral&utm_campaign=hp-footer&fg=1" class="izq">Sobre Google</a>
    <a href="https://ads.google.com/intl/es-419_mx/home/?subid=ww-ww-et-g-awa-a-g_hpafoot1_1!o2&utm_source=google.com&utm_medium=referral&utm_campaign=google_hpafooter&fg=1" class="izq">Publicidad</a>
    <a href="https://smallbusiness.withgoogle.com/intl/es-419_mx/?subid=ww-ww-et-g-awa-a-g_hpbfoot1_1!o2&utm_source=google&utm_medium=ep&utm_campaign=google_hpbfooter&utm_content=google_hpbfooter&gmbsrc=ww-ww-et-gs-z-gmb-s-z-u~sb-g4sb_srvcs-u&c=MX#!/" class="izq">Negocios</a>
    <a href="https://www.google.com/search/howsearchworks/?fg=1" class="izq">Cómo funciona la Búsqueda</a>
    <a href="https://policies.google.com/privacy?hl=es-419&fg=1" class="der">Privacidad</a>
    <a href="https://policies.google.com/terms?hl=es-419&fg=1" class="der">Condiciones</a>
    <a href="" class="der">Preferencias</a>
  </div>
</footer>


问:
How to append a dynamic element to an image opened in lightgallery.js
I have a page that show lots of photos which can be opened with lightgallery.js

I've already made some custom HTML caption which works fine. But now I want to add a label to the image itself. How can I do that?

I will show an example of what my photos page looks like:

When you open an image this is what it looks like:

The left part is a custom HTML caption which I linked with this attribute: data-sub-html.

Example code of my looped code:

```<code>$photomasonry .= '
<div class="tile scale-anm noselect">
  <a href="https://studio.website.nl/'.$getphotos['preview'].'" data-sub-html="#caption'.$imgcount.'" class="item masonrytile" data-src="https://studio.website.nl/'.$getphotos['preview'].'">
    <img src="https://studio.website.nl/'.$getphotos['preview'].'"/>
    <span class="idlabel">'.$getphotos['id'].'</span>
    <span class="sizelabel">'.$size.'</span>
  </a>
</div>';
$photomasonry .= '
<div id="caption'.$imgcount.'" style="display:none">
  <img src="https://studio.website.nl/images/logo.png">
  <h4 class="subhtmlh4">Maak iets moois met deze foto</h4>
  <div class="gallerypopupbtns">
    <a href="design-magazijn/stockfotos/'.$_GET['alias'].'/'.$getphotos['id'].'"><button class="btnstyle purplebtn" type="button" name="button">Maak iets moois</button></a>
  </div>
</div>';
$imgcount++;
</code>```

But now I want this purple size icon (L, XL, XX) as a label on the image when lightgallery is opened. How can I do this? The html of the lightgallery is only generated after the page is loaded.

I want to add an element inside this part:

```<code><div class="lg-img-wrap">
    <img class="lg-object lg-image" src="https://studio.website.nl/images/photos/previews/preview-bb58317c8d05e29b32963e7a295a5b9f.jpg">
</div>
</code>```

But not just that, the content is dynamic, so display the correct size for the correct image. I already created this for the photo overview page but not when clicking a photo.

答:
According to the lightgallery docs, you can use the event lgAfterOpen to execute code once the gallery is opened. However, lightgallery makes this slightly difficult as you can't access the image clicked on from this event, but you can access it from the event lgBeforeOpen. With this in mind, I'd accomplish this by doing two things.

Firstly, add the size as a data attribute of each image:

```
<p>Secondly, add the following functions when initialising lightgallery:</p>
<pre class="lang-js prettyprint-override"><code>// example gallery definition
const lg = document.getElementById('custom-events-demo');
// add the following functions
lg.addEventListener('lgBeforeOpen', (event) => {
  //add datasize property to target so it can be accessed in the afterOpen function
  event.target.dataset.size = event.explicitOriginalTarget.dataset.size;
});
lg.addEventListener('lgAfterOpen', (event) => {
  // get size from data attribute
  var size = event.target.dataset.size;
  // get the .lg-img-wrap div to append size to
  var imgWrap = document.querySelector(".lg-container.lg-show .lg-img-wrap");
  // create and append span
  var sizeSpan = document.createElement("span");
  sizeSpan.classList.add("sizelabel");
  sizeSpan.innerHTML = size;
  imgWrap.appendChild(sizeSpan);
});
//initialise lightgallery
lightGallery(lg);
</code>```

You may be using a different version of lightgallery, but when I tested this the .lg-img-wrap element was a picture element not a div, so I replaced the last line of the event listener function with the following to get the size to show:

imgWrap.parentElement.appendChild(sizeSpan);
```
<p>You might need a bit of extra CSS to position the size span as you wish, but just to get it to show all you need is:</p>
<pre class="lang-css prettyprint-override"><code>.sizelabel {
  position: relative;
}
</code>```

Note: I don't think this will work if you navigate to a different image from within lightgallery as it won't update the size, and in fact the size might just get removed. To fix this you'd probably need to do something using the lgAfterSlide event and the index of the image, but from your screenshot it looks like you don't expect the user to scroll through images within lightgallery anyway so this may not be an issue.

Body:
I have a page that show lots of photos which can be opened with lightgallery.js

I've already made some custom HTML caption which works fine. But now I want to add a label to the image itself. How can I do that?

I will show an example of what my photos page looks like:

When you open an image this is what it looks like:

The left part is a custom HTML caption which I linked with this attribute: data-sub-html.

Example code of my looped code:

$photomasonry .= '

    '.$getphotos['id'].'
    '.$size.'

';
$photomasonry .= '

Maak iets moois met deze foto

    <button class="btnstyle purplebtn" type="button" name="button">Maak iets moois</button>

';
$imgcount++;

But now I want this purple size icon (L, XL, XX) as a label on the image when lightgallery is opened. How can I do this? The html of the lightgallery is only generated after the page is loaded.

I want to add an element inside this part:

But not just that, the content is dynamic, so display the correct size for the correct image. I already created this for the photo overview page but not when clicking a photo.

Body:
According to the lightgallery docs, you can use the event lgAfterOpen to execute code once the gallery is opened. However, lightgallery makes this slightly difficult as you can't access the image clicked on from this event, but you can access it from the event lgBeforeOpen. With this in mind, I'd accomplish this by doing two things.

Firstly, add the size as a data attribute of each image:

<img src="https://studio.website.nl/'.$getphotos['preview'].'" data-size="'.$size.'"/>

Secondly, add the following functions when initialising lightgallery:

// example gallery definition
const lg = document.getElementById('custom-events-demo');
// add the following functions
lg.addEventListener('lgBeforeOpen', (event) => {
  //add datasize property to target so it can be accessed in the afterOpen function
  event.target.dataset.size = event.explicitOriginalTarget.dataset.size;
});
lg.addEventListener('lgAfterOpen', (event) => {
  // get size from data attribute
  var size = event.target.dataset.size;
  // get the .lg-img-wrap div to append size to
  var imgWrap = document.querySelector(".lg-container.lg-show .lg-img-wrap");
  // create and append span
  var sizeSpan = document.createElement("span");
  sizeSpan.classList.add("sizelabel");
  sizeSpan.innerHTML = size;
  imgWrap.appendChild(sizeSpan);
});
//initialise lightgallery
lightGallery(lg);

You may be using a different version of lightgallery, but when I tested this the .lg-img-wrap element was a picture element not a div, so I replaced the last line of the event listener function with the following to get the size to show:

imgWrap.parentElement.appendChild(sizeSpan);

You might need a bit of extra CSS to position the size span as you wish, but just to get it to show all you need is:

.sizelabel {
  position: relative;
}

Note: I don't think this will work if you navigate to a different image from within lightgallery as it won't update the size, and in fact the size might just get removed. To fix this you'd probably need to do something using the lgAfterSlide event and the index of the image, but from your screenshot it looks like you don't expect the user to scroll through images within lightgallery anyway so this may not be an issue.


问:
A value of type 'String?' can't be returned because function has return type of 'Future<String>?'
The documentation says:

If the function has a declared return type,  then update the type to
be Future<T>, where T is the type of the value that the function
returns.

When I do that with this code, I get an error: A value of type 'String?' can't be returned from the method 'amethod' because it has a return type of Future < String>?.

Why is it giving that error and what is the correct way to return a non-void value from an async function? Thanks.

```<code>class Demo{

 Future<String>? amethod() async{
 String? variable1;

   //await ...

  return variable1;
 }
}
</code>```

答: You need change Future<String>? to Future<String?>? or Future<String?>

Body:
The documentation says:

If the function has a declared return type,  then update the type to
be Future<T>, where T is the type of the value that the function
returns.

When I do that with this code, I get an error: A value of type 'String?' can't be returned from the method 'amethod' because it has a return type of Future < String>?.

Why is it giving that error and what is the correct way to return a non-void value from an async function? Thanks.

class Demo{

 Future<String>? amethod() async{
 String? variable1;

   //await ...

  return variable1;
 }
}


问:
How can one use multi threading in PHP applications
Is there a realistic way of implementing a multi-threaded model in PHP whether truly, or just simulating it. Some time back it was suggested that you could force the operating system to load another instance of the PHP executable and handle other simultaneous processes.

The problem with this is that when the PHP code finished executing the PHP instance remains in memory because there is no way to kill it from within PHP.  So if you are simulating several threads you can imagine whats going to happen.  So I am still looking for a way multi-threading can be done or simulated effectively from within PHP. Any ideas?

答:
While you can't thread, you do have some degree of process control in php. The two function sets that are useful here are:

Process control functions
http://www.php.net/manual/en/ref.pcntl.php

POSIX functions
http://www.php.net/manual/en/ref.posix.php

You could fork your process with pcntl_fork - returning the PID of the child. Then you can use posix_kill to despose of that PID.

That said, if you kill a parent process a signal should be sent to the child process telling it to die. If php itself isn't recognising this you could register a function to manage it and do a clean exit using pcntl_signal.

OwnerDisplayName: sobbayi

LastEditorDisplayName: buyutec

ContentLicense: CC BY-SA 2.5


问:
Any way to do a local CVS proxy/server?
I have an online CVS repository that I need to check code into. However, the server is outside my control and is often down.

So, is there a way to set up some sort of local CVS server/proxy such that I can check my code into the local CVS server regularly and have the local CVS server batch commit the changes to the online CVS repo periodically?

The local repository could possibly run some other SCM system, if that was necessary to prevent conflict with CVS. Online commits could possibly be done manually, or via cron. I'm open to suggestions.

I guess that my main concern would be the problems faced in trying to set up some sort of repository 'hierarchy'.

PS: I'm running Linux all along the 'hierarchy'.

Edit: Found a similar item here.

答:
I'd recommend running git locally while continuing to use your CVS server when you have a connection to it.  Here's a nicely-written article that explains how:

http://www.kernel.org/pub/software/scm/git/docs/v1.4.4.4/cvs-migration.html

OwnerDisplayName: sybreon

Title: Any way to do a local CVS proxy/server?

LastEditorDisplayName: sybreon

OwnerDisplayName: Adam Alexander


问:
CIM in an MVC3 app - how to instantiate ServiceSoap?
I'm integrating CIM into an MVC3 app.  I've added a service reference using the development url and coded the following:

```<code>public long x()
{
    var u = this.User.Identity as IClaimsIdentity;
    var id = u.Claims.First(x => x.ClaimType == ClaimTypes.NameIdentifier);

    AuthorizeNet.CustomerProfileType cust = new AuthorizeNet.CustomerProfileType();
    cust.merchantCustomerId = id.Value;

    AuthorizeNet.MerchantAuthenticationType merch = new AuthorizeNet.MerchantAuthenticationType();
    merch.name = "8aFRk4663XMd";
    merch.transactionKey = "4MS675e62fQEdUXN";
    AuthorizeNet.ServiceSoap svc = new AuthorizeNet.ServiceSoap();
    AuthorizeNet.CreateCustomerProfileResponseType response = svc.CreateCustomerProfile(
        merch, cust, AuthorizeNet.ValidationModeEnum.none
    );
    return response.customerProfileId;
}
</code>```

but, of course, it doesn't work because one cannot instantiate an interface like that (.ServiceSoap is an interface).  The sample code makes a reference to a .Service - but that doesn't exist AFAICT.

so how is this supposed to work?

TIA - e!

p.s. I did find an old posting with precisely my problem, but alas, no solution

答:
well... at least for now the answer seems to be: don't generate a Service Reference but a Web Reference (you can do it by clicking on the Advanced button of the Service Reference dialogue).

so eeky.

Body:
I'm integrating CIM into an MVC3 app.  I've added a service reference using the development url and coded the following:

public long x()
{
    var u = this.User.Identity as IClaimsIdentity;
    var id = u.Claims.First(x => x.ClaimType == ClaimTypes.NameIdentifier);

    AuthorizeNet.CustomerProfileType cust = new AuthorizeNet.CustomerProfileType();
    cust.merchantCustomerId = id.Value;

    AuthorizeNet.MerchantAuthenticationType merch = new AuthorizeNet.MerchantAuthenticationType();
    merch.name = "8aFRk4663XMd";
    merch.transactionKey = "4MS675e62fQEdUXN";
    AuthorizeNet.ServiceSoap svc = new AuthorizeNet.ServiceSoap();
    AuthorizeNet.CreateCustomerProfileResponseType response = svc.CreateCustomerProfile(
        merch, cust, AuthorizeNet.ValidationModeEnum.none
    );
    return response.customerProfileId;
}

but, of course, it doesn't work because one cannot instantiate an interface like that (.ServiceSoap is an interface).  The sample code makes a reference to a .Service - but that doesn't exist AFAICT.

so how is this supposed to work?

TIA - e!

p.s. I did find an old posting with precisely my problem, but alas, no solution


问:
Importing a long list of constants to a Python file
In Python, is there an analogue of the C preprocessor statement such as?:

#define MY_CONSTANT 50

Also, I have a large list of constants I'd like to import to several classes. Is there an analogue of declaring the constants as a long sequence of statements like the above in a .py file and importing it to another .py file?

Edit.

The file Constants.py reads:

```<code>#!/usr/bin/env python
# encoding: utf-8
"""
Constants.py
"""

MY_CONSTANT_ONE = 50
MY_CONSTANT_TWO = 51
</code>```

And myExample.py reads:

```<code>#!/usr/bin/env python
# encoding: utf-8
"""
myExample.py
"""

import sys
import os

import Constants

class myExample:
    def __init__(self):
        self.someValueOne = Constants.MY_CONSTANT_ONE + 1
        self.someValueTwo = Constants.MY_CONSTANT_TWO + 1

if __name__ == '__main__':
    x = MyClass()
</code>```

Edit.

From the compiler,

NameError: "global name
  'MY_CONSTANT_ONE' is not defined"

function init in myExample at line
  13 self.someValueOne =
  Constants.MY_CONSTANT_ONE + 1 copy
  output Program exited with code #1
  after 0.06 seconds.

答:
In more recent editions, it seems a bit pickier.

the mode in the top answer

Main.py

```<code>import constants
print(token)
</code>```

constants.py
enter code heretoken = "12345"

failed.
Instead, I had to import individual variable from constants.

Main.py

```<code>from constants import token
print(token)
</code>```

Body:
In Python, is there an analogue of the C preprocessor statement such as?:

#define MY_CONSTANT 50

Also, I have a large list of constants I'd like to import to several classes. Is there an analogue of declaring the constants as a long sequence of statements like the above in a .py file and importing it to another .py file?

Edit.

The file Constants.py reads:

#!/usr/bin/env python
# encoding: utf-8
"""
Constants.py
"""

MY_CONSTANT_ONE = 50
MY_CONSTANT_TWO = 51

And myExample.py reads:

#!/usr/bin/env python
# encoding: utf-8
"""
myExample.py
"""

import sys
import os

import Constants

class myExample:
    def __init__(self):
        self.someValueOne = Constants.MY_CONSTANT_ONE + 1
        self.someValueTwo = Constants.MY_CONSTANT_TWO + 1

if __name__ == '__main__':
    x = MyClass()

Edit.

From the compiler,

NameError: "global name
  'MY_CONSTANT_ONE' is not defined"

function init in myExample at line
  13 self.someValueOne =
  Constants.MY_CONSTANT_ONE + 1 copy
  output Program exited with code #1
  after 0.06 seconds.

Body:
In more recent editions, it seems a bit pickier.

the mode in the top answer

Main.py

import constants
print(token)

constants.py
enter code heretoken = "12345"

failed.
Instead, I had to import individual variable from constants.

Main.py

from constants import token
print(token)


问:
How can I compile and run C/C++ code in a Unix console or Mac terminal?
How can I compile/run C or C++ code in a Unix console or a Mac terminal?</p>

答:
I am on a new MacBook Pro with the Apple M1 Pro chip. I have my Xcode installed - both IDE and command line tools. This is how it worked for me:

g++ one.cpp -o one

./one
```


问:
Problems with Special Characters between Angular http post and PHP (and .net)
Email form on my site needs to be able to send an email via a server running with .net.

The code has worked beautifully, but the email server has been moved so that clients cannot directly access it.  My primary server can talk to it and I am converting all of my client -> email server code to client - > PHP Server -> Email Server. (I have more than email running through it, and all of that is working now).  I am struggling with special characters - my sample email:

Sample Email:

More special characters and multi-line

` ~ ! @ # $ % ^ & * ( ) _ - + =

{ [ } ] \ | ; : ' " < , > . ? /

and finally a last line.

This Works (AngularJS):

```<code>$http({
                method:'POST',
                //url:  "assets/api/SendMessage.php",
                url:'https://myemailserver.com/mygroup/SendMessage',
                headers: {
                    'Content-Type': "application/json"
                },
                data:{
                    "From": dataObj['firstname-email'] + ' ' + dataObj['lastname-email'],
                    "SenderEmail": dataObj['senderemail-email'],
                    "Message": dataObj['body-email'],
                    "Subject": dataObj['subject-email']
                }
            }).then(function successCallback(response){
                console.log('Email Response, success!',response);

                $scope.emailSuccess = true;
            }, function errorCallBack(response){
                console.log('Email Error:',response);
                $scope.emailFail = true;
            })
</code>```

But when I send it to my PHP Server (same code, different URL), which then uses curl to send the message, I get a failed message when there are any special characters including blank lines from the editor. (except , and .)

If the body of the message is a single line, then it works fine.

My PHP:

```<code> $url = 'https://myemailserver.com/mygroup/SendMessage';
$params = json_decode(file_get_contents('php://input'),true);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = array(
    "Content-Type: application/json",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

$data = '{"From":"' . $params["From"] . '","SenderEmail":"' . $params["SenderEmail"] . '","Message":"' .$params["Message"] . '","Subject":"' . $params["Subject"] .'"}';

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);
curl_close($curl);
echo($resp);
</code>```

I have tried several different options from the web:

Remove all special characters from a string

https://www.php.net/manual/en/function.addslashes.php

https://www.w3schools.com/php/func_string_htmlspecialchars.asp

and either way I handle it, I get a failed response from the Email server.

I need to maintain special characters (including line breaks).  Can anyone help me out with the how?
Thanks

答:
It's almost certainly the way you're compiling your JSON string. Those things are very persnickety and if at all possible you should not create them manually. Rather create the object (or array) as intended and use the built-in tools to stringify.

Instead of $data = '{"From":"' . $params["From"] . '","SenderEmail":"' . $params["SenderEmail"] . '","Message":"' .$params["Message"] . '","Subject":"' . $params["Subject"] .'"}';

Try this:

```<code>$data = array(
   "From" => $params["From"],
   "SenderEmail" => $params["SenderEmail"],
   "Message" => $params["Message"],
   "Subject" => $params["Subject"]);

$data = json_encode($data) ;
</code>```

That is not only easier to read and maintain but automatically takes care of a host of issues that could be encountered in trying to escape content for transit.

Body:
Email form on my site needs to be able to send an email via a server running with .net.

The code has worked beautifully, but the email server has been moved so that clients cannot directly access it.  My primary server can talk to it and I am converting all of my client -> email server code to client - > PHP Server -> Email Server. (I have more than email running through it, and all of that is working now).  I am struggling with special characters - my sample email:

Sample Email:

More special characters and multi-line

` ~ ! @ # $ % ^ & * ( ) _ - + =

{ [ } ] \ | ; : ' " < , > . ? /

and finally a last line.

This Works (AngularJS):

$http({
                method:'POST',
                //url:  "assets/api/SendMessage.php",
                url:'https://myemailserver.com/mygroup/SendMessage',
                headers: {
                    'Content-Type': "application/json"
                },
                data:{
                    "From": dataObj['firstname-email'] + ' ' + dataObj['lastname-email'],
                    "SenderEmail": dataObj['senderemail-email'],
                    "Message": dataObj['body-email'],
                    "Subject": dataObj['subject-email']
                }
            }).then(function successCallback(response){
                console.log('Email Response, success!',response);

                $scope.emailSuccess = true;
            }, function errorCallBack(response){
                console.log('Email Error:',response);
                $scope.emailFail = true;
            })

But when I send it to my PHP Server (same code, different URL), which then uses curl to send the message, I get a failed message when there are any special characters including blank lines from the editor. (except , and .)

If the body of the message is a single line, then it works fine.

My PHP:

 $url = 'https://myemailserver.com/mygroup/SendMessage';
$params = json_decode(file_get_contents('php://input'),true);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = array(
    "Content-Type: application/json",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

$data = '{"From":"' . $params["From"] . '","SenderEmail":"' . $params["SenderEmail"] . '","Message":"' .$params["Message"] . '","Subject":"' . $params["Subject"] .'"}';

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);
curl_close($curl);
echo($resp);

I have tried several different options from the web:

Remove all special characters from a string

https://www.php.net/manual/en/function.addslashes.php

https://www.w3schools.com/php/func_string_htmlspecialchars.asp

and either way I handle it, I get a failed response from the Email server.

I need to maintain special characters (including line breaks).  Can anyone help me out with the how?
Thanks

Body:
It's almost certainly the way you're compiling your JSON string. Those things are very persnickety and if at all possible you should not create them manually. Rather create the object (or array) as intended and use the built-in tools to stringify.

Instead of $data = '{"From":"' . $params["From"] . '","SenderEmail":"' . $params["SenderEmail"] . '","Message":"' .$params["Message"] . '","Subject":"' . $params["Subject"] .'"}';

Try this:

$data = array(
   "From" => $params["From"],
   "SenderEmail" => $params["SenderEmail"],
   "Message" => $params["Message"],
   "Subject" => $params["Subject"]);

$data = json_encode($data) ;

That is not only easier to read and maintain but automatically takes care of a host of issues that could be encountered in trying to escape content for transit.


答:
I was able to get it to work with

```<code>search = driver.find_element_by_class_name("ValidatedSearch")
search.send_keys("Hi My Name is Slicka Slicka Slim Shady")
</code>```

I used one class. I would say Selenium iirc only requires a single class. Also Im not primarily a webdesigner but these frameworks that are all over today are pretty much add the additionals are annoying. When I create Selenium scripts I use xpaths more and more more. You may want to look into that

Title: Error when trying to find an element using SELENIUM

Body:
Hopefully someone can help me out here.

My goal is to successfully connect to this website using Python (Selenium + Chromedriver) and successfully search for an address in the search bar. Im struggling to manage to find the actual search bar itself using Selenium. The HTML code doesn't have an ID or NAME to distinguish it by, all it has is a class and when i search for the class, i get an error saying it cannot be found.

Hopefully this is an easy fix and im just being silly. Thanks a lot.

P.S First post - please drop some hints on what to change next time :)

CODE

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)

driver.get("https://creeper.banano.cc/")
search = driver.find_element_by_class_name("ValidatedSearch form-control form-control-lg ")

ERROR CODE

NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":".ValidatedSearch form-control form-control-lg "}

Python Code + HTML of Website

Body:
I was able to get it to work with

search = driver.find_element_by_class_name("ValidatedSearch")
search.send_keys("Hi My Name is Slicka Slicka Slim Shady")

I used one class. I would say Selenium iirc only requires a single class. Also Im not primarily a webdesigner but these frameworks that are all over today are pretty much add the additionals are annoying. When I create Selenium scripts I use xpaths more and more more. You may want to look into that


问:
How to transform text categories into ones and zeros vector in Python for classification?
I'm preparing data for multilabel classification and I want to transform text categories into zeros/ones vector.

Example input (dataframe):

```<code>['a']
['b']
['e', 'd']
['a', 'g', 'x']
</code>```

etc.
example output:

```<code>[1 0 0 0 0 0 0 ... 0]
[0 1 0 0 0 0 0 ... 0]
[0 0 0 1 1 0 0 ... 0]
[1 0 0 0 0 0 1 ... 0]
</code>```

etc.

There's 200 categories.
I haven't found how to do it when you have to deal with multilabel classification.
Any help would be appreciated.

答:
Try using a combination of pd.get_dummies (designed for one-hot-encoding) and explode + groupby(level=0):`

```<code>out = pd.get_dummies(df['a'].explode()).groupby(level=0).sum()
</code>```

Output:

```<code>>>> out
   a  b  d  e  g  x
0  1  0  0  0  0  0
1  0  1  0  0  0  0
2  0  0  1  1  0  0
3  1  0  0  0  1  1
</code>```

Or a little shorter:

```<code>out = df['a'].str.join(',').str.get_dummies(',')
</code>```

Output:

```<code>>>> out
   a  b  d  e  g  x
0  1  0  0  0  0  0
1  0  1  0  0  0  0
2  0  0  1  1  0  0
3  1  0  0  0  1  1
</code>```

Then...

```<code>df['class'] = out.to_numpy().tolist()
</code>```

Output:

```<code>>>> df
           a               class
0        [a]  [1, 0, 0, 0, 0, 0]
1        [b]  [0, 1, 0, 0, 0, 0]
2     [e, d]  [0, 0, 1, 1, 0, 0]
3  [a, g, x]  [1, 0, 0, 0, 1, 1]
</code>```

Body:
I'm preparing data for multilabel classification and I want to transform text categories into zeros/ones vector.

Example input (dataframe):

['a']
['b']
['e', 'd']
['a', 'g', 'x']

etc.
example output:

[1 0 0 0 0 0 0 ... 0]
[0 1 0 0 0 0 0 ... 0]
[0 0 0 1 1 0 0 ... 0]
[1 0 0 0 0 0 1 ... 0]

etc.

There's 200 categories.
I haven't found how to do it when you have to deal with multilabel classification.
Any help would be appreciated.

Body:
Try using a combination of pd.get_dummies (designed for one-hot-encoding) and explode + groupby(level=0):`

out = pd.get_dummies(df['a'].explode()).groupby(level=0).sum()

Output:

>>> out
   a  b  d  e  g  x
0  1  0  0  0  0  0
1  0  1  0  0  0  0
2  0  0  1  1  0  0
3  1  0  0  0  1  1

Or a little shorter:

out = df['a'].str.join(',').str.get_dummies(',')

Output:

>>> out
   a  b  d  e  g  x
0  1  0  0  0  0  0
1  0  1  0  0  0  0
2  0  0  1  1  0  0
3  1  0  0  0  1  1

Then...

df['class'] = out.to_numpy().tolist()

Output:

>>> df
           a               class
0        [a]  [1, 0, 0, 0, 0, 0]
1        [b]  [0, 1, 0, 0, 0, 0]
2     [e, d]  [0, 0, 1, 1, 0, 0]
3  [a, g, x]  [1, 0, 0, 0, 1, 1]


问:
How to use item self as parameter in databind inner method
```<code>        <ListView
            x:Name="List"
            ItemsSource="{x:Bind itemlist}"
            SelectionMode="None">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="x:String">
                    <RelativePanel HorizontalAlignment="Stretch">
                        <TextBlock
                            x:Name="str"
                            HorizontalAlignment="Left"
                            RelativePanel.AlignLeftWithPanel="True"
                            Text="{x:Bind /* the method i want to use here */ }" />
                    </RelativePanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</code>```

To use method in DataTemplate,it seems that the method requires at least a parameter that was the property of databind item .
However, is there any way to use the method that use the item self rather than its property to work?(not ValueConverter)

答: Text="{Binding}" or Text="{Binding.}"

Body:
        <ListView
            x:Name="List"
            ItemsSource="{x:Bind itemlist}"
            SelectionMode="None">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="x:String">
                    <RelativePanel HorizontalAlignment="Stretch">
                        <TextBlock
                            x:Name="str"
                            HorizontalAlignment="Left"
                            RelativePanel.AlignLeftWithPanel="True"
                            Text="{x:Bind /* the method i want to use here */ }" />
                    </RelativePanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

To use method in DataTemplate,it seems that the method requires at least a parameter that was the property of databind item .
However, is there any way to use the method that use the item self rather than its property to work?(not ValueConverter)

Body: Text="{Binding}" or Text="{Binding.}"


问:
Can Netbeans configured to fix imports, using *, to decrease code lines
I know that with Ctrl + Shift + I, one can fix imports easily in Netbeans.

Can Netbeans configured in a way that

rather than importing com.google.gwt.user.client.ui.HTML,

it will import com.google.gwt.user.client.ui.*.

Hence, my code lines will be decreased.

答:
Navigate to Tools > Options > Editor > Formatting, then select Language: Java and Category: Imports. Finally, select the option Use Package Imports, and then click Apply:

Be aware that this configuration change will affect all of your projects; I don't think it can be set at the project level. Also, note that while the approach you are choosing certainly may reduce the number of lines in your source, it is more usual to have a separate import for each class.


问:
EditText does not trigger changes when back is pressed
In an application with shopping cart, I give the option to change the amount of items via an EditText which allows only numerical input.

Everything works fine, except when the user changes the field and then presses the back key to hide the soft keyboard. In this case, the field shows the changed value, but I don't know how I can detect this change and react on it. Waiting for a switch to another activity is not an option.

When the user confirms with "done" button, I can handle this with a "OnEditorActionListener". But what about the back key?

update:

As it turned out, neither onKeyDown / onBackPressed nor OnKeyListener on the edit field do trigger when closing the soft keyboard with back key.

答:
I had the same problem in an application which i wrote some time ago. It is discontiuned now but that's not your question xD.

In fact there is no option to track such a operation, but i've found a great (more or less) solution to add such a functionality. It's quite simple in theory but it's a "hack" too i think.

So what you will need is a custom linear layout which contains your application, or a special region. After that you have to add it a listener. And this will work only in portrait mode.

So here to the code: (i'm sorry but i can't remember the source)

The custom layout:

LinearLayoutThatDetactsSoftwarekeyboard.java (that's the original name of the layout xD)

```<code>package com.tundem.people.Layout;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.LinearLayout;

/*
 * LinearLayoutThatDetectsSoftKeyboard - a variant of LinearLayout that can detect when
 * the soft keyboard is shown and hidden (something Android can't tell you, weirdly).
 */

public class LinearLayoutThatDetectSoftkeyboard extends LinearLayout {

    public LinearLayoutThatDetectSoftkeyboard(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public interface Listener {
        public void onSoftKeyboardShown(boolean isShowing);
    }

    private Listener listener;

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int height = MeasureSpec.getSize(heightMeasureSpec);
        Activity activity = (Activity) getContext();
        Rect rect = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        int statusBarHeight = rect.top;
        int screenHeight = activity.getWindowManager().getDefaultDisplay().getHeight();
        int diff = (screenHeight - statusBarHeight) - height;
        if (listener != null) {
            listener.onSoftKeyboardShown(diff > 128); // assume all soft
                                                        // keyboards are at
                                                        // least 128 pixels high
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

}
</code>```

And how you add the listener:

```<code>final LinearLayoutThatDetectSoftkeyboard lltodetectsoftkeyboard = (LinearLayoutThatDetectSoftkeyboard) findViewById(R.id.LinearLayout_SoftKeyboard);
    lltodetectsoftkeyboard.setListener(new Listener() {

        public void onSoftKeyboardShown(boolean isShowing) {
            if (actMode == MODE_SMS && isShowing) {
                findViewById(R.id.LinearLayout_bottomnavigationbar).setVisibility(View.GONE);
            } else {
                findViewById(R.id.LinearLayout_bottomnavigationbar).setVisibility(View.VISIBLE);
            }
        }
    });
</code>```

The LinearLayout adds a Listener which will be called each time the layoutheight changes by at least 128 pixels. It's a trick and it won't work with keyboards that are smaller than 128 pixels (but i think each keyboard has such a height)
If the LayoutHeight has Changed you will get notified if it's showing now or not.

I hope my answer was useful. Perhaps you find the real source here on StackOverFlow again. I won't steal someones genius so. Credits goes to the unknown person ;)

Body:
I had the same problem in an application which i wrote some time ago. It is discontiuned now but that's not your question xD.

In fact there is no option to track such a operation, but i've found a great (more or less) solution to add such a functionality. It's quite simple in theory but it's a "hack" too i think.

So what you will need is a custom linear layout which contains your application, or a special region. After that you have to add it a listener. And this will work only in portrait mode.

So here to the code: (i'm sorry but i can't remember the source)

The custom layout:

LinearLayoutThatDetactsSoftwarekeyboard.java (that's the original name of the layout xD)

package com.tundem.people.Layout;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.LinearLayout;

/*
 * LinearLayoutThatDetectsSoftKeyboard - a variant of LinearLayout that can detect when
 * the soft keyboard is shown and hidden (something Android can't tell you, weirdly).
 */

public class LinearLayoutThatDetectSoftkeyboard extends LinearLayout {

    public LinearLayoutThatDetectSoftkeyboard(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public interface Listener {
        public void onSoftKeyboardShown(boolean isShowing);
    }

    private Listener listener;

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int height = MeasureSpec.getSize(heightMeasureSpec);
        Activity activity = (Activity) getContext();
        Rect rect = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        int statusBarHeight = rect.top;
        int screenHeight = activity.getWindowManager().getDefaultDisplay().getHeight();
        int diff = (screenHeight - statusBarHeight) - height;
        if (listener != null) {
            listener.onSoftKeyboardShown(diff > 128); // assume all soft
                                                        // keyboards are at
                                                        // least 128 pixels high
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

}

And how you add the listener:

final LinearLayoutThatDetectSoftkeyboard lltodetectsoftkeyboard = (LinearLayoutThatDetectSoftkeyboard) findViewById(R.id.LinearLayout_SoftKeyboard);
    lltodetectsoftkeyboard.setListener(new Listener() {

        public void onSoftKeyboardShown(boolean isShowing) {
            if (actMode == MODE_SMS && isShowing) {
                findViewById(R.id.LinearLayout_bottomnavigationbar).setVisibility(View.GONE);
            } else {
                findViewById(R.id.LinearLayout_bottomnavigationbar).setVisibility(View.VISIBLE);
            }
        }
    });

The LinearLayout adds a Listener which will be called each time the layoutheight changes by at least 128 pixels. It's a trick and it won't work with keyboards that are smaller than 128 pixels (but i think each keyboard has such a height)
If the LayoutHeight has Changed you will get notified if it's showing now or not.

I hope my answer was useful. Perhaps you find the real source here on StackOverFlow again. I won't steal someones genius so. Credits goes to the unknown person ;)


问:
Use Arrays and for-loops in BICEP
I am passing an array of services into the BICEP template

```<code>param objectarray array =[]
</code>```

I also have an array variable that contains a subset of the service names that I passed in

```<code>var objectarray =
[
'Abc'
'DEF'
'GHI'
]
</code>```

My intention is to see if the service names being passed in are in the subset and if so, then I need to set another variable accordingly. What's the best way to do that? I've used conditional loops and if statements in BICEP before but not together.

```<code>var isInSubset =
</code>```

Additional Info

I did try this

```<code>var apis_with_listener = contains(objectarray, objectarray)
</code>```

but the resource that I am creating is a backend policy and i am using a for loop in the resource creation and setting the value based on what apis_with_listener is set to. Sorry, this sounds confusing.

```<code>value: '<\r\n<policies>\r\n  <inbound>\r\n    <base />\r\n    <set-backend-service backend-id="${APIM_Name}" sf-resolve-condition="@(context.LastError?.Reason == "BackendConnectionFailure")" sf-service-instance-name="@("fabric:/${Application_Name}${Customer_AreaName}/${api}")" **sf-listener-name="${api}Service**" />\r\n  </inbound>\r\n  <backend>\r\n    <base />\r\n  </backend>\r\n  <outbound>\r\n    <base />\r\n  </outbound>\r\n  <on-error>\r\n    <base />\r\n  </on-error>\r\n</policies>'
</code>```

so the sf-listener-name needs to be set ONLY if the service is one of the ones in the subset. Not sure how to do a for loop and an if properly

```<code>resource BackendPolicy 'Microsoft.ApiManagement/service/apis/policies@2021-04-01-preview'= [for (api,i) in API_Names : {
  name: 'policy'
  parent:API_Service[i]
  properties: {
    value: '<\r\n<policies>\r\n  <inbound>\r\n    <base />\r\n    <set-backend-service backend-id="${APIM_Name}" sf-resolve-condition="@(context.LastError?.Reason == "BackendConnectionFailure")" sf-service-instance-name="@("fabric:/${Application_Name}${Customer_AreaName}/${api}")" sf-listener-name="${api}Service" />\r\n  </inbound>\r\n  <backend>\r\n    <base />\r\n  </backend>\r\n  <outbound>\r\n    <base />\r\n  </outbound>\r\n  <on-error>\r\n    <base />\r\n  </on-error>\r\n</policies>'
    format: 'xml'
  }
}]
</code>```

答:
First of all, Bicep doesn't allow loops within loops, but you don't need that here as you're just looking for whether an array contains the string value you're matching against. Let's start my saying that all the APIM policy setting is going to happen in its own module, 'sf-apimPolicy.bicep', for clarity.

You indicated that you want to pass in an array of your Service Fabric service names and see if any of them are in a subset, presumably one kept in your intended module, so we'll start with that.

```<code>// sf-apimPolicy.bicep

@description('Your APIM resource name')
param APIM_Name string

@description('The prefix of your SF application name')
param Application_Name string

@description('Used to route to the appropriate SF application per customer')
param Customer_AreaName string

@description('Contains each of your Service names being passed in')
param API_Names array //Presumably this is the 'objectarray' you mention in the question

@description('The array of service names that set a constraint on what can be set in this policy')
param ApiNameConstraints array

resource ApimService 'Microsoft.ApiManagement/service/apis@2021-04-01-preview' existing = {
  name: '${APIM_Name}/${ApiServiceName}'
}

//And finally you're looking to set the policy itself if ApiNameConstraints contains your api value
resource BackendPolicy 'Microsoft.ApiManagement/service/apis/policies@2021-04-01-preview' = [for (api, i) in API_Names: if (contains(ApiNameConstraints, api)): {
  name: 'policy'
  parent: ApimService
  properties: {
    value: '''
<policies>
  <inbound>
    <base> // As an aside, changed this from your original value as it used a content-less close tag
      <set-backend-service backend-id="${APIM_Name}" sf-resolve-condition="@(context.LastError?.Reason == "BackendConnectionFailure")" sf-service-instance-name="@("fabric:/${Application_Name}${Customer_AreaName}/${api}")" **sf-listener-name="${api}Service**" />
    </base> //Also changed this as it didn't use a close tag
  </inbound>
  <backend>
    <base />
  </backend>
  <outbound>
    <base />
  </outbound>
  <on-error>
    <base />
  </on-error>
</policies>
'''
    format: 'xml'
  }
}]
</code>```

Then merely call this module and populate the various parameters to call it and the loop will be handled internally.

Title: Use Arrays and for-loops in BICEP

Body:
I am passing an array of services into the BICEP template

param objectarray array =[]

I also have an array variable that contains a subset of the service names that I passed in

var objectarray =
[
'Abc'
'DEF'
'GHI'
]

My intention is to see if the service names being passed in are in the subset and if so, then I need to set another variable accordingly. What's the best way to do that? I've used conditional loops and if statements in BICEP before but not together.

var isInSubset =

Additional Info

I did try this

var apis_with_listener = contains(objectarray, objectarray)

but the resource that I am creating is a backend policy and i am using a for loop in the resource creation and setting the value based on what apis_with_listener is set to. Sorry, this sounds confusing.

value: '<\r\n<policies>\r\n  <inbound>\r\n    <base />\r\n    <set-backend-service backend-id="${APIM_Name}" sf-resolve-condition="@(context.LastError?.Reason == "BackendConnectionFailure")" sf-service-instance-name="@("fabric:/${Application_Name}${Customer_AreaName}/${api}")" **sf-listener-name="${api}Service**" />\r\n  </inbound>\r\n  <backend>\r\n    <base />\r\n  </backend>\r\n  <outbound>\r\n    <base />\r\n  </outbound>\r\n  <on-error>\r\n    <base />\r\n  </on-error>\r\n</policies>'

so the sf-listener-name needs to be set ONLY if the service is one of the ones in the subset. Not sure how to do a for loop and an if properly

resource BackendPolicy 'Microsoft.ApiManagement/service/apis/policies@2021-04-01-preview'= [for (api,i) in API_Names : {
  name: 'policy'
  parent:API_Service[i]
  properties: {
    value: '<\r\n<policies>\r\n  <inbound>\r\n    <base />\r\n    <set-backend-service backend-id="${APIM_Name}" sf-resolve-condition="@(context.LastError?.Reason == "BackendConnectionFailure")" sf-service-instance-name="@("fabric:/${Application_Name}${Customer_AreaName}/${api}")" sf-listener-name="${api}Service" />\r\n  </inbound>\r\n  <backend>\r\n    <base />\r\n  </backend>\r\n  <outbound>\r\n    <base />\r\n  </outbound>\r\n  <on-error>\r\n    <base />\r\n  </on-error>\r\n</policies>'
    format: 'xml'
  }
}]

Body:
First of all, Bicep doesn't allow loops within loops, but you don't need that here as you're just looking for whether an array contains the string value you're matching against. Let's start my saying that all the APIM policy setting is going to happen in its own module, 'sf-apimPolicy.bicep', for clarity.

You indicated that you want to pass in an array of your Service Fabric service names and see if any of them are in a subset, presumably one kept in your intended module, so we'll start with that.

// sf-apimPolicy.bicep

@description('Your APIM resource name')
param APIM_Name string

@description('The prefix of your SF application name')
param Application_Name string

@description('Used to route to the appropriate SF application per customer')
param Customer_AreaName string

@description('Contains each of your Service names being passed in')
param API_Names array //Presumably this is the 'objectarray' you mention in the question

@description('The array of service names that set a constraint on what can be set in this policy')
param ApiNameConstraints array

resource ApimService 'Microsoft.ApiManagement/service/apis@2021-04-01-preview' existing = {
  name: '${APIM_Name}/${ApiServiceName}'
}

//And finally you're looking to set the policy itself if ApiNameConstraints contains your api value
resource BackendPolicy 'Microsoft.ApiManagement/service/apis/policies@2021-04-01-preview' = [for (api, i) in API_Names: if (contains(ApiNameConstraints, api)): {
  name: 'policy'
  parent: ApimService
  properties: {
    value: '''
<policies>
  <inbound>
    <base> // As an aside, changed this from your original value as it used a content-less close tag
      <set-backend-service backend-id="${APIM_Name}" sf-resolve-condition="@(context.LastError?.Reason == &quot;BackendConnectionFailure&quot;)" sf-service-instance-name="@(&quot;fabric:/${Application_Name}${Customer_AreaName}/${api}&quot;)" **sf-listener-name="${api}Service**" />
    </base> //Also changed this as it didn't use a close tag
  </inbound>
  <backend>
    <base />
  </backend>
  <outbound>
    <base />
  </outbound>
  <on-error>
    <base />
  </on-error>
</policies>
'''
    format: 'xml'
  }
}]

Then merely call this module and populate the various parameters to call it and the loop will be handled internally.


问:
Using Keycloak with a FIPS-compliant JDK
I have the requirement to build a Docker image with Keycloak and a FIPS-compliant JDK (based on OpenJDK 8).

My company has an internal FIPS JDK distribution which works somewhat like this:

In a -Djava.endorsed.dirs directory, a security provider is installed, which dispatches all security calls to BouncyCastle. This security provider has dependencies, which I pull in via Maven: several BouncyCastle jars, but also other stuff like Jackson, Scala, Guava, the kitchen sink.

I'm doing mvn dependency:copy-dependencies to copy the BouncyCastle jars to a library folder, and I'm using the Maven Shade Plugin to build an UberJar with everything else, minus what's already present in Keycloak. To prevent conflicts, I apply package shading in this UberJar (package com.foo is moved to myteam.com.foo), except for the public entrypoint referenced by above security provider.

I have a little Java test class that verifies this setup works in FIPS-compatible mode, basically the test is that

```<code>MessageDigest.getInstance("SHA-256", "SUN").getProvider().getName()
</code>```

returns BCFIPS instead of SUN, and this works.

Now my problem is how to get this setup working on Keycloak, given that it runs on JBoss / WildFly, and has its completely own ideas about class loading.

I launch Keycloak with the -Djava.endorsed.dirs parameter in my JAVA_OPTS, which leaves the dependencies to BouncyCastle and the other libraries.

I have tried the following approaches

Approach 1:
Declare everything as a module. Inside /opt/jboss/keycloak/modules/system/layers/keycloak (or base, I tried both), declare an org/bouncycastle module with all bc jars and a com/mycompany module with the UberJar. Register both as global modules (KC currently runs on WildFly 18, so the global directories option isn't available yet)

Approach 2:
Place all jars in a directory and reference that using -Djava.ext.dirs in my JAVA_OPTS.

Each of these have led to the identical error message:

Caused by: java.lang.ClassNotFoundException:
  org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider from [Module
  "org.jboss.as.server" version 10.0.3.Final from local module loader
  @52a86356 (finder: local module finder @5ce81285 (roots:
  /opt/jboss/keycloak/modules, /opt/jboss/keycloak/modules/system/layers/keycloak, /opt/jboss/keycloak/modules/system/layers/base))]

Can anybody point me toward a solution?

答:
Sean, running into the exact same issue you did.

Getting NoSuchMethodError on keycloak startup from the server-dist distribution. My keycloak calls isInApprovedOnlyMode() from bc-fips upon startup, and since i dont have the library in my container, i get the NoSuchMethodError. I've included bc-fips,bctls-fips, and bcpkix-fips libraries from BouncyCastle, and now need to get them to work with WildFly/JBoss (never worked with these techs before).

I'm going to try adding these deps explicitly as you did.

Body:
I have the requirement to build a Docker image with Keycloak and a FIPS-compliant JDK (based on OpenJDK 8).

My company has an internal FIPS JDK distribution which works somewhat like this:

In a -Djava.endorsed.dirs directory, a security provider is installed, which dispatches all security calls to BouncyCastle. This security provider has dependencies, which I pull in via Maven: several BouncyCastle jars, but also other stuff like Jackson, Scala, Guava, the kitchen sink.

I'm doing mvn dependency:copy-dependencies to copy the BouncyCastle jars to a library folder, and I'm using the Maven Shade Plugin to build an UberJar with everything else, minus what's already present in Keycloak. To prevent conflicts, I apply package shading in this UberJar (package com.foo is moved to myteam.com.foo), except for the public entrypoint referenced by above security provider.

I have a little Java test class that verifies this setup works in FIPS-compatible mode, basically the test is that

MessageDigest.getInstance("SHA-256", "SUN").getProvider().getName()

returns BCFIPS instead of SUN, and this works.

Now my problem is how to get this setup working on Keycloak, given that it runs on JBoss / WildFly, and has its completely own ideas about class loading.

I launch Keycloak with the -Djava.endorsed.dirs parameter in my JAVA_OPTS, which leaves the dependencies to BouncyCastle and the other libraries.

I have tried the following approaches

Approach 1:
Declare everything as a module. Inside /opt/jboss/keycloak/modules/system/layers/keycloak (or base, I tried both), declare an org/bouncycastle module with all bc jars and a com/mycompany module with the UberJar. Register both as global modules (KC currently runs on WildFly 18, so the global directories option isn't available yet)

Approach 2:
Place all jars in a directory and reference that using -Djava.ext.dirs in my JAVA_OPTS.

Each of these have led to the identical error message:

Caused by: java.lang.ClassNotFoundException:
  org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider from [Module
  "org.jboss.as.server" version 10.0.3.Final from local module loader
  @52a86356 (finder: local module finder @5ce81285 (roots:
  /opt/jboss/keycloak/modules, /opt/jboss/keycloak/modules/system/layers/keycloak, /opt/jboss/keycloak/modules/system/layers/base))]

Can anybody point me toward a solution?


问:
how to deploy a create react app with express on heroku?
i have been trying for days now to deploy my beginner app on heroku with no success , i followed alot of guides and answers on how to do this but it didnt work , here is my code :

server

```<code>const dotenv = require('dotenv')
dotenv.config()
const express = require("express");
 //const PORT = 5000; got a binding error on heroku logs so i commented this
const app = express();
const path = require("path")
const fetch = require("node-fetch")
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
const cors = require ('cors') ;
app.use(cors());

if  (process.env.NODE_ENV === 'production')
    {app.use(express.static(path.resolve(__dirname, '../build')));
     app.get('*', (req, res) => {
     res.sendFile(path.resolve(__dirname, '../build', 'index.html'));
        }); }

app.listen(5000, () => {
 // console.log(`Server listening on ${PORT}`);
});

const url = "https://api.themoviedb.org/3/movie/"
const API_TMDB = process.env.API_TMDB

app.get('/api/moviesPopular' , async (req,res)=>{
  ---  // rest of code with similar get routes
</code>```

package.json  - server

```<code>{
  "name": "server",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "node index.js" ,
    "build": "cd .. && npm install && npm run build"
  },
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^14.3.2",
    "express": "^4.17.2",
    "node-fetch": "2",
    "nodemon": "^2.0.15"
  },
  "engines": {
    "node": "14.15.0"
  }
}
</code>```

app code

```<code>export const getPopular = () =>
  fetch(`/api/moviesPopular`)
    --- more functions like this
</code>```

the folder structure looks like this

```<code>root
├── server
│
├── src
└── public
</code>```

i created setupProxy.js in src folder

```<code>const proxy = require("http-proxy-middleware");

module.exports = app => {
  app.use(proxy("/api/*", { target: "http://localhost:5000/" }));
};
</code>```

package.json app

```<code>{
  "name": "movie",
  "version": "0.1.0",
  "private": true,

  "dependencies": {
    "@emotion/react": "^11.7.1",
    "@emotion/styled": "^11.6.0",
    "@mantine/core": "^3.6.2",
    "@mantine/hooks": "^3.6.2",
    "@mui/material": "^5.2.7",
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "baseui": "^10.7.1",
    "bootstrap": "5.1.3",
    "dotenv": "^10.0.0",
    "global": "^4.4.0",
    "gulp": "^4.0.2",
    "http-proxy-middleware": "^2.0.3",
    "react": "^17.0.2",
    "react-bootstrap": "^2.1.0",
    "react-dom": "^17.0.2",
    "react-icons": "^4.3.1",
    "react-router-dom": "^6.2.1",
    "react-scripts": "5.0.0",
    "react-slick": "^0.28.1",
    "semantic-ui-css": "^2.4.1",
    "semantic-ui-react": "^2.0.4",
    "styletron-engine-atomic": "^1.4.8",
    "styletron-react": "^6.0.2",
    "web-vitals": "^2.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

i get this from the logs in heroku dashboard

```<code>2022-02-09T00:49:14.963015+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=moviedbx.herokuapp.com request_id=74d2e5a4-b7f1-45fc-bd3d-13914adcbb55 fwd="197.48.32.48" dyno= connect= service= status=503 bytes= protocol=https
2022-02-09T00:49:15.378141+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=moviedbx.herokuapp.com request_id=487a1c6a-850d-4e05-a9ff-6a325c4fa731 fwd="197.48.32.48" dyno= connect= service= status=503 bytes= protocol=https
</code>```

the api key is in the (Config Vars) on heroku.

the app doesnt work locally after i removed ("proxy": "http://localhost:5000") from the app`s package.json

what can i do to deploy on heroku ? and after doing so the app would still works locally ?

答:
https://devcenter.heroku.com/articles/deploying-nodejs#specifying-a-start-script

The docs mention that the port is set to an environment variable. You're hardcoding your port.

Change you listen method to:

app.listen(process.env.PORT || 5000, () => {
  console.log(`Server listening on ${app.address().port}`);
});
```

See where that takes you.

Body:
i have been trying for days now to deploy my beginner app on heroku with no success , i followed alot of guides and answers on how to do this but it didnt work , here is my code :

server

const dotenv = require('dotenv')
dotenv.config()
const express = require("express");
 //const PORT = 5000; got a binding error on heroku logs so i commented this
const app = express();
const path = require("path")
const fetch = require("node-fetch")
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
const cors = require ('cors') ;
app.use(cors());

if  (process.env.NODE_ENV === 'production')
    {app.use(express.static(path.resolve(__dirname, '../build')));
     app.get('*', (req, res) => {
     res.sendFile(path.resolve(__dirname, '../build', 'index.html'));
        }); }

app.listen(5000, () => {
 // console.log(`Server listening on ${PORT}`);
});

const url = "https://api.themoviedb.org/3/movie/"
const API_TMDB = process.env.API_TMDB

app.get('/api/moviesPopular' , async (req,res)=>{
  ---  // rest of code with similar get routes

package.json  - server

{
  "name": "server",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "node index.js" ,
    "build": "cd .. && npm install && npm run build"
  },
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^14.3.2",
    "express": "^4.17.2",
    "node-fetch": "2",
    "nodemon": "^2.0.15"
  },
  "engines": {
    "node": "14.15.0"
  }
}

app code

export const getPopular = () =>
  fetch(`/api/moviesPopular`)
    --- more functions like this

the folder structure looks like this

root
├── server
│
├── src
└── public

i created setupProxy.js in src folder

const proxy = require("http-proxy-middleware");

module.exports = app => {
  app.use(proxy("/api/*", { target: "http://localhost:5000/" }));
};

package.json app

{
  "name": "movie",
  "version": "0.1.0",
  "private": true,

  "dependencies": {
    "@emotion/react": "^11.7.1",
    "@emotion/styled": "^11.6.0",
    "@mantine/core": "^3.6.2",
    "@mantine/hooks": "^3.6.2",
    "@mui/material": "^5.2.7",
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "baseui": "^10.7.1",
    "bootstrap": "5.1.3",
    "dotenv": "^10.0.0",
    "global": "^4.4.0",
    "gulp": "^4.0.2",
    "http-proxy-middleware": "^2.0.3",
    "react": "^17.0.2",
    "react-bootstrap": "^2.1.0",
    "react-dom": "^17.0.2",
    "react-icons": "^4.3.1",
    "react-router-dom": "^6.2.1",
    "react-scripts": "5.0.0",
    "react-slick": "^0.28.1",
    "semantic-ui-css": "^2.4.1",
    "semantic-ui-react": "^2.0.4",
    "styletron-engine-atomic": "^1.4.8",
    "styletron-react": "^6.0.2",
    "web-vitals": "^2.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

i get this from the logs in heroku dashboard

2022-02-09T00:49:14.963015+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=moviedbx.herokuapp.com request_id=74d2e5a4-b7f1-45fc-bd3d-13914adcbb55 fwd="197.48.32.48" dyno= connect= service= status=503 bytes= protocol=https
2022-02-09T00:49:15.378141+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=moviedbx.herokuapp.com request_id=487a1c6a-850d-4e05-a9ff-6a325c4fa731 fwd="197.48.32.48" dyno= connect= service= status=503 bytes= protocol=https

the api key is in the (Config Vars) on heroku.

the app doesnt work locally after i removed ("proxy": "http://localhost:5000") from the app`s package.json

what can i do to deploy on heroku ? and after doing so the app would still works locally ?

Body:
https://devcenter.heroku.com/articles/deploying-nodejs#specifying-a-start-script

The docs mention that the port is set to an environment variable. You're hardcoding your port.

Change you listen method to:

app.listen(process.env.PORT || 5000, () => {
  console.log(`Server listening on ${app.address().port}`);
});

See where that takes you.