问:
Display a loading bar before the entire page is loaded
I would like to display a loading bar before the entire page is loaded. For now, I'm just using a small delay:

```<code>$(document).ready(function(){
    $('#page').fadeIn(2000);
});
</code>```

The page already uses jQuery.

Note: I have tried this, but it didn't work for me: loading bar while the script runs

I also tried other solutions. In most cases, the page loads as usual, or the page won't load/display at all.

答:
Whenever you try to load any data in this window this gif will load.

HTML

Make a Div

```<code><div class="loader"></div>
</code>```

CSS

```<code>.loader {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background: url('https://lkp.dispendik.surabaya.go.id/assets/loading.gif') 50% 50% no-repeat rgb(249,249,249);
}
</code>```

jQuery

```<code>$(window).load(function() {
        $(".loader").fadeOut("slow");
});
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
</code>```

Body:
I would like to display a loading bar before the entire page is loaded. For now, I'm just using a small delay:

$(document).ready(function(){
    $('#page').fadeIn(2000);
});

The page already uses jQuery.

Note: I have tried this, but it didn't work for me: loading bar while the script runs

I also tried other solutions. In most cases, the page loads as usual, or the page won't load/display at all.

Body:
Whenever you try to load any data in this window this gif will load.

HTML

Make a Div

<div class="loader"></div>

CSS

.loader {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background: url('https://lkp.dispendik.surabaya.go.id/assets/loading.gif') 50% 50% no-repeat rgb(249,249,249);
}

jQuery

$(window).load(function() {
        $(".loader").fadeOut("slow");
});
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>


来源: stackexchange

问:
How to assign global variable into another file
I have file foo.py

PARAMS = None
def cals(x):
    return PARAMS + x
```

<p>I want to import <code>foo.py</code> into <code>bar.py</code> like below</p>

<pre class="lang-py prettyprint-override"><code>import foo
foo.PARAMS = 4

print(foo.cals(4))
</code>```

but in pycharm it show redeclared 'PARAMS' defined above without usage. what meaning of pycharm showed

答: when you import something, it runs through the file. I think it is saying that when you imported foo.py, the keyword PARAMS was not used. I would just ignore it, or if you have OCD you can change it and see if the warming goes away.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have file foo.py

PARAMS = None
def cals(x):
    return PARAMS + x

I want to import foo.py into bar.py like below

import foo
foo.PARAMS = 4

print(foo.cals(4))

but in pycharm it show redeclared 'PARAMS' defined above without usage. what meaning of pycharm showed


问:
How to read a file, and write it to a different file
I hope all is well. At this point, I plan on reading a file, and then writing it to another file. (The equivalent of cp in OCaml, before I go ahead and manipulate text.) Currently in my code, I am making using the extlib to read a file, and then output it. I am also using dune to build file as an executable file. My file looks something like the following:

```<code>(* example.ml file *)
let read_filename = "example_1.ts"
let filename = "example_2.ts"

let () =

  let text read_filename =
    let chan = open_in read_filename in
    Std.input_list chan

  let filename = filename in
  let text = text in
  Std.output_file ~filename ~text
  (* normal exit: all channels are flushed and closed *)
</code>```

When I build the file using dune build example.bc I receive the following error:

```<code>File "example.ml", line 11, characters 2-5:
Error: Syntax error
</code>```

I am trying to figure out what I am doing wrong, but to no avail. Any help would be more than appreciated. Thank you.

答:
When I have readed you code I remark these lines.

```<code>  let filename = filename in
  let text = text in
</code>```

Why have you writting this line ? (* You could delete it safely *)

And then I have found your syntax error was a line above you have forgotten a in

```<code>(* example.ml file *)
let read_filename = "example_1.ts"
let filename = "example_2.ts"

let () =
  let text read_filename =
    let chan = open_in read_filename in
    Std.input_list chan
  in
    Std.output_file ~filename ~text
  (* normal exit: all channels are flushed and closed *)
</code>```

The rule for each local definition you must have a in keyword
(* a local definition is a let inside a let expression *)

Body:
I hope all is well. At this point, I plan on reading a file, and then writing it to another file. (The equivalent of cp in OCaml, before I go ahead and manipulate text.) Currently in my code, I am making using the extlib to read a file, and then output it. I am also using dune to build file as an executable file. My file looks something like the following:

(* example.ml file *)
let read_filename = "example_1.ts"
let filename = "example_2.ts"

let () =

  let text read_filename =
    let chan = open_in read_filename in
    Std.input_list chan

  let filename = filename in
  let text = text in
  Std.output_file ~filename ~text
  (* normal exit: all channels are flushed and closed *)

When I build the file using dune build example.bc I receive the following error:

File "example.ml", line 11, characters 2-5:
Error: Syntax error

I am trying to figure out what I am doing wrong, but to no avail. Any help would be more than appreciated. Thank you.

Body:
When I have readed you code I remark these lines.

  let filename = filename in
  let text = text in

Why have you writting this line ? (* You could delete it safely *)

And then I have found your syntax error was a line above you have forgotten a in

(* example.ml file *)
let read_filename = "example_1.ts"
let filename = "example_2.ts"

let () =
  let text read_filename =
    let chan = open_in read_filename in
    Std.input_list chan
  in
    Std.output_file ~filename ~text
  (* normal exit: all channels are flushed and closed *)

The rule for each local definition you must have a in keyword
(* a local definition is a let inside a let expression *)


问:
Airflow not recognising zip file DAG built with pytest fixture
We are using Google Composer (a managed Airflow service) with airflow v1.10 and Python 3.6.8.
To deploy our DAGS, we are taking the Packaged DAG (https://airflow.apache.org/concepts.html?highlight=zip#packaged-dags) method.

All is well when the zip file is created from the cmd line like

```<code>zip -r dag_under_test.zip test_dag.py
</code>```

but when I try to do this from a pytest fixture, so I load in the DagBag and test the integrity of my DAG, airflow doesnt recognise this zip file at all. here is the code to my pytest fixture

```<code>@fixture
def setup(config):
    os.system("zip -r dag_under_test.zip test_zip.py")

def test_import_dags(setup):
    dagbag = DagBag(include_examples=False)
    noOfDags = len(dagbag.dags)
    dagbag.process_file("dag_under_test.zip")
    assert len(dagbag.dags) == noOfDags + 1, 'DAG import failures. Errors: {}'.format(dagbag.import_errors)
</code>```

I copied this zip file to the DAGs folder, but airflow isnt recognising it at all, no error messages.
But the zip file built with same command from cmdline is being loaded by airflow!! seems like I am missing something obvious here, cant figure out.

答:
So it turned out that where I am creating the zip file is important. As in this case I am creating the zip file from the test folder and archiving the files in src folders. Although the final zip file looks perfect for the naked eye, airflow is rejecting it.
I tried with adding '-j' to the zip command (to junk the directory names) and my test started working.

zip -r -j dag_under_test_metrics.zip ../src/metricsDAG.py

I had another bigger problem, i.e. to test the same scenario when there is a full folder structure in my DAG project. A dag file at the top level which references a lots of python modules with in the project. I couldnt get this working by the above trick, but came up with a workaround. I have created a small shell script, which does the zip part, like this..

```<code>SCRIPT_PATH=${0%/*/*}
cd $SCRIPT_PATH

zip -r -q test/dag_under_test.zip DagRunner.py
zip -r -q test/dag_under_test.zip tasks dag common resources
</code>```

This shell script is changing the currentdir to project home and archiving from there. I am invoking this shell from the pytest fixture like this

```<code>@fixture
def setup():
    os.system('rm {}'.format(DAG_UNDER_TEST))
    os.system('sh {}'.format(PACKAGE_SCRIPT))
    yield
    print("-------- clean up -----------")
    os.system('rm {}'.format(DAG_UNDER_TEST))
</code>```

This is perfectly working with my integration test.

```<code>def test_conversionDAG(setup):
    configuration.load_test_config()
    dagbag = DagBag(include_examples=False)
    noOfDags = len(dagbag.dags)
    dagbag.process_file(DAG_UNDER_TEST)
    assert len(dagbag.dags) == noOfDags + 1, 'DAG import failures. Errors: {}'.format(dagbag.import_errors)
    assert dagbag.get_dag("name of the dag")
</code>```

Body:
We are using Google Composer (a managed Airflow service) with airflow v1.10 and Python 3.6.8.
To deploy our DAGS, we are taking the Packaged DAG (https://airflow.apache.org/concepts.html?highlight=zip#packaged-dags) method.

All is well when the zip file is created from the cmd line like

zip -r dag_under_test.zip test_dag.py

but when I try to do this from a pytest fixture, so I load in the DagBag and test the integrity of my DAG, airflow doesnt recognise this zip file at all. here is the code to my pytest fixture

@fixture
def setup(config):
    os.system("zip -r dag_under_test.zip test_zip.py")

def test_import_dags(setup):
    dagbag = DagBag(include_examples=False)
    noOfDags = len(dagbag.dags)
    dagbag.process_file("dag_under_test.zip")
    assert len(dagbag.dags) == noOfDags + 1, 'DAG import failures. Errors: {}'.format(dagbag.import_errors)

I copied this zip file to the DAGs folder, but airflow isnt recognising it at all, no error messages.
But the zip file built with same command from cmdline is being loaded by airflow!! seems like I am missing something obvious here, cant figure out.

Body:
So it turned out that where I am creating the zip file is important. As in this case I am creating the zip file from the test folder and archiving the files in src folders. Although the final zip file looks perfect for the naked eye, airflow is rejecting it.
I tried with adding '-j' to the zip command (to junk the directory names) and my test started working.

zip -r -j dag_under_test_metrics.zip ../src/metricsDAG.py

I had another bigger problem, i.e. to test the same scenario when there is a full folder structure in my DAG project. A dag file at the top level which references a lots of python modules with in the project. I couldnt get this working by the above trick, but came up with a workaround. I have created a small shell script, which does the zip part, like this..

SCRIPT_PATH=${0%/*/*}
cd $SCRIPT_PATH

zip -r -q test/dag_under_test.zip DagRunner.py
zip -r -q test/dag_under_test.zip tasks dag common resources

This shell script is changing the currentdir to project home and archiving from there. I am invoking this shell from the pytest fixture like this

@fixture
def setup():
    os.system('rm {}'.format(DAG_UNDER_TEST))
    os.system('sh {}'.format(PACKAGE_SCRIPT))
    yield
    print("-------- clean up -----------")
    os.system('rm {}'.format(DAG_UNDER_TEST))

This is perfectly working with my integration test.

def test_conversionDAG(setup):
    configuration.load_test_config()
    dagbag = DagBag(include_examples=False)
    noOfDags = len(dagbag.dags)
    dagbag.process_file(DAG_UNDER_TEST)
    assert len(dagbag.dags) == noOfDags + 1, 'DAG import failures. Errors: {}'.format(dagbag.import_errors)
    assert dagbag.get_dag("name of the dag")


问:
ACI - Windows server 2019 - Can´t connect to internet
I have an Azure Container Instance created from the base image mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019. The container is running and i can connect to the web page via a public ip address.

The problem is that I cannot connect to the network from the container (for example, Invoke-WebRequest http://google.com)

If i run the following commands in container, everything is fine.

```<code>$nic = Get-NetAdapter
Set-DnsClientServerAddress -InterfaceIndex $nic.IfIndex -ServerAddresses ('8.8.8.8')
</code>```

Can you solve this problem?
Thank you!

答:
This is a known issue for the image mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019 in ACI. All windows 2019 images may have this issue.
This issue happens because the DNS server is not set properly.
The commands you ran sets the DNS server to 8.8.8.8. After that the container is able to resolve hostnames.

Current workaround is to run the same commands on the container startup or use the windows 2016 based images( tags 1607, ltsc2016 etc)

Body:
I have an Azure Container Instance created from the base image mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019. The container is running and i can connect to the web page via a public ip address.

The problem is that I cannot connect to the network from the container (for example, Invoke-WebRequest http://google.com)

If i run the following commands in container, everything is fine.

$nic = Get-NetAdapter
Set-DnsClientServerAddress -InterfaceIndex $nic.IfIndex -ServerAddresses ('8.8.8.8')

Can you solve this problem?
Thank you!


问:
multi-level html menu controlled by jquery
I'm facing an issue with a multi level menu. I need jQuery to show or hide the current selected submenu, and keep the others with no changes. I'm not very skillful with JQuery yet, so any help would be highly appreciated. I'm sharing here with you what I have. Thanks in advance!

I'd like to mention that I found an example on StackOverflow that is partially working. After some debugging I realized that the var mobileMenu.css returns undefined and that makes the code sometimes works.

var test1 = $('ul.hdrMenu li');

test1.on( 'click', function(e)
{
    var mobileMenuItem  = $(e.target).parent().find( '> ul.sub-menu' );

    if( **typeof mobileMenuItem.css('display') === "undefined"** )
    {
        mobileMenuItem  = $(e.target).parent().parent().find( '> ul.sub-menu' );
    }

    if( mobileMenuItem.css('display') == 'none' )
    {
        e.preventDefault();
        mobileMenuItem.slideDown();
        e.stopPropagation();
    }
    else if( mobileMenuItem.css('display') == 'block' )
    {
        e.preventDefault();
        mobileMenuItem.slideUp();
        e.stopPropagation();
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="hdrMenu">
  <li>Inicio</li>
  <li>Servicios
    <ul class="sub-menu">
      <li>L1</li>
      <li>L2
        <ul class="sub-menu">
          <li>L2-1</li>
          <li>L2-2</li>
        </ul>
      </li>
      <li>L3</li>
      <li>L4
        <ul class="sub-menu">
          <li>L4-1</li>
          <li>L4-4</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Acerca de
    <ul class="sub-menu">
      <li>Sub1</li>
      <li>Sub2</li>
      <li>Sub3</li>
      <li>Sub4</li>
    </ul>
  </li>
  <li>Contacto</li>
</ul></code>```

答:
The code work just fine I think you need just to remove the parent selector .hdrNav it must be like :

```<code>var test1 = $('ul.hdrMenu li');
</code>```

Or you can leave the selector as it's and add a parent div with the class hdrNav.

var test1 = $('ul.hdrMenu li');
test1.on('click', function(e) {
  var mobileMenu = $(e.target).parent().find('> ul.sub-menu');

  if (mobileMenu.css('display') == 'none') {
    e.preventDefault();
    mobileMenu.slideDown();
    e.stopPropagation();
  } else if (mobileMenu.css('display') == 'block') {
    e.preventDefault();
    mobileMenu.slideUp();
    e.stopPropagation();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="hdrMenu">
  <li>Inicio</li>
  <li>Servicios
    <ul class="sub-menu">
      <li>L1</li>
      <li>L2
        <ul class="sub-menu">
          <li>L2-1</li>
          <li>L2-2</li>
        </ul>
      </li>
      <li>L3</li>
      <li>L4
        <ul class="sub-menu">
          <li>L4-1</li>
          <li>L4-4</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Acerca de
    <ul class="sub-menu">
      <li>Sub1</li>
      <li>Sub2</li>
      <li>Sub3</li>
      <li>Sub4</li>
    </ul>
  </li>
  <li>Contacto</li>
</ul></code>```

Body:
I'm facing an issue with a multi level menu. I need jQuery to show or hide the current selected submenu, and keep the others with no changes. I'm not very skillful with JQuery yet, so any help would be highly appreciated. I'm sharing here with you what I have. Thanks in advance!

I'd like to mention that I found an example on StackOverflow that is partially working. After some debugging I realized that the var mobileMenu.css returns undefined and that makes the code sometimes works.

var test1 = $('ul.hdrMenu li');

test1.on( 'click', function(e)
{
    var mobileMenuItem  = $(e.target).parent().find( '> ul.sub-menu' );

    if( **typeof mobileMenuItem.css('display') === "undefined"** )
    {
        mobileMenuItem  = $(e.target).parent().parent().find( '> ul.sub-menu' );
    }

    if( mobileMenuItem.css('display') == 'none' )
    {
        e.preventDefault();
        mobileMenuItem.slideDown();
        e.stopPropagation();
    }
    else if( mobileMenuItem.css('display') == 'block' )
    {
        e.preventDefault();
        mobileMenuItem.slideUp();
        e.stopPropagation();
    }
});

Inicio

Servicios

L1

L2

L2-1

L2-2

L3

L4

L4-1

L4-4

Acerca de

Sub1

Sub2

Sub3

Sub4

Contacto

Body:
The code work just fine I think you need just to remove the parent selector .hdrNav it must be like :

var test1 = $('ul.hdrMenu li');

Or you can leave the selector as it's and add a parent div with the class hdrNav.

var test1 = $('ul.hdrMenu li');
test1.on('click', function(e) {
  var mobileMenu = $(e.target).parent().find('> ul.sub-menu');

  if (mobileMenu.css('display') == 'none') {
    e.preventDefault();
    mobileMenu.slideDown();
    e.stopPropagation();
  } else if (mobileMenu.css('display') == 'block') {
    e.preventDefault();
    mobileMenu.slideUp();
    e.stopPropagation();
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="hdrMenu">
  <li><a href="#">Inicio</a></li>
  <li><a href="#">Servicios</a>
    <ul class="sub-menu">
      <li><a href="#">L1</a></li>
      <li><a href="#">L2</a>
        <ul class="sub-menu">
          <li><a href="#">L2-1</a></li>
          <li><a href="#">L2-2</a></li>
        </ul>
      </li>
      <li><a href="#">L3</a></li>
      <li><a href="#">L4</a>
        <ul class="sub-menu">
          <li><a href="#">L4-1</a></li>
          <li><a href="#">L4-4</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li><a href="#">Acerca de</a>
    <ul class="sub-menu">
      <li><a href="#">Sub1</a></li>
      <li><a href="#">Sub2</a></li>
      <li><a href="#">Sub3</a></li>
      <li><a href="#">Sub4</a></li>
    </ul>
  </li>
  <li><a href="#">Contacto</a></li>
</ul>


问:
How do i display data passed from viewbag in controller to view
I have tried to display using @(foreach var x in viewbag.data2) loop in view

```<code> var data = from c in _context.Posts
                       join p in _context.PostViewCount on c.Id equals p.PostId
                       select new
                       {
                           posts = c,
                           p.Count,
                           c.Title,
                           p.PostId

                       };
            var dat = data.OrderByDescending(x=>x.Count).ToList();
            ViewBag.data2 = dat;
</code>```

I m getting invalid operation exception

答:
To access viewbag write the below code in your view
@ViewBag.data2

It will give you the data.

And place the debugger on it. You will understand the rest.

Body:
I have tried to display using @(foreach var x in viewbag.data2) loop in view

 var data = from c in _context.Posts
                       join p in _context.PostViewCount on c.Id equals p.PostId
                       select new
                       {
                           posts = c,
                           p.Count,
                           c.Title,
                           p.PostId

                       };
            var dat = data.OrderByDescending(x=>x.Count).ToList();
            ViewBag.data2 = dat;

I m getting invalid operation exception


问:
Creating 2 numbers from a one #C
I should create two new numbers from a one, the first group will contain digits which are divisible by 2 and the other group will contain the others.

```<code>int checkCount = 94321, num1 = 94321, count2 = 0, countRest = 0;

        while (checkCount > 0)
        {
            if (checkCount % 2 == 0)
                count2++;
            else
                countRest++;
            checkCount /= 10;
        }

        int[] a = new int[count2];
        int[] b = new int[countRest];

        int k2 = 0, kRest = 0;

        for (int j = 0; j < a.Length + b.Length; j++)
        {
            if (num1 % 2 == 0)
            {
                a[k2] = num1 % 10;
                k2++;
            }
            else
            {
                b[kRest] = num1 % 10;
                kRest++;
            }
            num1 /= 10;
        }
</code>```

I created two arrays with the numbers I should use, now how can I build two INT varabile when each one contains all of the numbers together from the array?

Example:
If I have this number - 12345 so
var = 24, other var = 135

If you have another solution without arrays I think it will be better.
Thank you.

答:
This splits number 12345 to numbers 135 and 24.</p>

```<code>int checkCount = 12345;
int even = 0;
int odd = 0;
int reverseEven = 0;
int reverseOdd = 0;

while (checkCount > 0) {
    int current = checkCount % 10;
    if (current % 2 == 0) {
        reverseEven = 10 * reverseEven + current;
    } else {
        reverseOdd = 10 * reverseOdd + current;
    }

    checkCount /= 10;
}

while (reverseEven > 0) {
    even = 10 * even + reverseEven % 10;
    reverseEven /= 10;
}

while (reverseOdd > 0) {
    odd = 10 * odd + reverseOdd % 10;
    reverseOdd /= 10;
}

Console.WriteLine("even: {0}", even);
Console.WriteLine("odd: {0}", odd);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Creating 2 numbers from a one #C

Body:
I should create two new numbers from a one, the first group will contain digits which are divisible by 2 and the other group will contain the others.

int checkCount = 94321, num1 = 94321, count2 = 0, countRest = 0;

        while (checkCount > 0)
        {
            if (checkCount % 2 == 0)
                count2++;
            else
                countRest++;
            checkCount /= 10;
        }

        int[] a = new int[count2];
        int[] b = new int[countRest];

        int k2 = 0, kRest = 0;

        for (int j = 0; j < a.Length + b.Length; j++)
        {
            if (num1 % 2 == 0)
            {
                a[k2] = num1 % 10;
                k2++;
            }
            else
            {
                b[kRest] = num1 % 10;
                kRest++;
            }
            num1 /= 10;
        }

I created two arrays with the numbers I should use, now how can I build two INT varabile when each one contains all of the numbers together from the array?

Example:
If I have this number - 12345 so
var = 24, other var = 135

If you have another solution without arrays I think it will be better.
Thank you.

Body:
This splits number 12345 to numbers 135 and 24.

int checkCount = 12345;
int even = 0;
int odd = 0;
int reverseEven = 0;
int reverseOdd = 0;

while (checkCount > 0) {
    int current = checkCount % 10;
    if (current % 2 == 0) {
        reverseEven = 10 * reverseEven + current;
    } else {
        reverseOdd = 10 * reverseOdd + current;
    }

    checkCount /= 10;
}

while (reverseEven > 0) {
    even = 10 * even + reverseEven % 10;
    reverseEven /= 10;
}

while (reverseOdd > 0) {
    odd = 10 * odd + reverseOdd % 10;
    reverseOdd /= 10;
}

Console.WriteLine("even: {0}", even);
Console.WriteLine("odd: {0}", odd);


问:
Google Chrome Developer Tools : Android Debugging returns HTTP/1.1 404 Not Found. Why?
This was working fine up until yesterday. Now when I connect my Android device for USB Debuggers. Chrome is no longer display my app.

Now the popup window shows HTTP/1.1 404 Not Found.

Looks to be connecting fine and the app runs fine on my Mobile Device.

答: Open https://chrome-devtools-frontend.appspot.com. If it returns 502, then it  is maybe a host error.</p>


问:
How to remove parentheses from string
This:

```<code>document = re.sub(r"(\)", " ", document)
</code>```

or this:

```<code>document = re.sub(r"()", " ", document)
</code>```

do not work for me.

So how can I simply remove the parentheses from a text.

For example this:

```<code>document = "(Hello World)"
</code>```

to become this:

```<code>document = "Hello World"
</code>```

答:
Use:

```<code>import re

document = "(Hello World)"
print(re.sub(r"\((.*?)\)", r"\1", document))
</code>```

Output:

```<code>Hello World
</code>```

Title: How to remove parentheses from string

Body:
This:

document = re.sub(r"(\)", " ", document)

or this:

document = re.sub(r"()", " ", document)

do not work for me.

So how can I simply remove the parentheses from a text.

For example this:

document = "(Hello World)"

to become this:

document = "Hello World"

Body:
Use:

import re

document = "(Hello World)"
print(re.sub(r"\((.*?)\)", r"\1", document))

Output:

Hello World


问:
Trying to initialize an Image
This is me clicking "fix"
Error
I created a new class and init method for my data with 3 variables. One being the UIImage. It can't seem to locate the images in my assets folder.

I tried UIimage(named:  String).

Below is my Code

```<code>    class DataForMeals {
    var mealName: String
    var mealImage: UIImage
    var description: String

    init(mealName: String, mealImage: UIImage, description: String) {
        self.mealImage = mealImage
        self.mealName = mealName
        self.description = description
    }

class func mealData() ->[DataForMeals] {
        var meal: [DataForMeals] = []

        let meal1 = DataForMeals(mealName: "", mealImage: UIImage(named: ""),description: "")

</code>```

It's supposed to find the image by name.

答:
Instead of empty string ("") in as imageName while creating the UIImage object, you need to give the name of actual image that resides in your Assets.xcassets

Example:

To get the image1 from assets, you need to use:

```<code>UIImage(named: "image1")
</code>```

The name should exactly match with the name of image in Assets.xcassets

Edit-1:

UIImage init() is a failable initialiser and so it return an optional UIImage object i.e. UIImage?. So you need to unwrap the image before using it, i.e.

```<code>if let image = UIImage(named: "frenchtoast") {
    let meal1 = DataForMeals(mealName: "French Toast", mealImage: image,description: "recipe")
}
</code>```

Title: Trying to initialize an Image

Body:
This is me clicking "fix"
Error
I created a new class and init method for my data with 3 variables. One being the UIImage. It can't seem to locate the images in my assets folder.

I tried UIimage(named:  String).

Below is my Code

    class DataForMeals {
    var mealName: String
    var mealImage: UIImage
    var description: String

    init(mealName: String, mealImage: UIImage, description: String) {
        self.mealImage = mealImage
        self.mealName = mealName
        self.description = description
    }

class func mealData() ->[DataForMeals] {
        var meal: [DataForMeals] = []

        let meal1 = DataForMeals(mealName: "", mealImage: UIImage(named: ""),description: "")

It's supposed to find the image by name.

Body:
Instead of empty string ("") in as imageName while creating the UIImage object, you need to give the name of actual image that resides in your Assets.xcassets

Example:

To get the image1 from assets, you need to use:

UIImage(named: "image1")

The name should exactly match with the name of image in Assets.xcassets

Edit-1:

UIImage init() is a failable initialiser and so it return an optional UIImage object i.e. UIImage?. So you need to unwrap the image before using it, i.e.

if let image = UIImage(named: "frenchtoast") {
    let meal1 = DataForMeals(mealName: "French Toast", mealImage: image,description: "recipe")
}


问:
How to add or remove attributes in laravel eloquent by condition on request
I have Post model with many post types. I need to control with post attributes by post type. For example I have 2 post types:

Song

Singer

Model only once Post.

Post model scheme:

```<code>id
title
description
parent_id
type
</code>```

When requesting song post type, how I can add attribute singer to response array automatically or when requesting singer post type add attribute songs?

I tired inside model ussing __construct() method but not work:

```<code>public function __construct() {
    if($this->type == "song") {
        //$this->with = array_push($this->with, "singer");
        $this->appends = array_push($this->appends, 'singer');
    }
}
</code>```

答:
```<code>public function __construct() {
   parent::__construct()
    if($this->type == "song") {
        //$this->with = array_push($this->with, "singer");
        $this->appends = array_push($this->appends, 'singer');
    }
}
</code>```

Body:
I have Post model with many post types. I need to control with post attributes by post type. For example I have 2 post types:

Song

Singer

Model only once Post.

Post model scheme:

id
title
description
parent_id
type

When requesting song post type, how I can add attribute singer to response array automatically or when requesting singer post type add attribute songs?

I tired inside model ussing __construct() method but not work:

public function __construct() {
    if($this->type == "song") {
        //$this->with = array_push($this->with, "singer");
        $this->appends = array_push($this->appends, 'singer');
    }
}


问:
Java: properly checked class instantiation using reflection
I'm trying to use one of the simplest forms of reflection to create an instance of class:

```<code>package some.common.prefix;

public interface My {
    void configure(...);
    void process(...);
}

public class MyExample implements My {
    ... // proper implementation
}

String myClassName = "MyExample"; // read from an external file in reality

Class<? extends My> myClass =
    (Class<? extends My>) Class.forName("some.common.prefix." + myClassName);
My my = myClass.newInstance();
</code>```

Typecasting unknown Class object we've got from Class.forName yields a warning:

```Type safety: Unchecked cast from Class<capture#1-of ?> to Class<? extends My>```

I've tried using instanceof check approach:

```<code>Class<?> loadedClass = Class.forName("some.common.prefix." + myClassName);
if (myClass instanceof Class<? extends RST>) {
    Class<? extends My> myClass = (Class<? extends My>) loadedClass;
    My my = myClass.newInstance();
} else {
    throw ... // some awful exception
}
</code>```

but this yields a compilation error:
Cannot perform instanceof check against parameterized type Class<? extends My>. Use the form Class<?> instead since further generic type information will be erased at runtime. So I guess I can't use instanceof approach.

How do I get rid of it and how am I supposed to do it properly? Is it possible to use reflection without these warnings at all (i.e. without ignoring or supressing them)?

答:
I think you can do it this way:</p>

```<code>Class<? extends My> myClass= null;
Class<?> loadedClass = Class.forName("some.common.prefix." + myClassName);
if(My.class.isAssignableFrom(loadedClass))
{
    myClass = loadedClass.asSubclass(My.class);
}
My my = myClass.newInstance();
</code>```

Body:
I'm trying to use one of the simplest forms of reflection to create an instance of class:

package some.common.prefix;

public interface My {
    void configure(...);
    void process(...);
}

public class MyExample implements My {
    ... // proper implementation
}

String myClassName = "MyExample"; // read from an external file in reality

Class<? extends My> myClass =
    (Class<? extends My>) Class.forName("some.common.prefix." + myClassName);
My my = myClass.newInstance();

Typecasting unknown Class object we've got from Class.forName yields a warning:

Type safety: Unchecked cast from Class<capture#1-of ?> to Class<? extends My>

I've tried using instanceof check approach:

Class<?> loadedClass = Class.forName("some.common.prefix." + myClassName);
if (myClass instanceof Class<? extends RST>) {
    Class<? extends My> myClass = (Class<? extends My>) loadedClass;
    My my = myClass.newInstance();
} else {
    throw ... // some awful exception
}

but this yields a compilation error:
Cannot perform instanceof check against parameterized type Class<? extends My>. Use the form Class<?> instead since further generic type information will be erased at runtime. So I guess I can't use instanceof approach.

How do I get rid of it and how am I supposed to do it properly? Is it possible to use reflection without these warnings at all (i.e. without ignoring or supressing them)?

Body:
I think you can do it this way:

Class<? extends My> myClass= null;
Class<?> loadedClass = Class.forName("some.common.prefix." + myClassName);
if(My.class.isAssignableFrom(loadedClass))
{
    myClass = loadedClass.asSubclass(My.class);
}
My my = myClass.newInstance();


问:
how to instantiate the imported class in angular
i am working on a angualr weather app.
for which i have created weather class

```<code> export class Weather{
          city: string;
          condition: string;
          icon: string;
          temp: number;
        }
</code>```

and i make a http api request for weather details.

i have imported this Weather class and want to assign the fields as per the json object from the api call.

like this.

```<code>weather:Weather;
getWeather():void{
               this.weatherserv.getWeather().subscribe(data=>{
                   this.weather.city=data.location.name;
                  this.weather.condition=data.condition.text;
                   this.weather.condition=data.condition.icon;
                   this.weather.temp=data.current.temp_c;
               })
             }
</code>```

Error i am getting is:

```<code>Error: Cannot set property 'city' of undefined
</code>```

答:
Test follow code:

```<code>weather: Weather = new Weather;
</code>```

Here: the stackblitz for it

Body:
i am working on a angualr weather app.
for which i have created weather class

 export class Weather{
          city: string;
          condition: string;
          icon: string;
          temp: number;
        }

and i make a http api request for weather details.

i have imported this Weather class and want to assign the fields as per the json object from the api call.

like this.

weather:Weather;
getWeather():void{
               this.weatherserv.getWeather().subscribe(data=>{
                   this.weather.city=data.location.name;
                  this.weather.condition=data.condition.text;
                   this.weather.condition=data.condition.icon;
                   this.weather.temp=data.current.temp_c;
               })
             }

Error i am getting is:

Error: Cannot set property 'city' of undefined

Body:
Test follow code:

weather: Weather = new Weather;

Here: the stackblitz for it


答:
```<code>document.replace('(','').replace(')','')
</code>```

Use replace method.

Title: How to remove parentheses from string

Body:
document.replace('(','').replace(')','')

Use replace method.


问:
How to access my wordpress files in EC2 without using filezilla or other FTP?
I need to change some lines in the wp-config.php code so I can change the URL of my wordpress site.

The thing is that I am completely new to Amazon Web Service and EC2. I am looking for something like File Manager in CPanel, but I can't find anything and they always say that you should connect by FTP using filezilla, for example, but I can't connect my FileZilla because it's giving me an error.

How can I acces my wordpress files without using FTP as filezilla?

答:
I doubt but you may have to use FTP or SFTP method to connect and access your files.

The filezilla must be giving you can error due to an step missed by you.

You can see below video tutorial which explains steps to connect EC2 using FileZilla.

https://www.youtube.com/watch?v=e9BDvg42-JI


问:
Problem with Converting a bootstrap site to React
I want to convert a bootstrap  to a react file i did all the changes but i get this error

```<code>./src/css/jquery-ui.min.css (./node_modules/css-loader??ref--6-oneOf-3-1!./node_modules/postcss-loader/src??postcss!./src/css/jquery-ui.min.css)
</code>```

Module not found: Can't resolve './images/ui-icons_444444_256x240.png' in 'E:\React\tejapak\src\css'

what's the problem?

答:
It' looks like you imported jquery's css in some component and deleted jQuery dependencies without removing import.

Search if there any place where jquery-ui.min.css is included in component and remove it.

Body:
I want to convert a bootstrap  to a react file i did all the changes but i get this error

./src/css/jquery-ui.min.css (./node_modules/css-loader??ref--6-oneOf-3-1!./node_modules/postcss-loader/src??postcss!./src/css/jquery-ui.min.css)

Module not found: Can't resolve './images/ui-icons_444444_256x240.png' in 'E:\React\tejapak\src\css'

what's the problem?


问:
Deprecate specific route out of multiple routes on single Web API method
Hi I have WEB API implementation as shown below. Where we are using multiple routes on single method.

```<code>[SwaggerOperation("Update Records By Id")]
[Route("/construction/field-record")]
[Route("/construction/fieldRecord")]
public async Task<IActionResult> UpdateRecord([FromBody] UpdateRecordRequest request)
{
   //  ...
}
</code>```

Two questions,

How to mark only one route out of two as deprecated?

How to update swagger indicating that route is "Deprecated" on sawagger UI?

-Thanks

答:
You can add an OperationFilter that checks the OperationId. This is a string version of the route that has a consistent format; parameters are rendered as "ByXXXX" where XXXX is the name of the variable in the route. You can check this OperationId for the routes you want to deprecate, e.g. In the controller:

```<code>[HttpGet]
//Obsolete route
[Route("api/customerId}/account/read/{orderId}")]
//Correct route
[Route("api/customerId}/account/{orderId}/read")]
</code>```

and then use an operation filter:

```<code>public class ExplictObsoleteRoutes : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
         if (operation.OperationId.EndsWith("ByOrderIdGet")"))
         {
             operation.Deprecated = true;
         }
    }
}
</code>```

Body:
Hi I have WEB API implementation as shown below. Where we are using multiple routes on single method.

[SwaggerOperation("Update Records By Id")]
[Route("/construction/field-record")]
[Route("/construction/fieldRecord")]
public async Task<IActionResult> UpdateRecord([FromBody] UpdateRecordRequest request)
{
   //  ...
}

Two questions,

How to mark only one route out of two as deprecated?

How to update swagger indicating that route is "Deprecated" on sawagger UI?

-Thanks

Body:
You can add an OperationFilter that checks the OperationId. This is a string version of the route that has a consistent format; parameters are rendered as "ByXXXX" where XXXX is the name of the variable in the route. You can check this OperationId for the routes you want to deprecate, e.g. In the controller:

[HttpGet]
//Obsolete route
[Route("api/customerId}/account/read/{orderId}")]
//Correct route
[Route("api/customerId}/account/{orderId}/read")]

and then use an operation filter:

public class ExplictObsoleteRoutes : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
         if (operation.OperationId.EndsWith("ByOrderIdGet")"))
         {
             operation.Deprecated = true;
         }
    }
}


问:
How to publish my documents folder in remoteapp
I'm publishing Documents folder to every user in Windows Server 2012, I'm using this code to publish the folder:

%SystemRoot%\explorer.exe %UserProfile%\My Documents

And it works, but I want to "hide" the quick access and exclude to explore any another drive or folder to show , just see Documents windows, I know it's possible, but I don't find the right option to hide it...

%SystemRoot%\explorer.exe %UserProfile%\My Documents

答:
Start a rooted Explorer:

```<code>%SystemRoot%\explorer.exe /e,/root,%UserProfile%\My Documents
</code>```

And My Documents might not be the correct name of the folder, you should use the shell protocol:

```<code>%SystemRoot%\explorer.exe /e,/root,shell:personal
</code>```

This will not prevent the user from viewing other folders in another Explorer window.

Body:
Start a rooted Explorer:

%SystemRoot%\explorer.exe /e,/root,%UserProfile%\My Documents

And My Documents might not be the correct name of the folder, you should use the shell protocol:

%SystemRoot%\explorer.exe /e,/root,shell:personal

This will not prevent the user from viewing other folders in another Explorer window.


问:
export CLOb data from oracle database in UTF8 format
I have CLOB data stored in the oracle DB and when I query it and print it on the web page, all non English characters appears in ??. They are in the DB in correct format but when exported to any file or printed it on the web, they appear incorrect.

how to solve this. I am using PHP + OCI8 for fetching records.

答: use AL32UTF8 as encoding type when connecting using OCI_CONNECT


问:
How to set syntax highlighting for Dart variable in Visual Studio Code
I am using Visual Studio Code for coding Dart with Flutter. I installed Dart and Flutter plugins as well as the Material theme from Matta Astorino. The problem is I can't specifically set the syntax highlight of my variables with Dart language using the Material Theme Ocean High Contrast color theme.

The settings i used:

```<code>  "editor.tokenColorCustomizations": {
    "[Material Theme Ocean High Contrast]": {
    "comments": "#229977",
    "variables": "#ffffff"
    }
  },
</code>```

 -Dart

From the picture above, the comments syntax highlighting seems to work fine but the syntax highlighting for variables is still showing in grey (which supposed to be white).

 -JavaScript

In JavaScript, it seems to work fine.

Please help on these Dart syntax highlighting for VSCode Thanks.

答:
I don't use Dart, but i can say that, sometimes you have to be more specific with setting syntax scope colors.

First of all - you need to know what the scope is. To do this, please run Inspect TM Scopes.

Here you have described how to do it:

https://code.visualstudio.com/blogs/2017/02/08/syntax-highlighting-optimizations#_new-textmate-scope-inspector-widget

To understand better, it is good to read:

https://macromates.com/manual/en/language_grammars 12.4 Naming Conventions

https://code.visualstudio.com/api/language-extensions/syntax-highlight-guide

Sublime Text have a good explanation too:

https://www.sublimetext.com/docs/3/scope_naming.html

Ok, and now:

When you find out what the scope is, then you have to create or overwrite it.
Example:

```<code>    "editor.tokenColorCustomizations": {
        "[My Theme Name]": {
            "textMateRules": [
                {
                    "name": "Entity",
                    "scope": "entity.name",
                    "settings": {
                        "foreground": "#FFC66D"
                    }
                },
            ]
        }
    },
</code>```

If you will create more and more new scopes, remember that:

being too specific will result in a color scheme that often only looks good for one or two syntaxes.

Body:
I am using Visual Studio Code for coding Dart with Flutter. I installed Dart and Flutter plugins as well as the Material theme from Matta Astorino. The problem is I can't specifically set the syntax highlight of my variables with Dart language using the Material Theme Ocean High Contrast color theme.

The settings i used:

  "editor.tokenColorCustomizations": {
    "[Material Theme Ocean High Contrast]": {
    "comments": "#229977",
    "variables": "#ffffff"
    }
  },

 -Dart

From the picture above, the comments syntax highlighting seems to work fine but the syntax highlighting for variables is still showing in grey (which supposed to be white).

 -JavaScript

In JavaScript, it seems to work fine.

Please help on these Dart syntax highlighting for VSCode Thanks.

Body:
I don't use Dart, but i can say that, sometimes you have to be more specific with setting syntax scope colors.

First of all - you need to know what the scope is. To do this, please run Inspect TM Scopes.

Here you have described how to do it:

https://code.visualstudio.com/blogs/2017/02/08/syntax-highlighting-optimizations#_new-textmate-scope-inspector-widget

To understand better, it is good to read:

https://macromates.com/manual/en/language_grammars 12.4 Naming Conventions

https://code.visualstudio.com/api/language-extensions/syntax-highlight-guide

Sublime Text have a good explanation too:

https://www.sublimetext.com/docs/3/scope_naming.html

Ok, and now:

When you find out what the scope is, then you have to create or overwrite it.
Example:

    "editor.tokenColorCustomizations": {
        "[My Theme Name]": {
            "textMateRules": [
                {
                    "name": "Entity",
                    "scope": "entity.name",
                    "settings": {
                        "foreground": "#FFC66D"
                    }
                },
            ]
        }
    },

If you will create more and more new scopes, remember that:

being too specific will result in a color scheme that often only looks good for one or two syntaxes.


问:
How to find old debug data(Logs) in report navigator in Xcode
Can i get the old Debug records from the report navigator in Xcode. There is no enough information in Report Navigator help, so i could not find it.

Is there any other way to find my old logs.

答:
Xcode has a little clock icon at the bottom of that tab to "Show only recent reports"

You either have that selected or have recently cleared your derived data folder, which I believe would remove all of your build history as your logs are stored there.

Derived data folder is usually at ~/Library/Developer/Xcode/DerivedData/


问:
What exactly is Lazy style programming
For a homework project I am building a Typesafe LINQ framework in Typescript, here is the project description: Project

The description says: "Your project will generate a chain of executable functions, in the lazy style."

But I don't know exactly what Lazy means here?

I have build a Table containing all the operators, but the problem is that all the functions return a result immediately.

```<code>interface Table<T, U> {
    readonly data: Pair<List<T>, List<U>>
    Select: <K extends keyof T>(this: Table<T, U>, properties: K[]) => Table<Omit<T, K>, Pick<T, K> & U>
}

const Table = <T, U>(data: Pair<List<T>, List<U>>): Table<T, U> => ({
    data: data,
    Select: function <K extends keyof T>(this: Table<T, U>, properties: K[]): Table<Omit<T, K>, Pick<T, K> & U> {
        let selection = this.data.First.map(entry => pickMany(entry, properties))

        let result = this.data.map(
            first => first.map(entry => omitMany(entry, properties))
            ,
            second => merge_list_types(second.zip(selection))
        )

        return Table(result)
    },
})
</code>```

So my basic understanding of Lazy is that the operators should return a executable function, that will be called later in the program. But I don't know how to do that.

Also the teachers provided me with a wrapper for a function:

```<code>export interface Func<a, b> {
    f: (_: a) => b
    then: <c>(this: Func<a, b>, g: Func<b, c>) => Func<a, c>
}

export let Func = <a, b>(f: (_: a) => b): Func<a, b> => {
    return {
        f: f,
        then: function <c>(this: Func<a, b>, g: Func<b, c>): Func<a, c> {
            return Func<a, c>(x => g.f(this.f(x)))
        },
}
</code>```

Should I just return a Func<Table<Something, Something>, Table<AnotherThing, AnotherThing>>, for every operator to make it lazy? I am not sure, seems like a decent solution. But I can use some help in the understanding of Lazy style programming.

答:
Lazy, in the context of porting LINQ, means returning an object that does work when iterated over, rather than doing some work iterating over your input data to generate iterable output data.

As an example

```<code>Print(allNumbers.Where(isEven).Take(10))
</code>```

If Where is Eager, this takes infinite time, enumerating every number. If Where is Lazy, it only enumerates numbers up to 20.

Title: What exactly is Lazy style programming

Body:
For a homework project I am building a Typesafe LINQ framework in Typescript, here is the project description: Project

The description says: "Your project will generate a chain of executable functions, in the lazy style."

But I don't know exactly what Lazy means here?

I have build a Table containing all the operators, but the problem is that all the functions return a result immediately.

interface Table<T, U> {
    readonly data: Pair<List<T>, List>
    Select: <K extends keyof T>(this: Table<T, U>, properties: K[]) => Table<Omit<T, K>, Pick<T, K> & U>
}

const Table = <T, U>(data: Pair<List<T>, List>): Table<T, U> => ({
    data: data,
    Select: function <K extends keyof T>(this: Table<T, U>, properties: K[]): Table<Omit<T, K>, Pick<T, K> & U> {
        let selection = this.data.First.map(entry => pickMany(entry, properties))

        let result = this.data.map(
            first => first.map(entry => omitMany(entry, properties))
            ,
            second => merge_list_types(second.zip(selection))
        )

        return Table(result)
    },
})

So my basic understanding of Lazy is that the operators should return a executable function, that will be called later in the program. But I don't know how to do that.

Also the teachers provided me with a wrapper for a function:

export interface Func {
    f: (_: a) => b
    then: <c>(this: Func, g: Func) => Func
}

export let Func = (f: (_: a) => b): Func => {
    return {
        f: f,
        then: function <c>(this: Func, g: Func): Func {
            return Func(x => g.f(this.f(x)))
        },
}

Should I just return a Func<Table<Something, Something>, Table<AnotherThing, AnotherThing>>, for every operator to make it lazy? I am not sure, seems like a decent solution. But I can use some help in the understanding of Lazy style programming.

Body:
Lazy, in the context of porting LINQ, means returning an object that does work when iterated over, rather than doing some work iterating over your input data to generate iterable output data.

As an example

Print(allNumbers.Where(isEven).Take(10))

If Where is Eager, this takes infinite time, enumerating every number. If Where is Lazy, it only enumerates numbers up to 20.


问:
AWS DynamoDB find Item by key in Map attribute (not Partition key)
I have a table in DynamoDB where I want to get an Item not by the partition key but by  a key in a Map attribute nested in the table.

```<code>{
    "MyItem": {
        "Key": "dfcwce",

        "NestedMap":
          {
          "map.key" : "value"
          "map.key2" : "value2"
          }
    }
}
</code>```

I would like to query the item to get the Key of the item by the map.key.

答:
Unfortunately, you can not query AWS Dynamodb without a Key field,

The Query operation finds items based on primary key values.

But you can query any table or secondary index that has a composite primary key (a partition key and a sort key).

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html

Body:
I have a table in DynamoDB where I want to get an Item not by the partition key but by  a key in a Map attribute nested in the table.

{
    "MyItem": {
        "Key": "dfcwce",

        "NestedMap":
          {
          "map.key" : "value"
          "map.key2" : "value2"
          }
    }
}

I would like to query the item to get the Key of the item by the map.key.


问:
WF and ASPNET MVC
Is there a way to use MS WF interactively in ASPNET MVC?</p>

答:
Did you see how WF and MVC were used inthe StoreFront example?

http://www.asp.net/learn/mvc-videos/video-428.aspx

OwnerDisplayName: from

Title: WF and ASPNET MVC

OwnerDisplayName: Leah

ContentLicense: CC BY-SA 2.5


答:
You can try :</p>

```<code>>>> import re
>>> document = "(Hello World)"
>>> print(re.sub('[()]', '', document))
Hello World
</code>```

Title: How to remove parentheses from string

Body:
This:

document = re.sub(r"(\)", " ", document)

or this:

document = re.sub(r"()", " ", document)

do not work for me.

So how can I simply remove the parentheses from a text.

For example this:

document = "(Hello World)"

to become this:

document = "Hello World"

Body:
You can try :

>>> import re
>>> document = "(Hello World)"
>>> print(re.sub('[()]', '', document))
Hello World


问:
How to select number content in element and add commas with jquery or js
I need to simply add commas to numbers in my code. I have tried a lot of hints here but something seems to be wrong.

I have tried with regex and the toLocalString() method and both haven't worked, can someone help me find the correct solution.

```<code><script type="text/javascript">
   $(document).ready(function () {
      // $("#price").toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      $('#price').html.toLocaleString('en');
   });
</script>
</code>```

Here's my element:

```<code><strong id="price"><%# Eval("OfferPrice") %></strong>
</code>```

Everything seems ok, can anyone help please. Thanks a lot!

答:
Replace in your DOM all id attributes by class attributes, then you can render all values by your desired formatting.

Your DOM elements will be edited as follow :

```<code><strong class="price"><%# Eval("OfferPrice") %></strong>
</code>```

From jQuery Documentation :

```<code>$(document).ready(function () {
        var x = parseFloat($('.price').html()).toLocaleString('en-US');
        $('.price').html(x)
 });
</code>```

Body:
I need to simply add commas to numbers in my code. I have tried a lot of hints here but something seems to be wrong.

I have tried with regex and the toLocalString() method and both haven't worked, can someone help me find the correct solution.

Here's my element:

<%# Eval("OfferPrice") %>

Everything seems ok, can anyone help please. Thanks a lot!

Body:
Replace in your DOM all id attributes by class attributes, then you can render all values by your desired formatting.

Your DOM elements will be edited as follow :

<strong class="price"><%# Eval("OfferPrice") %></strong>

From jQuery Documentation :

$(document).ready(function () {
        var x = parseFloat($('.price').html()).toLocaleString('en-US');
        $('.price').html(x)
 });


问:
Making an Angular Material data table rows scroll while maintaining a sticky a header
Stack Blitz Demo

I am having trouble figuring out how to get my code to behave as needed.

As the demo shows I have a table that when the add button is clicked a new row is added. Once the table rows reach a certain height (say for example after adding 5 rows) I need a vertical scroll bar to display and at the same time I need to maintain a sticky header. Basically I need to set the table rows to a fixed height.

The attached screen shot shows where I would like the scroll bar to display. Apologies for the shaky highlight.

The HTML looks looks like this

```<code><div class="table-container">
  <table mat-table [dataSource]="dataSource">
    <ng-container matColumnDef="category">
      <th mat-header-cell *matHeaderCellDef >Category</th>
      <td mat-cell *matCellDef="let code" >
        <mat-form-field class="code">
          <mat-select>
            <mat-option *ngFor=" let category of categories" [value]="category.code" class="dropdownpPopUp"  (keydown.ArrowDown)="onDown()">{{category.code}}</mat-option>
          </mat-select>
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="type">
      <th mat-header-cell *matHeaderCellDef>Type</th>
      <td mat-cell *matCellDef="let code" >
        <mat-form-field class="type">
          <mat-select >
            <mat-option *ngFor=" let type of types" [value]="type.code" class="dropdownpPopUp"  (keydown.ArrowDown)="onDown()">{{type.code}}</mat-option>
          </mat-select>
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="additionalCode" class="parent" >
      <th mat-header-cell *matHeaderCellDef>Additional Code</th>
      <td mat-cell *matCellDef="let element" class="parent" >
        <mat-form-field class="type">
          <input matInput (keyup)="toggleLookup($event)" autocomplete="off" (keydown.ArrowDown)="onDown()">
        </mat-form-field>
        <div *ngIf="expanded" class="child">Yah it expanded
          <button (click)="expanded = false">Close</button>
        </div>
      </td>
    </ng-container>
    <ng-container matColumnDef="ref">
      <th mat-header-cell *matHeaderCellDef>Reference</th>
      <td mat-cell *matCellDef="let element" >
        <mat-form-field>
          <input matInput [(ngModel)]="element.type"  (keydown.ArrowDown)="onDown()" autocomplete="off">
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="add">
      <th mat-header-cell *matHeaderCellDef>
        <button mat-icon-button (click)="addRow()" matTooltip="Add Row">
          <mat-icon>add</mat-icon>
        </button>
      </th>
      <td mat-cell *matCellDef="let code; let i = index;">
        <button mat-icon-button (click)="removeAt(i)" matTooltip="Remove Row">
          <mat-icon>clear</mat-icon>
        </button>
      </td>
    </ng-container>
    <tr mat-header-row *matHeaderRowDef="columns"></tr>
    <tr mat-row *matRowDef="let rows; columns: columns;"></tr>
  </table>
   <div *ngIf="dataSource.filteredData.length > 0" > <mat-paginator [pageSizeOptions]="[5]" showFirstLastButtons class="paginator"></mat-paginator></div>
</div>
</code>```

Component Add Function

```<code>addRow() {
    this.doAddRow();
    this.expanded = false;
  }
  private doAddRow() {
    ELEMENT_DATA.push({ code: '', type: '', reference: '' });
    this.dataSource = new MatTableDataSource(ELEMENT_DATA);
  }
</code>```

答:
what you have to do is add a div outside of your table and provide a
  min-height property.

app.component.css

```<code>.main-table{
  max-height:42vh;
  overflow-y:scroll;
  overflow-x:hidden;
}
</code>```

app.component.html

```<code><ol>
  <li>Select + to add rosw</li>
</ol>
<p>After 5 new rows added a vertical scroll bar should aprear and when srolling the header row should still be visible</p>
<div class="table-container">
  <div class="main-table">
  <table mat-table [dataSource]="dataSource">
    <ng-container matColumnDef="category">
      <th mat-header-cell *matHeaderCellDef >Category</th>
      <td mat-cell *matCellDef="let code" >
        <mat-form-field class="code">
          <mat-select>
            <mat-option *ngFor=" let category of categories" [value]="category.code" class="dropdownpPopUp"  (keydown.ArrowDown)="onDown()">{{category.code}}</mat-option>
          </mat-select>
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="type">
      <th mat-header-cell *matHeaderCellDef>Type</th>
      <td mat-cell *matCellDef="let code" >
        <mat-form-field class="type">
          <mat-select >
            <mat-option *ngFor=" let type of types" [value]="type.code" class="dropdownpPopUp"  (keydown.ArrowDown)="onDown()">{{type.code}}</mat-option>
          </mat-select>
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="additionalCode" class="parent" >
      <th mat-header-cell *matHeaderCellDef>Additional Code</th>
      <td mat-cell *matCellDef="let element" class="parent" >
        <mat-form-field class="type">
          <input matInput (keyup)="toggleLookup($event)" autocomplete="off" (keydown.ArrowDown)="onDown()">
        </mat-form-field>
        <div *ngIf="expanded" class="child">Yah it expanded
          <button (click)="expanded = false">Close</button>
        </div>
      </td>
    </ng-container>
    <ng-container matColumnDef="ref">
      <th mat-header-cell *matHeaderCellDef>Reference</th>
      <td mat-cell *matCellDef="let element" >
        <mat-form-field>
          <input matInput [(ngModel)]="element.type"  (keydown.ArrowDown)="onDown()" autocomplete="off">
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="add">
      <th mat-header-cell *matHeaderCellDef>
        <button mat-icon-button (click)="addRow()" matTooltip="Add Row">
          <mat-icon>add</mat-icon>
        </button>
      </th>
      <td mat-cell *matCellDef="let code; let i = index;">
        <button mat-icon-button (click)="removeAt(i)" matTooltip="Remove Row">
          <mat-icon>clear</mat-icon>
        </button>
      </td>
    </ng-container>
    <tr mat-header-row *matHeaderRowDef="columns"></tr>
    <tr mat-row *matRowDef="let rows; columns: columns;"></tr>
  </table>
  </div>
   <div *ngIf="dataSource.filteredData.length > 0" > <mat-paginator [pageSizeOptions]="[5]" showFirstLastButtons class="paginator"></mat-paginator></div>
</div>
</code>```

Body:
Stack Blitz Demo

I am having trouble figuring out how to get my code to behave as needed.

As the demo shows I have a table that when the add button is clicked a new row is added. Once the table rows reach a certain height (say for example after adding 5 rows) I need a vertical scroll bar to display and at the same time I need to maintain a sticky header. Basically I need to set the table rows to a fixed height.

The attached screen shot shows where I would like the scroll bar to display. Apologies for the shaky highlight.

The HTML looks looks like this

    <ng-container matColumnDef="category">
      Category

        <mat-form-field class="code">
          <mat-select>
            <mat-option *ngFor=" let category of categories" [value]="category.code" class="dropdownpPopUp"  (keydown.ArrowDown)="onDown()">{{category.code}}</mat-option>
          </mat-select>
        </mat-form-field>

    </ng-container>
    <ng-container matColumnDef="type">
      Type

        <mat-form-field class="type">
          <mat-select >
            <mat-option *ngFor=" let type of types" [value]="type.code" class="dropdownpPopUp"  (keydown.ArrowDown)="onDown()">{{type.code}}</mat-option>
          </mat-select>
        </mat-form-field>

    </ng-container>
    <ng-container matColumnDef="additionalCode" class="parent" >
      Additional Code

        <mat-form-field class="type">
          <input matInput (keyup)="toggleLookup($event)" autocomplete="off" (keydown.ArrowDown)="onDown()">
        </mat-form-field>

Yah it expanded
          <button (click)="expanded = false">Close</button>

    </ng-container>
    <ng-container matColumnDef="ref">
      Reference

        <mat-form-field>
          <input matInput [(ngModel)]="element.type"  (keydown.ArrowDown)="onDown()" autocomplete="off">
        </mat-form-field>

    </ng-container>
    <ng-container matColumnDef="add">

        <button mat-icon-button (click)="addRow()" matTooltip="Add Row">
          <mat-icon>add</mat-icon>
        </button>

        <button mat-icon-button (click)="removeAt(i)" matTooltip="Remove Row">
          <mat-icon>clear</mat-icon>
        </button>

    </ng-container>

 0" > <mat-paginator [pageSizeOptions]="[5]" showFirstLastButtons class="paginator"></mat-paginator>

Component Add Function

addRow() {
    this.doAddRow();
    this.expanded = false;
  }
  private doAddRow() {
    ELEMENT_DATA.push({ code: '', type: '', reference: '' });
    this.dataSource = new MatTableDataSource(ELEMENT_DATA);
  }

Body:
what you have to do is add a div outside of your table and provide a
  min-height property.

app.component.css

.main-table{
  max-height:42vh;
  overflow-y:scroll;
  overflow-x:hidden;
}

app.component.html

<ol>
  <li>Select + to add rosw</li>
</ol>
<p>After 5 new rows added a vertical scroll bar should aprear and when srolling the header row should still be visible</p>
<div class="table-container">
  <div class="main-table">
  <table mat-table [dataSource]="dataSource">
    <ng-container matColumnDef="category">
      <th mat-header-cell *matHeaderCellDef >Category</th>
      <td mat-cell *matCellDef="let code" >
        <mat-form-field class="code">
          <mat-select>
            <mat-option *ngFor=" let category of categories" [value]="category.code" class="dropdownpPopUp"  (keydown.ArrowDown)="onDown()">{{category.code}}</mat-option>
          </mat-select>
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="type">
      <th mat-header-cell *matHeaderCellDef>Type</th>
      <td mat-cell *matCellDef="let code" >
        <mat-form-field class="type">
          <mat-select >
            <mat-option *ngFor=" let type of types" [value]="type.code" class="dropdownpPopUp"  (keydown.ArrowDown)="onDown()">{{type.code}}</mat-option>
          </mat-select>
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="additionalCode" class="parent" >
      <th mat-header-cell *matHeaderCellDef>Additional Code</th>
      <td mat-cell *matCellDef="let element" class="parent" >
        <mat-form-field class="type">
          <input matInput (keyup)="toggleLookup($event)" autocomplete="off" (keydown.ArrowDown)="onDown()">
        </mat-form-field>
        <div *ngIf="expanded" class="child">Yah it expanded
          <button (click)="expanded = false">Close</button>
        </div>
      </td>
    </ng-container>
    <ng-container matColumnDef="ref">
      <th mat-header-cell *matHeaderCellDef>Reference</th>
      <td mat-cell *matCellDef="let element" >
        <mat-form-field>
          <input matInput [(ngModel)]="element.type"  (keydown.ArrowDown)="onDown()" autocomplete="off">
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="add">
      <th mat-header-cell *matHeaderCellDef>
        <button mat-icon-button (click)="addRow()" matTooltip="Add Row">
          <mat-icon>add</mat-icon>
        </button>
      </th>
      <td mat-cell *matCellDef="let code; let i = index;">
        <button mat-icon-button (click)="removeAt(i)" matTooltip="Remove Row">
          <mat-icon>clear</mat-icon>
        </button>
      </td>
    </ng-container>
    <tr mat-header-row *matHeaderRowDef="columns"></tr>
    <tr mat-row *matRowDef="let rows; columns: columns;"></tr>
  </table>
  </div>
   <div *ngIf="dataSource.filteredData.length > 0" > <mat-paginator [pageSizeOptions]="[5]" showFirstLastButtons class="paginator"></mat-paginator></div>
</div>


问:
How to remove parentheses from string
This:

```<code>document = re.sub(r"(\)", " ", document)
</code>```

or this:

```<code>document = re.sub(r"()", " ", document)
</code>```

do not work for me.

So how can I simply remove the parentheses from a text.

For example this:

```<code>document = "(Hello World)"
</code>```

to become this:

```<code>document = "Hello World"
</code>```

答:
If you simply want to remove all parentheses in the string, use this:

```<code>document = '(Hello World)))))(((('
document = re.sub(r'[()]', '', document)
# square brackets, [], will capture anything inside them, in this case, any '(' or ')'

print(document)
</code>```

Output:

```<code>Hello World
</code>```

Title: How to remove parentheses from string

Body:
If you simply want to remove all parentheses in the string, use this:

document = '(Hello World)))))(((('
document = re.sub(r'[()]', '', document)
# square brackets, [], will capture anything inside them, in this case, any '(' or ')'

print(document)

Output:

Hello World


答:
Try this:</p>

```<code>re.sub(r"\(|\)", "", document)
</code>```

Title: How to remove parentheses from string

Body:
Try this:

re.sub(r"\(|\)", "", document)


问:
How to test the `Mosquitto` server?
I am new to Mosquitto and MQTT, I downloaded the Mosquitto server library but I do not know how to  test it.

Is there any way to test the Mosquitto server?

答:
The OP has not defined the scope of testing, however, simple (gross) 'smoke testing' an install should be performed before any time is invested with functionality testing.

How to test if application is installed ('smoke-test')

Log into the mosquitto server's command line and type:

```<code>mosquitto
</code>```

If mosquitto is installed the machine will return:

```<code> mosquitto version 1.4.8 (build date Wed, date of installation) starting
 Using default config.
 Opening ipv4 listen socket on port 1883
</code>```

Title: How to test the `Mosquitto` server?

Body:
The OP has not defined the scope of testing, however, simple (gross) 'smoke testing' an install should be performed before any time is invested with functionality testing.

How to test if application is installed ('smoke-test')

Log into the mosquitto server's command line and type:

mosquitto

If mosquitto is installed the machine will return:

 mosquitto version 1.4.8 (build date Wed, date of installation) starting
 Using default config.
 Opening ipv4 listen socket on port 1883


问:
foundation javascript not working as expected
I have some issues that been troubleshooting all week long.  I tried it on bracket IDE and on codepen but I couldn't make the foundation framework to work as it should be like what on there website

for example this should work like below link: https://foundation.zurb.com/building-blocks/blocks/off-canvas-full-screen.html

    <button class="offcanvas-full-screen-close" aria-label="Close menu" type="button" data-close>
      ×
    </button>

Home

About us

Services

Contact us

      Site Title

      <button class="menu-icon dark" type="button" data-toggle="offcanvas-full-screen"></button>

```

答:
you forgot to initialize foundation.

just add

```<code><script>
    $(document).foundation();
</script>
</code>```

And it will work.

Body:
you forgot to initialize foundation.

just add

<script>
    $(document).foundation();
</script>

And it will work.


问:
Apache CXF WS Security WebService from NET Client - Cannot resolve KeyInfo for unwrapping key
I need to connect my NET Framework 4 Client App, to a Webservice, deployed on a Apache CXF, with WS Security. That service is out of my control.

The service is added to the project as a "Service Reference".

This is the proxy:

```<code>ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf AcceptAllCertifications)

Dim oBinding As New CustomBinding()
Dim oSecurity As SecurityBindingElement

oSecurity = AsymmetricSecurityBindingElement.CreateCertificateOverTransportBindingElement(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10)
oSecurity.IncludeTimestamp = True

oBinding.Elements.Add(oSecurity)
oBinding.Elements.Add(New CertFixEscapedComma.CertRefEncodingBindingElement())
   ( This a custom message encoder)
CertFixEscapedComma.CertRefEncoder.CERTIFICADO = Convert.ToBase64String(oCertificado.RawData)

oBinding.CloseTimeout = New TimeSpan(0, 2, 0)

Dim oTransport As New HttpsTransportBindingElement()
oBinding.Elements.Add(oTransport)

Dim oProxyClient As New NameServiceClient(oBinding, New System.ServiceModel.EndpointAddress(New Uri("https://url_service")))
Dim oCertificado As X509Certificate2
oCertificado = function_client_certificate() ' this get the proper cert

oProxyClient.ClientCredentials.ClientCertificate.Certificate = oCertificado
oProxyClient.name_function(params) 'call to the remote service
</code>```

Well. The server accepts my Request, and send the the response, in this way:

```<code><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" soap:mustUnderstand="1" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
      <xenc:EncryptedKey xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Id="EK-4A5A4F8820EFD673E7152328322340610394">
        <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
        <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
          <wsse:SecurityTokenReference>
            <ds:X509Data>
              <ds:X509IssuerSerial>
                <ds:X509IssuerName>issuer name etc etc cetc </ds:X509IssuerName>
                <ds:X509SerialNumber>62535066537829860999033107852056725154</ds:X509SerialNumber>
              </ds:X509IssuerSerial>
            </ds:X509Data>
          </wsse:SecurityTokenReference>
        </ds:KeyInfo>
        <xenc:CipherData>
          <xenc:CipherValue>SlU4B4BlMhsEc0ek ... ==</xenc:CipherValue>
        </xenc:CipherData>
        <xenc:ReferenceList>
          <xenc:DataReference URI="#ED-4A5A4F8820EFD673E7152328322340710395" />
        </xenc:ReferenceList>
      </xenc:EncryptedKey>
      <wsu:Timestamp wsu:Id="TS-4A5A4F8820EFD673E7152328322340510393">
        <wsu:Created>2018-04-09T14:13:43.405Z</wsu:Created>
        <wsu:Expires>2018-04-09T14:18:43.405Z</wsu:Expires>
      </wsu:Timestamp>
    </wsse:Security>
  </soap:Header>
  <soap:Body>
    <xenc:EncryptedData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Id="ED-4A5A4F8820EFD673E7152328322340710395" Type="http://www.w3.org/2001/04/xmlenc#Content">
      <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes128-cbc" />
      <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsse11="http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd" wsse11:TokenType="http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey">
          <wsse:Reference URI="#EK-4A5A4F8820EFD673E7152328322340610394" />
        </wsse:SecurityTokenReference>
      </ds:KeyInfo>
      <xenc:CipherData>
        <xenc:CipherValue>ZB7P3tYgRE4R7RZc0TONazc93t.... W5VoHVw5ywRj4D2hb9dIAaE8PQClm2vw==</xenc:CipherValue>
      </xenc:CipherData>
    </xenc:EncryptedData>
  </soap:Body>
</soap:Envelope>
</code>```

I get the error "Cannot resolve KeyInfo for unwrapping key".
Reading OASIS doc about that kind of soap messages, I think the message it's ok.

I have tried, with the custom encoder, changing "X509IssuerSerial" node, for a ". Same error.

I can, reading the message directly, perform a manual key decryption, using the cert. Then, with the key, I can decrypt the data. So data is correct.

BUT, I don't wan't this. I want use the Service Reference.

Going through NET Code, I see that stack trace:

```<code>System.ServiceModel.dll!System.ServiceModel.Security.WSSecurityJan2004.WrappedKeyTokenEntry.ReadTokenCore(System.Xml.XmlDictionaryReader reader, System.IdentityModel.Selectors.SecurityTokenResolver tokenResolver)
System.ServiceModel.dll!System.ServiceModel.Security.WSSecurityTokenSerializer.ReadTokenCore(System.Xml.XmlReader reader, System.IdentityModel.Selectors.SecurityTokenResolver tokenResolver)
System.ServiceModel.dll!System.ServiceModel.Security.WSSecurityOneDotZeroReceiveSecurityHeader.DecryptWrappedKey(System.Xml.XmlDictionaryReader reader)
System.ServiceModel.dll!System.ServiceModel.Security.ReceiveSecurityHeader.ReadEncryptedKey(System.Xml.XmlDictionaryReader reader, bool processReferenceListIfPresent)
System.ServiceModel.dll!System.ServiceModel.Security.ReceiveSecurityHeader.ExecuteFullPass(System.Xml.XmlDictionaryReader reader)
System.ServiceModel.dll!System.ServiceModel.Security.ReceiveSecurityHeader.Process(System.TimeSpan timeout, System.Security.Authentication.ExtendedProtection.ChannelBinding channelBinding, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy extendedProtectionPolicy)
System.ServiceModel.dll!System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessageCore(ref System.ServiceModel.Channels.Message message, System.TimeSpan timeout)
System.ServiceModel.dll!System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessage(ref System.ServiceModel.Channels.Message message, System.TimeSpan timeout)
System.ServiceModel.dll!System.ServiceModel.Security.SecurityProtocol.VerifyIncomingMessage(ref System.ServiceModel.Channels.Message message, System.TimeSpan timeout, System.ServiceModel.Security.SecurityProtocolCorrelationState[] correlationStates)
System.ServiceModel.dll!System.ServiceModel.Channels.SecurityChannelFactory<System.ServiceModel.Channels.IRequestChannel>.SecurityRequestChannel.ProcessReply(System.ServiceModel.Channels.Message reply, System.ServiceModel.Security.SecurityProtocolCorrelationState correlationState, System.TimeSpan timeout)
System.ServiceModel.dll!System.ServiceModel.Channels.SecurityChannelFactory<System.__Canon>.SecurityRequestChannel.Request(System.ServiceModel.Channels.Message message, System.TimeSpan timeout)
System.ServiceModel.dll!System.ServiceModel.Dispatcher.RequestChannelBinder.Request(System.ServiceModel.Channels.Message message, System.TimeSpan timeout)
System.ServiceModel.dll!System.ServiceModel.Channels.ServiceChannel.Call(string action, bool oneway, System.ServiceModel.Dispatcher.ProxyOperationRuntime operation, object[] ins, object[] outs, System.TimeSpan timeout)
System.ServiceModel.dll!System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(System.Runtime.Remoting.Messaging.IMethodCallMessage methodCall, System.ServiceModel.Dispatcher.ProxyOperationRuntime operation)
System.ServiceModel.dll!System.ServiceModel.Channels.ServiceChannelProxy.Invoke(System.Runtime.Remoting.Messaging.IMessage message)
mscorlib.dll!System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(ref System.Runtime.Remoting.Proxies.MessageData msgData, int type)
 ... mycode_calling_the_service()...
</code>```

So, in "System.ServiceModel.Security.WSSecurityJan2004.WrappedKeyTokenEntry.ReadTokenCore", it's trying to "CreateWrappedKeyToken", and the Exception it's throw here:

```<code>   WrappedKeySecurityToken CreateWrappedKeyToken(string id, string encryptionMethod, string carriedKeyName,
                SecurityKeyIdentifier unwrappingTokenIdentifier, byte[] wrappedKey, SecurityTokenResolver tokenResolver)
            {
                ISspiNegotiationInfo sspiResolver = tokenResolver as ISspiNegotiationInfo;
                if (sspiResolver != null)
                {
                    ISspiNegotiation unwrappingSspiContext = sspiResolver.SspiNegotiation;
                    // ensure that the encryption algorithm is compatible
                    if (encryptionMethod != unwrappingSspiContext.KeyEncryptionAlgorithm)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.BadKeyEncryptionAlgorithm, encryptionMethod)));
                    }
                    byte[] unwrappedKey = unwrappingSspiContext.Decrypt(wrappedKey);
                    return new WrappedKeySecurityToken(id, unwrappedKey, encryptionMethod, unwrappingSspiContext, unwrappedKey);
                }
                else
                {
                    if (tokenResolver == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("tokenResolver"));
                    }
                    if (unwrappingTokenIdentifier == null || unwrappingTokenIdentifier.Count == 0)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.MissingKeyInfoInEncryptedKey)));
                    }

                    SecurityToken unwrappingToken;
                    SecurityHeaderTokenResolver resolver = tokenResolver as SecurityHeaderTokenResolver;
                    if (resolver != null)
                    {
</code>```

unwrappingToken = resolver.ExpectedWrapper;
                               if (unwrappingToken != null)

```<code>                        {
                            if (!resolver.CheckExternalWrapperMatch(unwrappingTokenIdentifier))
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
                                    SR.GetString(SR.EncryptedKeyWasNotEncryptedWithTheRequiredEncryptingToken, unwrappingToken)));
                            }
                        }
                        else
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
                                SR.GetString(SR.UnableToResolveKeyInfoForUnwrappingToken, unwrappingTokenIdentifier, resolver)));
                        }
                    }
</code>```

...

So, in "unwrappingToken = resolver.ExpectedWrapper", I get a "null".

This could be some kind of "messages namespaces mismatch", or something like that, that I do not see?

Certificate it's ok and valid. It has all the x509v3 properties, and the issuer it's a trusted issuer...

Help me guys, my diopters are increasing with this ...

答:
Well, finally I could get rid of this message. You need to ensure if the service is using same certificate for auth and encription. You can get the public key's cert using fiddler, for example.

If 'NO' is the answer, you will need custom client credentials, something like this:

```<code>Public Class MyClientCredentials
  Inherits ClientCredentials

Public Sub New()

End Sub

' Perform client credentials initialization.
Protected Sub New(ByVal other As MyClientCredentials)
    MyBase.New(other)
End Sub

''' <summary>
''' Link to token manager
''' </summary>
''' <returns></returns>
Public Overrides Function CreateSecurityTokenManager() As SecurityTokenManager
    ' Return your implementation of the SecurityTokenManager.
    Return New MyClientCredentialsSecurityTokenManager(Me)

End Function
</code>```

Where, the custom token manager is doing something like this:

```<code>Public Class MyClientCredentialsSecurityTokenManager
  Inherits ClientCredentialsSecurityTokenManager
Private _oCredenciales As MyClientCredentials

Public Sub New(ByVal credentials As MyClientCredentials)
    MyBase.New(credentials)
    Me._oCredenciales = credentials

End Sub

''' <summary>
''' Custom token for each operation
''' </summary>
''' <param name="p_oRequirement"></param>
''' <returns></returns>
Public Overrides Function CreateSecurityTokenProvider(ByVal p_oRequirement As SecurityTokenRequirement) As SecurityTokenProvider

    Dim oRes As SecurityTokenProvider = Nothing
    If p_oRequirement.TokenType = SecurityTokenTypes.X509Certificate Then
        Dim direction = p_oRequirement.GetProperty(Of MessageDirection)(ServiceModelSecurityTokenRequirement.MessageDirectionProperty)
        If direction = MessageDirection.Output Then
            If p_oRequirement.KeyUsage = SecurityKeyUsage.Signature Then
                oRes = New X509SecurityTokenProvider(Me._oCredenciales.ClientCertificate.Certificate)
            Else
                oRes = New X509SecurityTokenProvider(Me._oCredenciales.ServiceCertificate.DefaultCertificate())
            End If
        End If
    Else
        oRes = MyBase.CreateSecurityTokenProvider(p_oRequirement)
    End If

    Return oRes

End Function
</code>```

Now, apply this to channel:

```<code>oServicio.ChannelFactory.Endpoint.Behaviors.Remove(Of ClientCredentials)()
oServicio.ChannelFactory.Endpoint.Behaviors.Add(oCred)
</code>```

I hope this will help someone on future.

Body:
I need to connect my NET Framework 4 Client App, to a Webservice, deployed on a Apache CXF, with WS Security. That service is out of my control.

The service is added to the project as a "Service Reference".

This is the proxy:

ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf AcceptAllCertifications)

Dim oBinding As New CustomBinding()
Dim oSecurity As SecurityBindingElement

oSecurity = AsymmetricSecurityBindingElement.CreateCertificateOverTransportBindingElement(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10)
oSecurity.IncludeTimestamp = True

oBinding.Elements.Add(oSecurity)
oBinding.Elements.Add(New CertFixEscapedComma.CertRefEncodingBindingElement())
   ( This a custom message encoder)
CertFixEscapedComma.CertRefEncoder.CERTIFICADO = Convert.ToBase64String(oCertificado.RawData)

oBinding.CloseTimeout = New TimeSpan(0, 2, 0)

Dim oTransport As New HttpsTransportBindingElement()
oBinding.Elements.Add(oTransport)

Dim oProxyClient As New NameServiceClient(oBinding, New System.ServiceModel.EndpointAddress(New Uri("https://url_service")))
Dim oCertificado As X509Certificate2
oCertificado = function_client_certificate() ' this get the proper cert

oProxyClient.ClientCredentials.ClientCertificate.Certificate = oCertificado
oProxyClient.name_function(params) 'call to the remote service

Well. The server accepts my Request, and send the the response, in this way:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" soap:mustUnderstand="1" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
      <xenc:EncryptedKey xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Id="EK-4A5A4F8820EFD673E7152328322340610394">
        <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
        <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
          <wsse:SecurityTokenReference>
            <ds:X509Data>
              <ds:X509IssuerSerial>
                <ds:X509IssuerName>issuer name etc etc cetc </ds:X509IssuerName>
                <ds:X509SerialNumber>62535066537829860999033107852056725154</ds:X509SerialNumber>
              </ds:X509IssuerSerial>
            </ds:X509Data>
          </wsse:SecurityTokenReference>
        </ds:KeyInfo>
        <xenc:CipherData>
          <xenc:CipherValue>SlU4B4BlMhsEc0ek ... ==</xenc:CipherValue>
        </xenc:CipherData>
        <xenc:ReferenceList>
          <xenc:DataReference URI="#ED-4A5A4F8820EFD673E7152328322340710395" />
        </xenc:ReferenceList>
      </xenc:EncryptedKey>
      <wsu:Timestamp wsu:Id="TS-4A5A4F8820EFD673E7152328322340510393">
        <wsu:Created>2018-04-09T14:13:43.405Z</wsu:Created>
        <wsu:Expires>2018-04-09T14:18:43.405Z</wsu:Expires>
      </wsu:Timestamp>
    </wsse:Security>
  </soap:Header>
  <soap:Body>
    <xenc:EncryptedData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Id="ED-4A5A4F8820EFD673E7152328322340710395" Type="http://www.w3.org/2001/04/xmlenc#Content">
      <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes128-cbc" />
      <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsse11="http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd" wsse11:TokenType="http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey">
          <wsse:Reference URI="#EK-4A5A4F8820EFD673E7152328322340610394" />
        </wsse:SecurityTokenReference>
      </ds:KeyInfo>
      <xenc:CipherData>
        <xenc:CipherValue>ZB7P3tYgRE4R7RZc0TONazc93t.... W5VoHVw5ywRj4D2hb9dIAaE8PQClm2vw==</xenc:CipherValue>
      </xenc:CipherData>
    </xenc:EncryptedData>
  </soap:Body>
</soap:Envelope>

I get the error "Cannot resolve KeyInfo for unwrapping key".
Reading OASIS doc about that kind of soap messages, I think the message it's ok.

I have tried, with the custom encoder, changing "X509IssuerSerial" node, for a ". Same error.

I can, reading the message directly, perform a manual key decryption, using the cert. Then, with the key, I can decrypt the data. So data is correct.

BUT, I don't wan't this. I want use the Service Reference.

Going through NET Code, I see that stack trace:

System.ServiceModel.dll!System.ServiceModel.Security.WSSecurityJan2004.WrappedKeyTokenEntry.ReadTokenCore(System.Xml.XmlDictionaryReader reader, System.IdentityModel.Selectors.SecurityTokenResolver tokenResolver)
System.ServiceModel.dll!System.ServiceModel.Security.WSSecurityTokenSerializer.ReadTokenCore(System.Xml.XmlReader reader, System.IdentityModel.Selectors.SecurityTokenResolver tokenResolver)
System.ServiceModel.dll!System.ServiceModel.Security.WSSecurityOneDotZeroReceiveSecurityHeader.DecryptWrappedKey(System.Xml.XmlDictionaryReader reader)
System.ServiceModel.dll!System.ServiceModel.Security.ReceiveSecurityHeader.ReadEncryptedKey(System.Xml.XmlDictionaryReader reader, bool processReferenceListIfPresent)
System.ServiceModel.dll!System.ServiceModel.Security.ReceiveSecurityHeader.ExecuteFullPass(System.Xml.XmlDictionaryReader reader)
System.ServiceModel.dll!System.ServiceModel.Security.ReceiveSecurityHeader.Process(System.TimeSpan timeout, System.Security.Authentication.ExtendedProtection.ChannelBinding channelBinding, System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy extendedProtectionPolicy)
System.ServiceModel.dll!System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessageCore(ref System.ServiceModel.Channels.Message message, System.TimeSpan timeout)
System.ServiceModel.dll!System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessage(ref System.ServiceModel.Channels.Message message, System.TimeSpan timeout)
System.ServiceModel.dll!System.ServiceModel.Security.SecurityProtocol.VerifyIncomingMessage(ref System.ServiceModel.Channels.Message message, System.TimeSpan timeout, System.ServiceModel.Security.SecurityProtocolCorrelationState[] correlationStates)
System.ServiceModel.dll!System.ServiceModel.Channels.SecurityChannelFactory<System.ServiceModel.Channels.IRequestChannel>.SecurityRequestChannel.ProcessReply(System.ServiceModel.Channels.Message reply, System.ServiceModel.Security.SecurityProtocolCorrelationState correlationState, System.TimeSpan timeout)
System.ServiceModel.dll!System.ServiceModel.Channels.SecurityChannelFactory<System.__Canon>.SecurityRequestChannel.Request(System.ServiceModel.Channels.Message message, System.TimeSpan timeout)
System.ServiceModel.dll!System.ServiceModel.Dispatcher.RequestChannelBinder.Request(System.ServiceModel.Channels.Message message, System.TimeSpan timeout)
System.ServiceModel.dll!System.ServiceModel.Channels.ServiceChannel.Call(string action, bool oneway, System.ServiceModel.Dispatcher.ProxyOperationRuntime operation, object[] ins, object[] outs, System.TimeSpan timeout)
System.ServiceModel.dll!System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(System.Runtime.Remoting.Messaging.IMethodCallMessage methodCall, System.ServiceModel.Dispatcher.ProxyOperationRuntime operation)
System.ServiceModel.dll!System.ServiceModel.Channels.ServiceChannelProxy.Invoke(System.Runtime.Remoting.Messaging.IMessage message)
mscorlib.dll!System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(ref System.Runtime.Remoting.Proxies.MessageData msgData, int type)
 ... mycode_calling_the_service()...

So, in "System.ServiceModel.Security.WSSecurityJan2004.WrappedKeyTokenEntry.ReadTokenCore", it's trying to "CreateWrappedKeyToken", and the Exception it's throw here:

   WrappedKeySecurityToken CreateWrappedKeyToken(string id, string encryptionMethod, string carriedKeyName,
                SecurityKeyIdentifier unwrappingTokenIdentifier, byte[] wrappedKey, SecurityTokenResolver tokenResolver)
            {
                ISspiNegotiationInfo sspiResolver = tokenResolver as ISspiNegotiationInfo;
                if (sspiResolver != null)
                {
                    ISspiNegotiation unwrappingSspiContext = sspiResolver.SspiNegotiation;
                    // ensure that the encryption algorithm is compatible
                    if (encryptionMethod != unwrappingSspiContext.KeyEncryptionAlgorithm)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.BadKeyEncryptionAlgorithm, encryptionMethod)));
                    }
                    byte[] unwrappedKey = unwrappingSspiContext.Decrypt(wrappedKey);
                    return new WrappedKeySecurityToken(id, unwrappedKey, encryptionMethod, unwrappingSspiContext, unwrappedKey);
                }
                else
                {
                    if (tokenResolver == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("tokenResolver"));
                    }
                    if (unwrappingTokenIdentifier == null || unwrappingTokenIdentifier.Count == 0)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.MissingKeyInfoInEncryptedKey)));
                    }

                    SecurityToken unwrappingToken;
                    SecurityHeaderTokenResolver resolver = tokenResolver as SecurityHeaderTokenResolver;
                    if (resolver != null)
                    {

unwrappingToken = resolver.ExpectedWrapper;
                               if (unwrappingToken != null)

                        {
                            if (!resolver.CheckExternalWrapperMatch(unwrappingTokenIdentifier))
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
                                    SR.GetString(SR.EncryptedKeyWasNotEncryptedWithTheRequiredEncryptingToken, unwrappingToken)));
                            }
                        }
                        else
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
                                SR.GetString(SR.UnableToResolveKeyInfoForUnwrappingToken, unwrappingTokenIdentifier, resolver)));
                        }
                    }

...

So, in "unwrappingToken = resolver.ExpectedWrapper", I get a "null".

This could be some kind of "messages namespaces mismatch", or something like that, that I do not see?

Certificate it's ok and valid. It has all the x509v3 properties, and the issuer it's a trusted issuer...

Help me guys, my diopters are increasing with this ...

Body:
Well, finally I could get rid of this message. You need to ensure if the service is using same certificate for auth and encription. You can get the public key's cert using fiddler, for example.

If 'NO' is the answer, you will need custom client credentials, something like this:

Public Class MyClientCredentials
  Inherits ClientCredentials

Public Sub New()

End Sub

' Perform client credentials initialization.
Protected Sub New(ByVal other As MyClientCredentials)
    MyBase.New(other)
End Sub

''' <summary>
''' Link to token manager
''' </summary>
''' <returns></returns>
Public Overrides Function CreateSecurityTokenManager() As SecurityTokenManager
    ' Return your implementation of the SecurityTokenManager.
    Return New MyClientCredentialsSecurityTokenManager(Me)

End Function

Where, the custom token manager is doing something like this:

Public Class MyClientCredentialsSecurityTokenManager
  Inherits ClientCredentialsSecurityTokenManager
Private _oCredenciales As MyClientCredentials

Public Sub New(ByVal credentials As MyClientCredentials)
    MyBase.New(credentials)
    Me._oCredenciales = credentials

End Sub

''' <summary>
''' Custom token for each operation
''' </summary>
''' <param name="p_oRequirement"></param>
''' <returns></returns>
Public Overrides Function CreateSecurityTokenProvider(ByVal p_oRequirement As SecurityTokenRequirement) As SecurityTokenProvider

    Dim oRes As SecurityTokenProvider = Nothing
    If p_oRequirement.TokenType = SecurityTokenTypes.X509Certificate Then
        Dim direction = p_oRequirement.GetProperty(Of MessageDirection)(ServiceModelSecurityTokenRequirement.MessageDirectionProperty)
        If direction = MessageDirection.Output Then
            If p_oRequirement.KeyUsage = SecurityKeyUsage.Signature Then
                oRes = New X509SecurityTokenProvider(Me._oCredenciales.ClientCertificate.Certificate)
            Else
                oRes = New X509SecurityTokenProvider(Me._oCredenciales.ServiceCertificate.DefaultCertificate())
            End If
        End If
    Else
        oRes = MyBase.CreateSecurityTokenProvider(p_oRequirement)
    End If

    Return oRes

End Function

Now, apply this to channel:

oServicio.ChannelFactory.Endpoint.Behaviors.Remove(Of ClientCredentials)()
oServicio.ChannelFactory.Endpoint.Behaviors.Add(oCred)

I hope this will help someone on future.